blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
2e784c734f1bb7a68f20c6803072c2c87af7eaf6
Java
Viral-patel703/Testyourbond-aut0
/lib/selenium-server-standalone-3.4.0/org/seleniumhq/jetty9/servlet/Invoker.java
UTF-8
8,009
1.976563
2
[]
no_license
package org.seleniumhq.jetty9.servlet; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.UnavailableException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import org.seleniumhq.jetty9.http.pathmap.MappedResource; import org.seleniumhq.jetty9.server.Handler; import org.seleniumhq.jetty9.server.Request; import org.seleniumhq.jetty9.server.handler.ContextHandler; import org.seleniumhq.jetty9.server.handler.ContextHandler.Context; import org.seleniumhq.jetty9.server.handler.HandlerWrapper; import org.seleniumhq.jetty9.util.ArrayUtil; import org.seleniumhq.jetty9.util.URIUtil; import org.seleniumhq.jetty9.util.log.Log; import org.seleniumhq.jetty9.util.log.Logger; public class Invoker extends HttpServlet { private static final Logger LOG = Log.getLogger(Invoker.class); private ContextHandler _contextHandler; private ServletHandler _servletHandler; private MappedResource<ServletHolder> _invokerEntry; private Map<String, String> _parameters; private boolean _nonContextServlets; private boolean _verbose; public Invoker() {} public void init() { ServletContext config = getServletContext(); _contextHandler = ((ContextHandler.Context)config).getContextHandler(); Handler handler = _contextHandler.getHandler(); while ((handler != null) && (!(handler instanceof ServletHandler)) && ((handler instanceof HandlerWrapper))) handler = ((HandlerWrapper)handler).getHandler(); _servletHandler = ((ServletHandler)handler); Enumeration<String> e = getInitParameterNames(); while (e.hasMoreElements()) { String param = (String)e.nextElement(); String value = getInitParameter(param); String lvalue = value.toLowerCase(Locale.ENGLISH); if ("nonContextServlets".equals(param)) { _nonContextServlets = ((value.length() > 0) && (lvalue.startsWith("t"))); } if ("verbose".equals(param)) { _verbose = ((value.length() > 0) && (lvalue.startsWith("t"))); } else { if (_parameters == null) _parameters = new HashMap(); _parameters.put(param, value); } } } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean included = false; String servlet_path = (String)request.getAttribute("javax.servlet.include.servlet_path"); if (servlet_path == null) { servlet_path = request.getServletPath(); } else included = true; String path_info = (String)request.getAttribute("javax.servlet.include.path_info"); if (path_info == null) { path_info = request.getPathInfo(); } String servlet = path_info; if ((servlet == null) || (servlet.length() <= 1)) { response.sendError(404); return; } int i0 = servlet.charAt(0) == '/' ? 1 : 0; int i1 = servlet.indexOf('/', i0); servlet = i1 < 0 ? servlet.substring(i0) : servlet.substring(i0, i1); ServletHolder[] holders = _servletHandler.getServlets(); ServletHolder holder = getHolder(holders, servlet); if (holder != null) { if (LOG.isDebugEnabled()) LOG.debug("Adding servlet mapping for named servlet:" + servlet + ":" + URIUtil.addPaths(servlet_path, servlet) + "/*", new Object[0]); ServletMapping mapping = new ServletMapping(); mapping.setServletName(servlet); mapping.setPathSpec(URIUtil.addPaths(servlet_path, servlet) + "/*"); _servletHandler.setServletMappings((ServletMapping[])ArrayUtil.addToArray(_servletHandler.getServletMappings(), mapping, ServletMapping.class)); } else { if (servlet.endsWith(".class")) servlet = servlet.substring(0, servlet.length() - 6); if ((servlet == null) || (servlet.length() == 0)) { response.sendError(404); return; } synchronized (_servletHandler) { _invokerEntry = _servletHandler.getHolderEntry(servlet_path); String path = URIUtil.addPaths(servlet_path, servlet); MappedResource<ServletHolder> entry = _servletHandler.getHolderEntry(path); if ((entry != null) && (!entry.equals(_invokerEntry))) { holder = (ServletHolder)entry.getResource(); } else { if (LOG.isDebugEnabled()) LOG.debug("Making new servlet=" + servlet + " with path=" + path + "/*", new Object[0]); holder = _servletHandler.addServletWithMapping(servlet, path + "/*"); if (_parameters != null) holder.setInitParameters(_parameters); try { holder.start(); } catch (Exception e) { LOG.debug(e); throw new UnavailableException(e.toString()); } if (!_nonContextServlets) { Object s = holder.getServlet(); if (_contextHandler.getClassLoader() != s.getClass().getClassLoader()) { try { holder.stop(); } catch (Exception e) { LOG.ignore(e); } LOG.warn("Dynamic servlet " + s + " not loaded from context " + request .getContextPath(), new Object[0]); throw new UnavailableException("Not in context"); } } if ((_verbose) && (LOG.isDebugEnabled())) { LOG.debug("Dynamic load '" + servlet + "' at " + path, new Object[0]); } } } } if (holder != null) { Request baseRequest = Request.getBaseRequest(request); holder.handle(baseRequest, new InvokedRequest(request, included, servlet, servlet_path, path_info), response); } else { LOG.info("Can't find holder for servlet: " + servlet, new Object[0]); response.sendError(404); } } class InvokedRequest extends HttpServletRequestWrapper { String _servletPath; String _pathInfo; boolean _included; InvokedRequest(HttpServletRequest request, boolean included, String name, String servletPath, String pathInfo) { super(); _included = included; _servletPath = URIUtil.addPaths(servletPath, name); _pathInfo = pathInfo.substring(name.length() + 1); if (_pathInfo.length() == 0) { _pathInfo = null; } } public String getServletPath() { if (_included) return super.getServletPath(); return _servletPath; } public String getPathInfo() { if (_included) return super.getPathInfo(); return _pathInfo; } public Object getAttribute(String name) { if (_included) { if (name.equals("javax.servlet.include.request_uri")) return URIUtil.addPaths(URIUtil.addPaths(getContextPath(), _servletPath), _pathInfo); if (name.equals("javax.servlet.include.path_info")) return _pathInfo; if (name.equals("javax.servlet.include.servlet_path")) return _servletPath; } return super.getAttribute(name); } } private ServletHolder getHolder(ServletHolder[] holders, String servlet) { if (holders == null) { return null; } ServletHolder holder = null; for (int i = 0; (holder == null) && (i < holders.length); i++) { if (holders[i].getName().equals(servlet)) { holder = holders[i]; } } return holder; } }
true
36eb5e9ba6a81b86cebf1e67a5516282418c942d
Java
ShaneMckenna23/cs4227-client
/src/main/java/com/cs4227/framework/filehandler/BaseContext.java
UTF-8
243
2.03125
2
[]
no_license
package com.cs4227.framework.filehandler; public class BaseContext { private String method; public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } }
true
be15fb232fa64db8a87eb3bfbac50a8e5b92cb21
Java
jayramrout/Batch30
/CoreJava/src/basics/method/MethodsExample.java
UTF-8
858
4.0625
4
[]
no_license
package basics.method; public class MethodsExample { public static void main(String[] args) { int a = 10; int b = 20; // output of the above a and b will be added to c MethodsExample methodsExample = new MethodsExample(); int result = methodsExample.add(a,b); int c = 30; int result2 = methodsExample.add(result,c); System.out.println(result2); // int result1 = methodsExample.addAndPrint(a,b); methodsExample.addAndPrint(2,3,"THis is a simple addition"); } public int add(int a , int b){ int result = a + b; return result; } /** * * @param a * @param b */ public void addAndPrint(int a, int b, String message) { int result = a + b; System.out.println(message+"-----"+ result); } }
true
6e5544eb7cab78ab814f1aac131790bdcf8bd635
Java
WoogLim/OurHouse
/src/ourhouse/common/vo/QnaListVO.java
UTF-8
2,481
2.3125
2
[]
no_license
package ourhouse.common.vo; /** * 홈 화면 (사진화면) 리스트 조회용 VO * @author 이경륜 */ public class QnaListVO{ private String postDate ; // 사진글 게시일 private int postNo ; // 사진글 번호 private String postTitle ; // 회원소개글 private String postContent ; // 프사경로 private int postView ; // 조회수 private int repCount ; // 댓글수 private String memId ; // 작성자이름 private String fileFileNm ; // 사진저장명 private String houseId ; // 사진저장명 private String spaceId ; // 사진저장명 private String roomId ; // 사진저장명 private String styleId ; // 사진저장명 private String colorId ; // 사진저장명 public String getPostDate() { return postDate; } public void setPostDate(String postDate) { this.postDate = postDate; } public int getPostNo() { return postNo; } public void setPostNo(int postNo) { this.postNo = postNo; } public String getPostTitle() { return postTitle; } public void setPostTitle(String postTitle) { this.postTitle = postTitle; } public String getPostContent() { return postContent; } public void setPostContent(String postContent) { this.postContent = postContent; } public int getPostView() { return postView; } public void setPostView(int postView) { this.postView = postView; } public int getRepCount() { return repCount; } public void setRepCount(int repCount) { this.repCount = repCount; } public String getMemId() { return memId; } public void setMemId(String memId) { this.memId = memId; } public String getFileFileNm() { return fileFileNm; } public void setFileFileNm(String fileFileNm) { this.fileFileNm = fileFileNm; } public String getHouseId() { return houseId; } public void setHouseId(String houseId) { this.houseId = houseId; } public String getSpaceId() { return spaceId; } public void setSpaceId(String spaceId) { this.spaceId = spaceId; } public String getRoomId() { return roomId; } public void setRoomId(String roomId) { this.roomId = roomId; } public String getStyleId() { return styleId; } public void setStyleId(String styleId) { this.styleId = styleId; } public String getColorId() { return colorId; } public void setColorId(String colorId) { this.colorId = colorId; } }
true
eaf601e0ee5fe063bf873de1c0bb7215f6bc89ec
Java
marappan/BaseProject
/compliance/src/main/java/com/bob/compliance/controller/ClientController.java
UTF-8
2,532
2.40625
2
[]
no_license
package com.bob.compliance.controller; import java.util.List; import org.apache.log4j.Logger; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.bob.compliance.model.Client; import com.bob.compliance.model.Status; import com.bob.compliance.services.ClientServices; @Controller @RequestMapping("/client") public class ClientController { @Autowired private ClientServices clientServices; ObjectMapper mapper; static final Logger logger = Logger.getLogger(ClientController.class); @RequestMapping(value = "/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Status addClient(@RequestBody Client client) { try { clientServices.saveEntity(client); return new Status(1, "Client added Successfully."); } catch (Exception e) { e.printStackTrace(); return new Status(0, e.toString()); } } @RequestMapping(value = "/list", method = RequestMethod.GET) public @ResponseBody List<Client> getClients() { List<Client> clientList = null; try { clientList = clientServices.getEntityList(); } catch (Exception e) { e.printStackTrace(); } return clientList; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public @ResponseBody Client geClient(@PathVariable("id") Integer id) { Client client = null; try { client = clientServices.getEntityById(id); mapper = new ObjectMapper(); System.out.println("JSON String : "+mapper.writeValueAsString(client)); } catch (Exception e) { e.printStackTrace(); } return client; } @RequestMapping(value = "/update", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Status updateClient(@RequestBody Client client) { try { Client updatedClient = clientServices.updateEntity(client); if (updatedClient == null) { return new Status(0, "Client record not found"); } return new Status(1, "Client updated successfully"); } catch (Exception e) { e.printStackTrace(); return new Status(0, e.toString()); } } }
true
6d3a59cd3af0bcbfa6dda506a310e99d19f67723
Java
Indigotin/DataStructure
/DSProject/src/Project4/MyLinkedList/MyLinkedListPane.java
UTF-8
8,401
3.03125
3
[]
no_license
package Project4.MyLinkedList; import javafx.application.Application; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.stage.Stage; public class MyLinkedListPane extends Application{ private MyLinkedList list = new MyLinkedList(); private Text top = new Text(); private Pane center = new Pane(); private TextField valueField = new TextField(); private TextField indexField = new TextField(); private Text tips = new Text(); @Override public void start(Stage primaryStage) throws Exception { BorderPane borderPane = new BorderPane(); borderPane.setTop(top); borderPane.setCenter(center); list.addFirst(5);list.addFirst("5");list.addFirst("5"); showCenter(list,-1); Text EnterValue = new Text("Enter a value"); Text EnterIndex = new Text("Enter an index"); Button Search = new Button("Search"); Button Insert = new Button("Insert"); Button Delete = new Button("Delete"); HBox bottom = new HBox(EnterValue,valueField,EnterIndex,indexField,Search,Insert,Delete); bottom.setSpacing(5); bottom.setAlignment(Pos.BOTTOM_RIGHT); borderPane.setBottom(bottom); Search.setOnAction(e->{ center.getChildren().removeAll(center.getChildren()); Search(primaryStage); }); Insert.setOnAction(e->{ center.getChildren().removeAll(center.getChildren()); Insert(primaryStage); }); Delete.setOnAction(e->{ center.getChildren().removeAll(center.getChildren()); Delete(primaryStage); }); primaryStage.setScene(new Scene(borderPane)); primaryStage.setTitle("MyLinkedList"); primaryStage.show(); } private void Search(Stage primaryStage){ try { String value = valueField.getText(); String indexStr = indexField.getText(); if(value.length() != 0){ int index = list.indexOf(value); if(index != -1){ showCenter(list,index); } else{ tips.setText("您输入的数据不存在!"); tipsPage(primaryStage); } } else { int index = Integer.parseInt(indexStr); if(index>=0 && index<list.size()) showCenter(list,index); else throw new NumberFormatException(); } } catch(NumberFormatException ex){ tips.setText("请输入有效的下标!"); tipsPage(primaryStage); } } private void Insert(Stage primaryStage){ try { String value = valueField.getText(); String indexStr = indexField.getText(); if(value.length() != 0){ list.addLast(value); } else { int index = Integer.parseInt(indexStr); if(index<=0) list.addFirst(value); else if(index>=list.size()) list.addLast(value); else list.set(index,value); } showCenter(list,-1); } catch(NumberFormatException ex){ tips.setText("请输入有效的下标!"); tipsPage(primaryStage); } } private void Delete(Stage primaryStage){ try { String value = valueField.getText(); String indexStr = indexField.getText(); if(value.length() != 0){ if(list.remove(value)){ showCenter(list,-1); } else{ tips.setText("请输入有效的数据!"); tipsPage(primaryStage); } } else if(indexStr.length() != 0){ int index = Integer.parseInt(indexStr); if(index>=0 && index<list.size()){ list.remove(index); showCenter(list,-1); } else throw new NumberFormatException(); } } catch(NumberFormatException ex){ tips.setText("请输入有效的下标!"); tipsPage(primaryStage); } } private void showCenter(MyLinkedList list, int SearchIndex){ int Width = 40; int Height = 30; int Gap = 50; Rectangle[] rectangles = new Rectangle[list.size()]; Line[] recLine = new Line[list.size()]; Line[] lines = new Line[list.size()]; Line[] lines1 = new Line[list.size()]; Line[] lines2 = new Line[list.size()]; Text[] texts = new Text[list.size()]; for(int i=0;i<list.size();i++){ rectangles[i] = new Rectangle(Gap+i*(Width+Gap),100,Width,Height); rectangles[i].setFill(Color.TRANSPARENT); rectangles[i].setStroke(Color.BLACK); recLine[i] = new Line(Gap+i*(Width+Gap)+Width/2,100,Gap+i*(Width+Gap)+Width/2,100+Height); center.getChildren().addAll(rectangles[i],recLine[i]); if(list.get(i) != null){ texts[i] = new Text(list.get(i)+""); if(SearchIndex != -1 && SearchIndex == i) texts[i].setFill(Color.RED); texts[i].setX(Gap+i*(Width+Gap)+Width/4); texts[i].setY(100+Height/2); center.getChildren().add(texts[i]); } //连接每个矩阵的箭头 if(i != list.size()-1){ lines[i] = new Line(Gap+i*Width+Gap*i+Width,100+Height/2,Gap+i*Width+Gap*i+Width+Gap,100+Height/2); lines1[i] = new Line(Gap+i*Width+Gap*i+Width+Gap,100+Height/2,Gap+i*Width+Gap*i+Width+Gap-5,100+Height/2-5); lines2[i] = new Line(Gap+i*Width+Gap*i+Width+Gap,100+Height/2,Gap+i*Width+Gap*i+Width+Gap-5,100+Height/2+5); center.getChildren().addAll(lines[i],lines1[i],lines2[i]); } //head箭头 if(i == 0){ Text head = new Text("head"); head.setX(Gap+i*(Width+Gap)+Width/4-5); head.setY(40); Line headLine = new Line(Gap+i*(Width+Gap)+Width/4,40,Gap+i*(Width+Gap)+Width/4,100); Line headLine1 = new Line(Gap+i*(Width+Gap)+Width/4,100,Gap+i*(Width+Gap)+Width/4-5,95); Line headLine2 = new Line(Gap+i*(Width+Gap)+Width/4,100,Gap+i*(Width+Gap)+Width/4+5,95); center.getChildren().addAll(head,headLine,headLine1,headLine2); } //tail箭头 if(i == list.size()-1){ Text tail = new Text("tail"); tail.setX(Gap+i*(Width+Gap)+Width/4+5); tail.setY(40); Line tailLine = new Line(Gap+i*(Width+Gap)+Width/4+10,40,Gap+i*(Width+Gap)+Width/4,100); Line tailLine1 = new Line(Gap+i*(Width+Gap)+Width/4,100,Gap+i*(Width+Gap)+Width/4-5,95); Line tailLine2 = new Line(Gap+i*(Width+Gap)+Width/4,100,Gap+i*(Width+Gap)+Width/4+5,95); center.getChildren().addAll(tail,tailLine,tailLine1,tailLine2); } } } //提示界面 public void tipsPage(Stage primaryStage){ Button button = new Button("确定"); VBox vBox = new VBox(); vBox.getChildren().addAll(tips,button); vBox.setAlignment(Pos.CENTER); button.setOnAction(e->{ MyLinkedListPane temp = new MyLinkedListPane(); try { temp.start(primaryStage); } catch (Exception e1) { e1.printStackTrace(); } }); Scene scene = new Scene(vBox,300,100); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { Application.launch(args); } }
true
9202a99a2b1b04d52041e902efc4bce7936982fa
Java
AY2021S2-CS2103T-W15-3/JJIMY
/src/main/java/seedu/address/storage/order/JsonSerializableOrderBook.java
UTF-8
1,664
2.828125
3
[ "MIT" ]
permissive
package seedu.address.storage.order; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.ReadOnlyBook; import seedu.address.model.order.Order; import seedu.address.model.order.OrderBook; /** * An immutable OrderBook that is serializable to JSON format. */ @JsonRootName(value = "orderbook") public class JsonSerializableOrderBook { public static final String MESSAGE_DUPLICATE_DISH = "Order list contains duplicate orders."; private final List<Order> orders = new ArrayList<>(); /** * Constructs a {@code JsonSerializableOrderBook} with the given persons. */ @JsonCreator public JsonSerializableOrderBook(@JsonProperty("orders") List<Order> orders) { this.orders.addAll(orders); } /** * Converts a given {@code ReadOnlyBook<Order>} into this class for Jackson use. * * @param source future changes to this will not affect the created {@code JsonSerializableOrderBook}. */ public JsonSerializableOrderBook(ReadOnlyBook<Order> source) { orders.addAll(source.getItemList()); } /** * Converts this order book into the model's {@code OrderBook} object. * @return OrderBook model type * @throws IllegalValueException */ public OrderBook toModelType() throws IllegalValueException { OrderBook orderBook = new OrderBook(); orderBook.setOrders(orders); return orderBook; } }
true
51ade33de31814d40ebe3c7f4e9e2f7dfd68a131
Java
Vikki111/SpringBootApp
/lab1/src/main/java/sprboot/service/CompositionService.java
UTF-8
464
1.976563
2
[]
no_license
package sprboot.service; import sprboot.model.Composition; import java.util.List; public interface CompositionService { void save(Composition composition); Composition getById(int id); void update(Composition composition); List<Composition> findAll(); void delete(int id); List<Composition> findAllByCompName(String compName); List<Composition> findAllByOrderByCompNameAsc(); List<Composition> findAllByOrderByCompNameDesc(); }
true
09f3c2118114d5db1c2bf4d8afa1c82b8a7c89e9
Java
vcampanholi/ampere-web
/src/main/java/com/vandersoncamp/ampereweb/service/CalculoCorrenteService.java
UTF-8
601
1.773438
2
[]
no_license
package com.vandersoncamp.ampereweb.service; import com.vandersoncamp.ampereweb.model.CalculoCorrente; import com.vandersoncamp.ampereweb.util.GenericDao; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.inject.Inject; @Stateless @TransactionAttribute(TransactionAttributeType.REQUIRED) public class CalculoCorrenteService extends AbstractCrudService<CalculoCorrente> { @Inject private GenericDao<CalculoCorrente> dao; @Override protected GenericDao<CalculoCorrente> getDao() { return dao; } }
true
8981d46cbc3921bf2231f5a3b134da7b92b9fbbe
Java
caik123/mail_template
/mail_template_server/src/main/java/com/ghostkang/mail_template_server/dao/GoodDao.java
UTF-8
568
1.804688
2
[]
no_license
package com.ghostkang.mail_template_server.dao; import com.ghostkang.mail_template_server.bean.good.GoodVo; import com.ghostkang.mail_template_server.bean.good.ListRequest; import com.ghostkang.mail_template_server.bean.good.ListResponse; import com.ghostkang.mail_template_server.domain.Good; import com.ghostkang.mail_template_server.framework.core.Mapper; import java.util.List; /** * 商品 数据层 * * @author GhostKang * @date 2020-11-10 11:08:07 */ public interface GoodDao extends Mapper<Good> { List<GoodVo> getGoodList(ListRequest listRequest); }
true
d1c2fdb28907add9b023df9b404f747b2d6c6ebc
Java
alfisyar520/Fit-Pack
/app/src/main/java/com/example/fitpack/Model/User.java
UTF-8
1,220
2.34375
2
[]
no_license
package com.example.fitpack.Model; public class User { private String id; private String username; private String imageUrl; private String kategori; private String tglLahir; public User() { } public User(String id, String username, String imageUrl, String kategori, String tglLahir) { this.id = id; this.username = username; this.imageUrl = imageUrl; this.kategori = kategori; this.tglLahir = tglLahir; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getKategori() { return kategori; } public void setKategori(String kategori) { this.kategori = kategori; } public String getTglLahir() { return tglLahir; } public void setTglLahir(String tglLahir) { this.tglLahir = tglLahir; } }
true
1cbf03eaf9fd1e39884a66e3eab9b21f2328ad17
Java
mahmoudEldeeb/SmartWare
/app/src/main/java/com/m_eldeeb/smartware/Contact.java
UTF-8
3,335
2.296875
2
[]
no_license
package com.m_eldeeb.smartware; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.m_eldeeb.smartware.models.ContactModel; import com.m_eldeeb.smartware.models.RegisterModel; import static com.m_eldeeb.smartware.R.id.course; /** * A simple {@link Fragment} subclass. */ public class Contact extends Fragment { public Contact() { // Required empty public constructor } EditText name,email,subject,message; Button send; ProgressBar progressBar; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view=inflater.inflate(R.layout.fragment_contact, container, false); name= (EditText) view.findViewById(R.id.name); email= (EditText) view.findViewById(R.id.email); subject= (EditText) view.findViewById(R.id.subject); message= (EditText) view.findViewById(R.id.message); progressBar= (ProgressBar) view.findViewById(R.id.progressBar3); send= (Button) view.findViewById(R.id.send); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Contact(); } }); return view; } public void Contact(){ FirebaseDatabase database = FirebaseDatabase.getInstance(); final DatabaseReference Contacts = database.getReference("Contacts"); if (name.getText().toString() == null || email.getText().toString() == null || subject.getText().toString() == null || message.getText().toString() == null) { Toast.makeText(getActivity(), "fill all data", Toast.LENGTH_SHORT).show(); } else { progressBar.setVisibility(View.VISIBLE); ContactModel model = new ContactModel(); model.setName(name.getText().toString()); model.setEmail(email.getText().toString()); model.setSubject(subject.getText().toString()); model.setMessage(message.getText().toString()); Contacts.push().setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { progressBar.setVisibility(View.INVISIBLE); if (task.isSuccessful()) { // progressBar.setVisibility(View.INVISIBLE); Toast.makeText(getActivity(), "done", Toast.LENGTH_SHORT).show(); } else { // progressBar.setVisibility(View.INVISIBLE); Log.v("ee",task.toString()); Toast.makeText(getActivity(), "there is a problem try later ", Toast.LENGTH_SHORT).show(); } } }); } } }
true
c6bd2382bc29c0b8a6de8473796d7a32d8d43684
Java
vidyabhisol/SRCalculator
/SRCalculator/src/main/java/com/vidyabisol/srcalculator/fragment/ElliottFragment.java
UTF-8
16,938
2.15625
2
[]
no_license
package com.vidyabisol.srcalculator.fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.vidyabisol.srcalculator.HelperUtility; import com.vidyabisol.srcalculator.R; import com.vidyabisol.srcalculator.data.ElliottWaveDataBin; import com.vidyabisol.srcalculator.data.StockDataBin; import java.util.List; import java.util.Locale; import static android.content.Context.INPUT_METHOD_SERVICE; public class ElliottFragment extends FragmentDataInterface implements View.OnClickListener, TextView.OnEditorActionListener{ private static final String ARG_SECTION_NUMBER = "section_number"; private View rootView; private Button btnElliottCalc; private String decimalFormat="%.2f"; private EditText etElliottHigh, etElliottLow, etElliottClose,etElliottPeriod; private TextView tvElliottUpTrend,tvElliottDownTrend; private TextView tvElliottUp1,tvElliottUp2,tvElliottUp3,tvElliottUp4,tvElliottUp5,tvElliottUpA,tvElliottUpB,tvElliottUpC; private TextView tvElliottDown1,tvElliottDown2,tvElliottDown3,tvElliottDown4,tvElliottDown5,tvElliottDownA,tvElliottDownB,tvElliottDownC; private LinearLayout elliottLayout; private List<StockDataBin> _selectedStockList; public ElliottFragment() { // Required empty public constructor } public static ElliottFragment newInstance() { ElliottFragment fragment = new ElliottFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, 2); fragment.setArguments(args); return fragment; } @Override public void clearData() { HelperUtility.clearForm(elliottLayout); _selectedStockList = null; } private void setHighLowForElliott(int limit,List<StockDataBin> selectedStockList){ try{ if(selectedStockList!=null && selectedStockList.size()>0){ int cnt=0; //find last high low in limit Double high = selectedStockList.get(0).get_prevHigh(); Double low = selectedStockList.get(0).get_prevLow(); Double close = selectedStockList.get(0).get_prevClose(); for(StockDataBin curStock:selectedStockList){ if(cnt<limit){ if(high<curStock.get_prevHigh()){ high = curStock.get_prevHigh(); } if(low>curStock.get_prevLow()){ low = curStock.get_prevLow(); } } else{ break; } cnt++; } //set the trend text if(selectedStockList.get(0).get_prevClose()<selectedStockList.get(limit-1).get_prevClose()){ tvElliottUpTrend.setText(R.string.uptrend); tvElliottDownTrend.setText(R.string.downTrendStar); } else{ tvElliottUpTrend.setText(R.string.uptrendStar); tvElliottDownTrend.setText(R.string.downTrend); } etElliottClose.setText(String.format(Locale.getDefault(),decimalFormat,close)); etElliottHigh.setText(String.format(Locale.getDefault(),decimalFormat,high)); etElliottLow.setText(String.format(Locale.getDefault(),decimalFormat,low)); } } catch (Exception ex){ ex.printStackTrace(); } } @Override public void updateData(List<StockDataBin> selectedStockList){ try{ _selectedStockList = selectedStockList; etElliottPeriod.setText(R.string.default_period); btnElliottCalc.performClick(); } catch (Exception ex){ ex.printStackTrace(); } } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment rootView = inflater.inflate(R.layout.fragment_elliott, container, false); btnElliottCalc = rootView.findViewById(R.id.btnElliottCalculate); elliottLayout = rootView.findViewById(R.id.linearLayoutElliott); tvElliottUpTrend = rootView.findViewById(R.id.tvElliottUpTrend); tvElliottDownTrend = rootView.findViewById(R.id.tvElliottDownTrend); etElliottHigh = rootView.findViewById(R.id.etElliottHigh); etElliottLow = rootView.findViewById(R.id.etElliottLow); etElliottClose = rootView.findViewById(R.id.etElliottClose); tvElliottUp1 = rootView.findViewById(R.id.tvElliottWaveUpValue1); tvElliottUp2 = rootView.findViewById(R.id.tvElliottWaveUpValue2); tvElliottUp3 = rootView.findViewById(R.id.tvElliottWaveUpValue3); tvElliottUp4 = rootView.findViewById(R.id.tvElliottWaveUpValue4); tvElliottUp5 = rootView.findViewById(R.id.tvElliottWaveUpValue5); tvElliottUpA = rootView.findViewById(R.id.tvElliottWaveUpValueA); tvElliottUpB = rootView.findViewById(R.id.tvElliottWaveUpValueB); tvElliottUpC = rootView.findViewById(R.id.tvElliottWaveUpValueC); tvElliottDown1 = rootView.findViewById(R.id.tvElliottWaveDownValue1); tvElliottDown2 = rootView.findViewById(R.id.tvElliottWaveDownValue2); tvElliottDown3 = rootView.findViewById(R.id.tvElliottWaveDownValue3); tvElliottDown4 = rootView.findViewById(R.id.tvElliottWaveDownValue4); tvElliottDown5 = rootView.findViewById(R.id.tvElliottWaveDownValue5); tvElliottDownA = rootView.findViewById(R.id.tvElliottWaveDownValueA); tvElliottDownB = rootView.findViewById(R.id.tvElliottWaveDownValueB); tvElliottDownC = rootView.findViewById(R.id.tvElliottWaveDownValueC); etElliottPeriod = rootView.findViewById(R.id.etElliottPeriod); btnElliottCalc.setOnClickListener(this); etElliottClose.setOnEditorActionListener(this); etElliottHigh.setSelectAllOnFocus(true); etElliottLow.setSelectAllOnFocus(true); etElliottClose.setSelectAllOnFocus(true); etElliottPeriod.setSelectAllOnFocus(true); etElliottPeriod.setOnEditorActionListener(this); //Check data in shared preference and populate try{ if(getActivity()!=null){ List<StockDataBin> stkBin = HelperUtility.getSharedPreferenceStockDataBin(getActivity().getApplicationContext()); if(stkBin!=null && stkBin.size()>0){ updateData(stkBin); } } } catch (Exception ex){ ex.printStackTrace(); } return rootView; } private ElliottWaveDataBin CalculateElliottWave(double low, double high){ ElliottWaveDataBin elliottDataBin = null; try{ //for uptrend double highLowDiff = high - low; double wave2UpEnd = high - (highLowDiff*0.618); double wave3UpEnd = wave2UpEnd + (highLowDiff*1.618); double wave4UpEnd = wave3UpEnd - ((wave3UpEnd- wave2UpEnd)*0.382); double wave5UpEnd = wave4UpEnd + highLowDiff; double waveAUpEnd = wave5UpEnd - ((wave5UpEnd- wave4UpEnd)*0.382); double waveBUpEnd = waveAUpEnd + ((wave5UpEnd -waveAUpEnd)*0.618); double waveCUpEnd = waveBUpEnd - (highLowDiff*0.382); //for uptrend double wave2DownEnd = low + (highLowDiff*0.618); double wave3DownEnd = wave2DownEnd - (highLowDiff*1.618); double wave4DownEnd = wave3DownEnd + ((wave2DownEnd -wave3DownEnd)*0.382); double wave5DownEnd = wave4DownEnd - highLowDiff; double waveADownEnd = wave5DownEnd + ((wave4DownEnd -wave5DownEnd)*0.382); double waveBDownEnd = waveADownEnd - ((waveADownEnd- wave5DownEnd)*0.618); double waveCDownEnd = waveBDownEnd + (highLowDiff*0.382); String wave1Up = String.format(Locale.getDefault(),decimalFormat, low) + " - " + String.format(Locale.getDefault(),decimalFormat, high); String wave2Up = String.format(Locale.getDefault(),decimalFormat, high) + " - " + String.format(Locale.getDefault(),decimalFormat,wave2UpEnd); String wave3Up = String.format(Locale.getDefault(),decimalFormat, wave2UpEnd) + " - " + String.format(Locale.getDefault(),decimalFormat,wave3UpEnd); String wave4Up = String.format(Locale.getDefault(),decimalFormat, wave3UpEnd) + " - " + String.format(Locale.getDefault(),decimalFormat,wave4UpEnd); String wave5Up = String.format(Locale.getDefault(),decimalFormat, wave4UpEnd) + " - " + String.format(Locale.getDefault(),decimalFormat,wave5UpEnd); String waveAUp = String.format(Locale.getDefault(),decimalFormat, wave5UpEnd) + " - " + String.format(Locale.getDefault(),decimalFormat,waveAUpEnd); String waveBUp = String.format(Locale.getDefault(),decimalFormat, waveAUpEnd) + " - " + String.format(Locale.getDefault(),decimalFormat,waveBUpEnd); String waveCUp = String.format(Locale.getDefault(),decimalFormat, waveBUpEnd) + " - " + String.format(Locale.getDefault(),decimalFormat,waveCUpEnd); String wave1Down = String.format(Locale.getDefault(),decimalFormat, high) + " - " + String.format(Locale.getDefault(),decimalFormat, low); String wave2Down = String.format(Locale.getDefault(),decimalFormat, low) + " - " + String.format(Locale.getDefault(),decimalFormat,wave2DownEnd); String wave3Down = String.format(Locale.getDefault(),decimalFormat, wave2DownEnd) + " - " + String.format(Locale.getDefault(),decimalFormat,wave3DownEnd); String wave4Down = String.format(Locale.getDefault(),decimalFormat, wave3DownEnd) + " - " + String.format(Locale.getDefault(),decimalFormat,wave4DownEnd); String wave5Down = String.format(Locale.getDefault(),decimalFormat, wave4DownEnd) + " - " + String.format(Locale.getDefault(),decimalFormat,wave5DownEnd); String waveADown = String.format(Locale.getDefault(),decimalFormat, wave5DownEnd) + " - " + String.format(Locale.getDefault(),decimalFormat,waveADownEnd); String waveBDown = String.format(Locale.getDefault(),decimalFormat, waveADownEnd) + " - " + String.format(Locale.getDefault(),decimalFormat,waveBDownEnd); String waveCDown = String.format(Locale.getDefault(),decimalFormat, waveBDownEnd) + " - " + String.format(Locale.getDefault(),decimalFormat,waveCDownEnd); elliottDataBin = new ElliottWaveDataBin(wave1Up,wave2Up,wave3Up,wave4Up,wave5Up,waveAUp,waveBUp,waveCUp, wave1Down,wave2Down,wave3Down,wave4Down,wave5Down,waveADown,waveBDown,waveCDown); } catch (Exception ex){ ex.printStackTrace(); } return elliottDataBin; } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btnElliottCalculate: try { InputMethodManager imm = (InputMethodManager) rootView.getContext().getSystemService(INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(rootView.getWindowToken(), 0); } if(_selectedStockList!=null && _selectedStockList.size()>0){ if(etElliottPeriod.getText() !=null && etElliottPeriod.getText().toString().length()>0){ int default_limit = Integer.parseInt(etElliottPeriod.getText().toString()); if(default_limit >200 || default_limit <=0){ etElliottPeriod.setError(getString(R.string.validperiodrange)); } else { setHighLowForElliott(default_limit,_selectedStockList); } } } if (etElliottHigh.getText().toString().length() == 0) { etElliottHigh.setError(getString(R.string.validHigh)); } else if (etElliottLow.getText().toString().length() == 0) { etElliottLow.setError(getString(R.string.validLow)); } else if (etElliottClose.getText().toString().length() == 0) { etElliottClose.setError(getString(R.string.validClose)); } else { double high = Double.parseDouble(etElliottHigh.getText().toString()); double low = Double.parseDouble(etElliottLow.getText().toString()); double close = Double.parseDouble(etElliottClose.getText().toString()); //Logic to find out the decimal place precision int closeDp = 2,highDp=2, lowDP=2; int dpHighest=2; if (etElliottClose.getText().toString().contains(".")) { closeDp = etElliottClose.getText().toString().length() - etElliottClose.getText().toString().indexOf(".") - 1; } if (etElliottHigh.getText().toString().contains(".")) { highDp = etElliottHigh.getText().toString().length() - etElliottHigh.getText().toString().indexOf(".") - 1; } if (etElliottLow.getText().toString().contains(".")) { lowDP = etElliottLow.getText().toString().length() - etElliottLow.getText().toString().indexOf(".") - 1; } if(closeDp==highDp && highDp==lowDP){ dpHighest = closeDp; } decimalFormat = "%." + String.valueOf(dpHighest) + "f"; if(low>=high){ etElliottLow.setError(getString(R.string.lowhighValid)); } else if(close>high){ etElliottClose.setError(getString(R.string.closeinhighlow)); } else if(close<low){ etElliottClose.setError(getString(R.string.closeinhighlow)); } else{ ElliottWaveDataBin resultElliott = CalculateElliottWave(low, high); if (resultElliott != null) { tvElliottUp1.setText(resultElliott.get_waveUp1()); tvElliottUp2.setText(resultElliott.get_waveUp2()); tvElliottUp3.setText(resultElliott.get_waveUp3()); tvElliottUp4.setText(resultElliott.get_waveUp4()); tvElliottUp5.setText(resultElliott.get_waveUp5()); tvElliottUpA.setText(resultElliott.get_waveUpA()); tvElliottUpB.setText(resultElliott.get_waveUpB()); tvElliottUpC.setText(resultElliott.get_waveUpC()); tvElliottDown1.setText(resultElliott.get_waveDown1()); tvElliottDown2.setText(resultElliott.get_waveDown2()); tvElliottDown3.setText(resultElliott.get_waveDown3()); tvElliottDown4.setText(resultElliott.get_waveDown4()); tvElliottDown5.setText(resultElliott.get_waveDown5()); tvElliottDownA.setText(resultElliott.get_waveDownA()); tvElliottDownB.setText(resultElliott.get_waveDownB()); tvElliottDownC.setText(resultElliott.get_waveDownC()); } } } } catch (Exception ex){ ex.printStackTrace(); } break; } } @Override public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { switch (textView.getId()){ case R.id.etElliottClose: if(i== EditorInfo.IME_ACTION_DONE){ btnElliottCalc.performClick(); } break; case R.id.etElliottPeriod: if(i==EditorInfo.IME_ACTION_DONE){ btnElliottCalc.performClick(); } break; } return false; } }
true
12ff8da0a93edc715736aac6afdd7c7ee47408cd
Java
Neidschel/OPRAufgaben
/OPR2_UE06_NiglM_MC12028/src/at/fhhgb/mc/Aufgabe02/Abstract/AbstractMember.java
UTF-8
2,804
3.84375
4
[]
no_license
package at.fhhgb.mc.Aufgabe02.Abstract; /** * All sections and members inherit the methods of this class. It's the skeletal * structure of the whole section and member administration. * * All values of the member (income, costs, name) are stored here. * * @author Michael Nigl * @version 1.1 */ public abstract class AbstractMember implements Comparable<AbstractMember> { private double income; private double costs; private String name; /** * This Constructor is called by every extending class in the packed for * initializing the name, income and costs. * * @param name * the name of the section or the member or failfailfail if the * name was null * @param income * the money the member earns or the money the section has * because of its members * @param costs * the money a member cost or the money all members cost a * section * @throws NullPointerException * if name is null */ public AbstractMember(String name, double income, double costs) throws NullPointerException { if (name == null) { throw new NullPointerException("The new Member has no name!"); } else { this.name = name; } this.income = income; this.costs = costs; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setIncome(double income) { this.income = income; } public double getIncome() { return income; } public void setCosts(double costs) { this.costs = costs; } public double getCosts() { return costs; } public double getSurplus() { return income - costs; } /** * The compare method used to compare different Member Objects for correct * sorting into the tree. * * @param m * the AbstractMember to be compared with this one * @return 1 if this Objects value is bigger, -1 if this value is smaller * @throws NullPointerException * if m is null */ public int compareTo(AbstractMember m) throws NullPointerException { if (m == null) { throw new NullPointerException( "No valid comparable in the transfer parameter!"); } else if (this.getSurplus() > m.getSurplus()) { return 1; } else if (this.getSurplus() < m.getSurplus()) { return -1; } else { if (this.getName().compareTo(m.getName()) > 1) { return 1; } else { return -1; } } } /** * Prints the Member or the Section with all it's Members hierarchically * below it. * * @param ascending * true of the Members of the different Section are sorted * ascending by their surplus, false otherwise * @return a String representation of the Section and Members */ public abstract String toString(boolean ascending); }
true
fde2bfaf3e1ef15949a89a6be95300af8cf08fe7
Java
konglinghai123/his
/his-inner-interface/src/main/java/cn/honry/inner/inpatient/nurseInfoPack/service/impl/NurseInfoPackInInterServiceImpl.java
UTF-8
4,851
1.914063
2
[]
no_license
package cn.honry.inner.inpatient.nurseInfoPack.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.honry.base.bean.model.HospitalParameter; import cn.honry.base.bean.model.InpatientInfo; import cn.honry.base.bean.model.InpatientKind; import cn.honry.base.bean.model.InpatientOrder; import cn.honry.base.bean.model.VidExecdrugBedname; import cn.honry.base.bean.model.VidExecdrugBednameKs; import cn.honry.base.bean.model.VidExecundrugBedname; import cn.honry.base.bean.model.VidExecundrugBednameKs; import cn.honry.base.bean.model.VidInfoOrder; import cn.honry.inner.inpatient.nurseInfoPack.dao.NurseInfoPackInInterDao; import cn.honry.inner.inpatient.nurseInfoPack.service.NurseInfoPackInInterService; @Service("nurseInfoPackInInterService") @Transactional @SuppressWarnings({ "all" }) public class NurseInfoPackInInterServiceImpl implements NurseInfoPackInInterService { @Autowired @Qualifier(value = "nurseInfoPackInInterDao") private NurseInfoPackInInterDao nurseInfoPackInInterDao; public VidInfoOrder getInfoID(String id) { return nurseInfoPackInInterDao.getIdbyORder(id); } private VidInfoOrder order; public void removeUnused(String id) { } public VidInfoOrder get(String id) { return null; } public void saveOrUpdate(VidInfoOrder entity) { } /** * 带条件分页查询临时医嘱 */ public List<InpatientOrder> viewInfos(InpatientOrder vidInfoOrder, String rows, String page) { return nurseInfoPackInInterDao.viewInfos(vidInfoOrder, rows, page); } /** * 查询临时医嘱的总数 */ public int getTotals(InpatientOrder vidInfoOrder) { return nurseInfoPackInInterDao.getTotals(vidInfoOrder); } //------------------------------------------------------------------------------------------------------------------------------------------------------------- /** * 带条件分页查询长期医嘱 */ public List<InpatientOrder> viewInfo(InpatientOrder vidInfoOrder, String rows, String page) { return nurseInfoPackInInterDao.viewInfo(vidInfoOrder, rows, page); } /** * 获得长期医嘱的总数 */ public int getTotal(InpatientOrder vidInfoOrder) { return nurseInfoPackInInterDao.getTotal(vidInfoOrder); } //根据系统参数名称获得数据 public HospitalParameter getByHosInfoByName(String name) { return nurseInfoPackInInterDao.getByHosInfoByName(name); } public VidInfoOrder getOrderByOrderId(String id) { return nurseInfoPackInInterDao.getOrderByOrderId(id); } public List<InpatientKind> getCombobox() { return nurseInfoPackInInterDao.getCombobox(); } /** * 分页查询药嘱执行档 */ public List<VidExecdrugBedname> execDruglist(VidExecdrugBedname execdrug,String page, String rows,String deptId) { return nurseInfoPackInInterDao.execDruglist(execdrug, page, rows,deptId); } /** * 统计药嘱执行档数据 */ public int execDrugTotal(VidExecdrugBedname execdrug,String deptId) { return nurseInfoPackInInterDao.execDrugTotal(execdrug,deptId); } /** * 分页查询药嘱执行档ks */ public List<VidExecdrugBednameKs> execDruglistks(VidExecdrugBednameKs execdrug,String page, String rows,String deptId) { return nurseInfoPackInInterDao.execDruglistks(execdrug, page, rows,deptId); } /** * 统计药嘱执行档数据ks */ public int execDrugTotalks(VidExecdrugBednameKs execdrug,String deptId) { return nurseInfoPackInInterDao.execDrugTotalks(execdrug,deptId); } /** * 分页查询非药品执行档 */ public List<VidExecundrugBedname> execUnDrugList(VidExecundrugBedname execundrug, String page, String rows,String deptId) { return nurseInfoPackInInterDao.execUnDrugList(execundrug, page, rows,deptId); } /** * 统计非要执行档 */ public int execUnDrugTotal(VidExecundrugBedname execundrug,String deptId) { return nurseInfoPackInInterDao.execUnDrugTotal(execundrug,deptId); } /** * 分页查询非药品执行档 */ public List<VidExecundrugBednameKs> execUnDrugListks(VidExecundrugBednameKs execundrug, String page, String rows,String deptId) { return nurseInfoPackInInterDao.execUnDrugListks(execundrug, page, rows,deptId); } /** * 统计非要执行档 */ public int execUnDrugTotalks(VidExecundrugBednameKs execundrug,String deptId) { return nurseInfoPackInInterDao.execUnDrugTotalks(execundrug,deptId); } /** * 渲染患者 */ public List<InpatientInfo> infos() { return nurseInfoPackInInterDao.infos(); } }
true
54dc109829cc228950006093b7fd46d220ad6553
Java
coolhy123/jwt-
/src/main/java/com/hydu/controller/LoginController.java
UTF-8
2,042
2.34375
2
[]
no_license
package com.hydu.controller; import com.hydu.config.JwtUtil; import io.jsonwebtoken.Claims; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; /** * Created on 2019/10/9 * * @author heyong */ @RestController @RequestMapping("/user") public class LoginController { @Autowired public JwtUtil jwtUtil; @Autowired private HttpServletRequest request; @RequestMapping(value = "/findAll",method = RequestMethod.GET) @ResponseBody public String findAll(){ return "访问成功"; } /*** 用户登陆 * @return * */ @RequestMapping(value="/login",method= RequestMethod.POST) public Map login(@RequestBody Map<String,String> loginMap){ boolean flag = false; if("admin".equals(loginMap.get("name")) && "123".equals(loginMap.get("password"))){ flag = true; } //生成token Map map=new HashMap(); if(flag){ String token = jwtUtil.createJwt(loginMap.get("id"), loginMap.get("name"), "admin"); map.put("token",token); map.put("name",loginMap.get("name")); map.put("code",200); map.put("msg","登录成功"); //登陆名 return map; }else{ map.put("token",null); map.put("name",null); map.put("code",201); map.put("msg","登录失败"); return map; } } /*** * 删除 * @param id **/ @RequestMapping(value="/{id}",method= RequestMethod.DELETE) public Map<String,String> delete(@PathVariable String id ){ Claims claims=(Claims) request.getAttribute("admin_claims"); Map map=new HashMap(); if(claims==null){ map.put("code",500); map.put("msg","无权访问"); return map; } map.put("code",200); map.put("msg","删除成功"); return map; } }
true
e027b3b467b49322a1ed21d7115602d99a8d53b7
Java
h474lab/habits-builder
/app/src/main/java/com/example/habitsbuilder/DailyTaskFragment.java
UTF-8
5,156
2.234375
2
[]
no_license
package com.example.habitsbuilder; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CalendarView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentContainerView; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import com.example.habitsbuilder.Database.Habit; import com.example.habitsbuilder.Database.HabitDay; import com.example.habitsbuilder.dummy.DummyContent; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; /** * A simple {@link Fragment} subclass. * Use the {@link DailyTaskFragment#newInstance} factory method to * create an instance of this fragment. */ public class DailyTaskFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; //private CalendarView calendar; public DailyTaskFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment DailyTaskFragment. */ // TODO: Rename and change types and number of parameters public static DailyTaskFragment newInstance(String param1, String param2) { DailyTaskFragment fragment = new DailyTaskFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } private static Context context; private static FragmentManager childFragmentManager; private static CalendarView calendar; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_daily_task, container, false); } @RequiresApi(api = Build.VERSION_CODES.O) @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); calendar = (CalendarView) view.findViewById(R.id.calendar); FragmentTransaction ft = getChildFragmentManager().beginTransaction(); ft.replace(R.id.habit_list_fragment, new CheckListFragment()); ft.commit(); context = getContext(); childFragmentManager = getChildFragmentManager(); updateHabitList(); calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() { @Override public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) { Calendar cal = Calendar.getInstance(); cal.set(year, month, dayOfMonth); calendar.setDate(cal.getTimeInMillis()); updateHabitList(); } }); } public static String pickedHabitDate = ""; public static void updateHabitDay(HabitDay habitDay) { if (context == null) return; DatabaseHelper db = new DatabaseHelper(context); db.updateHabitDay(habitDay); } @RequiresApi(api = Build.VERSION_CODES.O) public static void updateHabitList() { if (context == null) return; DatabaseHelper db = new DatabaseHelper(context); db.createHabitDayItems(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); pickedHabitDate = sdf.format(new Date(calendar.getDate())); List<HabitDay> habitDays = db.getAllHabitOfDay(pickedHabitDate); DummyContent.DummyHabitDay_ITEMS.clear(); DummyContent.DummyHabitDay_ITEM_MAP.clear(); for (HabitDay habitDay : habitDays) { DummyContent.DummyHabitDay_addItem(DummyContent.DummyHabitDay_createDummyItem(habitDay, db.getHabit(habitDay.getHabitId()))); } try { FragmentTransaction ft = childFragmentManager.beginTransaction(); ft.replace(R.id.habit_list_fragment, new CheckListFragment()); ft.commit(); } catch (Exception ex) { Log.i("Exception", ex.getMessage()); } } }
true
6c12f5da6450abb41db8226dfce002ce33e7fcea
Java
445672428/cvf
/cvf/src/main/java/com/hibernate/pojo/Gysypml.java
UTF-8
1,355
2.09375
2
[]
no_license
package com.hibernate.pojo; /** * Gysypml entity. @author MyEclipse Persistence Tools */ public class Gysypml implements java.io.Serializable { // Fields private String id; private Ypxx ypxx; private String usergysid; private String vchar1; private String vchar2; // Constructors /** default constructor */ public Gysypml() { } /** minimal constructor */ public Gysypml(String id, Ypxx ypxx, String usergysid) { this.id = id; this.ypxx = ypxx; this.usergysid = usergysid; } /** full constructor */ public Gysypml(String id, Ypxx ypxx, String usergysid, String vchar1, String vchar2) { this.id = id; this.ypxx = ypxx; this.usergysid = usergysid; this.vchar1 = vchar1; this.vchar2 = vchar2; } // Property accessors public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Ypxx getYpxx() { return this.ypxx; } public void setYpxx(Ypxx ypxx) { this.ypxx = ypxx; } public String getUsergysid() { return this.usergysid; } public void setUsergysid(String usergysid) { this.usergysid = usergysid; } public String getVchar1() { return this.vchar1; } public void setVchar1(String vchar1) { this.vchar1 = vchar1; } public String getVchar2() { return this.vchar2; } public void setVchar2(String vchar2) { this.vchar2 = vchar2; } }
true
d114a69eb168e33b92b88c5353a37786f5d2cc30
Java
robotman2412/fabric_litemod
/src/main/java/com/robotman2412/litemod/block/itemduct/util/PathBit.java
UTF-8
584
2.234375
2
[ "CC0-1.0" ]
permissive
package com.robotman2412.litemod.block.itemduct.util; import net.minecraft.block.entity.BlockEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; public class PathBit { public BlockPos pos; public BlockEntity blockEntity; public Direction directionFromPrevious; public PathBit previous; public int cost; public PathBit(BlockPos pos, BlockEntity blockEntity, Direction fromPrevious, PathBit previous) { this.pos = pos; this.blockEntity = blockEntity; this.directionFromPrevious = fromPrevious; this.previous = previous; } }
true
796009c7ae8f9bad7112624a1bb45541faf089e8
Java
bellmit/self
/yimao/yimao-system/src/main/java/com/yimao/cloud/system/controller/waterdevice/SimCardAccountController.java
UTF-8
3,243
2.203125
2
[]
no_license
package com.yimao.cloud.system.controller.waterdevice; import com.yimao.cloud.base.exception.BadRequestException; import com.yimao.cloud.pojo.dto.water.SimCardAccountDTO; import com.yimao.cloud.pojo.vo.PageVO; import com.yimao.cloud.system.feign.WaterFeign; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; /** * 描述:SIM运营商分配的权限账号 * * @Author Zhang Bo * @Date 2019/4/25 */ @RestController @Api(tags = "SimCardAccountController") public class SimCardAccountController { @Resource private WaterFeign waterFeign; /** * 创建SIM运营商分配的权限账号 * * @param dto SIM运营商分配的权限账号 */ @PostMapping(value = "/simcard/account") @ApiOperation(value = "创建SIM运营商分配的权限账号") @ApiImplicitParam(name = "dto", value = "SIM运营商分配的权限账号", required = true, dataType = "SimCardAccountDTO", paramType = "body") public void save(@RequestBody SimCardAccountDTO dto) { waterFeign.saveSimCardAccount(dto); } /** * 修改SIM运营商分配的权限账号 * * @param dto SIM运营商分配的权限账号 */ @PutMapping(value = "/simcard/account") @ApiOperation(value = "修改SIM运营商分配的权限账号") @ApiImplicitParam(name = "dto", value = "SIM运营商分配的权限账号", required = true, dataType = "SimCardAccountDTO", paramType = "body") public void update(@RequestBody SimCardAccountDTO dto) { if (dto.getId() == null) { throw new BadRequestException("修改对象不存在。"); } else { waterFeign.updateSimCardAccount(dto); } } /** * 查询SIM运营商分配的权限账号(分页) * * @param pageNum 第几页 * @param pageSize 每页大小 */ @GetMapping(value = "/simcard/account/{pageNum}/{pageSize}") @ApiOperation(value = "查询SIM运营商分配的权限账号(分页)") @ApiImplicitParams({ @ApiImplicitParam(name = "pageNum", value = "第几页", required = true, dataType = "Long", paramType = "path"), @ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, dataType = "Long", paramType = "path") }) public PageVO<SimCardAccountDTO> page(@PathVariable Integer pageNum, @PathVariable Integer pageSize) { return waterFeign.pageSimCardAccount(pageNum, pageSize); } /** * 获取所有SIM运营商 */ @GetMapping(value = "/simcard/account/all") @ApiOperation(value = "获取所有SIM运营商") public List<SimCardAccountDTO> list() { return waterFeign.listSimCardAccount(); } }
true
973c49e193487a75d5601b62b56b55b702563156
Java
Midalas/leetCode
/leetCode697.java
UTF-8
1,075
3.359375
3
[]
no_license
package leetCode; import java.util.ArrayList; import java.util.List; public class leetCode697 { public static void main(String[] args) throws Exception { int[] nums = { 1, 2, 2, 3, 1, 4, 2 }; int x = findShortestSubArray(nums); System.out.println(); } //runtime 45ms public static int findShortestSubArray(int[] nums) { int[] count = new int[50000]; int start = -1; int end = nums.length; int max = 0; List<Integer> maxList = new ArrayList<Integer>(); for (int i = 0; i < nums.length; i++) count[nums[i]] += 1; for (int i = 0; i < count.length; i++) if (count[i] == max) { maxList.add(i); } else if (count[i] > max) { maxList.clear(); maxList.add(i); max = count[i]; } int res = Integer.MAX_VALUE; for (Integer num : maxList) { for (int i = 0; i < nums.length; i++) if (nums[i] == num) { start = i; break; } for (int i = nums.length - 1; i >= 0; i--) if (nums[i] == num) { end = i; break; } res = end - start + 1 < res ? end - start + 1 : res; } return res; } }
true
47d3f3de11ec11ef348b17252fc83aee7bb554a6
Java
richard-nguyen22/tendering-system-object-oriented-java
/tendering-system-text-data/src/GUI/OfficerGUI.java
UTF-8
24,990
2.15625
2
[ "Apache-2.0" ]
permissive
package GUI; import classes.Login; import classes.Officer; import classes.Staff; import classes.Tender; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; public class OfficerGUI extends javax.swing.JFrame { Staff officer = main.staff; /** * Creates new form OfficerGUI */ public OfficerGUI() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); add_button = new javax.swing.JButton(); delete_button = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tender_products_table = new javax.swing.JTable(); jLabel2 = new javax.swing.JLabel(); tender_id_field = new javax.swing.JTextField(); search_tender_button = new javax.swing.JButton(); logout_button = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); products_list_table = new javax.swing.JTable(); jLabel3 = new javax.swing.JLabel(); keyword_field = new javax.swing.JTextField(); search_products_button = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); product_id_field = new javax.swing.JTextField(); quantity_field = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); tender_products_label1 = new javax.swing.JLabel(); tender_id_label = new javax.swing.JLabel(); name_label = new javax.swing.JLabel(); price_label = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("OFFICER MAIN MENU"); add_button.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N add_button.setText("Add product"); add_button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { add_buttonActionPerformed(evt); } }); delete_button.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N delete_button.setText("Delete"); delete_button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { delete_buttonActionPerformed(evt); } }); tender_products_table.setFont(new java.awt.Font("Times New Roman", 0, 16)); // NOI18N tender_products_table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ID", "Brand", "Model", "Type", "Discount Price (RM)", "Quantity" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(tender_products_table); jLabel2.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N jLabel2.setText("Tender ID:"); tender_id_field.setFont(new java.awt.Font("Dialog", 0, 16)); // NOI18N search_tender_button.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N search_tender_button.setText("Search Tender"); search_tender_button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { search_tender_buttonActionPerformed(evt); } }); logout_button.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N logout_button.setText("Logout"); logout_button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { logout_buttonActionPerformed(evt); } }); products_list_table.setFont(new java.awt.Font("Times New Roman", 0, 16)); // NOI18N products_list_table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ID", "Brand", "Model", "Type", "Original Price (RM)" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane2.setViewportView(products_list_table); jLabel3.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N jLabel3.setText("Keyword:"); keyword_field.setFont(new java.awt.Font("Dialog", 0, 16)); // NOI18N search_products_button.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N search_products_button.setText("Search Products"); search_products_button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { search_products_buttonActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N jLabel4.setText("Product ID:"); product_id_field.setFont(new java.awt.Font("Dialog", 0, 16)); // NOI18N quantity_field.setFont(new java.awt.Font("Dialog", 0, 16)); // NOI18N jLabel5.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N jLabel5.setText("Quantity:"); tender_products_label1.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N tender_products_label1.setText("Products in products list"); tender_id_label.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N tender_id_label.setText("Tender ID: "); name_label.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N name_label.setText("Name:"); price_label.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N price_label.setText("Total products price: RM"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(delete_button, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(logout_button, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(1, 1, 1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(tender_id_field, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(search_tender_button, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(tender_id_label, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(name_label, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(price_label, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 624, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(product_id_field, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(quantity_field, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(add_button, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(keyword_field, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(search_products_button)) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 528, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tender_products_label1, javax.swing.GroupLayout.PREFERRED_SIZE, 410, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(21, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tender_id_field, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(search_tender_button, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(keyword_field, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(search_products_button, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(name_label, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tender_products_label1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tender_id_label, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(price_label, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 455, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 455, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(delete_button, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(logout_button, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(product_id_field, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(quantity_field, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(add_button, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(19, 19, 19)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void add_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_buttonActionPerformed // TODO add your handling code here: String tender_id = tender_id_label.getText().split(": ")[1], product_id = product_id_field.getText(); String quantiry_str; if (tender_id.equals(" ")) { JOptionPane.showMessageDialog(null, "Search tendering request to add products in the left table first"); return; } else if (products_list_table.getRowCount() == 0) { JOptionPane.showMessageDialog(null, "No products in the right table. Search product to check product ID"); return; } if (product_id.equals("")) { JOptionPane.showMessageDialog(null, "No product ID to add. Enter product ID that is in the right table"); return; } else { try { if (Integer.parseInt(product_id) < 1) { JOptionPane.showMessageDialog(null, "Invalid product ID"); return; } } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid product ID"); return; } } DefaultTableModel model = (DefaultTableModel) products_list_table.getModel(); int row_counts = model.getRowCount(); boolean found_product = false; for (int i = 0; i <row_counts; i++) { if (model.getValueAt(i, 0).equals(product_id)) { found_product = true; } } if (!found_product) { JOptionPane.showMessageDialog(null, "Product ID: " + product_id + " is not in the right table"); return; } quantiry_str = quantity_field.getText(); if (quantiry_str.equals("")) { JOptionPane.showMessageDialog(null, "Enter the quantity of the product you want to add into tendering request"); return; } else { try { if (Integer.parseInt(quantiry_str) < 1) { JOptionPane.showMessageDialog(null, "Invalid quantity"); return; } } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid quantity"); return; } } int dialog_button = JOptionPane.YES_NO_OPTION; int dialog_result = JOptionPane.showConfirmDialog(null, "Do you want to add "+quantiry_str+" product ID: "+product_id+" in tender ID: "+tender_id,"Add confirmation",dialog_button); if (dialog_result == 0) { DefaultTableModel model2 = (DefaultTableModel) tender_products_table.getModel(); String[] result = ((Officer) officer).addProductToTender(tender_id, product_id, Integer.parseInt(quantiry_str)); String[] pieces = result[0].split("!"); price_label.setText("Total products price: RM"+result[1]); row_counts = model2.getRowCount(); found_product = false; for (int i = 0; i <row_counts; i++) { if (model2.getValueAt(i, 0).equals(product_id)) { model2.setValueAt(pieces[7], i, 5); found_product = true; } } if (found_product == false) { String[] new_row = {pieces[0], pieces[1], pieces[2], pieces[3], pieces[6], pieces[7]}; model2.insertRow(row_counts, new_row); } JOptionPane.showMessageDialog(null, quantiry_str+" product ID: "+product_id+" is added in tender ID: "+tender_id); } else { JOptionPane.showMessageDialog(null, quantiry_str+" product ID: "+product_id+" is not added in tender ID: "+tender_id); } }//GEN-LAST:event_add_buttonActionPerformed private void delete_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delete_buttonActionPerformed // TODO add your handling code here: DefaultTableModel model = (DefaultTableModel) tender_products_table.getModel(); String tender_id = tender_id_label.getText().split(": ")[1]; if (tender_id.equals(" ")) { JOptionPane.showMessageDialog(null, "No product to delete. Search tendering request first"); return; } if (tender_products_table.getSelectedRow() == -1) { if (tender_products_table.getRowCount() == 0) { JOptionPane.showMessageDialog(null, "There is no product in tender id: "+tender_id); } else { JOptionPane.showMessageDialog(null, "Select a product in the table to delete"); } } else { int dialog_button = JOptionPane.YES_NO_OPTION; String product_id = tender_products_table.getValueAt(tender_products_table.getSelectedRow(),0)+""; int dialog_result = JOptionPane.showConfirmDialog(null, "Do you want to delete product id: "+product_id+" from tender id: "+tender_id,"Delete confirmation",dialog_button); if (dialog_result == 0) { model.removeRow(tender_products_table.getSelectedRow()); String new_price = ""+((Officer) officer).deleteProduct(tender_id, product_id); price_label.setText("Total products price: RM"+new_price); } } }//GEN-LAST:event_delete_buttonActionPerformed private void search_tender_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_search_tender_buttonActionPerformed // TODO add your handling code here: String id = tender_id_field.getText(); if (id.equals("")) { JOptionPane.showMessageDialog(null, "Enter tender ID to search"); return; } else { try { Integer.parseInt(id); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "ID is not number. Enter ID as number"); tender_id_label.setText("Tender ID: "); name_label.setText("Name: "); price_label.setText("Total products price: RM"); return; } if (Integer.parseInt(id) <= 0) { JOptionPane.showMessageDialog(null, "Invalid ID"); tender_id_label.setText("Tender ID: "); name_label.setText("Name: "); price_label.setText("Total products price: RM"); return; } } Tender found_tender = ((Officer) officer).searchTender(id); if (found_tender == null) { JOptionPane.showMessageDialog(null, "Cannot find tender ID: " + id); showTenderProducts(new ArrayList<>()); tender_id_label.setText("Tender ID: "); name_label.setText("Name: "); price_label.setText("Total products price: RM"); return; } List<String> products = ((Officer) officer).getTenderProducts(found_tender.getID() +""); if (products.isEmpty()) { JOptionPane.showMessageDialog(null, "There is no product in tender ID: " + id); } tender_id_label.setText("Tender ID: " + id); name_label.setText("Name: " + found_tender.getName()); price_label.setText("Total products price: RM" + found_tender.getTenderPrice()); showTenderProducts(products); }//GEN-LAST:event_search_tender_buttonActionPerformed private void showTenderProducts(List<String> tender_products) { DefaultTableModel model = (DefaultTableModel) tender_products_table.getModel(); String[] cols = {"ID", "Brand", "Model", "Type", "Discount Price (RM)", "Quantity"}; if (tender_products.isEmpty()) { String[][] rows = new String[0][7]; model.setDataVector(rows, cols); } else { String[][] rows = new String[tender_products.size()][7]; int row_count = 0; for (String tender: tender_products) { String[] pieces = tender.split("!"); rows[row_count] = new String[] {pieces[0], pieces[1], pieces[2], pieces[3], pieces[6], pieces[7]}; row_count++; } model.setDataVector(rows, cols); } } private void logout_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logout_buttonActionPerformed // TODO add your handling code here: Login.recordLog(main.staff.getUserName(), "out"); this.dispose(); LoginGUI new_GUI = new LoginGUI(); new_GUI.setLocationRelativeTo(null); new_GUI.setVisible(true); }//GEN-LAST:event_logout_buttonActionPerformed private void search_products_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_search_products_buttonActionPerformed // TODO add your handling code here: if (keyword_field.getText().equals("")) { JOptionPane.showMessageDialog(null, "No search keyword. Enter product brand, model or type to search"); } else { showProducts(keyword_field.getText()); } }//GEN-LAST:event_search_products_buttonActionPerformed private void showProducts(String keyword) { List<String> found_products = ((Officer) officer).searchProduct(keyword); DefaultTableModel model = (DefaultTableModel) products_list_table.getModel(); String[] cols = {"ID", "Brand", "Model", "Type", "Price (RM)"}; String[][] rows = new String[0][7]; if (found_products.isEmpty()) { JOptionPane.showMessageDialog(null, "Cannot find product"); } else { int row_count = 0; rows = new String[found_products.size()][5]; for (String product: found_products) { rows[row_count] = product.split("!"); row_count++; } } model.setDataVector(rows, cols); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton add_button; private javax.swing.JButton delete_button; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextField keyword_field; private javax.swing.JButton logout_button; private javax.swing.JLabel name_label; private javax.swing.JLabel price_label; private javax.swing.JTextField product_id_field; private javax.swing.JTable products_list_table; private javax.swing.JTextField quantity_field; private javax.swing.JButton search_products_button; private javax.swing.JButton search_tender_button; private javax.swing.JTextField tender_id_field; private javax.swing.JLabel tender_id_label; private javax.swing.JLabel tender_products_label1; private javax.swing.JTable tender_products_table; // End of variables declaration//GEN-END:variables }
true
5882d8eed7a953f0514f4a4e2d378562dcd3eaff
Java
RashmiKute/Automation_Repository-6th-jan-19-
/BasicCoreJava/src/oops/abstraction/Citi.java
UTF-8
376
2.515625
3
[]
no_license
package oops.abstraction; public class Citi implements RBI { public void savingsAccount() { System.out.println("Citi Saving account"); } public void currentAccount() { System.out.println("Citi Current account"); } public void creditCard() { System.out.println("Citi Credit card"); } public void debitCard() { System.out.println("Citi Debit card"); } }
true
42309ca3c36e5e5ba9c5919669d5e0706d806a19
Java
OlegChapurin/innopolis
/src/main/java/part01/lesson06/task02/Text.java
UTF-8
6,062
3.640625
4
[]
no_license
package part01.lesson06.task02; import java.util.ArrayList; import java.util.Random; /** * Creates a file and fills in a random way * * @author Oleg_Chapurin */ public class Text implements TextGenerator { /** * Letter string */ private String listLetters = "abcdefghijklmnopqrstuvwxyz"; /** * Character list */ private String punctuation = ".!?"; /** * Array word */ private ArrayList<String> arrayWords = new ArrayList<>(); /** * Random number generator */ private Random random = new Random(); /** * Text for file */ private StringBuffer text = new StringBuffer(); /** * Word for array randomly generated */ private StringBuffer word = new StringBuffer(); /** * Size file */ private int size; /** * probability % */ private double probability; /** * Array select latch */ private boolean ofArray = true; /** * Checks text size in characters */ private boolean startGenerate() { return size > text.length() ? true : false; } /** * Add char */ private boolean addChar(char symbol) { if (size > text.length()) { text.append(symbol); return true; } return false; } /** * Deletes the character at the end */ private boolean deleteLastChar() { if (text.length() > 0) { text.deleteCharAt(text.length() - 1); return true; } return false; } /** * Generate a word to populate an array */ private String generateWord(int maxLengthWord) { word.delete(0, word.length()); int randomLength = random.nextInt(maxLengthWord - 1) + 1; for (int i = 0; i < randomLength; i++) { word.append(listLetters.charAt( random.nextInt(listLetters.length()))); } return word.substring(0); } /** * Generate word */ private void generateWord(int maxLengthWord, boolean newStart) { int index; char symbol; int randomLength = random.nextInt(maxLengthWord - 1) + 1; for (int i = 0; i < randomLength; i++) { index = random.nextInt(listLetters.length()); symbol = listLetters.charAt(index); /** Form a capital letter */ if (newStart) { symbol = Character.toUpperCase(symbol); newStart = false; } if (!addChar(symbol)) { /** Stop the cycle when reaching the specified size */ break; } } } /** * Fill the array */ private void getWordOfArray(int maxLengthWord) { double randomLength = random.nextDouble(); if ((randomLength <= probability) & ((size - text.length()) >= maxLengthWord)) { int index = random.nextInt(arrayWords.size() - 1); text.append(arrayWords.get(index).toCharArray()); ofArray = false; } else { generateWord(maxLengthWord, false); } } /** * Generate offer */ private void generateOffer(int maxLengthWord, int randomLengthOffer) { int randomLength = random.nextInt(randomLengthOffer - 1) + 1; int end = randomLength - 1; for (int i = 0; i < randomLength; i++) { if ((i != 0) & ofArray & (arrayWords.size() > 0)) { getWordOfArray(maxLengthWord); } else { generateWord(maxLengthWord, i == 0 ? true : false); } if (startGenerate()) { if (i < end) { if (random.nextInt(5) == 1) { if (!addChar(",".charAt(0))) { break; } } if (!addChar(" ".charAt(0))) { break; } } } else { break; } } if (addChar(punctuation.charAt(random.nextInt(2) + 1))) { addChar(" ".charAt(0)); } ofArray = true; } /** * Generate paragraph */ private void generateParagraph(int maxLengthWord, int randomLengthOffer, int randomLengthParagraph) { int randomLength = random.nextInt(randomLengthParagraph - 1) + 1; for (int i = 0; i < randomLength; i++) { if (startGenerate()) { generateOffer(maxLengthWord, randomLengthOffer); } else { break; } } addChar("\n".charAt(0)); addChar("\r".charAt(0)); } /** * Fills an array with randomly generated words **/ private void fillArrayWords(int maxSize, int maxLengthWord) { int size = random.nextInt(maxSize); for (int i = 0; i < size; i++) { arrayWords.add(generateWord(maxLengthWord)); } } /*** Get formed text */ @Override public String getText(int maxLengthWord, int randomLengthOffer, int randomLengthParagraph) { while (startGenerate()) { generateParagraph(maxLengthWord, randomLengthOffer, randomLengthParagraph); } deleteLastChar(); addChar(punctuation.charAt(random.nextInt(2) + 1)); return text.substring(0); } /** * Fills an array with data from an input array */ @Override public void fillArrayWords(ArrayList<String> arrayList, int maxLengthWord) { if (arrayList.size() > 1) { arrayWords.addAll(arrayList); } else { fillArrayWords(1000, maxLengthWord); } } /** * Sets the size of the text. */ @Override public void setSizeText(int size) { this.size = size; } /** * Sets probability. */ @Override public void setProbability(int prob) { this.probability = 1.0 / prob; } }
true
38a506274f4f4615ea16a55efcdb78d3b50c8848
Java
ddumesle/MyMovies
/app/src/main/java/com/example/mymovies/activities/MainActivity.java
UTF-8
6,003
2.40625
2
[]
no_license
package com.example.mymovies.activities; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.GridView; import com.example.mymovies.R; import com.example.mymovies.models.Favorites; import com.example.mymovies.models.Movie; import com.example.mymovies.models.MovieGridAdapter; import com.google.android.material.snackbar.Snackbar; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.List; /** * A class the manages the overall flow of the * entire application. */ public class MainActivity extends AppCompatActivity { private Favorites favorites; private FirebaseAuth mAuth = FirebaseAuth.getInstance(); private FirebaseUser currentUser = mAuth.getCurrentUser(); private static final String KEY_YEAR = "Year"; private static final String KEY_TITLE = "Title"; private static final String KEY_POSTER = "Poster"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initToolbar(); checkCredentials(); } private void initToolbar() { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { Intent intent; switch (item.getItemId()) { case R.id.search: intent = new Intent(this, SearchActivity.class); startActivity(intent); return true; case R.id.logout: mAuth.signOut(); intent = new Intent(this, SplashActivity.class); startActivity(intent); return true; default: super.onOptionsItemSelected(item); } return true; } /** * A function that checks whether a user is currently * authenticated with FirebaseAuth. */ private void checkCredentials() { if (currentUser != null) { favorites = new Favorites(); updateUI(); } else { Intent intent = new Intent(this, SplashActivity.class); startActivity(intent); } } /** * A function that updates the view with information * that is saved from the user's favorites in Firebase. */ private void updateUI() { favorites.getFavorites(new Favorites.FavoriteCallback() { @Override public void onFailure(String reason) { Snackbar.make(findViewById(R.id.parent), reason, Snackbar.LENGTH_SHORT).show(); } @Override public void onComplete(QuerySnapshot snapshot) { List<Movie> movies = new ArrayList<>(); for (QueryDocumentSnapshot documentSnapshot : snapshot) { Movie movie = new Movie(documentSnapshot.getId()); movie.setYear(documentSnapshot.getString(KEY_YEAR)); movie.setTitle(documentSnapshot.getString(KEY_TITLE)); movie.setPoster(documentSnapshot.getString(KEY_POSTER)); movies.add(movie); } initComponent(movies); } @Override public void onSuccess() {} }); } /** * A function that initializes the movie adapter to bind * the view and the movie model. * @param movies */ private void initComponent(List movies) { MovieGridAdapter adapter = new MovieGridAdapter(movies); GridView gridView = findViewById(R.id.gridview); gridView.setAdapter(adapter); // Set a listener for each movie that is returned from the DB adapter.setOnItemClickListener(new MovieGridAdapter.OnItemClickListener() { @Override public void onItemClick(View view, final Movie movie, String action) { // If user clicks the trash icon, delete movie from DB if (action.equals("delete")) { favorites.deleteFavorite(movie.getImdbID(), new Favorites.FavoriteCallback() { @Override public void onSuccess() { Snackbar.make(findViewById(R.id.parent), "Deleted \"" + movie.getTitle() + "\" from favorites.", Snackbar.LENGTH_SHORT).show(); updateUI(); } @Override public void onFailure(String reason) { Snackbar.make(findViewById(R.id.parent), reason, Snackbar.LENGTH_SHORT).show(); } @Override public void onComplete(QuerySnapshot snapshot) {} }); } // If user clicks the movie poster, start a new activity to show details if (action.equals("detail")) { Intent intent = new Intent(getApplicationContext(), MovieDetailActivity.class); intent.putExtra("ID", movie.getImdbID()); startActivity(intent); } } }); } }
true
917b62fc75918785938bdec65c73d8676ea47e67
Java
C71-S3-Tim/C71-S3-Tim-Project-demo
/C71-S3-Tltbm-take-out/src/main/java/com/yc/spirngboot/takeout/admin/web/admIndexAction.java
UTF-8
4,073
1.914063
2
[]
no_license
package com.yc.spirngboot.takeout.admin.web; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.yc.spirngboot.takeout.admin.biz.AdminBiz; import com.yc.spirngboot.takeout.bean.Admin; import com.yc.spirngboot.takeout.bean.AdminExample; import com.yc.spirngboot.takeout.bean.Gift; import com.yc.spirngboot.takeout.bean.GiftExample; import com.yc.spirngboot.takeout.bean.Giftorder; import com.yc.spirngboot.takeout.bean.GiftorderExample; import com.yc.spirngboot.takeout.bean.Seller; import com.yc.spirngboot.takeout.bean.SellerExample; import com.yc.spirngboot.takeout.biz.BizExcption; import com.yc.spirngboot.takeout.dao.AdminMapper; import com.yc.spirngboot.takeout.dao.GiftMapper; import com.yc.spirngboot.takeout.dao.GiftorderMapper; import com.yc.spirngboot.takeout.dao.SellerMapper; import com.yc.spirngboot.takeout.vo.Result; @Controller public class admIndexAction { @GetMapping(path= {"admin/login","admin/login.do"}) public String index() { return "admin/login"; } @Resource private AdminMapper admm; @Resource private AdminBiz admBiz; @PostMapping("admin/admlogin") @ResponseBody public Result admlogin(String admusername, String admpass, Model m, HttpSession httpS) throws BizExcption { System.out.println("aaaaaaaaa=" + admusername + "bnbbb=" + admpass); Result res=new Result(); AdminExample adminExample = new AdminExample(); adminExample.createCriteria().andNameEqualTo(admusername); List<Admin> admins = admm.selectByExample(adminExample); Admin pwd = admins.get(0); if(admusername.trim().isEmpty() == true || admpass.trim().isEmpty() == true) { res.setData(admins); res.setMsg("用户名或密码不能为空"); res.setCode(1); }else if(admins.size()==0) { res.setMsg("用户不存在"); res.setCode(2); }else if(pwd.getPwd().equals(admpass)==false){ res.setMsg("密码错误!"); res.setCode(3); }else { res.setData(admins); res.setCode(0); httpS.setAttribute("loginedAdm", admins.get(0)); } return res; } @Resource private SellerMapper admsm; @Resource private GiftorderMapper admgom; @Resource private AdminMapper adm; @Resource private GiftMapper admgm; @GetMapping("admin/index") public String index(Model m, HttpSession httpS) { Admin adminss = (Admin) httpS.getAttribute("loginedAdm"); Integer newzt = 1; Integer toage = 0; //正在运营店铺 SellerExample sellerExample = new SellerExample(); sellerExample.createCriteria().andQualifiedEqualTo(toage); List<Seller> sellerlist = admsm.selectByExample(sellerExample); m.addAttribute("sellernum", sellerlist.size()); //待审核店铺 SellerExample se = new SellerExample(); se.createCriteria().andQualifiedEqualTo(newzt); List<Seller> sellertoage = admsm.selectByExample(se); m.addAttribute("toageseller", sellertoage.size()); //礼品订单 List<Giftorder> giftorders = admgom.selectByExample(null); m.addAttribute("giftorders", giftorders.size()); //礼品已兑完 GiftExample giftExample = new GiftExample(); giftExample.createCriteria().andNumberEqualTo(toage); List<Gift> togiftnum = admgm.selectByExample(giftExample); m.addAttribute("nogiftnums", togiftnum.size()); //礼品 List<Gift> giftnum = admgm.selectByExample(null); m.addAttribute("giftnums", giftnum.size()); //审核比例 List<Seller> allseller = admsm.selectByExample(null); Float all = (float) allseller.size(); Float agre = (float) sellerlist.size(); Float bl = (agre/all)*100; m.addAttribute("bili", bl.byteValue()); return "admin/index"; } }
true
f2c7a40b784607d71dc96559c23ac141f617b6eb
Java
1qase4/zhike_koubei
/src/main/java/com/czc/bi/util/ExportData.java
UTF-8
6,328
2.59375
3
[]
no_license
package com.czc.bi.util; import com.czc.bi.pojo.excel.DataRow; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors; import java.lang.reflect.Method; /** * Copyright © 武汉辰智商务信息咨询有限公司. All rights reserved. * * @author : zchong * @Desc : 数据导出功能 * @date : 2016/12/22. * @version: V1.0 */ public class ExportData { private List<Method> method; // 设置排除字段 private List<String> exclude; public List<String> getExclude() { return exclude; } public static byte[] writeExcel(List<DataRow> rows) { // 创建Excel的工作书册 Workbook,对应到一个excel文档 HSSFWorkbook wb = new HSSFWorkbook(); // 创建Excel的工作sheet,对应到一个excel文档的tab HSSFSheet sheet = wb.createSheet("sheet1"); // 设置正文格式 HSSFFont font = wb.createFont(); font.setFontName("Verdana"); font.setFontHeight((short) 200); HSSFCellStyle bodyStyle = wb.createCellStyle(); bodyStyle.setFont(font); bodyStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框 bodyStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框 bodyStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框 bodyStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框 // 设置标题格式 font = wb.createFont(); font.setFontName("微软雅黑"); font.setFontHeight((short) 220); HSSFCellStyle titleStyle = wb.createCellStyle(); titleStyle.setFont(font); titleStyle.setFillBackgroundColor(HSSFColor.RED.index); titleStyle.setFillForegroundColor(HSSFColor.TURQUOISE.index);// 设置填充颜色 titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 设置填充方式 titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框 titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框 titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框 titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框 HSSFRow row = null; HSSFCell cell = null; HSSFCellStyle style = null; // 循环提取每一行 for (int i = 0; i < rows.size(); i++) { row = sheet.createRow(i); DataRow dr = rows.get(i); if (dr == null) { continue; } List<String> record = dr.getRecord(); if (record == null) { continue; } // 设置样式 style = dr.getTitle() ? titleStyle : bodyStyle; // 循环提取每一列 for (int n = 0; n < record.size(); n++) { cell = row.createCell(n); cell.setCellStyle(style); cell.setCellValue(record.get(n)); } } // 自适应列宽 如果存在合并单元格 sheet.autoSizeColumn(1, true); sheet.autoSizeColumn((short)0); //调整第一列宽度 sheet.autoSizeColumn((short)1); //调整第二列宽度 sheet.autoSizeColumn((short)2); //调整第三列宽度 sheet.autoSizeColumn((short)3); //调整第四列宽度 // 转换为byte[] 输出 ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] bytes = null; /*try { wb.write(bos); bytes = bos.toByteArray(); bos.close(); wb.close(); } catch (IOException e) { e.printStackTrace(); }*/ return bytes; } // 添加排除字段 public ExportData addExclude(String exclude) { if (this.exclude == null) { this.exclude = new ArrayList<>(); } this.exclude.add(exclude); return this; } public String listPojo2String(List pojos, Class cls) throws Exception { //pojo.stream().mapping() //t.getClass() //PropertyDescriptor pd = new PropertyDescriptor(); getPojoField(cls); int totalLen = pojos.size(); String[] rows = new String[pojos.size()]; for (int m = 0; m < totalLen; m++) { int len = this.method.size(); String[] row = new String[len]; for (int i = 0; i < len; i++) { Object invoke = this.method.get(i).invoke(pojos.get(m)); row[i] = invoke == null ? "" : invoke.toString(); } rows[m] = String.join(",", row); } return String.join("\r\n", rows); } // 获取pojo字段名称和对应的get方法 private void getPojoField(Class clazz) throws Exception { List<String> files = new ArrayList<>(); //获得属性 Field[] fields = clazz.getDeclaredFields(); this.method = Arrays.stream(fields) .filter(a -> { return this.exclude == null ? true : !this.exclude.contains(a.getName()); }) .map(a -> { try { PropertyDescriptor pd = new PropertyDescriptor(a.getName(), clazz); return pd.getReadMethod();//获得get方法 } catch (IntrospectionException e) { e.printStackTrace(); } return null; }) .collect(Collectors.toList()); } // public static void main(String[] args) { // List<Simple> a = new ArrayList<>(); // Simple s = new Simple(); // s.setKey("11111"); // s.setValue("aaaaa"); // a.add(s); // // s = new Simple(); // s.setKey("22222"); // s.setValue("bbbbb"); // a.add(s); // // ExportData<Simple> ed = new ExportData<>(); // try { // String s1 = ed.listPojo2FileStream(a,Simple.class); // System.out.println(s1); // } catch (Exception e) { // e.printStackTrace(); // } // // // } }
true
2c14248312950d4e069096bf9a6d10d517548ff0
Java
wangxuelong/design-patterns
/proxy-pattern/src/main/java/com/wxl/design/patterns/proxy/v2/MyRemote.java
UTF-8
293
2.109375
2
[]
no_license
/** * */ package com.wxl.design.patterns.proxy.v2; import java.rmi.Remote; import java.rmi.RemoteException; /** * * @author Wang XueLong * @Date 2017年3月15日 下午9:03:54 */ public interface MyRemote extends Remote { public String sayHello() throws RemoteException; }
true
c4c319a155a5206fee8ac6bdd62cf165c503d1fb
Java
a11enyang/TrainBookingSystemAdministratorBackEnd
/src/main/java/com/bupt/trainbookingsystem/dao/LogRespository.java
UTF-8
306
1.71875
2
[]
no_license
package com.bupt.trainbookingsystem.dao; import com.bupt.trainbookingsystem.entity.LoginfoEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface LogRespository extends JpaRepository<LoginfoEntity,Integer> { }
true
1c32ab0c559bcd702e0584f0b4fdc4fd1e22c90c
Java
xformation/cms-backend
/src/main/java/com/synectiks/cms/graphql/types/BankAccounts/UpdateBankAccountsPayload.java
UTF-8
282
1.726563
2
[]
no_license
package com.synectiks.cms.graphql.types.BankAccounts; import com.synectiks.cms.domain.BankAccounts; public class UpdateBankAccountsPayload extends AbstractBankAccountsPayload { public UpdateBankAccountsPayload(BankAccounts bankAccounts) { super(bankAccounts); } }
true
f342a6538bebd2d3809b497854c29c30f72a7718
Java
pfirmstone/JGDMS
/qa/src/org/apache/river/test/spec/config/configurationexception/ToString_Test.java
UTF-8
4,018
2.46875
2
[ "Apache-2.0", "CC-BY-SA-3.0", "MIT", "BSD-3-Clause" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.river.test.spec.config.configurationexception; import java.util.logging.Level; import org.apache.river.qa.harness.QATestEnvironment; import org.apache.river.qa.harness.QAConfig; import org.apache.river.qa.harness.TestException; import org.apache.river.qa.harness.TestException; import org.apache.river.qa.harness.QAConfig; import org.apache.river.qa.harness.Test; import java.util.logging.Logger; import java.util.logging.Level; import net.jini.config.ConfigurationException; /** * <pre> * Purpose: * This test verifies the behavior of the toString method of * ConfigurationException class. * * Actions: * Test performs the following steps: * 1) construct a ConfigurationException object * passing options with the some string as a parameters * for message, and some exception for causing exception; * 2) assert the result includes the name of actual class; * 3) assert the result includes the string for message; * 4) assert the result includes result of calling toString * on the causing exception; * 5) construct an instance of a subclass of ConfigurationException * passing options with the some string as a parameters * for message; * 6) assert the result includes the name of actual class; * </pre> */ class ConfigurationExceptionSuccessor extends ConfigurationException { /** * Creates an instance with the specified detail message. * * @param s the detail message */ public ConfigurationExceptionSuccessor(String s) { super(s); } } public class ToString_Test extends QATestEnvironment implements Test { /** * This method performs all actions mentioned in class description. */ public void run() throws Exception { logger.log(Level.INFO, "======================================"); String messageString = "message string"; String exceptionString = "exception string"; Exception e = new Exception(exceptionString); ConfigurationException ce = new ConfigurationException(messageString, e); String result = ce.toString(); logger.log(Level.INFO, "result = " + result); assertion(result != null, "result should not be null"); String actualClassName = ce.getClass().getName(); logger.log(Level.INFO, "actual class name = " + actualClassName); assertion(result.indexOf(actualClassName) != -1, "result string doesn't includes the name of actual class"); assertion(result.indexOf(messageString) != -1, "result string doesn't includes the string for message"); assertion(result.indexOf(e.toString()) != -1, "result string doesn't includes the result of calling" + " toString on the causing exception"); ce = new ConfigurationExceptionSuccessor(messageString); result = ce.toString(); actualClassName = ce.getClass().getName(); logger.log(Level.INFO, "successor actual class name = " + actualClassName); assertion(result.indexOf(actualClassName) != -1, "result string doesn't includes the name of actual class"); } }
true
7f07f73163da48ede5d70a12a8e3fd4ef70596bd
Java
kingwarluo/testZK
/src/main/java/com/设计模式/biz/excel/handler/ExcelCheckDataHandler.java
UTF-8
651
2.40625
2
[]
no_license
package com.设计模式.biz.excel.handler; import com.设计模式.biz.excel.ExcelImportUtil; import lombok.Data; import org.apache.poi.ss.usermodel.Row; import java.util.List; import java.util.concurrent.Callable; /** * @description:校验数据格式是否正确 * * @author jianhua.luo * @date 2019/7/29 */ @Data public class ExcelCheckDataHandler implements Callable { /** * 导入对象 */ private ExcelImportUtil excelImport; /** * 校验的数据 */ private List<Row> rows; @Override public Object call() throws Exception { excelImport.checkData(rows); return this; } }
true
8f1295e5f704e2cbf549d9efea032aae422f0f79
Java
monika32/Intoduction
/Batting.java
UTF-8
394
3.25
3
[]
no_license
import java.util.Scanner; public class Batting { public static void main(String[] args) { Scanner s=new Scanner(System.in); System.out.println("enter no of runs ,innings played and no of times not out:"); int run=s.nextInt(); int innings=s.nextInt(); int notout=s.nextInt(); s.close(); double avg=(run/(innings-notout)); System.out.println("batting average is :"+avg); } }
true
c575e8f592f2baf2049d669be331d04cf1449849
Java
changer2014/hiloGitTest
/hilo-service/src/main/java/com/hilo/service/api/confiuration/security/JwtTokenProvider.java
UTF-8
3,576
2.515625
3
[]
no_license
package com.hilo.service.api.confiuration.security; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Component; import com.hilo.service.api.model.UserInfo; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; @Component public class JwtTokenProvider { /** * The constant ACCESS_TOKEN_VALID_TIME. */ private static final long ACCESS_TOKEN_VALID_TIME = 24 * 60 * 60 * 1000; /** * The constant REFRESH_TOKEN_VALID_TIME. */ private static final long REFRESH_TOKEN_VALID_TIME = 7 * 24 * 60 * 60 * 1000; /** * The constant SIGN_KEY. */ private static final String SIGN_KEY = "ScooterJWTSecret"; /** * The constant status of user have unfinished trip */ public static final String USER_STATUS_UNFINISHED_TRIP = "1"; /** * The constant status of user have unfinished order */ public static final String USER_STATUS_UNFINISHED_ORDER = "2"; /** * Gets token. * * @param user the user * @return the token */ public String getAccessToken(UserInfo user) { Map<String, Object> claims = new HashMap<>(4); claims.put("id", user.getId()); claims.put("phone", user.getPhone()); return Jwts.builder() .setClaims(claims) .setSubject(user.getPhone()) .setExpiration(new Date(System.currentTimeMillis() + ACCESS_TOKEN_VALID_TIME)) .signWith(SignatureAlgorithm.HS512, SIGN_KEY) .compact(); } /** * Gets refresh token. * * @param phone the phone * @return the refresh token */ public String getRefreshToken(String phone) { Map<String, Object> claims = new HashMap<>(4); return Jwts.builder() .setClaims(claims) .setSubject(phone) .setExpiration(new Date(System.currentTimeMillis() + REFRESH_TOKEN_VALID_TIME)) .signWith(SignatureAlgorithm.HS512, SIGN_KEY) .compact(); } /** * Gets user. * * @param token the token * @return the user * @throws InvalidJwtTokenException the invalid jwt token exception */ public UserInfo parseAccessToken(String token) throws InvalidJwtTokenException { try { Claims claims = Jwts.parser().setSigningKey(SIGN_KEY) .parseClaimsJws(token) .getBody(); String phone = claims.getSubject(); Date expiration = claims.getExpiration(); if (System.currentTimeMillis() > expiration.getTime() || phone == null) { throw new InvalidJwtTokenException("Invalid access token"); } UserInfo user = new UserInfo(); user.setPhone(phone); user.setId(claims.get("id").toString()); return user; } catch (Exception e) { throw new InvalidJwtTokenException("Invalid access token"); } } /** * Parse refresh token string. * * @param token the token * @return the string * @throws InvalidJwtTokenException the invalid jwt token exception */ public String parseRefreshToken(String token) throws InvalidJwtTokenException { try { Claims claims = Jwts.parser().setSigningKey(SIGN_KEY) .parseClaimsJws(token) .getBody(); Date expiration = claims.getExpiration(); if (System.currentTimeMillis() > expiration.getTime()) { throw new InvalidJwtTokenException("Invalid refresh token"); } return claims.getSubject(); } catch (Exception e) { throw new InvalidJwtTokenException("Invalid refresh token"); } } }
true
04264178e872375177eaa024507d9cfce61ae267
Java
elimlk/MotoRoutes
/app/src/main/java/com/motoroutes/model/AppRepository.java
UTF-8
8,791
2.09375
2
[]
no_license
package com.motoroutes.model; import android.app.Application; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.lifecycle.MutableLiveData; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.motoroutes.R; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; public class AppRepository { private static AppRepository appRepository =null; private Application application; private FirebaseAuth firebaseAuth; private MutableLiveData<FirebaseUser> userMutableLiveData; private MutableLiveData<Boolean> loggedOutMutableLiveData; private MutableLiveData<Route> routeMutableLiveData; private MutableLiveData<String> toolBarItemStateMutableLiveData; private MutableLiveData<Boolean> routeListUpdatedLiveData; public static ArrayList<MyLocation> listPointsArray= new ArrayList<>(); private ArrayList<Route> routesList; private AppRepository(Application application) { this.application = application; routesList = new ArrayList<Route>(); firebaseAuth = FirebaseAuth.getInstance(); userMutableLiveData = new MutableLiveData<FirebaseUser>(); loggedOutMutableLiveData = new MutableLiveData<>(); routeMutableLiveData = new MutableLiveData<Route>(); routeListUpdatedLiveData = new MutableLiveData<Boolean>(); routeListUpdatedLiveData.setValue(false); toolBarItemStateMutableLiveData = new MutableLiveData<>(); if(firebaseAuth.getCurrentUser() != null){ userMutableLiveData.postValue(firebaseAuth.getCurrentUser()); loggedOutMutableLiveData.postValue(false); } } public static AppRepository getInstance(Application application) { if (appRepository == null){ appRepository = new AppRepository(application); appRepository.updateRoutesFromDB(); return appRepository; } else return appRepository; } public void register(String email, String password, String fullName, String phone){ if (email.isEmpty() || password.isEmpty()) { Toast.makeText(application,application.getString(R.string.fill_all), Toast.LENGTH_SHORT).show(); return; } firebaseAuth.createUserWithEmailAndPassword(email,password) .addOnCompleteListener(application.getMainExecutor(), new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull @NotNull Task<AuthResult> task) { if (task.isSuccessful()){ if(loggedOutMutableLiveData.getValue() == null) { loggedOutMutableLiveData.postValue(false); } User user = new User(email,password,fullName,phone); FirebaseDatabase.getInstance().getReference("Users"). child(FirebaseAuth.getInstance().getCurrentUser().getUid()). setValue(user).addOnCompleteListener(new OnCompleteListener<Void>(){ @Override public void onComplete(@NonNull @NotNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(application,application.getString(R.string.Registartion_success), Toast.LENGTH_SHORT).show(); } else { //display a failure message } } }); userMutableLiveData.postValue(firebaseAuth.getCurrentUser()); } else { Toast.makeText(application,application.getString(R.string.register_failed) +task.getException() .getMessage(), Toast.LENGTH_SHORT).show(); } } }); } public void login(String email, String password){ if (email == "geust" && password == "geust") { loggedOutMutableLiveData.postValue(false); toolBarItemStateMutableLiveData.postValue(String.valueOf(R.id.map)); } else{ firebaseAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(application.getMainExecutor(), new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull @NotNull Task<AuthResult> task) { if (task.isSuccessful()){ loggedOutMutableLiveData.postValue(false); toolBarItemStateMutableLiveData.postValue(String.valueOf(R.id.map)); userMutableLiveData.postValue(firebaseAuth.getCurrentUser()); } else{ Toast.makeText(application,application.getString(R.string.login_failed) +task.getException() .getMessage(), Toast.LENGTH_SHORT).show(); userMutableLiveData.postValue(null); } } }); } } public void logout(){ firebaseAuth.signOut(); userMutableLiveData.setValue(null); loggedOutMutableLiveData.postValue(true); } public void addRoute(Route route){ if(route.isValid()){ FirebaseDatabase.getInstance().getReference("Routes"). child(route.getName()). setValue(route).addOnCompleteListener(new OnCompleteListener<Void>(){ @Override public void onComplete(@NonNull @NotNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(application,application.getString(R.string.routeAdded), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(application,application.getString(R.string.err_add_route), Toast.LENGTH_SHORT).show(); } } }); } } public ArrayList<Route> getRoutes(){ updateRoutesFromDB(); return routesList; } public void updateRoutesFromDB(){ DatabaseReference df = FirebaseDatabase.getInstance().getReference().child("Routes"); df.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() { @Override public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) { if (!task.isSuccessful()) { //Log.e("firebase", "Error getting data", task.getException()); } else { //Log.d("firebase", String.valueOf(task.getResult().getValue())); if (routesList != null) routesList.clear(); for (DataSnapshot child : task.getResult().getChildren()) { Route route = child.getValue(Route.class); routesList.add(route); } routeListUpdatedLiveData.setValue(true); } } }); } public ArrayList<MyLocation> getListPointsArray() { return listPointsArray; } public void setToolBarItemState(String ItemStateID){ toolBarItemStateMutableLiveData.setValue(ItemStateID); } public MutableLiveData<Boolean> getLoggedOutMutableLiveData() { return loggedOutMutableLiveData; } public MutableLiveData<FirebaseUser> getUserMutableLiveData() { return userMutableLiveData; } public MutableLiveData<Route> getRouteMutableLiveData() { return routeMutableLiveData; } public MutableLiveData<Boolean> getRouteListUpdatedLiveData(){ return routeListUpdatedLiveData; } public void setRouteListUpdatedLiveData(Boolean state){ routeListUpdatedLiveData.setValue(state); } public MutableLiveData<String> getToolBarItemStateMutableLiveData() { return toolBarItemStateMutableLiveData; } }
true
253a3dd54716759355254dbc311501e2f1e502b3
Java
fjh658/bindiff
/src_cfr/com/google/security/zynamics/zylib/gui/zygraph/proximity/MultiEdgeHider.java
UTF-8
2,230
2.15625
2
[]
no_license
/* * Decompiled with CFR 0_115. */ package com.google.security.zynamics.zylib.gui.zygraph.proximity; import com.google.security.zynamics.zylib.gui.zygraph.edges.IViewEdge; import com.google.security.zynamics.zylib.gui.zygraph.helpers.IEdgeCallback; import com.google.security.zynamics.zylib.gui.zygraph.helpers.INodeCallback; import com.google.security.zynamics.zylib.gui.zygraph.nodes.IGroupNode; import com.google.security.zynamics.zylib.gui.zygraph.nodes.IViewNode; import com.google.security.zynamics.zylib.gui.zygraph.proximity.MultiEdgeHider$1; import com.google.security.zynamics.zylib.gui.zygraph.proximity.MultiEdgeHider$2; import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.AbstractZyGraph; import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.nodes.ZyGraphNode; import java.util.HashSet; import java.util.Iterator; import java.util.List; public class MultiEdgeHider { public static void hideMultipleEdgesInternal(AbstractZyGraph abstractZyGraph) { abstractZyGraph.iterate(new MultiEdgeHider$1()); } public static void hideMultipleEdgesInternal(ZyGraphNode zyGraphNode) { Object object; Object object22; if (!zyGraphNode.isVisible()) return; if (zyGraphNode.getRawNode() instanceof IGroupNode) { return; } HashSet<Object> hashSet = new HashSet<Object>(); for (Object object22 : zyGraphNode.getRawNode().getOutgoingEdges()) { object = object22.getTarget(); if (hashSet.contains(object)) { object22.setVisible(false); continue; } hashSet.add(object); } HashSet hashSet2 = new HashSet(); object22 = zyGraphNode.getRawNode().getIncomingEdges().iterator(); while (object22.hasNext()) { object = (IViewEdge)object22.next(); if (hashSet2.contains(object.getSource())) { object.setVisible(false); continue; } hashSet2.add(object.getSource()); } } public static void unhideMultipleEdgesInternal(AbstractZyGraph abstractZyGraph) { abstractZyGraph.iterateEdges(new MultiEdgeHider$2()); } }
true
f79d9f7de7209ccb42c2e5e84bfc6bf2ecbfb9d9
Java
pazzainfer/DMD
/DbDesigner/src/com/leven/dmd/pro/nav/action/pack/TablePackageEditAction.java
UTF-8
2,199
2.0625
2
[]
no_license
package com.leven.dmd.pro.nav.action.pack; import java.util.List; import org.eclipse.jface.action.Action; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PlatformUI; import com.leven.dmd.gef.editor.SchemaDiagramEditor; import com.leven.dmd.gef.model.Schema; import com.leven.dmd.gef.model.TablePackage; import com.leven.dmd.gef.tmpfile.util.SchemaTemplateConstants; import com.leven.dmd.pro.Activator; import com.leven.dmd.pro.Messages; import com.leven.dmd.pro.nav.domain.INavigatorTreeNode; import com.leven.dmd.pro.nav.view.SchemaNavigatorView; public class TablePackageEditAction extends Action { private Object obj; public TablePackageEditAction(Object obj) { super(); this.setText(Messages.TablePackageEditAction_0); this.obj=obj; this.setImageDescriptor(Activator.getImageDescriptor(SchemaTemplateConstants.EDIT_IMAGE_PATH)); } @Override public void run() { Object root = ((INavigatorTreeNode)obj).getRoot(); if(root==null || !(root instanceof Schema)){ return; } Schema schema = (Schema)root; TablePackage tablePackage = (TablePackage)obj; List<TablePackage> packageList = schema.getTablePackages(); TablePackageEditWizard wizard = new TablePackageEditWizard(tablePackage,packageList); WizardDialog wd = new WizardDialog(Display.getCurrent().getActiveShell(),wizard); wd.create(); wd.open(); TablePackage tablePackage1; if((tablePackage1 = wizard.getTablePackage())!=null){ tablePackage.setDescription(tablePackage1.getDescription()); tablePackage.modifyName(tablePackage1.getName()); }else { return; } IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); if(page!=null){ try{ IViewPart registry = page.findView(SchemaNavigatorView.VIEW_ID); if(registry!=null && registry instanceof SchemaNavigatorView){ SchemaNavigatorView view = (SchemaNavigatorView)registry; view.getCommonViewer().refresh(obj); } ((SchemaDiagramEditor)page.getActiveEditor()).setDirty(true); }catch(Exception e){ e.printStackTrace(); } } } }
true
196b0bbf1d4893bd5b555d69101f1da6a248cadc
Java
p455w0rd/StingyOres
/src/main/java/p455w0rd/stingyores/init/ModBlocks.java
UTF-8
860
2.09375
2
[ "MIT" ]
permissive
package p455w0rd.stingyores.init; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.registry.GameRegistry; import p455w0rd.stingyores.items.ItemBlockStingyOre; import p455w0rd.stingyyores.blocks.BlockStingyOre; public class ModBlocks { public static void preInit() { } public static void init() { for (BlockStingyOre stingyOre : ModGlobals.ORES_LIST) { GameRegistry.register(stingyOre); GameRegistry.register(new ItemBlockStingyOre(stingyOre), new ResourceLocation(ModGlobals.MODID, "stingy_" + stingyOre.getName() + "_ore")); stingyOre.registerOreDict(); if (stingyOre.getBaseBlock() == Blocks.GOLD_ORE) { GameRegistry.addSmelting(stingyOre, new ItemStack(Items.GOLD_NUGGET), 0.1f); } } } }
true
7ab6f6a17f0da97aadf5e60ca79c2fa77037539c
Java
LakshanWeerasinghe/BluetoothRSSILogger
/app/src/main/java/com/example/util/Util.java
UTF-8
247
2.15625
2
[]
no_license
package com.example.util; import android.app.Activity; import android.widget.Toast; public class Util { public static void showToast(Activity activity, String msg) { Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show(); } }
true
81c12ca06822d8211e03f08d6d9c064baf1007d1
Java
wild-lotus/dprojekt
/app/src/main/java/com/dprojekt/domain/decisions/usecases/CheckDecImgUseCase.java
UTF-8
2,246
2.671875
3
[]
no_license
package com.dprojekt.domain.decisions.usecases; import com.dprojekt.domain.common.rx.PostExecutionThread; import com.dprojekt.domain.common.rx.ThreadExecutor; import com.dprojekt.domain.common.UseCase; import com.dprojekt.domain.decisions.DecRepository; import com.dprojekt.domain.decisions.models.DecModel; import com.dprojekt.presentation.common.di.PerActivity; import javax.inject.Inject; import rx.Observable; import rx.Subscriber; /** * This class is an implementation of {@link UseCase} that represents a use case to * check if the image of a {@link DecModel} needs to be updated. */ @PerActivity public class CheckDecImgUseCase extends UseCase { // ========================================================================== // Member variables // ========================================================================== private long mDecId; private final DecRepository mDecRepository; // ========================================================================== // Constructor // ========================================================================== @Inject public CheckDecImgUseCase(DecRepository decRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread) { super(threadExecutor, postExecutionThread); mDecRepository = decRepository; } // ========================================================================== // Public methods // ========================================================================== /** Start asynchronous execution of this use case * * @param decId ID of the Decision whose image we are checking. * @param useCaseSubscriber subscriber to receive notifications from Observables. */ public void execute(long decId, Subscriber useCaseSubscriber) { mDecId = decId; super.execute(useCaseSubscriber); } // ========================================================================== // UseCase methods // ========================================================================== @Override protected Observable buildUseCaseObservable() { return mDecRepository.checkDecImg(mDecId); } }
true
ff8192b6d19add76c262027f44c2fcf7f41a535e
Java
Toxa-p07a1330/encriptedStorage
/src/main/java/ru/bmstu/iu3/Theory.java
UTF-8
940
1.992188
2
[]
no_license
package ru.bmstu.iu3; import org.apache.wicket.Component; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.WebPage; public class Theory extends WebPage { private static final long serialVersionUID = 1L; public Theory(final PageParameters parameters) { super(parameters); Link toDirectoryInterface = new Link<Void>("toDirectoryInterface") { @Override public void onClick() { setResponsePage(DirectoryInterface.class); } }; Link toEditor = new Link<Void>("toEditor") { @Override public void onClick() { setResponsePage(Editor.class); } }; WebMarkupContainer menu = new WebMarkupContainer("menu"); menu.add(toDirectoryInterface); menu.add(toEditor); add(menu); } }
true
43cde027baf9d6f8220027c0bb489b6a64960273
Java
dch1994/Demo
/store/src/com/hxzy/store/web/servlet/ProductServlet.java
UTF-8
1,280
2.15625
2
[]
no_license
package com.hxzy.store.web.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hxzy.store.domain.PageModel; import com.hxzy.store.domain.Product; import com.hxzy.store.serviceimpl.ProductServiceImpl; import com.hxzy.store.web.base.BaseServlet; public class ProductServlet extends BaseServlet { public String findProductByPid(HttpServletRequest request,HttpServletResponse response) throws IOException, SQLException{ //获取pid String pid=request.getParameter("pid"); //业务层 ProductServiceImpl p=new ProductServiceImpl(); Product m=p.findProductByPid(pid); //带数据 request.setAttribute("p1", m); return "/jsp/product_info.jsp"; } public String findProductByIdWithPage(HttpServletRequest request,HttpServletResponse response) throws SQLException { int curnum=Integer.parseInt(request.getParameter("num"));//1 String cid1=request.getParameter("cid"); ProductServiceImpl ps=new ProductServiceImpl(); PageModel pm=ps.findProductByIdWithPage(cid1, curnum); request.setAttribute("page", pm); return "/jsp/product_list.jsp"; } }
true
fa5774284eedf3c1660579a54bd7979bfe888e69
Java
charles-wangkai/codeforces
/1200/B/Main.java
UTF-8
670
3.328125
3
[]
no_license
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int tc = 0; tc < t; tc++) { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int[] h = new int[n]; for (int i = 0; i < h.length; i++) { h[i] = sc.nextInt(); } System.out.println(solve(h, m, k) ? "YES" : "NO"); } sc.close(); } static boolean solve(int[] h, int m, int k) { for (int i = 0; i < h.length - 1; i++) { int needed = Math.max(0, h[i + 1] - k); if (h[i] + m < needed) { return false; } m += h[i] - needed; } return true; } }
true
0da62c14b48550da0324c8072fbf2c5879430581
Java
ArnolPlazas/JAVA
/src/Uso_arraysII.java
UTF-8
379
3.1875
3
[]
no_license
import javax.swing.*; public class Uso_arraysII { public static void main(String[] args){ String[] paises=new String[8]; for(int i=0;i<8;i++){ paises[i]=JOptionPane.showInputDialog("Introduce pais "+(i+1)); } for(String elemento:paises){ System.out.println("Pais: "+elemento); } } }
true
e38a84da76ef89db853dc7ebf33753b7c3305ab2
Java
serenity-dojo/static-website-tests
/src/test/java/lta/actions/navigation/TopLevelMenuBar.java
UTF-8
893
2.15625
2
[ "Apache-2.0" ]
permissive
package lta.actions.navigation; import net.serenitybdd.core.pages.PageObject; import org.openqa.selenium.By; public class TopLevelMenuBar extends PageObject { private static String TOP_LEVEL_MENU_ENTRY = "//a[normalize-space()='%s']"; private static String TOP_LEVEL_MENU_TOGGLE = "//div[contains(.,'%s')][contains(@class,'nav-link')]"; public static By NAVBAR_TOGGLE = By.cssSelector(".navbar-toggler-icon"); public static By topLevelMenuItemCalled(String menuItemName) { return By.xpath(String.format(TOP_LEVEL_MENU_ENTRY, menuItemName)); } public static By topLevelMenuToggleFor(String menuItemName) { return By.xpath(String.format(TOP_LEVEL_MENU_TOGGLE, menuItemName)); } public boolean isSquashed() { return $(NAVBAR_TOGGLE).isCurrentlyVisible(); } public void expandMenu() { $(NAVBAR_TOGGLE).click(); } }
true
3bb3db907b38c44255029ab4056ab552ce812ab0
Java
caoguobin-git/jinghang-travel
/src/main/java/com/travel/controller/StrategyController.java
UTF-8
4,119
2.03125
2
[]
no_license
package com.travel.controller; import com.travel.common.entity.StrategyEntity; import com.travel.common.vo.JsonResult; import com.travel.common.vo.PageObject; import com.travel.service.StrategyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; @SuppressWarnings("ALL") @Controller @RequestMapping("/strategy") public class StrategyController { @Autowired private StrategyService strategyService; @RequestMapping("/doStrategyListUI") public String doStrategyListUI() { return "sys/strategy_list"; } @RequestMapping("/doFindPageObjects") @ResponseBody public JsonResult doFindPageObjects(Integer pageCurrent, Integer pageSize, String sceneryName) { if (pageCurrent == null) { pageCurrent = 1; } if (pageSize == null) { pageSize = 6; } PageObject pageObject = strategyService.doFindPageObjects(pageCurrent, pageSize, sceneryName); return new JsonResult(pageObject); } @RequestMapping("/doFindObjectById") @ResponseBody public JsonResult doFindObjectById(String id) { StrategyEntity strategyEntity = strategyService.doFindObjectById(id); return new JsonResult(strategyEntity); } @RequestMapping("/getSceneryOptions") @ResponseBody public JsonResult getSceneryOptions(String cityName){ List<String> scenerys=strategyService.getSceneryOptions(cityName); return new JsonResult(scenerys); } @RequestMapping("/doStrategyEditUI") public String doStrategyEditUI() { return "sys/strategy_edit"; } @RequestMapping("/doSaveObject") @ResponseBody public JsonResult doSaveObject(String sceneryName, String strategyTitle, String strategyContent,@RequestParam MultipartFile[] strategyPicFile) throws IOException { System.out.println(sceneryName); System.out.println(strategyTitle); System.out.println(strategyContent); System.out.println(strategyPicFile); System.out.println(strategyPicFile.length); String result = strategyService.doSaveObject(sceneryName,strategyTitle,strategyContent,strategyPicFile); if ("ok".equals(result)) { return new JsonResult("OK"); } else { return new JsonResult("201", "操作失败", "请重试"); } } @RequestMapping("/doUpdateObject") @ResponseBody public JsonResult doUpdateObject(String strategyId,String sceneryName, String strategyTitle, String strategyContent,@RequestParam MultipartFile[] strategyPicFile) throws IOException { String result = strategyService.doUpdateObject(strategyId,sceneryName,strategyTitle,strategyContent,strategyPicFile); if ("ok".equals(result)) { return new JsonResult("OK"); } else { return new JsonResult("201", "操作失败", "请重试"); } } @RequestMapping("/doDeleteObject") @ResponseBody public JsonResult doDeleteObject(String strategyId) { String result = strategyService.doDeleteObject(strategyId); if ("ok".equals(result)) { return new JsonResult("OK"); } else { return new JsonResult("201", "操作失败", "删除失败,记录可能已经不存在"); } } @RequestMapping("/getStrategysByCityName") @ResponseBody public JsonResult getStrategysByCityName(Integer pageCurrent, Integer pageSize, String cityName) { if (pageCurrent == null) { pageCurrent = 1; } if (pageSize == null) { pageSize = 20; } PageObject pageObject = strategyService.getStrategysByCityName(pageCurrent, pageSize, cityName); return new JsonResult(pageObject); } }
true
d23cc031baca142a208c474ec7a4f3f1a75a6762
Java
Stormpx/mqttbroker
/src/main/java/com/stormpx/ex/SharedSubscriptionsNotSupportedException.java
UTF-8
715
1.976563
2
[]
no_license
package com.stormpx.ex; public class SharedSubscriptionsNotSupportedException extends RuntimeException { public SharedSubscriptionsNotSupportedException() { } public SharedSubscriptionsNotSupportedException(String message) { super(message); } public SharedSubscriptionsNotSupportedException(String message, Throwable cause) { super(message, cause); } public SharedSubscriptionsNotSupportedException(Throwable cause) { super(cause); } public SharedSubscriptionsNotSupportedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
true
19d4d5470aa1f0c0afd04f12a265915f4d629b09
Java
shileicomeon/MyDemo
/hotnews/src/main/java/collect/jhjz/com/hotnews/HotNewsFragment.java
UTF-8
424
1.851563
2
[]
no_license
package collect.jhjz.com.hotnews; import collect.jhjz.com.common.base.BaseFragment; /** * Created by 时雷 2019/5/17 14:28 */ public class HotNewsFragment extends BaseFragment { @Override public int initView() { return R.layout.fragment_hot_news; } @Override public void initData() { } public static HotNewsFragment newInstance(){ return new HotNewsFragment(); } }
true
925b6287077613654e08045eef7d452b51fe622a
Java
liugang-snow/Equipment
/RuoYi/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/EquSupplierServiceImpl.java
UTF-8
2,405
2
2
[ "MIT" ]
permissive
package com.ruoyi.system.service.impl; import java.util.List; import com.ruoyi.common.utils.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.system.mapper.EquSupplierMapper; import com.ruoyi.system.domain.EquSupplier; import com.ruoyi.system.service.IEquSupplierService; import com.ruoyi.common.core.text.Convert; /** * 设备供应商Service业务层处理 * * @author ruoyi * @date 2020-02-17 */ @Service public class EquSupplierServiceImpl implements IEquSupplierService { @Autowired private EquSupplierMapper equSupplierMapper; /** * 查询设备供应商 * * @param supId 设备供应商ID * @return 设备供应商 */ @Override public EquSupplier selectEquSupplierById(Long supId) { return equSupplierMapper.selectEquSupplierById(supId); } /** * 查询设备供应商列表 * * @param equSupplier 设备供应商 * @return 设备供应商 */ @Override public List<EquSupplier> selectEquSupplierList(EquSupplier equSupplier) { return equSupplierMapper.selectEquSupplierList(equSupplier); } /** * 新增设备供应商 * * @param equSupplier 设备供应商 * @return 结果 */ @Override public int insertEquSupplier(EquSupplier equSupplier) { equSupplier.setCreateTime(DateUtils.getNowDate()); return equSupplierMapper.insertEquSupplier(equSupplier); } /** * 修改设备供应商 * * @param equSupplier 设备供应商 * @return 结果 */ @Override public int updateEquSupplier(EquSupplier equSupplier) { equSupplier.setUpdateTime(DateUtils.getNowDate()); return equSupplierMapper.updateEquSupplier(equSupplier); } /** * 删除设备供应商对象 * * @param ids 需要删除的数据ID * @return 结果 */ @Override public int deleteEquSupplierByIds(String ids) { return equSupplierMapper.deleteEquSupplierByIds(Convert.toStrArray(ids)); } /** * 删除设备供应商信息 * * @param supId 设备供应商ID * @return 结果 */ @Override public int deleteEquSupplierById(Long supId) { return equSupplierMapper.deleteEquSupplierById(supId); } }
true
d4903151342dcbf22107cc68f2c2af1a558e72a3
Java
Realictik15/hotel-sys
/src/main/java/com/vsu/project/configs/SpringConfig.java
UTF-8
632
2.234375
2
[]
no_license
package com.vsu.project.configs; import com.vsu.project.models.Apartment; import com.vsu.project.models.Client; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @ComponentScan("com.vsu.project") @PropertySource("classpath:project.properties") public class SpringConfig { @Bean public Apartment apartment(){ return new Apartment(); } @Bean public Client client(){ return new Client(); } }
true
ae7c9a3fa41badbcde4d77b6e57eb7fc6eeef383
Java
jamesvwilfong/Programming
/Java/Java271/Lab5/PersonTester.java
UTF-8
999
3.453125
3
[]
no_license
// James Wilfong // Dr. Stephan // CSE 271, Section C public class PersonTester { public static void main(String[] args) { Person a = new Person("james",1998); System.out.println("Expected: james"); System.out.println(Person.getName()); System.out.println("Expected: 1998"); System.out.println(Person.getYearOfBirth()); System.out.println("Expected:\nName: james\nBirth Year: 1998"); System.out.println(a.toString("james", 1998)); Student b = new Student("james",1998,"Engineering"); System.out.println("Expected: Engineering"); System.out.println(b.getMajor()); System.out.println("Expected: \nName: james\nBirth Year: 1998\nMajor: Engineering"); System.out.println(b.toString("Engineering")); Instructor c = new Instructor("james",1998,130000.0); System.out.println("Expected: 130000.0"); System.out.println(c.getSalary()); System.out.println("Expcted: \nName: james\nBirth Year: 1998\nSalary: 130000.0"); System.out.println(c.toString(130000.0)); }//end main }//end PersonTester class
true
9e8deef98b6fba86752950dcf16035be2b0b07b6
Java
VVoev/Telerik-Academy
/18.Mobile-Applications-for-Android/Topics/java sintaks/untitled2/src/ScientificCalculator.java
UTF-8
182
2.921875
3
[ "MIT" ]
permissive
public class ScientificCalculator extends Calculator { public double CalculateSinus(double value){ return value*3.14; } public ScientificCalculator(){ } }
true
f7751bbe5b5e1a0d071f3eb6b38603907793b2cb
Java
kowshikbharathi/VitalSignModule
/src/main/java/com/module/vitalSignModule/vitalSignModule/service/VitalSignServiceImpl.java
UTF-8
2,076
2.3125
2
[]
no_license
package com.module.vitalSignModule.vitalSignModule.service; import java.sql.Date; import java.util.Objects; import java.util.Optional; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.module.vitalSignModule.vitalSignModule.client.PatientClient; import com.module.vitalSignModule.vitalSignModule.dto.VitalSignDto; import com.module.vitalSignModule.vitalSignModule.dto.VitalSignKey; import com.module.vitalSignModule.vitalSignModule.entity.PatientEntity; import com.module.vitalSignModule.vitalSignModule.entity.VitalSignEntity; import com.module.vitalSignModule.vitalSignModule.repository.VitalSignRepository; /** * VitalSignService which implement VitalSignService. * @author Kowshik Bharathi M */ @Service public class VitalSignServiceImpl implements VitalSignService{ @Autowired public VitalSignServiceImpl(VitalSignRepository vitalSignRepository,PatientClient patientClient) { super(); this.vitalSignRepository=vitalSignRepository; this.patientClient=patientClient; } private final VitalSignRepository vitalSignRepository; private final PatientClient patientClient; @Override public Boolean save(VitalSignEntity vitalSignEntity) { vitalSignRepository.save(VitalSignEntity.formDto(vitalSignEntity)); PatientEntity patientEntity=new PatientEntity(); patientEntity.setPatientId(vitalSignEntity.getPatientId()); patientEntity.setLastVisitDate(vitalSignEntity.getVisitDate()); PatientEntity patientEntityResponse =patientClient.updateVistDate(patientEntity); if(Objects.nonNull(patientEntityResponse)){ return true; } return false; } @Override public VitalSignEntity getByKeys(String userId, Date visitDate) { VitalSignKey vitalSignKey=new VitalSignKey(); vitalSignKey.setPatientId(UUID.fromString(userId)); vitalSignKey.setVisitDate(visitDate); Optional<VitalSignDto> optionalDto= vitalSignRepository.findById(vitalSignKey); if(optionalDto.isPresent()) { return VitalSignEntity.formEntity(optionalDto.get()); } return null; } }
true
75403a3940ce3f6f27018db4f39fff2fd4aed4ec
Java
tstott/cs228hw1
/School/CS228/PredatorPrey.java
UTF-8
4,336
3.546875
4
[]
no_license
package edu.iastate.cs228.hw1; import java.io.FileNotFoundException; import java.util.Scanner; import java.lang.System; import java.lang.String; /** * @author Tate Stottmann * The PredatorPrey class does the predator-prey simulation over a grid world * with squares occupied by badgers, foxes, rabbits, grass, or none. * */ public class PredatorPrey{ /** * Update the new world from the old world in one cycle. * @param wOld old world * @param wNew new world */ public static void updateWorld(World wOld, World wNew){ int oww = wOld.getWidth(); wNew = new World(oww); for(int r = 0;r < oww;++r){ for(int c = 0;c < oww;++c){ wNew.grid[r][c] = (wOld.grid[r][c]).next(wOld);}}} // TODO // // For every life form (i.e., a Living object) in the grid wOld, generate // a Living object in the grid wNew at the corresponding location such that // the former life form changes into the latter life form. // // Employ the method next() of the Living class. /** * Repeatedly generates worlds either randomly or from reading files. * Over each world, carries out an input number of cycles of evolution. * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException{ Scanner scan = new Scanner(System.in); int trialnum = 1; int cycles = 0; int width = 0; String fileName = ""; World initial = new World(0); World finWor = new World(0); boolean test = true; while(test){ System.out.print("The Predator-Prey Simulator \n keys: 1 (Random World) 2 (File Input) 3 (Exit) \n \n Trial " + trialnum + ": "); int choice = scan.nextInt(); switch(choice){ case 1: System.out.print("Random World \nEnter Grid Width: "); width = scan.nextInt(); initial = new World(width); initial.randomInit(); if(initial.grid[0][0] == null) System.out.println("Here"); System.out.print("Number of Cycles: "); cycles = scan.nextInt(); finWor = new World(width); //finWor = simulate(initial,cycles); System.out.print("Initial World: \n \n" + initial.toString()); System.out.print(" \n \n Final World: \n \n" + finWor.toString()); break; case 2: System.out.println("World input from file \n File Name: "); fileName = "grid1.txt"; System.out.println("Number of Cycles: "); cycles = scan.nextInt(); initial = new World(fileName); finWor = simulate(initial,cycles); System.out.println("Initial World: \n \n" + initial.toString() + " \n \n Final World: \n \n" + finWor.toString()); break; case 3: test = false;}}} // TODO // // Generate predator-prey simulations repeatedly like shown in the // sample run in the project description. // // 1. Enter 1 to generate a random world, 2 to read a world from an input // file, and 3 to end the simulation. (An input file always ends with // the suffix .txt.) // // 2. Print out standard messages as given in the project description. // // 3. For convenience, you may define two worlds even and odd as below. // In an even numbered cycle (starting at zero), generate the world // odd from the world even; in an odd numbered cycle, generate even // from odd. // 4. Print out initial and final worlds only. No intermediate worlds should // appear in the standard output. (When debugging your program, you can // print intermediate worlds.) // // 5. You may save some randomly generated worlds as your own test cases. // // 6. It is not necessary to handle file input & output exceptions for this // project. Assume data in an input file to be correctly formated. /** * Does the actual simulation and returns final world. *@param initW */ private static World simulate(World initW,int cycles){ World even = initW; World odd = new World(initW.getWidth()); for(int cy = cycles;cy > 0;--cy){ if((cy & 1) == 0) updateWorld(odd,even); else updateWorld(even,odd);} if((cycles & 1) == 0) return even; else return odd;} }
true
d781f70b7aae5bcd3114de45a6c86a98a9b72a6b
Java
peregrine-cms/sling-org-apache-sling-multipackageupdate
/mpu/src/test/java/com/headwire/sling/mpu/comps/MultiPackageUpdateModelTest.java
UTF-8
2,518
1.75
2
[ "Apache-2.0" ]
permissive
package com.headwire.sling.mpu.comps; import com.headwire.sling.mpu.HttpStatusCodeMapper; import com.headwire.sling.mpu.MultiPackageUpdate; import com.headwire.sling.mpu.MultiPackageUpdateResponse; import com.headwire.sling.mpu.MultiPackageUpdate.Operation; import com.headwire.sling.mpu.MultiPackageUpdateResponse.Code; import junitx.util.PrivateAccessor; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestPathInfo; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Parameter; import static com.headwire.sling.mpu.impl.MultiPackageUpdateServiceTest.TEST_CONFIG_NAME; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public abstract class MultiPackageUpdateModelTest<ModelType extends MultiPackageUpdateModel> { private final ModelType model; @Mock protected MultiPackageUpdate updater; @Mock private HttpStatusCodeMapper httpMapper; @Mock private SlingHttpServletRequest request; @Mock private RequestPathInfo requestPathInfo; @Mock private SlingHttpServletResponse response; @Mock protected MultiPackageUpdateResponse mpuResponse; protected MultiPackageUpdateModelTest(final ModelType model) { this.model = model; } @Before public void setUp() throws NoSuchFieldException { PrivateAccessor.setField(model, "updater", updater); PrivateAccessor.setField(model, "httpMapper", httpMapper); PrivateAccessor.setField(model, "request", request); PrivateAccessor.setField(model, "response", response); when(request.getRequestPathInfo()).thenReturn(requestPathInfo); when(requestPathInfo.getSuffix()).thenReturn(TEST_CONFIG_NAME); when(httpMapper.getStatusCode(any(Operation.class), any(Code.class))) .thenReturn(HttpServletResponse.SC_OK); setUpImpl(); } @Test public final void execute() { Assert.assertNotNull(model.execute()); verify(response).setStatus(HttpServletResponse.SC_OK); verifyExecuteImpl(); } protected abstract void setUpImpl(); protected abstract void verifyExecuteImpl(); }
true
bc45693ea50b73df3e3c4848a8ad5562ed118c28
Java
yizhichangyuan/o2o-SpringBoot
/src/test/java/com/imooc/o2o/dao/ProductSellDailyDaoTest.java
UTF-8
1,454
2.15625
2
[]
no_license
package com.imooc.o2o.dao; import com.imooc.o2o.entity.ProductSellDaily; import com.imooc.o2o.entity.Shop; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class ProductSellDailyDaoTest { @Autowired private ProductSellDailyDao productSellDailyDao; @Test public void testAInsertProductSellDaily(){ int effectNum = productSellDailyDao.insertProductSellDaily(); System.out.println(effectNum); } @Test public void testBQueryProductSellDailyList() throws ParseException { ProductSellDaily productSellDaily = new ProductSellDaily(); Shop shop = new Shop(); shop.setShopId(79L); productSellDaily.setShop(shop); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date beginTime = format.parse("2021-02-17"); Date endTime = format.parse("2021-02-19"); List<ProductSellDaily> list = productSellDailyDao.queryProductSellDailyList(productSellDaily, beginTime, endTime); System.out.println(list.size()); } }
true
248aa9f4d3922d69c05ca61ef8dfb9bd84c0ac3c
Java
JetBrains/teamcity-s3-artifact-storage-plugin
/teamcity-s3-sdk/src/main/java/jetbrains/buildServer/artifacts/s3/publish/presigned/util/S3ErrorDto.java
UTF-8
1,325
1.976563
2
[ "Apache-2.0" ]
permissive
package jetbrains.buildServer.artifacts.s3.publish.presigned.util; import com.amazonaws.AmazonServiceException; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.jetbrains.annotations.NotNull; @XmlRootElement(name = "error") public class S3ErrorDto { @XmlElement(name = "Code") private String code; @XmlElement(name = "Message") private String message; @XmlElement(name = "RequestId") private String requestId; @XmlElement(name = "HostId") private String hostId; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getHostId() { return hostId; } public void setHostId(String hostId) { this.hostId = hostId; } @NotNull public AmazonServiceException toException() { AmazonServiceException exception = new AmazonServiceException(message); exception.setErrorCode(code); exception.setProxyHost(hostId); exception.setRequestId(requestId); return exception; } }
true
6d69c912fc4dc1be898943e4e8ee886bd00250e7
Java
fraterblack/projeto-teoria-grafos
/src/com/grafos/algorithm/Dijkstra.java
ISO-8859-1
7,583
3.3125
3
[]
no_license
package com.grafos.algorithm; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import java.util.stream.Collectors; public class Dijkstra extends Graph { //Results private int distanceToDestination; private TreeMap<Integer, Edge> pathToDestination = new TreeMap<Integer, Edge>();; private TreeMap<Integer, String> processingLog; public Dijkstra(int vertexQuantity) throws Exception { super(vertexQuantity); } public void findSmallestPath(int origin, int destination) throws Exception { try { //Reseta o status do ltimo processamento resetProcessingState(); //Validate origin and destination if (origin < 0) { throw new Exception("Origem deve ser maior ou igual a zero"); } if (destination >= getNodesQuantity()) { throw new Exception("Destino deve ser menor ou igual a " + (getNodesQuantity() - 1)); } TreeMap<Integer, Integer> unsolvedNodes = new TreeMap<Integer, Integer>(); TreeMap<Integer, Integer> solvedNodes = new TreeMap<Integer, Integer>(); TreeMap<Integer, Edge> processedPaths = new TreeMap<Integer, Edge>(); for (int i = 0; i < getNodesQuantity(); i++) { //Cria o vetor de ns restantes unsolvedNodes.put(unsolvedNodes.size(), new Integer(i)); } //Move n de origem no map de resolvidos solvedNodes.put(origin, 0); unsolvedNodes.remove(new Integer(origin)); //Enquanto houver ns no resolvidos while (!unsolvedNodes.isEmpty()) { //Variveis de controle int smallestResolvedNode = -1; int smallestAdjacentNode = -1; int smallestAdjacentValue = 0; for (Map.Entry<Integer, Integer> entry : solvedNodes.entrySet()) { Integer currentNode = entry.getKey(); Integer acummulatedDistance = entry.getValue(); //Logging addLog("Itera sobre n resolvido [" + currentNode + "]"); //Apartir do n resolvido (linha na matriz), itera sobre os ns adjacentes (colunas na matriz) for (int i = 0; i < getNodesQuantity(); i++) { //S considera ns com valor maior que zero e que seja adjascente a uma n no resolvido if (getMatrix()[currentNode][i] > 0 && solvedNodes.get(i) == null) { //Soma do peso do n adjascente ao valor acumulado do n resolvido int adjacentDistance = getMatrix()[currentNode][i] + acummulatedDistance; //Logging String logMessage = " N adjascente [" + i + "] - Distncia: " + adjacentDistance + "(" + acummulatedDistance + ")"; //Se for a primeira iterao if (smallestAdjacentNode == -1 || adjacentDistance <= smallestAdjacentValue) { smallestResolvedNode = currentNode; smallestAdjacentNode = i; smallestAdjacentValue = adjacentDistance; //Logging logMessage += " ***"; //Identifica o n adjascente como o de menor caminho at o momento } //Logging addLog(logMessage); } } } //Logging addLog("[Menor caminho: " + smallestResolvedNode + "->" + smallestAdjacentNode + " = " + smallestAdjacentValue + "]"); //Adiciona o caminho para lista de processados processedPaths.put(processedPaths.size(), new Edge(smallestResolvedNode, smallestAdjacentNode, smallestAdjacentValue)); //Move menor n adjacente dos no resolvidos para os resolvidos solvedNodes.put(smallestAdjacentNode, smallestAdjacentValue); unsolvedNodes.remove(new Integer(smallestAdjacentNode)); addLog("........................................................."); //Menor caminho possvel encontrado if (smallestAdjacentNode == destination) { //Logging addLog("----- Menor caminho encontrado: " + smallestAdjacentValue + " -----"); distanceToDestination = smallestAdjacentValue; break; } } //Gera o caminho at o destino apartir dos caminhos processados no clculo generatePathToDestination(processedPaths); } catch (Exception error) { if (error.getMessage().equals("-1")) { throw new Exception("No existe um caminho vivel entre os pontos"); } throw new Exception(error.getMessage()); } } public TreeMap<Integer, Edge> getPathToDestination() { return pathToDestination; } public Integer getDistanceToDestination() { return distanceToDestination; } public void printLog() { processingLog.forEach((index, log) -> System.out.println(log)); } private void resetProcessingState() { processingLog = new TreeMap<Integer, String>(); distanceToDestination = 0; pathToDestination.clear(); } private void generatePathToDestination(TreeMap<Integer, Edge> processedPaths) { int lastOriginToFound = -1; for (Entry<Integer, Edge> entry : processedPaths.entrySet().stream() .sorted((p1, p2) -> p2.getKey().compareTo(p1.getKey())) .collect(Collectors.toList()) ) { if (lastOriginToFound == -1) { lastOriginToFound = entry.getValue().getNodeOrigin(); pathToDestination.put(entry.getKey(), entry.getValue()); } else { if (entry.getValue().getNodeDestin() == lastOriginToFound) { lastOriginToFound = entry.getValue().getNodeOrigin(); pathToDestination.put(entry.getKey(), entry.getValue()); } } } } private void addLog(String message) { processingLog.put(processingLog.size(), message); } public static void main(String[] args) { try { Dijkstra dij = new Dijkstra(8); dij.insertEdge(0, 1, 4); dij.insertEdge(0, 2, 4); dij.insertEdge(0, 4, 2); dij.insertEdge(0, 6, 6); dij.insertEdge(1, 0, 4); dij.insertEdge(1, 2, 2); dij.insertEdge(1, 3, 7); dij.insertEdge(1, 6, 3); dij.insertEdge(2, 0, 4); dij.insertEdge(2, 1, 2); dij.insertEdge(2, 3, 3); dij.insertEdge(2, 4, 2); dij.insertEdge(3, 1, 7); dij.insertEdge(3, 2, 3); dij.insertEdge(3, 7, 2); dij.insertEdge(4, 0, 2); dij.insertEdge(4, 2, 2); dij.insertEdge(4, 5, 7); dij.insertEdge(4, 7, 4); dij.insertEdge(5, 4, 7); dij.insertEdge(5, 7, 3); dij.insertEdge(6, 0, 6); dij.insertEdge(6, 1, 3); dij.insertEdge(7, 3, 2); dij.insertEdge(7, 4, 4); dij.insertEdge(7, 5, 3); System.out.println("########### Test Case ##########"); long startTime = System.currentTimeMillis(); dij.findSmallestPath(2, 5); long finishTime = System.currentTimeMillis(); System.out.println("Tempo de execuo: " + (finishTime - startTime) + "ms"); System.out.println("Rota:"); dij.getPathToDestination().forEach((key, edge) -> { System.out.println(edge.getNodeOrigin() + "->" + edge.getNodeDestin() + "=" + edge.getAccumulatedDistance()); }); System.out.println("Menor distncia:"); System.out.println(dij.getDistanceToDestination()); /*System.out.println("Log:"); dij.printLog();*/ System.out.println("#"); System.out.println("########### Test Case 2 ##########"); /////// //Case 2 dij.findSmallestPath(3, 5); System.out.println("Rota:"); dij.getPathToDestination().forEach((key, edge) -> { System.out.println(edge.getNodeOrigin() + "->" + edge.getNodeDestin() + "=" + edge.getAccumulatedDistance()); }); System.out.println("Menor distncia:"); System.out.println(dij.getDistanceToDestination()); /*System.out.println("Log:"); dij.printLog();*/ /////// } catch (Exception ex) { if (ex.getMessage() == null) System.out.println("Ocorreu um erro de " + ex + " no main"); else System.out.println("Erro: " + ex.getMessage()); } } }
true
d63652cefe54aa9e1c55127c658bda6d59df72bb
Java
omidketabchi/Ticketing
/app/src/main/java/com/example/ticketing/Adapter/BusAdapter.java
UTF-8
3,222
2.140625
2
[]
no_license
package com.example.ticketing.Adapter; import android.content.Context; import android.content.Intent; import android.os.Parcelable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import com.example.ticketing.BusInformationActivity; import com.example.ticketing.Model.BusModel; import com.example.ticketing.R; import java.util.ArrayList; import java.util.List; public class BusAdapter extends RecyclerView.Adapter<BusAdapter.BusViewHolder> { Context context; List<BusModel> models; public BusAdapter(Context context, List<BusModel> models) { this.context = context; this.models = models; } @NonNull @Override public BusViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(context).inflate(R.layout.bus_item, viewGroup, false); return new BusViewHolder(view); } @Override public void onBindViewHolder(@NonNull BusViewHolder holder, int position) { BusModel model = models.get(position); holder.txtCompany.setText(model.getType()); holder.txtCapacity.setText(model.getCapacity()); holder.txtDestinationTerminal.setText(model.getDestinationTerminal()); holder.txtSourceTerminal.setText(model.getSourceTerminal()); holder.txtPrice.setText(model.getPrice()); holder.txtSource.setText(model.getSource()); holder.parent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, BusInformationActivity.class); intent.putExtra("model", model); intent.putParcelableArrayListExtra("chair", (ArrayList<? extends Parcelable>) model.getChairModel()); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }); } @Override public int getItemCount() { return models.size(); } public class BusViewHolder extends RecyclerView.ViewHolder { TextView txtSource; TextView txtCompany; TextView txtCapacity; TextView txtPrice; TextView txtSourceTerminal; TextView txtDestinationTerminal; CardView parent; public BusViewHolder(@NonNull View itemView) { super(itemView); txtSource = (TextView) itemView.findViewById(R.id.txt_busItem_source); txtCompany = (TextView) itemView.findViewById(R.id.txt_busItem_company); txtCapacity = (TextView) itemView.findViewById(R.id.txt_busItem_capacityValue); txtPrice = (TextView) itemView.findViewById(R.id.txt_busItem_price); txtSourceTerminal = (TextView) itemView.findViewById(R.id.txt_busItem_sourceTerminal); txtDestinationTerminal = (TextView) itemView.findViewById(R.id.txt_busItem_destinationTerminal); parent = (CardView) itemView.findViewById(R.id.cv_busItem_parent); } } }
true
ba2650133c58bbbb583e32d176cd18621a3ba8c5
Java
moutainhigh/vmi-openInstall
/vmi-video-api-server/vmi-video-interface/src/main/java/com/tigerjoys/shark/miai/inter/entity/AppAreaCityEntity.java
UTF-8
1,926
2.171875
2
[]
no_license
package com.tigerjoys.shark.miai.inter.entity; import java.io.Serializable; import java.util.Date; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.annotations.Column; import org.apache.ibatis.annotations.Id; import org.apache.ibatis.annotations.Table; import com.tigerjoys.nbs.mybatis.core.BaseEntity; /** * 数据库中 城市级别对应表[t_app_area_city] 表对应的实体类 * @author shiming * @Date 2019-07-26 14:49:39 * */ @Table(name="t_app_area_city") public class AppAreaCityEntity extends BaseEntity implements Serializable { /** * */ private static final long serialVersionUID = 1L; /** * id标识 */ @Id @Column(name="id",nullable=false,jdbcType=JdbcType.BIGINT,comment="id标识") private Long id; /** * 城市名称 */ @Column(name="name",nullable=true,jdbcType=JdbcType.VARCHAR,comment="城市名称") private String name; /** * 百度code */ @Column(name="baidu_code",nullable=true,jdbcType=JdbcType.INTEGER,comment="百度code") private Integer baidu_code; /** * 城市级别 */ @Column(name="code",nullable=true,jdbcType=JdbcType.INTEGER,comment="城市级别") private Integer code; /** * 创建时间 */ @Column(name="create_time",nullable=true,jdbcType=JdbcType.TIMESTAMP,comment="创建时间") private Date create_time; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getBaidu_code() { return baidu_code; } public void setBaidu_code(Integer baidu_code) { this.baidu_code = baidu_code; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public Date getCreate_time() { return create_time; } public void setCreate_time(Date create_time) { this.create_time = create_time; } }
true
37a25cc29abcae1fcdc5ae885a8e55690486fbeb
Java
KBSure/JavaWebProgramming
/study01re/src/main/java/examples/Server.java
UTF-8
968
2.78125
3
[]
no_license
package examples; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws IOException { ServerSocket listener = new ServerSocket(8080); Socket client = listener.accept(); InputStream is = client.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String fileName = br.readLine(); // FileOutputStream fos = new FileOutputStream(fileName+".txt"); // PrintWriter pw = new PrintWriter(fos); PrintWriter pw = new PrintWriter(new FileWriter(fileName+".txt")); String line = null; while((line = br.readLine()) != null){ System.out.println(line); if(line.equals("quit")) break; pw.println(line); } pw.close(); client.close(); listener.close(); } }
true
435142777d162e7e66ca7799541041226425046e
Java
AngryCow1111/exercises
/algorithm/src/main/java/com/ac/algorithm/resolution/FindEvenCountNumsInArray.java
UTF-8
1,437
3.84375
4
[]
no_license
package com.ac.algorithm.resolution; import java.util.Arrays; /** * FindEvenCountNumsInArray * 假如一个无需数组中,有2个数字出现奇数次,而其他都出现偶数次。 * 找出这2个出现奇数次的数。 * 基本思路: * 1.分治 * 2.异或 * * @author <a href="mailto:[email protected]">angrycow1111</a> * @since 2019/9/10 */ public class FindEvenCountNumsInArray { public static int[] findEvenCountNumsInArray(int[] srcArray) { int[] result = new int[2]; int xOrResult = srcArray[0]; for (int i = 1; i < srcArray.length; i++) { xOrResult ^= srcArray[i]; } /** * 异或结果为0,代表与题意不符 */ if (xOrResult == 0) { return null; } /** * 从后往前找到第一个为1的数 */ int separator = 1; while (0 == (xOrResult & separator)) { separator <<= 1; } for (int i = 0; i < srcArray.length; i++) { if (0 == (separator & srcArray[i])) { result[0] ^= srcArray[i]; } else { result[1] ^= srcArray[i]; } } return result; } public static void main(String[] args) { int[] evenCountNumsInArray = findEvenCountNumsInArray(new int[]{1, 3, 4, 4, 1, 5}); System.out.println(Arrays.toString(evenCountNumsInArray)); } }
true
dff8a040f52e415535b256458ebd53343b97b02f
Java
fedpet/Galactic-Adventures
/src/it/unibo/oop17/ga_game/view/entities/AbstractStateChangingEntityView.java
UTF-8
4,355
2.9375
3
[]
no_license
package it.unibo.oop17.ga_game.view.entities; import java.util.HashMap; import java.util.Map; import it.unibo.oop17.ga_game.model.entities.components.EntityState; import it.unibo.oop17.ga_game.view.SpriteAnimation; import javafx.animation.Animation; import javafx.animation.Transition; import javafx.geometry.Dimension2D; import javafx.geometry.Rectangle2D; import javafx.scene.Group; import javafx.scene.image.Image; import javafx.util.Duration; /** * Base class for {@link StateChangingEntityView}. * * @param <S> * {@link EntityState} type. */ public abstract class AbstractStateChangingEntityView<S extends EntityState> extends AbstractEntityView implements StateChangingEntityView<S> { private final Map<S, Runnable> animations = new HashMap<>(); private Animation currentAnimation; /** * @param group * The {@link Group} instance in which the entity view is added. * @param dimension * The entity view dimension. */ public AbstractStateChangingEntityView(final Group group, final Dimension2D dimension) { super(group, dimension); currentAnimation = new Transition() { @Override protected void interpolate(final double frac) { // dummy animation } }; } /** * {@inheritDoc}. */ @Override public void changeState(final S state) { if (animations.containsKey(state)) { animations.get(state).run(); } } /** * {@inheritDoc} * The current animation is stopped. */ @Override public final void remove() { currentAnimation.stop(); super.remove(); } /** * Used to make a looping sprite animation. * * @param image * The {@link Image} instance containing the frame animations. * @param duration * The {@link Duration} instance defining the seconds of a frame. * @param frames * The number of frames used for the animation. * @return A {@link Runnable} instance animation. */ protected Runnable aSpriteAnimation(final Image image, final Duration duration, final int frames) { return () -> { setImage(image); final Animation newAnim = new SpriteAnimation(getView(), duration, frames, getDimension().getWidth(), getDimension().getHeight()); newAnim.setCycleCount(Animation.INDEFINITE); setAnimation(newAnim); }; } /** * Used to make a static sprite animation. * * @param image * The sprite {@link Image} instance. * @return A {@link Runnable} animation instance. */ protected Runnable justAnImage(final Image image) { return () -> { setImage(image); }; } /** * Used to start an animation from the mapped animations. * * @param state * The {@link EntityState} instance associated to the specific animation that has to start. */ protected void startAnimation(final S state) { currentAnimation.stop(); animations.get(state).run(); } /** * Map an animation for the entity view. * * @param state * The {@link EntityState} instance to which the animation has to be associated. * @param runnable * The {@link Runnable} animation instance to map. */ protected void mapAnimation(final S state, final Runnable runnable) { animations.put(state, runnable); } /** * Used to set an animation for the entity view. * * @param animation * The {@Animation} instance to set for the entity view. */ protected void setAnimation(final Animation animation) { currentAnimation.stop(); currentAnimation = animation; currentAnimation.play(); } /** * Used to set an image for the entity view. * * @param image * The {@link Image} instance to set for the entity view. */ protected void setImage(final Image image) { getView().setImage(image); getView().setViewport(new Rectangle2D(0, 0, getDimension().getWidth(), getDimension().getHeight())); } }
true
8fb89854804ed9c0b32375c64e52f335e3a3c312
Java
chirhotec/gurella
/core/src/com/gurella/engine/scene/renderable/terrain/TerrainTexture.java
UTF-8
1,672
2.546875
3
[]
no_license
package com.gurella.engine.scene.renderable.terrain; import com.badlogic.gdx.utils.ObjectMap; import com.gurella.engine.scene.renderable.terrain.SplatTexture.Channel; /** * Copied from * https://github.com/mbrlabs/Mundus/blob/master/commons/src/main/com/mbrlabs/mundus/commons/terrain/TerrainTexture.java * * @author Marcus Brummer */ public class TerrainTexture { private ObjectMap<Channel, SplatTexture> textures; private SplatMap splatmap; public TerrainTexture() { textures = new ObjectMap<Channel, SplatTexture>(5, 1); } public SplatTexture getTexture(Channel channel) { return textures.get(channel); } public void removeTexture(Channel channel) { if (splatmap != null) { textures.remove(channel); splatmap.clearChannel(channel); splatmap.updateTexture(); } } public void setSplatTexture(SplatTexture tex) { textures.put(tex.channel, tex); } public Channel getNextFreeChannel() { // base SplatTexture st = textures.get(Channel.BASE); if (st == null) { return Channel.BASE; } // r st = textures.get(Channel.R); if (st == null) { return Channel.R; } // g st = textures.get(Channel.G); if (st == null) { return Channel.G; } // b st = textures.get(Channel.B); if (st == null) { return Channel.B; } // a st = textures.get(Channel.A); if (st == null) { return Channel.A; } return null; } public boolean hasTextureChannel(Channel channel) { return textures.containsKey(channel); } public int countTextures() { return textures.size; } public SplatMap getSplatmap() { return splatmap; } public void setSplatmap(SplatMap splatmap) { this.splatmap = splatmap; } }
true
05c622ea4db2e9f4e4709fceef816fa9929f3ae7
Java
arizajose/MyApp_TiendaVirtual
/app/src/main/java/com/example/myapp_tiendavirtual/ArticuloActivity.java
UTF-8
3,654
1.96875
2
[]
no_license
package com.example.myapp_tiendavirtual; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.example.myapp_tiendavirtual.adapters.AdaptadorArticulo; import com.example.myapp_tiendavirtual.adapters.AdaptadorCategoria; import com.example.myapp_tiendavirtual.beans.Articulo; import com.example.myapp_tiendavirtual.beans.Categoria; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class ArticuloActivity extends AppCompatActivity { JsonObjectRequest jsonObjectRequest; JSONArray jsonArray; RecyclerView recyclerView; List<Articulo> articuloList; String url ="https://arizajose.000webhostapp.com/tControla.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_articulo); recyclerView = findViewById(R.id.recyclerViewArticulos); String codArt = getIntent().getStringExtra("codcategoria"); Log.w("categoria",codArt); llenarArticulos(codArt); } public void llenarArticulos(String cod){ String enlace = url+"?tag=consulta2&cod="+cod; articuloList = new ArrayList<>(); jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, enlace, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { jsonArray = response.getJSONArray("dato"); Log.w("datos",jsonArray.toString()); for (int i=0; i<jsonArray.length();i++){ JSONObject fila = (JSONObject) jsonArray.get(i); Articulo a = new Articulo(); a.setId(fila.getString("codc")); a.setNombre(fila.getString("nomc")); a.setPrecio(fila.getDouble("precio")); a.setImagen(fila.getString("imagen")); articuloList.add(a); } //Adaptador AdaptadorArticulo ap = new AdaptadorArticulo (articuloList,getApplication()); recyclerView.setLayoutManager( new LinearLayoutManager(getApplication())); recyclerView.setAdapter(ap); } catch (JSONException ex) { Toast.makeText(getApplication(),ex.getMessage(),Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplication(),error.getMessage(),Toast.LENGTH_SHORT).show(); } }); RequestQueue cola = Volley.newRequestQueue(this); cola.add(jsonObjectRequest); } }
true
cdbb7fa1ea0022cb410885c5f8c8fc95e587be82
Java
Romern/gms_decompiled
/sources/com/google/android/gms/nearby/sharing/view/ExpandableView.java
UTF-8
1,850
1.507813
2
[]
no_license
package com.google.android.gms.nearby.sharing.view; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import com.felicanetworks.mfc.C0126R; import com.google.android.libraries.view.text.ExpandableTextView; /* compiled from: :com.google.android.gms@[email protected] (120300-306758586) */ public class ExpandableView extends LinearLayout { /* renamed from: a */ public ExpandableTextView f81147a; public ExpandableView(Context context) { super(context); m67620a(context); } /* renamed from: a */ private final void m67620a(Context context) { int i; LayoutInflater.from(context).inflate((int) C0126R.C0128layout.sharing_view_expandable_titled_text, this); View findViewById = findViewById(C0126R.C0129id.expandableView); ExpandableTextView expandableTextView = (ExpandableTextView) findViewById(C0126R.C0129id.expandable_text); this.f81147a = expandableTextView; expandableTextView.f150655a = bmxv.m108567c(findViewById(C0126R.C0129id.toggle_icon)); if (!expandableTextView.f150657c && expandableTextView.f150655a.mo66813a()) { View view = (View) expandableTextView.f150655a.mo66814b(); if (!expandableTextView.mo70845a()) { i = 4; } else { i = 0; } view.setVisibility(i); } findViewById.setOnClickListener(new akja(this)); } public ExpandableView(Context context, AttributeSet attributeSet) { super(context, attributeSet); m67620a(context); } public ExpandableView(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); m67620a(context); } }
true
4f91311352b01789fa3f26eaae05365f52f9db7f
Java
tangchuanyan/bbb
/src/main/java/cn/itcast/aop/Book.java
UTF-8
281
2.265625
2
[]
no_license
package cn.itcast.aop; import org.springframework.stereotype.Controller; @Controller public class Book { public void add() { //目的:增强Book类里的add方法 ,要增强的方法即为切入点 System.out.println("类book的方法..........."); } }
true
6ff02588a65f612b33b119baa4726f83c2a3d953
Java
AlexBolot/Dronizone
/OrderService/src/main/java/fr/unice/polytech/entities/Coord.java
UTF-8
615
2.359375
2
[]
no_license
package fr.unice.polytech.entities; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Getter @Setter @ToString @EqualsAndHashCode @Entity public class Coord { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String lon; private String lat; public Coord() { } public Coord(String lon, String lat) { this.lon = lon; this.lat = lat; } }
true
03f088ddfc0b858cf40f9a305688c876854cc4aa
Java
zhaoqidev/Android_App
/src/cc/upedu/online/domin/QuestionListBean.java
UTF-8
2,941
2.46875
2
[]
no_license
package cc.upedu.online.domin; import java.util.List; public class QuestionListBean { private Entity entity; private String message; private String success; public Entity getEntity() { return entity; } public void setEntity(Entity entity) { this.entity = entity; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getSuccess() { return success; } public void setSuccess(String success) { this.success = success; } @Override public String toString() { return "CourseBean [entity=" + entity + ", message=" + message + ", success=" + success + "]"; } public class Entity{ private List<QuestionItem> questionList; private String totalPage; public List<QuestionItem> getQuestionList() { return questionList; } public void setQuestionList(List<QuestionItem> questionList) { this.questionList = questionList; } public String getTotalPage() { return totalPage; } public void setTotalPage(String totalPage) { this.totalPage = totalPage; } @Override public String toString() { return "Entity [questionList=" + questionList + ", totalPage=" + totalPage + "]"; } public class QuestionItem{ //公司名称 private String company; //同学头像 private String avatar; //职位 private String position; //问题内容 private String content; //发布时间 private String createTime; //问题id private String id; //同学姓名 private String name; //同学的用户id private String userId; public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } @Override public String toString() { return "QuestionItem [company=" + company + ", avatar=" + avatar + ", position=" + position + ", content=" + content + ", createTime=" + createTime + ", id=" + id + ", name=" + name + ", userId=" + userId + "]"; } } } }
true
4c0cea96dac8417942e40ac52bcc0e0757e3ae9c
Java
thetajwar2003/Java-Projects
/NumberConverter.java
UTF-8
4,027
3.953125
4
[]
no_license
import java.util.Scanner; import java.lang.StringBuffer; //this class allows me to reverse the numbers when I find bi and hex for dec import java.lang.Integer; //this class allows me to manipulate the input and see if the hex input is a digit or not public class NumberConverter{ public static void main (String[] args){ Scanner kb = new Scanner(System.in); System.out.println("What do you want to convert?\n" + "1)Binary\n"+ "2)Decimal\n" + "3)Hexadecimal"); int choice = kb.nextInt(); if (choice == 1){ System.out.print("Enter the Binary number you want to convert: "); int n = kb.nextInt(); bi2_dec_hex(n); //converts binary to decimal and hex } if (choice == 2){ System.out.print("Enter the Decimal number you want to convert: "); int n = kb.nextInt(); dec2_bi_hex(n); // call the methods } if (choice == 3){ System.out.print("Enter the hexadecimal number you want to convert: "); String n = kb.nextLine();//For some reason, whenever I use n, java automatically inputs 0 and ends the code so I used a heref String a = kb.nextLine();// if I get rid of n, the same thing happens hex2_dec_bi(a); // call the methods } } //CHECK TO SEE IF INPUT IS A BINARY public static boolean isItBinary(int n){ if (n % 10 > 1){ return false; } return true; } //BINARY TO REST public static void bi2_dec_hex(int n){ int print_one = n; //BINARY TO DECIMAL int ans = 0; int place_value = 0; if (isItBinary(n)){ while (n != 0){ ans += (n%10) * Math.pow(2,place_value); //the remainder * 2^of the place n = n / 10; //goes on to the next binary digit & changes the original input place_value++; // increases the power } System.out.println(print_one +" in decimal form is: " + ans); //DECIMAL TO HEX if (ans == 0){ System.out.println(print_one + " in hexadecimal form is: " + 0); } else{ String hex_list = "0123456789ABCDEF"; String hex = ""; while (ans != 0){ int num = ans%16; hex += hex_list.charAt(num); ans /= 16; } String reverse_list = new StringBuffer(hex).reverse().toString();// when you divide and flip the remainders System.out.println(print_one + " in hexadecimal form is: " + reverse_list); } } else{ System.out.println("Please enter a binary number"); } } //DECIMAL TO THE REST public static void dec2_bi_hex(int n){ int print_one = n; int temp = n; //DECIMAL TO BINARY String dec_bi = ""; if (n <= 4095){ while (n != 0){ dec_bi += n % 2; n /= 2; } String reverse_list = new StringBuffer(dec_bi).reverse().toString(); System.out.println(print_one + " in binary form is: " + reverse_list); //DECIMAL TO HEX String dec_hex = ""; String hex_list = "0123456789ABCDEF"; while (temp != 0){ int num = temp % 16; dec_hex += hex_list.charAt(num); temp /= 16; } String reverse_list2 = new StringBuffer(dec_hex).reverse().toString(); System.out.println(print_one + " in hexadecimal form is: " + reverse_list2); } else { System.out.println("Please enter a smaller number."); } } //HEX TO REST public static void hex2_dec_bi(String a){ a = a.toUpperCase(); String hex = "0123456789ABCDEF"; int ans = 0; //HEX TO DEC if (a.length() <= 3){ for(int i = 0; i < a.length(); i++){ char c = a.charAt(i); int hex_num = hex.indexOf(c);//checks the input and sees where in the string is the input ans += hex_num * Math.pow(16, i); //ex) if the user inputs a, A is the 10th character of string hex so the index of takes the place of letter a and I use it as an int } System.out.println( a + " in decimal form is: " + ans); //DEC TO BINARY int temp = ans; String hex_bi = ""; while (temp != 0){ hex_bi += temp % 2; temp /= 2; } String reverse_list = new StringBuffer(hex_bi).reverse().toString(); System.out.println(a + " in binary form is: " + reverse_list); } else { System.out.println("Please enter a smaller number."); } } }
true
a9579192275b3e797155a9e6751e775a6ff68a90
Java
GabeOchieng/ggnn.tensorflow
/data/libgdx/GwtGL20_glBindTexture.java
UTF-8
116
2.65625
3
[]
no_license
@Override public void glBindTexture(int target, int texture) { gl.bindTexture(target, textures.get(texture)); }
true
895211f4339329d4e8a258968a3e73f5fdcd6e29
Java
saralein/java-server
/server/src/main/java/com/saralein/server/middleware/AuthMiddleware.java
UTF-8
1,106
2.5
2
[]
no_license
package com.saralein.server.middleware; import com.saralein.server.authorization.Authorizer; import com.saralein.server.callable.Callable; import com.saralein.server.request.Request; import com.saralein.server.response.ErrorResponse; import com.saralein.server.response.Response; public class AuthMiddleware implements Middleware { private final Authorizer authorizer; private final String realm; private Callable next; public AuthMiddleware(Authorizer authorizer, String realm) { this.authorizer = authorizer; this.realm = realm; this.next = null; } @Override public Middleware apply(Callable callable) { next = callable; return this; } @Override public Response call(Request request) { if (authorizer.isAuthorized(request)) { return next.call(request); } return unauthorized(); } private Response unauthorized() { String basicRealm = String.format("Basic realm=\"%s\"", realm); return new ErrorResponse(401).respond("WWW-Authenticate", basicRealm); } }
true
8b3d23b788b6746b13238d08b4ff9edb44d89390
Java
hwa1049/kobis-utils
/KobisUtils/src/org/kobic/kobis/file/excel/obj/XProteinSequenceSheetObj.java
UTF-8
4,025
2.3125
2
[]
no_license
package org.kobic.kobis.file.excel.obj; import org.apache.ibatis.type.Alias; import org.apache.poi.xssf.usermodel.XSSFRow; import org.kobic.kobis.file.excel.obj.internal.AbstractSheetObj; import org.kobic.kobis.file.excel.obj.internal.OpenObj; import org.kobic.kobis.file.excel.obj.internal.PatentObj; import org.kobic.kobis.file.excel.obj.internal.ReferenceObj; @Alias("D1_ProteinSequence") public class XProteinSequenceSheetObj extends AbstractSheetObj implements OpenPatentReferenceInterface{ private String source; private String proteinName; private String accessionNo; private String sequence; private OpenObj open; private PatentObj patent; private ReferenceObj reference; public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getProteinName() { return proteinName; } public void setProteinName(String proteinName) { this.proteinName = proteinName; } public String getAccessionNo() { return accessionNo; } public void setAccessionNo(String accessionNo) { this.accessionNo = accessionNo; } public String getSequence() { return sequence; } public void setSequence(String sequence) { this.sequence = sequence; } public OpenObj getOpen() { if( this.open == null ) this.open = new OpenObj(); return open; } public void setOpen(OpenObj open) { this.open = open; } public PatentObj getPatent() { if( this.patent == null ) this.patent = new PatentObj(); return patent; } public void setPatent(PatentObj patent) { this.patent = patent; } public ReferenceObj getReference() { if( this.reference == null ) this.reference = new ReferenceObj(); return reference; } public void setReference(ReferenceObj reference) { this.reference = reference; } public static XProteinSequenceSheetObj getNewInstance(XSSFRow row) { return new XProteinSequenceSheetObj().getInstance(row); } @Override public XProteinSequenceSheetObj getInstance( XSSFRow row ) { XProteinSequenceSheetObj obj = new XProteinSequenceSheetObj(); for(int i=row.getFirstCellNum(); i<=row.getLastCellNum(); i++) { if( i == 0 ) obj.setAccess_num( this.getVal(row.getCell(i) ) ); else if( i == 1 ) obj.setSource( this.getVal(row.getCell(i) ) ); else if( i == 2 ) obj.setProteinName( this.getVal(row.getCell(i) ) ); else if( i == 3 ) obj.setAccessionNo( this.getVal(row.getCell(i) ) ); else if( i == 4 ) obj.setSequence( this.getVal(row.getCell(i) ) ); else if( i == 5 ) obj.getOpen().setOpenYn( this.getVal(row.getCell(i) ) ); else if( i == 6 ) obj.getOpen().setOpenUrl( this.getVal(row.getCell(i) ) ); else if( i == 7 ) obj.getPatent().setParentNo( this.getVal(row.getCell(i) ) ); else if( i == 8 ) obj.getPatent().setRegNo( this.getVal(row.getCell(i) ) ); else if( i == 9 ) obj.getReference().setReference( this.getVal(row.getCell(i) ) ); } return obj; } @Override public String getPrintLine() { String line = this.getAccess_num() + ","; line += this.getSource() + ","; line += this.getProteinName() + ","; line += this.getAccessionNo() + ","; line += this.getSequence() + ","; line += this.getOpen().getOpenYn() + ","; line += this.getOpen().getOpenUrl() + ","; line += this.getPatent().getParentNo() + ","; line += this.getPatent().getRegNo() + ","; line += this.getReference().getReference(); return line; } @Override public String getOpenYn() { // TODO Auto-generated method stub return this.getOpen().getOpenYn(); } @Override public String getOpenUrl() { // TODO Auto-generated method stub return this.getOpen().getOpenUrl(); } @Override public String getParentNo() { // TODO Auto-generated method stub return this.getPatent().getParentNo(); } @Override public String getRegNo() { // TODO Auto-generated method stub return this.getPatent().getRegNo(); } @Override public String getReferenceStr() { // TODO Auto-generated method stub return this.reference.getReference(); } }
true
e41849892125cab9c9558a82359d3f3417968d45
Java
kael-aiur/redis-mock
/src/main/java/com/github/zxl0714/redismock/SocketContextHolder.java
UTF-8
645
2.15625
2
[ "MIT" ]
permissive
package com.github.zxl0714.redismock; /** * @author snowmeow(yuki754685421 @ 163.com) * @date 2021-7-19 */ public class SocketContextHolder { private static final ThreadLocal<SocketAttributes> socketAttributesThreadLocal = new ThreadLocal<SocketAttributes>(); public static void setSocketAttributes(SocketAttributes socketAttributes) { socketAttributesThreadLocal.set(socketAttributes); } public static SocketAttributes getSocketAttributes() { return socketAttributesThreadLocal.get(); } public static void removeSocketAttributes() { socketAttributesThreadLocal.remove(); } }
true
a4a547f599c098bdc39af3a1bc8b66ef633de1bb
Java
LimeyJohnson/RandomProjects
/JavaWorkSpace/Programming Studio Assignment 1/src/HTML/Main.java
UTF-8
2,814
3.328125
3
[]
no_license
package HTML; import java.io.*; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class Main { //vGames, vUsers, vPlays are the main data structurs used in the program static Vector<Game> Vgames = new Vector<Game>(); static Vector<User> Vusers = new Vector<User>(); static Vector<Play> Vplays = new Vector<Play>(); //DateFormat to convert to and from our given Date format static DateFormat DateFormatter = new SimpleDateFormat("MM/dd/yyyy"); public static void main(String[] args){//process's the given file based on the specs of the project try { Scanner consoleScanner = new Scanner(System.in); System.out.printf("What file would you like: "); File file = new File(consoleScanner.next()); Scanner scanner = new Scanner(file); String line; //Process each line in the file and split it into tokens while((line = scanner.nextLine())!=null){ String[] tokens = line.split(" "); if(line.charAt(0)>=48&&line.charAt(0)<=57){//line is a game spec or end of file if(tokens[1].equals("END"))break;//end of the input file String name = tokens[1]; for(int i = 2; i<tokens.length;i++)name+=" "+tokens[i]; findGame(name).setPoints(Integer.parseInt(tokens[0])); } else{//line is user spec (joined or played a game) User user = findUser(tokens[0]); if(tokens[2].equals("JOIN")){//Join statment user.setDateJoined(DateFormatter.parse(tokens[1])); } else{//user played a game String gamename = tokens[2]; for(int i = 3; i<tokens.length;i++)gamename+=" "+tokens[i]; Game game = findGame(gamename); Play play = new Play(user,game,DateFormatter.parse(tokens[1])); Vplays.add(play); } } } } catch (FileNotFoundException e) {//file input error e.printStackTrace(); } catch (ParseException e) {//Date Parse error // TODO Auto-generated catch block e.printStackTrace(); } for(Play p: Vplays){//check all users Joined before they played a game if(p.user.DateJoined.after(p.date)){ System.err.println(p.user.Name+" played "+p.game+" before joining"); } } HtmlWriter HW = new HtmlWriter();//write HTML files HW.writeFiles(Vusers, Vgames, Vplays); } static Game findGame(String s ){//Check if the game exists with a certain name. Returns a new game if no game exists for(Game u: Vgames){ if(u.getName().equals(s)){ return u; } } Game game = new Game(s); Vgames.add(game); return game; } static User findUser(String name){//Check if the user exists with a certain name. Returns a new user if no game exists for(User u: Vusers){ if(u.getName().equals(name)){ return u; } } User user = new User(name); Vusers.add(user); return user; } }
true
aa3df3019002dd4bd0086db20de800d2ad66dfe5
Java
Porodin/SportCoachPublic
/MyProject/backend/src/main/java/com/sportCoach/config/ApplicationWebMvcConfig.java
UTF-8
1,759
2.015625
2
[]
no_license
package com.sportCoach.config; /* * @created 09/03/2021 - 16:37 * @project IntelliJ IDEA * @author Temnyakov Nikolay */ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc public class ApplicationWebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } @Bean public ViewResolver viewResolver() { final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/view/"); viewResolver.setSuffix(".html"); return viewResolver; } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns( "*" ) .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") .allowedHeaders("X-Auth-Token", "Content-Type") .allowCredentials(true) .maxAge(4800); } }
true
6aa27ad489bb491308ff7caf6fbf6f2524d19078
Java
blonsky95/London-Runner
/app/src/main/java/my/london/pablotrescoli/londonrunner/parkrun/RegisterNewUser.java
UTF-8
647
1.804688
2
[]
no_license
package my.london.pablotrescoli.londonrunner.parkrun; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import my.london.pablotrescoli.londonrunner.R; @SuppressLint("SetJavaScriptEnabled") public class RegisterNewUser extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webview); WebView webView = findViewById(R.id.webView1); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl(getString(R.string.parkrun_register_url)); } }
true
38eb5472e42939f9289baf68de127e49a6d82ba8
Java
navicore/augie
/libraries/Augie/src/main/java/com/onextent/augie/ments/DrawBase.java
UTF-8
2,394
2.4375
2
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
/** * copyright Ed Sweeney, 2012, 2013 all rights reserved */ package com.onextent.augie.ments; import java.util.Set; import android.graphics.Point; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import com.onextent.augie.AugieScape; import com.onextent.augie.Augiement; import com.onextent.augie.AugiementException; import com.onextent.augie.marker.AugLine; import com.onextent.augie.marker.impl.AugLineImpl; public abstract class DrawBase implements Augiement, OnTouchListener { protected AugieScape augieScape; public float closePixelDist = 25; static class VLine extends AugLineImpl { VLine(int top, int bottom, int x, float width) { super(new Point(x, top), new Point(x, bottom)); setWidth(width); } } static class HLine extends AugLineImpl { HLine(int left, int right, int y, float width) { super(new Point(left, y), new Point(right, y)); setWidth ( width ); } } public DrawBase() { super(); } static public boolean isVerticalLine(AugLine l) { if (l.getP1().x == l.getP2().x) return true; return false; } @Override public void onCreate(AugieScape av, Set<Augiement> helpers) throws AugiementException { augieScape = av; } protected boolean xcloseToEdge(MotionEvent e) { float x = e.getX(); if ( x < closePixelDist ) return true; if ( x > (augieScape.getWidth() - closePixelDist )) return true; return false; } protected boolean ycloseToEdge(MotionEvent e) { float y = e.getY(); if ( y < closePixelDist ) return true; if ( y > (augieScape.getHeight() - closePixelDist )) return true; return false; } protected boolean closeToEdge(MotionEvent e) { return xcloseToEdge(e) || ycloseToEdge(e); } @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub return false; } @Override public void updateCanvas() { // TODO Auto-generated method stub } @Override public void stop() { //noop } @Override public void resume() { //noop } @Override public void clear() { //noop } public float getClosePixelDist() { return closePixelDist; } public void setClosePixelDist(float sz) { closePixelDist = sz; } }
true
d4f42cb51639f4d280d6015f777db60d146a94f3
Java
luBubble/OrderFood
/src/dao/imp/OrderItemDaoImp.java
UTF-8
2,491
2.46875
2
[]
no_license
package dao.imp; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import beans.Cart; import beans.Food; import beans.OrderItem; import dao.inf.OrderItemDao; import db.DBHelper; public class OrderItemDaoImp implements OrderItemDao { @Override public boolean addOrderItem(OrderItem orderItem) throws SQLException { // TODO Auto-generated method stub Connection conn=null; PreparedStatement ps=null; try { conn=DBHelper.getConnection(); if(conn!=null) { String sql="insert into orderitem(oioid,oifid,oiquantity,oiprices) value(" +orderItem.getOioid()+","+orderItem.getOifid()+","+orderItem.getOiquantity()+","+ orderItem.getOiprices()+")"; ps = conn.prepareStatement(sql); ps.executeUpdate(); } else { System.out.println("数据库连接失败"); return false; } } catch(Exception e) { e.printStackTrace(); } finally { DBHelper.closeAction(ps, null, null, conn); } return true; } @Override public List<OrderItem> getAllOrderItem(int oid) throws SQLException { // TODO Auto-generated method stub Connection conn=null; PreparedStatement ps=null; ResultSet rs = null; List<OrderItem> orderItems=new ArrayList<>(); try { conn=DBHelper.getConnection(); if(conn!=null) { String sql="select * from orderItem where oioid="+oid; ps=conn.prepareStatement(sql); rs=ps.executeQuery(sql); if(rs!=null) { while(rs.next()) { FoodDaoImp foodDao=new FoodDaoImp(); Food food=foodDao.getFood(rs.getInt("oifid")); OrderItem orderItem=new OrderItem(); orderItem.setOiid(rs.getInt("oiid")); orderItem.setOioid(rs.getInt("oioid")); orderItem.setOifid(rs.getInt("oifid")); orderItem.setOiquantity(rs.getInt("oiquantity")); orderItem.setOiprices(rs.getDouble("oiprices")); orderItem.setFname(food.getFname()); orderItem.setFprice(food.getFprice());//单价 orderItem.setFpicture(food.getFpicture()); orderItems.add(orderItem); } } else { System.out.println("暂无商家"); return null; } } else { System.out.println("数据库连接失败"); return null; } } catch(Exception e) { e.printStackTrace(); } finally { DBHelper.closeAction(ps, rs, null, conn); } return orderItems; } }
true
aa7c8b31d1dde749bc4a7d7a57899c195adcc54c
Java
YoooBrayan/AppAjedrez
/app/src/main/java/org/itiud/modelo/Alfil.java
UTF-8
3,397
3.15625
3
[]
no_license
package org.itiud.modelo; import java.util.Arrays; public class Alfil extends Ficha { public Alfil(int[] coordenadas, int color, Ajedrez matriz, char letra) { super(coordenadas, color, matriz, letra); } public void posiblesMovimientos() { this.movimientos.clear(); moverDiagonalIzquierdaAbajo(); moverDiagonalIzquierdaArriba(); moverDiagonalDerechaAbajo(); moverDiagonalDerechaArriba(); } public void moverDiagonalIzquierdaArriba() { boolean b = true; int fila = this.coordenadas[0] - 1; int col = this.coordenadas[1] - 1; while (fila >= 0 && col >= 0 && b) { if (this.matriz.getMatriz()[fila][col] == null || (this.matriz.getMatriz()[fila][col] != null && this.matriz.getMatriz()[fila][col].getColor() != this.color)) { this.movimientos.add(new int[]{fila, col}); if(this.matriz.getMatriz()[fila][col] != null && this.matriz.getMatriz()[fila][col].getColor() != this.color){ b = false; } } else { b = false; } fila--; col--; } } public void moverDiagonalDerechaArriba() { boolean b = true; int fila = this.coordenadas[0] - 1; int col = this.coordenadas[1] + 1; while (fila >= 0 && col <= 7 && b) { if (this.matriz.getMatriz()[fila][col] == null || (this.matriz.getMatriz()[fila][col] != null && this.matriz.getMatriz()[fila][col].getColor() != this.color)) { this.movimientos.add(new int[]{fila, col}); if(this.matriz.getMatriz()[fila][col] != null && this.matriz.getMatriz()[fila][col].getColor() != this.color){ b = false; } } else { b = false; } fila--; col++; } } public void moverDiagonalDerechaAbajo() { boolean b = true; int fila = this.coordenadas[0] + 1; int col = this.coordenadas[1] + 1; while (fila <= 7 && col <= 7 && b) { if (this.matriz.getMatriz()[fila][col] == null || (this.matriz.getMatriz()[fila][col] != null && this.matriz.getMatriz()[fila][col].getColor() != this.color)) { this.movimientos.add(new int[]{fila, col}); if(this.matriz.getMatriz()[fila][col] != null && this.matriz.getMatriz()[fila][col].getColor() != this.color){ b = false; } } else { b = false; } fila++; col++; } } public void moverDiagonalIzquierdaAbajo() { boolean b = true; int fila = this.coordenadas[0] + 1; int col = this.coordenadas[1] - 1; while (fila <= 7 && col >= 0 && b) { if (this.matriz.getMatriz()[fila][col] == null || (this.matriz.getMatriz()[fila][col] != null && this.matriz.getMatriz()[fila][col].getColor() != this.color)) { this.movimientos.add(new int[]{fila, col}); if(this.matriz.getMatriz()[fila][col] != null && this.matriz.getMatriz()[fila][col].getColor() != this.color){ b = false; } } else { b = false; } fila++; col--; } } }
true
decbe087e156c9fcf598196969cd19a3e8c4454c
Java
waterlu/spring-inside
/src/main/java/cn/lu/spring/ioc/UserService.java
UTF-8
154
1.71875
2
[ "Apache-2.0" ]
permissive
package cn.lu.spring.ioc; /** * @author lu * @date 2018/5/22 */ public interface UserService { User get(Long id); boolean save(User user); }
true
ecb05bd478f170265ad70853bd53dd62e32171f5
Java
RedSunCMX/benchmark
/packing_utilities/winners/CITYU-ZHU/source_code/src/feasibilityCheck/Statistics.java
UTF-8
6,940
2.359375
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2020. Huawei Technologies Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package feasibilityCheck; import feasibilityCheck.entity.*; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class Statistics { private String inputDir; private String outputDirOld; private String outputDirNew; private File orders; private FileWriter resultWriter; public Statistics(String inputDir, String outputDirOld, String outputDirNew, String resultFile) throws IOException { this.inputDir = inputDir; this.outputDirOld = outputDirOld; this.outputDirNew = outputDirNew; this.orders = new File(inputDir); if (!this.orders.isDirectory()) { throw new IOException("inputDir and outputDir should be directories."); } // Write the results to file. if (resultFile == null || resultFile.equals("")) { resultWriter = null; } else { resultWriter = new FileWriter(resultFile, false); } } public Statistics(String inputDir, String outputDirOld, String outputDirNew) throws IOException { this(inputDir, outputDirOld, outputDirNew, null); } public void calc() throws IOException { // Calculate the volumes of boxes and bins by groups of the numbers of bins Map<Integer, Double> boxesVolumeStat = new HashMap<>(); Map<Integer, Double> binsVolumeStatOld = new HashMap<>(); Map<Integer, Double> binsVolumeStatNew = new HashMap<>(); Map<Integer, Integer> orderNumStat = new HashMap<>(); for (File order: Objects.requireNonNull(this.orders.listFiles())) { String orderName = order.getName(); String orderNameOri = orderName.replace("_d", ""); Check orderCheckOld; try { orderCheckOld = Check.getOrderCheck(this.inputDir, this.outputDirOld, orderName); } catch (IllegalArgumentException e) { print("Order missed in old results: " + orderNameOri); continue; } Check orderCheckNew; try { orderCheckNew = Check.getOrderCheck(this.inputDir, this.outputDirNew, orderName); } catch (IllegalArgumentException e) { print("Order missed in new results: " + orderNameOri); continue; } Map<Integer, Bin> allBinsOld = orderCheckOld.getAllBins(); Map<Integer, Bin> allBinsNew = orderCheckNew.getAllBins(); ArrayList<Box> inputBoxes = orderCheckOld.getInputBoxes(); double boxesVolume = 0.; for (Box box: inputBoxes) { boxesVolume += box.getLength() * box.getWidth() * box.getHeight(); } double binsVolume1 = 0.; for (Bin bin: allBinsOld.values()) { binsVolume1 += bin.getLength() * bin.getWidth() * bin.getHeight() * 1000; } double binsVolume2 = 0.; for (Bin bin: allBinsNew.values()) { binsVolume2 += bin.getLength() * bin.getWidth() * bin.getHeight() * 1000; } int binNum = allBinsOld.size(); boxesVolumeStat.put(binNum, boxesVolumeStat.getOrDefault(binNum, 0.) + boxesVolume); binsVolumeStatOld.put(binNum, binsVolumeStatOld.getOrDefault(binNum, 0.) + binsVolume1); binsVolumeStatNew.put(binNum, binsVolumeStatNew.getOrDefault(binNum, 0.) + binsVolume2); orderNumStat.put(binNum, orderNumStat.getOrDefault(binNum, 0) + 1); } double totalBoxesVolume = 0.; double totalBinsVolumeOld = 0.; double totalBinsVolumeNew = 0.; Integer totalOrderNum = 0; print("truck_num order_num old_rate new_rate diff"); for (Integer binNum: boxesVolumeStat.keySet()) { totalBoxesVolume += boxesVolumeStat.get(binNum); totalBinsVolumeOld += binsVolumeStatOld.get(binNum); totalBinsVolumeNew += binsVolumeStatNew.get(binNum); totalOrderNum += orderNumStat.get(binNum); double packingRateOld = boxesVolumeStat.get(binNum) / binsVolumeStatOld.get(binNum); double packingRateNew = boxesVolumeStat.get(binNum) / binsVolumeStatNew.get(binNum); String statMessage = String.join( " ", binNum.toString(), orderNumStat.get(binNum).toString(), String.format("%.4f", packingRateOld), String.format("%.4f", packingRateNew), String.format("%.4f", packingRateNew - packingRateOld) ); print(statMessage); } double totalPackingRateOld = totalBoxesVolume / totalBinsVolumeOld; double totalPackingRateNew = totalBoxesVolume / totalBinsVolumeNew; String totalStatMessage = String.join( " ", "overall", totalOrderNum.toString(), String.format("%.4f", totalPackingRateOld), String.format("%.4f", totalPackingRateNew), String.format("%.4f", totalPackingRateNew - totalPackingRateOld) ); print(totalStatMessage); if (this.resultWriter != null) { this.resultWriter.close(); } } /** * Print to the console or the file. */ private void print(String message) throws IOException { if (this.resultWriter == null) { System.out.println(message); } else { this.resultWriter.write(message + '\n'); } } public static void main(String[] args) throws IOException { String inputDir = ".\\data\\data0923\\input"; String outputDirOld = ".\\data\\result1"; String outputDirNew = ".\\data\\result3"; String resultFile = ".\\result\\statResult3.txt"; Statistics statistics = new Statistics(inputDir, outputDirOld, outputDirNew, resultFile); statistics.calc(); } }
true
397b36aeb79c12c10d39aee1ffee7f82c9a634ef
Java
zhangzibao/my_qq
/src/main/java/com/springboot/my_qq/dao/UserMapper.java
UTF-8
613
1.890625
2
[]
no_license
package com.springboot.my_qq.dao; import com.springboot.my_qq.model.User; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserMapper { int deleteByPrimaryKey(Integer id); int insert(User record); List<User> findAllUser(String username); int insertSelective(User record); int get_user_id(String username); String get_user_id_by_openId(String open_id); User selectByPrimaryKey(Integer id); String find_password(String username); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
true
bfffac8af74d0d597eb7b04a8e58a615183a2c7c
Java
pyromobile/nubomedia-ouatclient-src
/android/LiveTales/app/src/main/java/com/zed/livetales/models/user/User.java
UTF-8
4,049
2.34375
2
[ "Apache-2.0" ]
permissive
package com.zed.livetales.models.user; import android.os.Parcel; import android.os.Parcelable; import com.zed.livetales.models.LobbyType; /** * Created by jemalpartida on 24/11/2016. */ public class User implements Parcelable { public User() { this.id = ""; this.name = ""; this.password = ""; this.secretCode = ""; this.nick = "Guest"; this.lobby = LobbyType.Free; this.roomId = ""; this.acceptedRoomInvitation = false; this.narrator = false; } public User(Parcel in) { this.id = in.readString(); this.name = in.readString(); this.password = in.readString(); this.secretCode = in.readString(); this.nick = in.readString(); this.lobby = in.readByte() == 0 ? LobbyType.Tale : LobbyType.Free; this.roomId = in.readString(); this.acceptedRoomInvitation = in.readByte() != 0; this.narrator = in.readByte() != 0; } public boolean isLogged() { return !this.id.isEmpty() && !this.name.isEmpty(); } public void setProfile(String id, String name, String password, String secretCode) { this.id = id; this.name = name; this.password = password; this.secretCode = secretCode; } public void reset() { this.id = ""; this.name = ""; this.password = ""; this.secretCode = ""; this.nick = "Guest"; this.lobby = LobbyType.Free; this.roomId = ""; this.acceptedRoomInvitation = false; this.narrator = false; } public void setNick(String nick) { this.nick = ( ( nick == null ) || nick.isEmpty() ) ? "Guest" : nick; } public String getNick() { return this.nick; } public void setLobby(LobbyType lobby) { this.lobby = lobby; } public LobbyType getLobby() { return this.lobby; } public void setRoomId(String roomId) { this.roomId = roomId; } public String getRoomId() { return this.roomId; } public void setAcceptedRoomInvitation(boolean acceptedRoomInvitation) { this.acceptedRoomInvitation = acceptedRoomInvitation; } public boolean isAcceptedRoomInvitation() { return this.acceptedRoomInvitation; } public void setNarrator(boolean narrator) { this.narrator = narrator; } public boolean isNarrator() { return this.narrator; } /*============================================================================================*/ /* Override from Parcelable */ /*============================================================================================*/ @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeString( this.id ); parcel.writeString( this.name ); parcel.writeString( this.password ); parcel.writeString( this.secretCode ); parcel.writeString( this.nick ); parcel.writeByte( (byte)( (this.lobby == LobbyType.Tale) ? 0 : 1 ) ); parcel.writeString( this.roomId ); parcel.writeByte( (byte)( this.acceptedRoomInvitation ? 1 : 0 ) ); parcel.writeByte( (byte)( this.narrator ? 1 : 0 ) ); } public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { public User createFromParcel(Parcel in) { return new User( in ); } public User[] newArray(int size) { return new User[size]; } }; private String id; private String name; private String password; private String secretCode; private String nick; private LobbyType lobby; private String roomId; private boolean acceptedRoomInvitation; private boolean narrator; }
true
331609672abadc6e0e5f3c19b7d63771def20711
Java
yanchangyou/ware
/GHCC-1/code/ware/lang/impl/ether/concept/activeconcept/Ether$Request.java
UTF-8
634
2.171875
2
[]
no_license
package ware.lang.impl.ether.concept.activeconcept; import ware.lang.design.concept.activeconcept.Request; import ware.lang.design.concept.staticconcept.WareProtocolData; /** * request : ware的请求<br> * ware之间通过request来请求服务, 然后通过response来响应<br> * <br> * * @author yanchangyou * @date 2010-8-18 23:40:57 */ public class Ether$Request extends Ether$Deliver implements Request { public void execute() { // TODO Auto-generated method stub } public WareProtocolData getRequestWareProtocolData() { // TODO Auto-generated method stub return null; } }
true
341b1a250877fa7c866be28b3e1b786fbedd3d4a
Java
centurybits504/corejava
/src/Keywords/InterafaceKeywordExample.java
UTF-8
455
3.75
4
[]
no_license
package Keywords; /*Interface Keyword Example: Providing implementaion for Vehicle_4 interface using MyCar_2 class*/ interface Vehicle_3{ public String breaks(); } class MyCar_2 implements Vehicle_3{ @Override public String breaks() { return "WaggonCar"; } } public class InterafaceKeywordExample { public static void main(String[] args) { MyCar_2 obj = new MyCar_2(); System.out.println(obj.breaks()); } }
true
264ba620c342ab2ebad383265af6b8afd06b522d
Java
obaralic/control-widget
/Toggler/src/com/obaralic/toggler/service/commands/content/ContentStateChangeServiceCommandTemplate.java
UTF-8
2,301
1.710938
2
[]
no_license
/* * Copyright 2013 oBaralic, Inc. (owner Zivorad Baralic) * ____ ___ * ____ / __ )____ __________ _/ (_)____ * / __ \/ __ / __ `/ ___/ __ `/ / / ___/ * / /_/ / /_/ / /_/ / / / /_/ / / / /__ * \____/_____/\__,_/_/ \__,_/_/_/\___/ * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.obaralic.toggler.service.commands.content; import android.content.Context; import com.obaralic.toggler.service.ContentStateChangeService; import com.obaralic.toggler.utilities.analytics.AnalyticsFactory; import com.obaralic.toggler.utilities.analytics.AnalyticsFactory.AnalyticsProviderType; import com.obaralic.toggler.utilities.analytics.AnalyticsInterface; import com.obaralic.toggler.utilities.debug.LogUtil; public class ContentStateChangeServiceCommandTemplate implements ContentStateChangeServiceInterface { private static final String TAG = LogUtil.getTag(ContentStateChangeServiceCommandTemplate.class); @Override public void execute(ContentStateChangeService togglerService) { LogUtil.d(TAG, "Called execute"); doBeforeToggle(togglerService); performToggle(togglerService); doAfterToggle(togglerService); } @Override public void doBeforeToggle(Context context) { AnalyticsInterface analytics = AnalyticsFactory.get(AnalyticsProviderType.FLURRY_ANALYTICS); analytics.startAnalyticsSession(context); } @Override public void performToggle(Context context) { } @Override public void doAfterToggle(Context context) { AnalyticsInterface analytics = AnalyticsFactory.get(AnalyticsProviderType.FLURRY_ANALYTICS); analytics.endAnalyticsSession(context); } }
true
121517bc81d5d705ff7601cc00fbd611d511ca2e
Java
AbdullahHalari/JAVA
/project/bankaccount/Loan.java
UTF-8
4,975
3.3125
3
[]
no_license
package bankaccount; import java.util.*; public class Loan extends Account{ Scanner sc = new Scanner(System.in); Loan(String Name, int phone){ super(Name, phone); } public void home(){ System.out.println("##########################################"); System.out.println("\tLOAN CONDITIONS: \n\tInterest Rate is 4% after 12 months \n\tMinimum Amount 2,00,000 \n\tMaximum 20,00,000 \n\tTime Period 2 to 5 years"); System.out.println("##########################################"); System.out.println("\tHow much loan you want:"); int loan = sc.nextInt(); System.out.println("\tHow many years would you like to repay?"); int time = sc.nextInt(); if(loan >= 200000){ if(time==1){ System.out.println("\tSUCCESSFULLY your loan application accepted "); System.out.println("\tyou repay" + loan + "with 12months"); } else{ System.out.println("\tSUCCESSFULLY your loan application accepted "); int interest = loan*4/100; int year = (time-1)*interest; System.out.println("\tyou repay " + (loan+year) + " with in " + time + " years" ); } } else{ System.out.println("\tyou must apply for loan upto 2,00,000\n"); } } public void bussiness(){ System.out.println("##########################################"); System.out.println("\tLOAN CONDITIONS: \n\tInterest Rate is 2% \n\tMinimum Amount 1,00,000 \n\tMaximum 10,00,000 \n\tTime Period 1 to 3 years"); System.out.println("##########################################"); System.out.println("\tHow much loan you want:"); int loan = sc.nextInt(); System.out.println("\tHow long would you like to repay?"); int time = sc.nextInt(); if(loan >= 100000){ System.out.println("\tSUCCESSFULLY your loan application accepted "); int interest = loan*2/100; int year = (time)*interest; System.out.println("\tyou repay " + (loan+year) + " with in " + time + " years" ); } else{ System.out.println("\tyou must apply for loan upto 1,00,000\n"); } } public void other(){ System.out.println("##########################################"); System.out.println("\tLOAN CONDITIONS: \n\tInterest Rate is 3% \n\tMinimum Amount 50,000 \n\tMaximum 5,00,000 \n\tTime Period 1 to 4 years"); System.out.println("##########################################"); System.out.println("\tHow much loan you want:"); int loan = sc.nextInt(); System.out.println("\tHow many years would you like to repay ?"); int time = sc.nextInt(); System.out.println("\tWhat are you borrowing for ?"); String others = sc.next(); if(loan >= 50000){ System.out.println("\tSUCCESSFULLY your loan application for " + others + " accepted."); int interest = loan*3/100; int year = (time)*interest; System.out.println("\tyou repay " + (loan+year) + " with in " + time + " years" ); } else{ System.out.println("\tyou must apply for loan upto 50,000\n"); } } public void loan_types(){ System.out.println("\tdo you want loan:"); String ask_loan = sc.nextLine(); if(ask_loan.equals("yes")){ boolean quit = false; int a; do{ System.out.println("\n\tDo You want to: \n\t1]LOAN FOR HOME\n\t2]LOAN FOR BUSSINESS\n\t3]LOAN FOR OTHERS \n\t4] Quit\n\tEnter your choice: "); a = sc.nextInt(); switch(a){ case 1: home(); break; case 2: bussiness(); break; case 3: other(); break; case 4: quit = true; break; default: System.out.println("\tInvalid option!\n"); break; } }while(quit!=true); } else { System.out.println("\tThank you for your response\n"); } } }
true
56b6a6a24e030ec462ad48a4e396be6c99ab78ce
Java
shitallondhe/NavigationView-Master
/app/src/main/java/com/example/shitalbharatlondhe/navigationview_master/SteelGradeFragment.java
UTF-8
3,367
2.265625
2
[]
no_license
package com.example.shitalbharatlondhe.navigationview_master; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; /** * Created by Shital Bharat Londhe on 25-Nov-16. */ public class SteelGradeFragment extends Fragment { EditText mEdtHardness,mEdtCarbonContent,mEdtTensileStrngth,mEdtGrade; TextView mTxtHardness,mTxtCarbonCotent,mTxtTesileStrength,mTxtGrade; Button mBtnResult; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate (R.layout.fragment_steel_grade, container, false); mEdtHardness =(EditText)v.findViewById(R.id.edtHardness); mEdtCarbonContent =(EditText)v.findViewById(R.id.edtCarbonContent); mEdtTensileStrngth =(EditText)v.findViewById(R.id.edtTensileStrength); mEdtGrade =(EditText)v.findViewById(R.id.edtGrde); mTxtHardness = (TextView)v.findViewById(R.id.txtHardness); mTxtCarbonCotent = (TextView)v.findViewById(R.id.txtCarbonContent); mTxtTesileStrength = (TextView)v.findViewById(R.id.txtTensileStrength); mTxtGrade = (TextView)v.findViewById(R.id.txtGrade); mBtnResult =(Button)v.findViewById(R.id.btnResult); mEdtHardness.requestFocus(); mBtnResult.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mEdtHardness.getText().length()>0 && mEdtCarbonContent.getText().length()>0 && mEdtTensileStrngth.getText().length()>0) { int hardness; double carbon_content, tensile_strength; hardness = Integer.parseInt(mEdtHardness.getText().toString()); carbon_content = Double.parseDouble(mEdtCarbonContent.getText().toString()); tensile_strength = Double.parseDouble(mEdtTensileStrngth.getText().toString()); if (hardness > 50 && carbon_content < 0.7 && tensile_strength > 5600) { mEdtGrade.setText("Grade is 10 "); } else if (hardness > 50 && carbon_content < 0.7 && tensile_strength < 5600) { mEdtGrade.setText("Grade is 9 "); } else if (hardness < 50 && carbon_content < 0.7 && tensile_strength > 5600) { mEdtGrade.setText("Grade is 8 "); } else if (hardness > 50 && carbon_content < 0.7 && tensile_strength > 5600) { mEdtGrade.setText("Grade is 7 "); } else if (hardness > 50 || carbon_content < 0.7 || tensile_strength > 5600) { mEdtGrade.setText("Grade is 6"); } else { mEdtGrade.setText("Grade is 5"); } } else { Toast.makeText(getActivity(),"Plz Enter All Fields",Toast.LENGTH_LONG).show(); } mEdtHardness.requestFocus(); } }); return v; } }
true
606163ee90e1b9835907be3f3fe0e0cf826cfb50
Java
liwenzhi/header_uc_viewPager
/src/com/example/uc_viewPager/fragment/MyFragment2.java
UTF-8
750
2.21875
2
[]
no_license
package com.example.uc_viewPager.fragment; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * 碎片2 */ public class MyFragment2 extends Fragment { TextView textView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { textView = new TextView(getActivity()); textView.setGravity(Gravity.CENTER); textView.setText("碎片 2"); textView.setTextSize(40); textView.setBackgroundColor(Color.RED); return textView; } }
true
6396066a336d9e154176795e48e5b6c69ff38208
Java
huanghaoxuan/hhxMVC
/src/main/java/com/hhx/core/annotation/Service.java
UTF-8
476
2.015625
2
[]
no_license
package com.hhx.core.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @Author: HuangHaoXuan * @Email: [email protected] * @github https://github.com/huanghaoxuan * @Date: 2019/9/19 11:36 * @Version 1.0 */ // Service注解,用于标记Service层的组件 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Service { }
true
63f327e2100ec744db56224a47fa61697516c686
Java
ThiriWai26/AllBugFire
/app/src/main/java/com/example/bugfire/model/TopicCategories.java
UTF-8
273
1.65625
2
[]
no_license
package com.example.bugfire.model; import com.google.gson.annotations.SerializedName; public class TopicCategories { @SerializedName("name") public String name; @SerializedName("type") public String type; @SerializedName("id") public int id; }
true
9205faeada9507822cf5f9cc58cdf11e9b767918
Java
pocoman/pocoProject
/javaWork/Quita/src/MyF/_main.java
UTF-8
153
1.710938
2
[]
no_license
package MyF; public class _main { public static void main(String [] args) { System.out.println(Function.RandomInt(100, 1)); } }
true
1dcf130c7e7049f2267151985bcd53e465697892
Java
jiachen1120/RESTful_demo
/src/main/java/com/jiachen/home/service/IHomeService.java
UTF-8
208
1.601563
2
[]
no_license
package com.jiachen.home.service; import java.util.List; import com.jiachen.home.entity.JcHome; public interface IHomeService { public List<JcHome> getUserList(); public void addUser(JcHome jchome); }
true
bfbe22afe6382d48dc77488e397db4f6c63d02e5
Java
ChanWoongLee/Algorithm
/practice/B11279.java
UHC
1,445
3.375
3
[]
no_license
package practice; import java.util.ArrayList; import java.util.Scanner; public class B11279 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int k=sc.nextInt(); long[] h = new long[k]; ArrayList<Long> ans = new ArrayList<Long>(); int index=0; for (int i = k; i >0 ; i--) { long value = sc.nextLong(); if (value==0) { if(index==0) ans.add((long) 0); else { bulidMaxHeap(h, index+1); ans.add(h[0]); for (int j = 0; j < index; j++) { h[j]=h[j+1]; } h[index]=0; index--; } } else { h[index]=value; index++; } } for (int i = 0; i < ans.size(); i++) { System.out.println(ans.get(i)); } } static void bulidMaxHeap(long[] h, int n) { for (int i = n ; i >=0; i--) { heapify(h,i,n+1); } } static void heapify(long[] h , int index, int n) {// i ϰϵ n̻ ǵ! int leftChild = index*2+1; int rightChild =leftChild +1 ; int large1=0; if(leftChild>=n&&rightChild>=n) return; if(h[leftChild]>h[index]) large1=leftChild; else large1=index; if(rightChild<n && h[rightChild]>h[large1]) large1=rightChild; if(large1!=index) { swap(h,large1,index); heapify(h,large1,n); } if(large1==index)return; } static void swap(long[] h ,int i, int j) { long save=0; save=h[i]; h[i]=h[j]; h[j]=save; } }
true
05cbd3ed2748a33e8ae44a5a440a46e8fae95dc0
Java
bePartOf-Creation/Deitel-Exercise
/src/com/javaChapter4/SumTenIntegerApp.java
UTF-8
265
2.203125
2
[]
no_license
package com.javaChapter4; public class SumTenIntegerApp { public static void main(String[] args) { SumTenIntegers sumTenInteger = new SumTenIntegers(); sumTenInteger.sumIntegersOfTenNumbers(); sumTenInteger.displaySumMessage(); } }
true
98b47889970a0b26b01c1974fec9c81d4f3c2a17
Java
BlackCat1606/QuestionsResponses
/src/javafxapplication3/ChoiceController.java
UTF-8
2,426
2.421875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javafxapplication3; import Code.Joueur; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXRadioButton; import java.net.URL; import java.util.ResourceBundle; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.fxml.Initializable; import static javafxapplication3.Partie.Jcourant; /** * FXML Controller class * * @author BLACKCAT */ public class ChoiceController implements Initializable { // Controleur des choix aprés le duel @FXML JFXRadioButton p1; @FXML JFXRadioButton p2; @FXML JFXRadioButton p3; @FXML JFXButton Confirmer; public static Joueur winner; public static boolean challengeur; public static int lastpos; public static int newpos; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO Confirmer.setDisable(true); ChangeListener<Boolean> ConfirmerListener = new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { Confirmer.setDisable(p1.isSelected() ==false && p2.isSelected()==false && p3.isSelected()==false ); } }; p1.selectedProperty().addListener(ConfirmerListener); p2.selectedProperty().addListener(ConfirmerListener); p3.selectedProperty().addListener(ConfirmerListener); p1.setOnMouseClicked(v->{ p2.setSelected(false); p3.setSelected(false); }); p2.setOnMouseClicked(v->{ p1.setSelected(false); p3.setSelected(false); }); p3.setOnMouseClicked(v->{ p2.setSelected(false); p1.setSelected(false); }); } public void confirmer() /// Confirmer votre choix { if(p1.isSelected()) { Jcourant.setAvancement(newpos); } if(p2.isSelected()) { Jcourant = winner; Partie.Namej.setText("Le tour est à : "+Jcourant.getNom()); } if(p3.isSelected()) { // prendre la main } } }
true
d5a7cb4f955d5648d8a005e34b9bf8cda5d5238e
Java
nntoan/vietspider
/client-plugin/src/main/java/org/vietspider/content/ImportDataPlugin.java
UTF-8
945
1.789063
2
[ "Apache-2.0" ]
permissive
/*************************************************************************** * Copyright 2001-2008 The VietSpider All rights reserved. * **************************************************************************/ package org.vietspider.content; import org.eclipse.swt.widgets.Control; import org.vietspider.ui.services.ClientRM; /** * Author : Nhu Dinh Thuan * [email protected] * Aug 14, 2008 */ public class ImportDataPlugin extends AdminDataPlugin { private String label; public ImportDataPlugin() { ClientRM resources = new ClientRM("Plugin"); label = resources.getLabel(getClass().getName()+".itemImportData"); } @Override public boolean isValidType(int type) { return type == DOMAIN; } public String getLabel() { return label; } public void invoke(Object...objects) { if(!enable) return; final Control control = (Control) objects[0]; new ImportDataDialog(control.getShell()); } }
true
ef7c3a4633938b86ea526f0aac66e547ba90062c
Java
AnastasiaKuznetzova/Miles
/miles.java
UTF-8
255
2.78125
3
[]
no_license
public class Main { public static void main(String[] args) { int ticketPriceInKopecks = 1300000; int milesInKopecks = 2000; int totalMiles = ticketPriceInKopecks / milesInKopecks; System.out.println(totalMiles); } }
true
aeb453fd34e9ee567aad91772583e07345600136
Java
mateuszstaszkow/food-finder
/src/main/java/com/foodfinder/user/service/AccountService.java
UTF-8
1,729
2.15625
2
[]
no_license
package com.foodfinder.user.service; import com.foodfinder.container.configuration.security.LoggedUserGetter; import com.foodfinder.day.domain.dto.DayDTO; import com.foodfinder.user.domain.dto.BasicUserDTO; import com.foodfinder.user.domain.entity.User; import com.foodfinder.user.domain.mapper.UserMapper; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; @Service @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class AccountService { private final UserService userService; private final LoggedUserGetter loggedUserGetter; private final UserMapper userMapper; public BasicUserDTO getAccount() { User loggedUser = loggedUserGetter.getLoggedUser(); return userMapper.toBasicDto(loggedUser); } public void updateAccount(BasicUserDTO user) { Long loggedUserId = loggedUserGetter.getLoggedUser().getId(); userService.updateBasicUser(loggedUserId, user); } public List<DayDTO> getAccountDays(Date from, Date to) { Long loggedUserId = loggedUserGetter.getLoggedUser().getId(); return userService.getUserDays(loggedUserId, from, to); } public DayDTO getAccountDays(Date date) { Long loggedUserId = loggedUserGetter.getLoggedUser().getId(); return userService.getUserDay(loggedUserId, date); } public ResponseEntity<?> addOrUpdateAccountDay(DayDTO dayDTO) { Long loggedUserId = loggedUserGetter.getLoggedUser().getId(); return userService.addOrUpdateUserDay(loggedUserId, dayDTO); } }
true