text
stringlengths
14
410k
label
int32
0
9
public boolean equals(final Object o) { if (!(o instanceof Method)) { return false; } Method other = (Method) o; return name.equals(other.name) && desc.equals(other.desc); }
2
public void changeDictionary(String filePath) { updateDictFile(filePath); if (!configFileUpdated) { try { duplicateConfigFile(); } catch (IOException e) { e.printStackTrace(); } } // Update the dict file info in the setting file SAXBuilder builder = new SAXBuilder(); File xmlFile = new File("src/input/" + configFilePath); try { Document doc = (Document) builder.build(xmlFile); Element rootNode = doc.getRootElement(); List<Element> elements = rootNode.getChildren("component"); List<Element> childElements = null; for (Element e : elements) { if (e.getAttributeValue("name").equals("jsgfGrammar")) { childElements = e.getChildren(); break; } } for (Element element : childElements) { if (element.getAttributeValue("name").equals("grammarLocation")) { element.getAttribute("value").setValue( "resource:/" + dictFilePath+"/"); } else if (element.getAttributeValue("name").equals( "grammarName")) { element.getAttribute("value").setValue(dictFileName); } } XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput .output(doc, new FileWriter("src/input/" + configFilePath)); // Reload the setting file setVoiceManager(); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
9
public boolean estEntoureDeMurs() { int imax = Xsize() - 1; int jmax = Ysize() - 1; for (int i = 0; i < Xsize(); i++) { if (carte[i][jmax] != ContenuCase.MUR) return false; if (carte[i][0] != ContenuCase.MUR) return false; } for (int j = 0; j < Ysize(); j++) { if (carte[0][j] != ContenuCase.MUR) return false; if (carte[imax][j] != ContenuCase.MUR) return false; } return true; }
6
public boolean checkIllustrationValues(String imageId, String name, String author){ boolean resultCheck = false; if(imageId.length() <= Model.getInstance().getIllustrationIdSize() && name.length() <= Model.getInstance().getIllustrationNameSize() && author.length() <= Model.getInstance().getIllustrationAuthorSize() && !(imageId.isEmpty())){ resultCheck = true; } else if(!(imageId.length() <= Model.getInstance().getIllustrationIdSize()) || imageId.isEmpty()){ View.getInstance().printErrorText(8); } else if(!(name.length() <= Model.getInstance().getIllustrationNameSize())){ View.getInstance().printErrorText(11); } else {View.getInstance().printErrorText(12);} if(LOGGER.isLoggable(Level.FINE)){ LOGGER.log(Level.FINE, "The result of check illustration values is: ", resultCheck);} return resultCheck; }
8
public byte decodeWithMatchByte(com.swemel.sevenzip.compression.rangecoder.Decoder rangeDecoder, byte matchByte) throws IOException { int symbol = 1; do { int matchBit = (matchByte >> 7) & 1; matchByte <<= 1; int bit = rangeDecoder.decodeBit(m_Decoders, ((1 + matchBit) << 8) + symbol); symbol = (symbol << 1) | bit; if (matchBit != bit) { while (symbol < 0x100) { symbol = (symbol << 1) | rangeDecoder.decodeBit(m_Decoders, symbol); } break; } } while (symbol < 0x100); return (byte) symbol; }
3
@Override public String toString() {return String.valueOf(cur);}
0
public static void assign4ElementArrayFromYamlObject(float[] output, Object yamlObject) { if (!(yamlObject instanceof List)) throw new RuntimeException("yamlObject not a List"); List<?> yamlList = (List<?>)yamlObject; output[0] = Float.valueOf(yamlList.get(0).toString()); output[1] = Float.valueOf(yamlList.get(1).toString()); output[2] = Float.valueOf(yamlList.get(2).toString()); output[3] = Float.valueOf(yamlList.get(3).toString()); }
3
public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AjoutStockForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AjoutStockForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AjoutStockForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AjoutStockForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AjoutStockForm().setVisible(true); } }); }
6
public static void createFacility(int[][] blockSheet) { Scanner s = null; try { s = new Scanner(new File("res/facility/FacilityInfo.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } ArrayList<ArrayList<Integer>> textInfo = new ArrayList<ArrayList<Integer>>(); while(s.hasNext()) { String line = s.nextLine(); ArrayList<Integer> lineNumbers = new ArrayList<Integer>(); for(int i = 0; i < line.length(); i++) { lineNumbers.add(Integer.parseInt(line.substring(i, i+1))); } textInfo.add(lineNumbers); } for(int x = 0; x < textInfo.size(); x++) { for(int y = 0; y < textInfo.get(x).size(); y++) { blockSheet[y + GraphicsMain.WIDTH/2][x + WorldGenerator.dirtBoundary - 38] = textInfo.get(x).get(y); } } }
5
public String getForcePanelCityName() { if (playerForce == null){ return ""; } else if (playerForce.getCityList().size() == 1) { return playerForce.getCityList().get(0).getCityName(); } else { return playerForce.getCityList().size() + ""; } }
2
@Override public int attack(double agility, double luck) { if(random.nextInt(100) < luck) { System.out.println("I just did a silenced attack!"); return random.nextInt((int) agility) * 2; } return 0; }
1
public void handleRestart() { restarting = true; if(config.getBoolean(ServerRestarterConfigNodes.CREATE_STATE_FILE)) { File file = new File(config.getString(ServerRestarterConfigNodes.STATE_FILE)); if(file.isDirectory()) getLogger().severe("Status file is a directory!"); try { file.createNewFile(); } catch(IOException exception) { getLogger().severe("Unable to create status file!"); exception.printStackTrace(); } } for(Player player : getServer().getOnlinePlayers()) player.kickPlayer(replaceColorCodes(restartMessage)); getServer().shutdown(); }
4
public void visit(Graph<String, String>.Vertex v) { if (!done.contains(v.getLabel()) || fileInfoMap.get(v.getLabel()) < currTime) { circle.add(v.getLabel()); if (preReq.get(v.getLabel()) != null) { for (String x : preReq.get(v.getLabel())) { Graph<String, String>.Vertex v1 = makeMap.get(x); if (v1 == null) { System.err.println("unknown target"); System.exit(1); } else if (circle.contains(x)) { System.err.println("circular dependency detected"); System.exit(1); } _graph.add(v, v1, v.getLabel() + " to " + v1.getLabel()); } } } }
6
String finder(String s, int start, int currentMax) { if (s.length() - start <= currentMax) return null; int stop = start + currentMax - 1; for (int i = s.length() - 1; i > stop; i--) { if (isPalindorme(s, start, i)) { String next = finder(s, start + 1, i - start + 1); if (next == null) return s.substring(start, i + 1); return next; } } String next = finder(s, start + 1, currentMax); if (next == null) return null; return next; }
5
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub JSONObject jb = new JSONObject(); String userId = request.getParameter("userId"); String eventName = new String( request.getParameter("eventName").getBytes("ISO-8859-1"),"UTF-8"); String calFrom = request.getParameter("calFrom"); String calTo = request.getParameter("calTo"); String locationName = new String( request.getParameter("locationName").getBytes("ISO-8859-1"),"UTF-8"); String locationCoordinate = new String( request.getParameter("locationCoordinate").getBytes("ISO-8859-1"),"UTF-8"); String decription = new String( request.getParameter("decription").getBytes("ISO-8859-1"),"UTF-8"); String updateTime = request.getParameter("updateTime"); String targetGroup = request.getParameter("targetGroup"); try{ connection = new Mongo(); scheduleDB = connection.getDB("schedule"); eventCollection = scheduleDB.getCollection("event_"+userId); WriteResult writeResult; DBObject event = new BasicDBObject(); //event.put("userId", userId); event.put("eventName", eventName); Date dateFrom = new Date(); Date dateTo = new Date(); dateFrom.setTime(Long.parseLong(calFrom)); dateTo.setTime(Long.parseLong(calTo)); event.put("calFrom", dateFrom); event.put("calTo", dateTo); event.put("locationName", locationName); event.put("locationCoordinate", locationCoordinate); event.put("decription", decription); event.put("photo", "null"); event.put("record", "null"); event.put("commentCount", 0); event.put("updateTime", updateTime); event.put("targetGroup", targetGroup); writeResult = eventCollection.save(event); int N = writeResult.getN(); DBCollection groupCollection = scheduleDB.getCollection("group_"+userId); DBObject groupQuery = new BasicDBObject(); groupQuery.put("_id", new ObjectId(targetGroup)); DBCursor cur = groupCollection.find(groupQuery); while(cur.hasNext()){ JSONObject eventJSONObject= new JSONObject(); DBObject dbo = cur.next(); ArrayList<String> members= new ArrayList(); try{ members = (ArrayList<String>)dbo.get("member"); for(int i = 0; i<members.size(); i++){ DBCollection socialCollection = scheduleDB.getCollection("social_"+members.get(i)); DBObject socialEvent = new BasicDBObject(); socialEvent.put("eventId", event.get("_id").toString()); socialEvent.put("userId", userId); socialEvent.put("updateTime", updateTime); WriteResult wr2 = socialCollection.save(socialEvent); if(wr2.getN() != 0 ){ jb.put("result", Primitive.DBSTOREERROR); } } }catch(Exception e){ } } if(N != 0 ){ jb.put("result", Primitive.DBSTOREERROR); }else{ jb.put("result", Primitive.ACCEPT); } }catch(MongoException e){ jb.put("result", Primitive.DBCONNECTIONERROR); e.printStackTrace(); } PrintWriter writer = response.getWriter(); writer.write(jb.toString()); writer.flush(); writer.close(); }
6
public void insert(Key v) { // Insert pq[++N] = v; swim(N); // resizing if (N >= pq.length - 1) pq = resize(pq, 2 * pq.length); }
1
public static int DateOfWeekday(int date, int weekday) { if (weekday == 0) { return date; } int curweekday = date % 7; boolean isPos = false; if (weekday > 0) { isPos = true; } weekday = weekday % 7; if (weekday >= 0) { if (weekday == curweekday && isPos) { return date + 7; } else if (weekday > curweekday) { return date + (weekday - curweekday); } else { return date + 7 - (curweekday - weekday); } } else { if (weekday == curweekday && !isPos) { return date - 7; } else if (curweekday > Math.abs(weekday)) { return date - (curweekday - Math.abs(weekday)); } else { return date - (7 - (Math.abs(weekday) - curweekday)); } } }
9
public void createFolder(String folderName) throws UpYunExcetion { try { StringBuffer url = new StringBuffer(); for (String str : folderName.split("/")) { if (str == null || str.length() == 0) { continue; } url.append(UrlCodingUtil.encodeBase64(str.getBytes("utf-8")) + "/"); } sign.setUri(url.toString()); } catch (UnsupportedEncodingException e) { LogUtil.exception(logger, e); } sign.setContentLength(0); sign.setMethod(HttpMethod.POST.name()); String url = autoUrl + sign.getUri(); Map<String, String> headers = sign.getHeaders(); headers.put("folder", "true"); headers.put("mkdir", "true"); HttpResponse httpResponse = HttpClientUtils.postByHttp(url, headers); if (httpResponse.getStatusLine().getStatusCode() != 200) { throw new UpYunExcetion(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine() .getReasonPhrase()); } }
5
public TBlock createBlock(TBlkType type, Color cl, TBlockBox box) { TBlock blk = null; switch (type) { case Z: blk = new TBlock_Z(box); break; case ZOPPOSITE: blk = new TBlock_ZOpposite(box); break; case L: blk = new TBlock_L(box); break; case LOPPOSITE: blk = new TBlock_LOpposite(box); break; case SQUARE: blk = new TBlock_Square(box); break; case T: blk = new TBlock_T(box); break; case STICK: blk = new TBlock_Stick(box); break; default: break; } blk.setColor(cl); return blk; }
7
Object unpack(Info vi, Buffer opb){ InfoFloor0 info=new InfoFloor0(); info.order=opb.read(8); info.rate=opb.read(16); info.barkmap=opb.read(16); info.ampbits=opb.read(6); info.ampdB=opb.read(8); info.numbooks=opb.read(4)+1; if((info.order<1)||(info.rate<1)||(info.barkmap<1)||(info.numbooks<1)){ return (null); } for(int j=0; j<info.numbooks; j++){ info.books[j]=opb.read(8); if(info.books[j]<0||info.books[j]>=vi.books){ return (null); } } return (info); }
7
public void action(){ }
0
private String validateMnemonic(String mnemonic) { int space = mnemonic.indexOf(" "); // Get the location of the closest space if (space == 3) { mnemonic = mnemonic.substring(0, 3); // Get the 3 char mnemonic } else if (space == -1) ; // Mnemonic is the entire line for (String i : mnemonics) { if (mnemonic.equals(i)) { // Check if the mnemonic matches up w/ a known mnemonic return mnemonic; // Return the valid mnemonic } } Error.codeError(line, lineNumber, 3); // 3 -- The mnemonic is not valid error = true; return "ERROR"; // Return an error }
4
private String getCipherInitString() { if (algName.equals("Blowfish")) { return "Blowfish/CBC/PKCS5Padding"; } else if (algName.equals("DES")) { return "DES/CBC/PKCS5Padding"; } else if (algName.equals("TripleDES")) { return "TripleDES/CBC/PKCS5Padding"; } else if (algName.equals("AES")) { return "AES/CBC/PKCS5Padding"; } else if (algName.equals("RC4")) { return "RC4"; //stream chiffre } else { return algName; } }
5
private void classificationDiagramUpdate() { DefaultListModel definitiveModel = new DefaultListModel(); DefaultListModel dominantModel = new DefaultListModel(); DefaultListModel dangerousModel = new DefaultListModel(); DefaultListModel dependentModel = new DefaultListModel(); DefaultListModel dormantModel = new DefaultListModel(); DefaultListModel discretionaryModel = new DefaultListModel(); DefaultListModel demandingModel = new DefaultListModel(); DefaultListModel nonStakeholderModel = new DefaultListModel(); // for(int i = 0;i < Stakeholders.size();i++) { Stakeholder obj=Stakeholders.get(i); if(Stakeholders.get(i).getClassification().equals("Non-Stakeholder")) { nonStakeholderModel.addElement(obj.getName()); } else if(Stakeholders.get(i).getClassification().equals("Dormant")) { dormantModel.addElement(obj.getName()); } else if(Stakeholders.get(i).getClassification().equals("Discretionary")) { discretionaryModel.addElement(obj.getName()); } else if(Stakeholders.get(i).getClassification().equals("Dominant")) { dominantModel.addElement(obj.getName()); } else if(Stakeholders.get(i).getClassification().equals("Definitive")) { definitiveModel.addElement(obj.getName()); } else if(Stakeholders.get(i).getClassification().equals("Dangerous")) { dangerousModel.addElement(obj.getName()); } else if(Stakeholders.get(i).getClassification().equals("Dependent")) { dependentModel.addElement(obj.getName()); } else { demandingModel.addElement(obj.getName()); } } //fill in new stakeholder classification lists definitiveList.setModel(definitiveModel); dominantList.setModel(dominantModel); dangerousList.setModel(dangerousModel); dependentList.setModel(dependentModel); dormantList.setModel(dormantModel); discretionaryList.setModel(discretionaryModel); demandingList.setModel(demandingModel); nonStakeholderList.setModel(nonStakeholderModel); }
8
@RequestMapping(value = "/speciality-list/{hallEventId}", method = RequestMethod.GET) @ResponseBody public SpecialityListResponse specialityList( @PathVariable(value = "hallEventId") final String hallEventIdStr ) { Boolean success = true; String errorMessage = null; List<Speciality> specialityList = null; Long hallEventId = null; try { hallEventId = controllerUtils.convertStringToLong(hallEventIdStr, true); specialityList = specialityPresenter.findSpecialitiesByHallEventId(hallEventId); } catch (UrlParameterException e) { success = false; errorMessage = "Hall event ID is wrong or empty"; } return new SpecialityListResponse(success, errorMessage, specialityList); }
1
public void buildLeft(PathQuad quad) { if(!quad.noChildren()) { this.buildLeft(quad.getChild(1)); this.buildLeft(quad.getChild(3)); } else if(!quad.isBlocked() && ((this.getBox().getY() >= quad.getBox().getY() && this.getBox().getY() < quad.getBox().getMaxY()) || (quad.getBox().getY() >= this.getBox().getY() && quad.getBox().getY() < this.getBox().getMaxY()))) { this.left.add(quad); } }
6
public SingleTreeNode uct() { SingleTreeNode selected = null; double bestValue = -Double.MAX_VALUE; for (SingleTreeNode child : this.children) { double hvVal = child.totValue; double childValue = hvVal / (child.nVisits + this.epsilon); childValue = Utils.normalise(childValue, bounds[0], bounds[1]); double uctValue = childValue + K * Math.sqrt(Math.log(this.nVisits + 1) / (child.nVisits + this.epsilon)); // small sampleRandom numbers: break ties in unexpanded nodes uctValue = Utils.noise(uctValue, this.epsilon, this.m_rnd.nextDouble()); //break ties randomly // small sampleRandom numbers: break ties in unexpanded nodes if (uctValue > bestValue) { selected = child; bestValue = uctValue; } } if (selected == null) { throw new RuntimeException("Warning! returning null: " + bestValue + " : " + this.children.length); } return selected; }
3
public synchronized static void dealWith (final Throwable t) { // First, print the stack trace t.printStackTrace(); // Second, write the exception to a log file String osName = System.getProperty ("os.name"); String userHome = System.getProperty ("user.home"); String propertiesDirectory; if (osName.startsWith ("Windows")) { String applicationDataName = System.getenv ("APPDATA"); if (applicationDataName == null) { applicationDataName = "Application Data"; } propertiesDirectory = userHome + File.separator + applicationDataName + File.separator + "Itadaki"; } else { propertiesDirectory = userHome + File.separator + ".itadaki"; } File propertiesDirectoryFile = new File (propertiesDirectory); if (!propertiesDirectoryFile.exists()) { propertiesDirectoryFile.mkdirs(); } String logFilename = propertiesDirectory + File.separator + "itadaki.log"; FileWriter fileWriter = null; try { fileWriter = new FileWriter (new File (logFilename), true); PrintWriter printWriter = new PrintWriter (fileWriter); printWriter.println ("Exception caught at " + DateFormat.getDateTimeInstance().format (new Date())); t.printStackTrace (printWriter); printWriter.println(); printWriter.println(); } catch (IOException e) { // Not much to do about it really } finally { try { if (fileWriter != null) { fileWriter.close(); } } catch (IOException e) { // Ignore } } // Finally, attempt to show an explanatory dialog SwingUtilities.invokeLater (new Runnable() { /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { if (exceptionDialog == null) { createDialog(); } if (!exceptionDialog.isVisible()) { stackTraceTextArea.setText(""); } Writer stringWriter = new StringWriter(); t.printStackTrace (new PrintWriter (stringWriter)); stackTraceTextArea.append (stringWriter.toString()); stackTraceTextArea.append ("\n\n"); exceptionDialog.setVisible (true); } }); }
8
public final int getCamsize() { return cam.size(); }
0
public ConfirmPaymentResponse confirmPayment(ConfirmPaymentRequest request) throws GongmingConnectionException, GongmingApplicationException { URL path = _getPath(CONFIRM_PAYMENT); ConfirmPaymentResponse response = _POST(path, request, ConfirmPaymentResponse.class); if (response.code != GMResponseCode.COMMON_SUCCESS) { throw new GongmingApplicationException(response.code.toString(), response.errorMessage); } return response; }
1
public TrapStateTool(AutomatonPane view, AutomatonDrawer drawer, AddTrapStateController controller) { super(view, drawer); myController = controller; }
0
public void setVar(PVar node) { if(this._var_ != null) { this._var_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._var_ = node; }
3
public boolean saveTemplate(){ try { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); try { //writer.write(tabletoString(columnnames)); writer.newLine(); } catch (IOException e) { e.printStackTrace(); } writer.close(); return true; } catch (FileNotFoundException e) { writeLog(e); return false; } catch (IOException e) { writeLog(e); return false; } }
3
@Override public void run() { try { listenSocket = new ServerSocket(SERVER_PORT); System.out.printf("CommandListener listening on port %s.\n", SERVER_PORT); while (true) { dataSocket = listenSocket.accept(); System.out.printf("Accepted connection.\n"); ObjectInputStream ois = new ObjectInputStream(dataSocket.getInputStream()); ObjectOutputStream oos = new ObjectOutputStream(dataSocket.getOutputStream()); System.out.printf("Got I/O Streams.\n"); String message = (String)ois.readObject(); System.out.printf("Got a Message: %s\n", message); switch (message) { case STATUS_REQUEST: String remoteAddr = stripAddress(dataSocket.getRemoteSocketAddress().toString()); System.out.printf("CommandListener received STATUS request from %s.\n", remoteAddr); dInfo.refresh(); Dimension dimension = dInfo.getScreenDimension(); // add here more status information String outMessage = String.format("SD%04d%04d", (int)dimension.getWidth(), (int)dimension.getHeight()); System.out.printf("StatusSender: Sending STATUS reply to %s: %s\n", remoteAddr, outMessage); oos.writeObject(outMessage); break; case DATABASE_DUMP: System.out.println(DBUtility.getImageMapFromDB().toString()); oos.writeObject("Done."); break; case IMAGE_LIST_REQUEST: ImageMap iMap = DBUtility.getImageMapFromDB(); oos.writeObject(iMap); break; default: System.err.printf("CommandListener received malformed message from %s. IGNORED. Message: %s\n", dataSocket.getRemoteSocketAddress().toString(), message); break; } oos.close(); ois.close(); } } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } }
5
protected static String getString(String name, JSONObject json, boolean decode) { String returnValue = null; try { returnValue = json.getString(name); if (decode) { try { returnValue = URLDecoder.decode(returnValue, "UTF-8"); } catch (UnsupportedEncodingException ignore) { } } } catch (JSONException ignore) { // refresh_url could be missing } return returnValue; }
3
public TypedObject decodeInvoke(byte[] data) throws NotImplementedException, EncodingException { reset(); dataBuffer = data; dataPos = 0; TypedObject result = new TypedObject("Invoke"); if (dataBuffer[0] == 0x00) { dataPos++; result.put("version", 0x00); } result.put("result", decodeAMF0()); result.put("invokeId", decodeAMF0()); result.put("serviceCall", decodeAMF0()); result.put("data", decodeAMF0()); if (dataPos != dataBuffer.length) throw new EncodingException("Did not consume entire buffer: " + dataPos + " of " + dataBuffer.length); return result; }
2
@Override public Iterator getExtensions() { return extensions.keySet().iterator(); }
0
private void selectedOrderSleeve1() { if(ord == null) { txtOrderName2.setText(""); txtOrderId3.setText(""); lblSleeves.setText(""); } if(operator == null) { txtId.setText(""); txtName.setText(""); txtLastName.setText(""); } else { txtOrderName2.setText(ord.getOrderName()); //txtOrderId3.setText(String.valueOf(ord.getOrderId())); txtId.setText(String.valueOf(operator.getId())); txtName.setText(String.valueOf(operator.getFirstName())); txtLastName.setText(String.valueOf(operator.getLastName())); lblSleeves.setText(String.valueOf("Sleeves to be made " + ord.getConductedQuantity() + " / " + ord.getQuantity())); try { // txtHasCut1.setText(String.valueOf(managerSleeveLog.getQuantity(ord.getSleeve()))); managerSleeve.addObserver(this); slmodel = new SleeveTableModel(managerSleeve.getSleevesByOrder(ord)); tblSleeve2.setModel(slmodel); managerOrder.addObserver(this); managerStockItem.addObserver(this); tblSleeve2.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent es) { int selectedRow = tblSleeve2.getSelectedRow(); if (selectedRow == -1) { return; } sleeve = slmodel.getEventsByRow(selectedRow); if (sleeve.getStartTime() != null) { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss"); txtStartTime17.setText(sdf.format(sleeve.getStartTime().getTime())); txtEndTime17.setText(sdf.format(sleeve.getEndTime().getTime())); btnPause17.setEnabled(true); btnFinish18.setEnabled(true); btnStart17.setEnabled(true); String status = "Finished"; if (ord.getConductedQuantity() == ord.getQuantity() && ord.getStatus().equalsIgnoreCase(status)) { btnPause17.setEnabled(false); btnFinish18.setEnabled(false); btnStart17.setEnabled(false); } else if (ord.getConductedQuantity() == ord.getQuantity()) { btnPause17.setEnabled(false); btnFinish18.setEnabled(true); btnStart17.setEnabled(false); } } else { btnStart17.setEnabled(true); } } }); } catch (Exception e) { e.printStackTrace(); } } }
8
public static String md5Java(String message) { String digest = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] hash = md.digest(message.getBytes("UTF-8")); //converting byte array to Hexadecimal String StringBuilder sb = new StringBuilder(2 * hash.length); for (byte b : hash) { sb.append(String.format("%02x", b & 0xff)); } digest = sb.toString(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(sun.security.provider.MD5.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(sun.security.provider.MD5.class.getName()).log(Level.SEVERE, null, ex); } return digest; }
3
public static int changeEnergy(float x, float y, int amount) { if (x < 0) x = 0; if (x > Game.width - 1) x = Game.width - 1; if (y < 0) y = 0; if (y > Game.height - 1) y = Game.height - 1; energy[(int) (x / 20)][(int) (y / 20)] += amount; if (energy[(int) (x / 20)][(int) (y / 20)] < 0) { amount -= energy[(int) (x / 20)][(int) (y / 20)]; energy[(int) (x / 20)][(int) (y / 20)] = 0; } return amount; }
5
private void manageClients() { manage = new Thread(this, "Manage") { public void run() { while (running) { sendToAll("/i/server"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0; i < clients.size(); i++) { ServerClient c = clients.get(i); if (!clientResponse.contains(c.getID())) { if (c.attempt >= MAX_ATTEMPTS) { // Unnatural disconnect, therefore status is false. disconnect(c.getID(), false); } else { c.attempt++; } } else { clientResponse.remove(new Integer(c.getID())); c.attempt = 0; } } } } }; manage.start(); }
5
@Override public void serialEvent(SerialPortEvent event) { if (!event.isRXCHAR()) {//Ensure data is avaiable return; } if (event.getEventValue() <= 0) {//Ensure there is data to read return; } //Get the data from the serial port byte buffer[]; try { buffer = serialPort.readBytes(event.getEventValue()); } catch (SerialPortException ex) { System.err.println(ex); buffer = new byte[0]; } //Buffer the data in rawSensorData for (byte b : buffer) { rawSensorData.add(b); } //Look for valid streams while (rawSensorData.size() >= sensorDataLength) { if (rawSensorData.get(0) != (byte) SENSOR_STREAM_HEADER) {//Quickly serch for a possible header, dumping anything ahead of it rawSensorData.remove(0); } else if (checkRawSensorData()) {//A valid stream at the start of the buffer // System.out.println("Found a good one!"); interpretRawSensorData(); sensorDataIsValid.set(true); watchdog.set(true); if (sensorPacketListenerAdded) { sensorPacketListener.sensorPacketReceived(); } } else {//It was not a header after all rawSensorData.remove(0); } } }
8
public KeyType createKeyType() { return new KeyType(); }
0
private Drawable parseDrawable() { String token = this.scanner.next(); Drawable drawable = null; if ("Circle".equals(token)) { // Circleの場合 int x = this.scanner.nextInt(); int y = this.scanner.nextInt(); int r = this.scanner.nextInt(); drawable = new Circle(x, y, r); } else if ("Rectangle".equals(token)) { // Rectangleの場合 int x0 = this.scanner.nextInt(); int y0 = this.scanner.nextInt(); int x1 = this.scanner.nextInt(); int y1 = this.scanner.nextInt(); drawable = new Rectangle(x0, y0, x1, y1); } else if ("Line".equals(token)) { // Lineの場合 int x0 = this.scanner.nextInt(); int y0 = this.scanner.nextInt(); int x1 = this.scanner.nextInt(); int y1 = this.scanner.nextInt(); drawable = new Line(x0, y0, x1, y1); } else { // 図形の種類を増やす時はここに追加 } if (drawable instanceof ColoredShape) { // 色の読み込み if (this.scanner.hasNext("color")) { this.scanner.next(); Color color = new Color(this.scanner.nextInt(), true); ((ColoredShape)drawable).setColor(color); } // 影の読み込み if (this.scanner.hasNext("dropShadow")) { this.scanner.next(); boolean dropShadow = this.scanner.nextBoolean(); ((ColoredShape)drawable).setDropShadow(dropShadow); } } return drawable; }
6
public int getVidas(){ return this.vidas; }
0
public static void removeDuplicates(char[] str) { if (str == null) return; int len = str.length; if (len < 2) return; int tail = 1; for (int i = 1; i < len; ++i) { int j; for (j = 0; j < tail; ++j) { if (str[i] == str[j]) break; } if (j == tail) { str[tail] = str[i]; ++tail; } } str[tail] = 0; }
6
public int checkDiag() { int found = 0; boolean same; char[][] checker = new char[2][3]; int x = 0; int y = 0; for(x=0; x<ROWCOL; x++, y++){ checker[0][x] = titato[x][y]; } for(x=2, y=0; y<ROWCOL; x--,y++) { checker[1][y] = titato[x][y]; } for(x=0; ((x<DIAGS) && (found==0)); x++) { same = checkSame(checker[x]); if(same){ found = (x+7); } } return found; }
5
public boolean esta(Nodo x) { if (nodos.isEmpty()) { return false; } for (Nodo n : nodos) { if (x.equals(n)) { return true; } } return false; }
3
public Schematic(String resourceName) { Scanner sc = new Scanner(getClass().getResourceAsStream(resourceName)); Vector<String> lines = new Vector<>(); while (sc.hasNextLine()) lines.add(sc.nextLine()); this.height = lines.size(); int h = 0, w, d; for (String line : lines) { String[] rows = line.split(","); w = 0; for (String row : rows) { if (width == 0) { width = row.length(); blockMap = new Material[height * width * depth]; } if (row.length() != width) throw new IllegalArgumentException("Wrong width in resourse " + resourceName); String[] blocks = row.split(":"); if (depth == 0) depth = blocks.length; if (blocks.length != depth) throw new IllegalArgumentException("Wrong depth in resourse " + resourceName); d = 0; for (String block : blocks) { Material m = Material.AIR; try { m = Material.getMaterial(Integer.parseInt(block)); setMaterial(h, w, d, m); d++; } catch (NumberFormatException e) { Logger.getLogger(Schematic.class.getSimpleName()).log( Level.INFO, "Wrong block in resourse " + resourceName ); } finally { setMaterial(h, w, d, m); } } w++; } h++; } }
9
public static boolean sudoku(int[][] feld) { // 1-9 durchgehen for (int zahl = 1; zahl <= 9; zahl++) { // vorbelegen, dass Zahl nicht gefunden wurde boolean gefunden = false; // Sudoku feld nach Zahl absuchen for (int i = 0; i < feld.length; i++) { for (int j = 0; j < feld[i].length; j++) { if (feld[i][j] == zahl) // Wenn Zahl gefunden entsprechend auf true setzen gefunden = true; } } // Falls Zahl nicht gefunden, fehlt diese Zahl und das Sudokufeld ist unvollstaendig if (gefunden == false) return false; } // Falls alle Zahlen gefunden wurde Sudokufeld vollstaendig return true; }
5
@Override public Object getValueAt(int row, int col) { Entry entry; try { entry = dic.getEntry(ids.get(row)); } catch (Exception ex) { return Localization.getInstance().get("error") + " " + ex; } switch(col) { case 0: return escapeString(entry.getWord()); case 1: return escapeString(entry.getDefinition()); case 2: return escapeString(entry.getCategory()); case 3: return escapeString(entry.getTagsAsString()); default: return null; } }
5
@Override public void applyMoveAction(double s_elapsed) { switch (next_action.move) { case NONE: double move_velocity = Math.hypot(move_x_velocity, move_y_velocity); double delta = s_elapsed * SPEED_DECREASE_PER_SECOND * move_x_velocity / move_velocity; if (Math.abs(move_x_velocity) > Math.abs(delta)) { move_x_velocity -= delta; } else { move_x_velocity = 0.0; } delta = s_elapsed * SPEED_DECREASE_PER_SECOND * move_y_velocity / move_velocity; if (Math.abs(move_y_velocity) > Math.abs(delta)) { move_y_velocity -= delta; } else { move_y_velocity = 0.0; } break; case FORWARD: double max = move_speed * Math.cos(direction); move_x_velocity += SPEED_INCREASE_PER_SECOND * Math.cos(direction) * s_elapsed; if (Math.abs(move_x_velocity) > Math.abs(max)) { move_x_velocity = max; } max = move_speed * Math.sin(direction); move_y_velocity += SPEED_INCREASE_PER_SECOND * Math.sin(direction) * s_elapsed; if (Math.abs(move_y_velocity) > Math.abs(max)) { move_y_velocity = max; } break; case BACKWARD: max = move_speed * Math.cos(direction); move_x_velocity -= SPEED_INCREASE_PER_SECOND * Math.cos(direction) * s_elapsed; if (Math.abs(move_x_velocity) > Math.abs(max)) { move_x_velocity = -max; } max = move_speed * Math.sin(direction); move_y_velocity -= SPEED_INCREASE_PER_SECOND * Math.sin(direction) * s_elapsed; if (Math.abs(move_y_velocity) > Math.abs(max)) { move_y_velocity = -max; } break; default: throw new DescentMapException("Unexpected MoveDirection: " + next_action.move); } }
9
public boolean newProductoAction(String id_productos, String nombre, String cantidad, String precio_venta, String descripcion) throws SQLException, EmptyFieldException { boolean res; conn = ConexionBD.getInstance(); if(id_productos.isEmpty() || nombre.isEmpty() || cantidad.isEmpty() || precio_venta.isEmpty()|| descripcion.isEmpty()) { throw new EmptyFieldException(); } res = conn.insertRecordToTable( "INSERT INTO productos " + "VALUES(" + id_productos + "', '" + nombre + "', " + cantidad + "', '" + precio_venta + "', '" + descripcion + "', '" + "')"); return res; }
5
public void setRequestWrapper(RequestWrapper requestWrapper) { this.requestWrapper = requestWrapper; }
0
protected void rotateRight(Node<T> node) { Position parentPosition = null; Node<T> parent = node.parent; if (parent != null) { if (node.equals(parent.lesser)) { // Lesser parentPosition = Position.LEFT; } else { // Greater parentPosition = Position.RIGHT; } } Node<T> lesser = node.lesser; node.lesser = null; Node<T> greater = lesser.greater; lesser.greater = node; node.parent = lesser; node.lesser = greater; if (greater != null) greater.parent = node; if (parent!=null && parentPosition != null) { if (parentPosition == Position.LEFT) { parent.lesser = lesser; } else { parent.greater = lesser; } lesser.parent = parent; } else { root = lesser; lesser.parent = null; } }
6
public CommandResult getDBStats() { return db.getStats(); }
0
public void actionPerformed(ActionEvent e) { Object o = e.getSource(); if (o == typeComboBox) { if (myRecipe != null) { selectedRow = notesTable.getSelectedRow(); myRecipe.setNoteType(selectedRow, (String)typeComboBox.getSelectedItem()); if(((JComboBox)o).isPopupVisible() && (String)typeComboBox.getSelectedItem() == "Brewed") { int dialogResult = JOptionPane.showConfirmDialog(null, "Do you want to subtract the ingredients from your stock levels?", "Info", JOptionPane.YES_NO_OPTION ); // does the user want to subtract the ingredients from stock? if(dialogResult == JOptionPane.YES_OPTION) { // run the DB Subtract Debug.print("Subtracting ingredients"); myRecipe.substractIngredients(); } } } } else if (o == addNoteButton) { if (myRecipe != null) { Note n = new Note(); myRecipe.addNote(n); // select the new note so the text is associated with it: ListSelectionModel selectionModel = notesTable.getSelectionModel(); int i = notesTableModel.getRowCount() -1; selectionModel.setSelectionInterval(i, i); notesTable.updateUI(); } } else if (o == delNoteButton) { if (myRecipe != null) { int i = notesTable.getSelectedRow(); myRecipe.delNote(i); notesTable.updateUI(); } } }
9
public static void select(GlkEvent e) { long cur = 0l; GlkEvent ev = null; boolean done = false; synchronized(EVENT_QUEUE) { if (Window.root != null) Window.root.doLayout(); while (!done) { if (!EVENT_QUEUE.isEmpty()) { ev = (GlkEvent) EVENT_QUEUE.removeFirst(); if (ev != null) done = true; } else if (TIMER > 0 && (cur = System.currentTimeMillis()) - TIMESTAMP >= TIMER) { e.type = EVTYPE_TIMER; e.win = null; e.val1 = 0; e.val2 = 0; TIMESTAMP = cur; done = true; } else { try { if (TIMER > 0) EVENT_QUEUE.wait(TIMER - (cur - TIMESTAMP)); else EVENT_QUEUE.wait(); } catch(InterruptedException ex) {} } } if (ev != null) { e.type = ev.type; e.win = ev.win; e.val1 = ev.val1; e.val2 = ev.val2; } } }
9
private void runBlottoProblem(Evolution evo){ int generations = Integer.parseInt(generationsField.getText()); int populationSize = Integer.parseInt(populationSizeField.getText()); double[] avgEntropy = new double[generations]; double[] stdDev = new double[generations]; List<Individual> individuals = problem.createPopulation(populationSize); try { for (int i = 0; i < generations; i++){ individuals = evo.runGeneration(individuals); double[] fitnesses = new double[populationSize]; int numParents = 0; for(Individual ind: individuals){ if(ind.age() > 0){ fitnesses[numParents] = ind.fitness(); BlottoPhenotype pheno = (BlottoPhenotype) ind.phenotype(); double sum = 0.0; for (int j = 0; j < pheno.pheno.length; j++){ double value = pheno.pheno[j]; if (value != 0.0){ double logcalc = (value * (Math.log(value)/Math.log(2.0))); sum -= logcalc; } } avgEntropy[i] += sum; numParents++; } } avgEntropy[i] = avgEntropy[i] / (double)numParents; stdDev[i] = StandardDeviation.StandardDeviationMean(fitnesses); } }catch (Exception ex) { System.out.println(ex.getMessage()); return; } List<Map> statistics = evo.getStatistics(); String formattedString = ""; double[] maxfitnessplot = new double[generations]; double[] avgfitnessplot = new double[generations]; int i = 0; for(Map m: statistics){ formattedString += "Generation:" + (i+1) + "\t Best: " + m.get("bestIndividual").toString() + "\n"; maxfitnessplot[i] = Double.parseDouble(m.get("maxFitness").toString()); avgfitnessplot[i] = Double.parseDouble(m.get("avgFitness").toString()); i++; } Plot2DPanel plot = new Plot2DPanel(); plot.addLinePlot("Max fitness", Color.RED, maxfitnessplot); plot.addLinePlot("Average fitness", Color.ORANGE, avgfitnessplot); plot.addLinePlot("Standard deviation", Color.BLACK, stdDev); plot.addLegend("SOUTH"); BaseLabel title = new BaseLabel(problemBox.getSelectedItem().toString() + ", " + adultBox.getSelectedItem().toString() + ", " + parentBox.getSelectedItem().toString() + ", mutation: " + mutationRateField.getText() + "%, crossover: " + crossoverRateField.getText() + "%" , Color.BLACK, 0.5, 1.1); plot.addPlotable(title); graphpanel.add(plot); Plot2DPanel plot2 = new Plot2DPanel(); plot2.addLinePlot("Average entropy", Color.BLUE, avgEntropy); plot2.addLegend("SOUTH"); BaseLabel title2 = new BaseLabel("Entropy graph: " + problemBox.getSelectedItem().toString() + ", " + adultBox.getSelectedItem().toString() + ", " + parentBox.getSelectedItem().toString() + ", mutation: " + mutationRateField.getText() + "%, crossover: " + crossoverRateField.getText() + "%" , Color.BLACK, 0.5, 1.1); plot2.addPlotable(title2); graphpanel.add(plot2); CardLayout card = (CardLayout) graphpanel.getLayout(); card.last(graphpanel); outputScreen.setText(formattedString); }
7
public void evolvePlayers() { for (NPC npc : NPC.getNPCList()) { Direction nextDir = npc.getCurrentDirectionInScript(); Move move = npc.getMove(); if (nextDir != Direction.NONE) { if (!npc.canWalkOnSquare(nextDir)) { npc.setPosture(Posture.getPosture(nextDir, 0)); move.setDir(Direction.NONE); move.reset(); npc.setMovementIFP(nextDir); } else { npc.setOnSquare(nextDir); move.setDir(nextDir); npc.setPosture(Posture.getPosture(nextDir, move.getStep())); boolean timerEnded = move.updateTimer(); if(timerEnded) { move.nextStep(); if(move.isMoveFinished()) { npc.moveSquare(nextDir); npc.goToNextStepOfScript(); } } } } } }
5
public static void printHand(Hand hand) { // print hand header ArrayList<String> attrs = new ArrayList<String>(3); if(!hand.getDescription().equals("")) attrs.add(hand.getDescription()); attrs.add("score: " + hand.getScoreString()); if(hand.getBet() > 0.0f) attrs.add("bet: $" + hand.getBet()); output.println(hand.getPlayer().getName() + "\'s hand (" + join(attrs, ", ") + ")"); if(UNICODE) { // create a "buffer" to contain the ASCII hand StringBuilder[] buffer; buffer = new StringBuilder[5]; // card height is 5 for(int i=0; i<5; i++) buffer[i] = new StringBuilder(); try { for(Card c : hand.getCards()) printCardToBuffer(buffer, c); } catch (Exception e) { e.printStackTrace(); } // hand buffer populated, print to output stream for(StringBuilder sb : buffer) output.println(sb.toString()); } else { for(Card c : hand.getCards()) { output.print(rank(c) + suit(c) + " "); } output.println(); } }
8
public EchoFilter(int numDelaySamples, float decay) { delayBuffer = new short[numDelaySamples]; this.decay = decay; }
0
public void faceObject(Entity obj){ if (obj==null) return; float dx = obj.getPosition().x - getPosition().x; if(dx > 0 && facingLeft) changeDirection(); else if(dx < 0 && !facingLeft) changeDirection(); }
5
private static void begin() { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { StringTokenizer st = new StringTokenizer(sc.nextLine()); int nbrInts = Integer.parseInt(st.nextToken()); if (nbrInts <= 0) { System.out.println("Not jolly"); continue; } else if (nbrInts == 1) { System.out.println("Jolly"); continue; } boolean[] data = new boolean[nbrInts - 1]; int prev = Integer.parseInt(st.nextToken()); while (st.hasMoreTokens()) { int curr = Integer.parseInt(st.nextToken()); int absDiff = Math.abs(prev - curr); if (absDiff > 0 && absDiff <= nbrInts - 1) { data[absDiff - 1] = true; } prev = curr; } boolean isJolly = true; for (boolean b : data) { if (!b) { isJolly = false; break; } } if (isJolly) { System.out.println("Jolly"); } else { System.out.println("Not jolly"); } } }
9
public static void setLevel(Block block, int level) { if (!isApplicable(block)) return; TileEntityBeacon beacon = (TileEntityBeacon) ((CraftWorld) block .getWorld()).getHandle().getTileEntity(block.getX(), block.getY(), block.getZ()); Field lvl = null; try { lvl = TileEntityBeacon.class.getDeclaredField("e"); lvl.setAccessible(true); lvl.set(beacon, level); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
5
public List<Warehouse> getWarehouseByBranch(int branchid) { List<Warehouse> warehouses = new ArrayList<Warehouse>(); Connection con = null; Statement stmt = null; try { DBconnection dbCon = new DBconnection(); Class.forName(dbCon.getJDBC_DRIVER()); con = DriverManager.getConnection(dbCon.getDATABASE_URL(), dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD()); stmt = con.createStatement(); String query="Select wrh_id,wrh_quantity,wrh_salerentprice,wrh_minlimit,wrh_maxlimit,wrh_isavailable,wrh_isactive,item_id,branch_id " +"From warehouse where branch_id="+branchid; ResultSet rs = stmt.executeQuery(query); while (rs.next()) { Warehouse warehouse=new Warehouse(); warehouse=new Warehouse(); warehouse.setId(rs.getLong(1)); warehouse.setQuantity(rs.getInt(2)); warehouse.setSaleRentPrice(rs.getDouble(3)); warehouse.setMinLimit(rs.getInt(4)); warehouse.setMaxLimit(rs.getInt(5)); warehouse.setIsAvailable(rs.getBoolean(6)); warehouse.setIsActive(rs.getBoolean(7)); warehouse.setItem(rs.getInt(8)); warehouse.setBranch(rs.getInt(9)); warehouses.add(warehouse); } } catch (SQLException | ClassNotFoundException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } } return warehouses; }
5
private void processIdentifiers(Expression e) { String type=e.getType(); if(type.equals("identifier")) { identifiers.add(e.getValue()); } for (int i = 0; i < Expression.unaryTypes.length; i++) { if (type.equals (Expression.unaryTypes[i])) { processIdentifiers(e.getSubexpression()); } } for (int i = 0; i < Expression.binaryTypes.length; i++) { if (type.equals (Expression.binaryTypes[i])) { processIdentifiers(e.getSubexpression("left")); processIdentifiers(e.getSubexpression("right")); } } }
5
public void setDateNull() { for (int i = 0; i < 42; i++) { labelDay[i].setText(""); } }
1
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Domain)) return false; Domain other = (Domain) obj; if (price == null) { if (other.price != null) return false; } else if (!price.equals(other.price)) return false; if (suffix == null) { if (other.suffix != null) return false; } else if (!suffix.equals(other.suffix)) return false; return true; }
9
public static void main (String[] args) { int meanGoal = 5; //arrival interval of people int m = 10; //15; //amount of numbers needed int n = m; //3000; Random tmpRnd = new Random(); Exponential p0 = new Exponential(meanGoal, tmpRnd); System.out.println("First " + m + " of " + n + " samples from an Exponential distribution\n" + "with mean " + meanGoal); double total = 0; double totalSquares = 0; for (int i=0; i < n; i++) { int next = p0.next(); if ( i < m ) { System.out.println(next); } total += next; totalSquares += next*next; } double mean = total/n; double variance = totalSquares/n - mean*mean; System.out.println("mean goal: " + meanGoal + "\nachieved: " + mean + "\nstandard deviation: " + Math.sqrt(variance)); }
2
public Image getTileImage(int x, int y){ switch(level.fields[y][x]){ case dest: return iDest; case floor: return iFloor; case grass: return iGrass; case src: return iSrc; case wall: return iWall; default: return null; } }
5
public void setDefinition(String value) { this.definition = value; }
0
public static void main(String[] args) { Input objInput = new Input(); boolean blnGoon = true; do { switch(Main.showMenu()) { case 1: System.out.println("[1] Encrypt text\n\n" + "Please enter the text you whant to encrypt:"); objInput.setTxtplaintext(Main.objIn.nextLine()); System.out.println("\nPlease enter keyword:"); objInput.setStrkeyword(Main.objIn.nextLine()); objInput.doPreparevalues(0); Table objTable = new Table(objInput.getStrkeyword()); System.out.println("Your playfair crypt square:\n" + objTable); Encrypt objEncrypt = new Encrypt(objInput.getLisbigrams(), objTable.getListable()); List<String> lisCrypted = objEncrypt.doEncrypt(); System.out.println("Your crypted bigrams:"); for(String strBigram : lisCrypted) { System.out.print(strBigram + " "); } Main.objIn.nextLine(); break; case 2: System.out.println("[2] Decrypt text\n\n" + "Please enter the text you whant to decrypt:"); objInput.setTxtplaintext(Main.objIn.nextLine()); System.out.println("\nPlease enter Keyword:"); objInput.setStrkeyword(Main.objIn.nextLine()); objInput.doPreparevalues(1); Table objTable2 = new Table(objInput.getStrkeyword()); System.out.println("Your playfair crypt square:\n" + objTable2); Decrypt objDecrypt = new Decrypt(objInput.getLisbigrams(), objTable2.getListable()); List<String> lisPlain = objDecrypt.doDecrypt(); System.out.println("Your decrypted bigrams:"); for(String strBigram : lisPlain) { System.out.print(strBigram + " "); } Main.objIn.nextLine(); break; case 0: default: System.out.println("Thank you and good bye..."); blnGoon = false; break; } System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); } while(blnGoon); }
6
public int compareTo(final Object o) { Item other = (Item) o; int retVal = name.compareTo(other.name); if (retVal == 0) { retVal = desc.compareTo(other.desc); } return retVal; }
1
public ArrayList<int[]> getWalk() { return walkList; }
0
private void processIdentifiers(Expression e) { String type=e.getType(); if(type.equals("identifier")) { identifiers.add(e.getValue()); } for (int i = 0; i < Expression.unaryTypes.length; i++) { if (type.equals (Expression.unaryTypes[i])) { processIdentifiers(e.getSubexpression()); } } for (int i = 0; i < Expression.binaryTypes.length; i++) { if (type.equals (Expression.binaryTypes[i])) { processIdentifiers(e.getSubexpression("left")); processIdentifiers(e.getSubexpression("right")); } } }
5
public void addPoint(float x, float y) { if (includes(x,y) && (!allowDups)) { return; } ArrayList tempPoints = new ArrayList(); for(int i=0;i<points.length;i++) { tempPoints.add(new Float(points[i])); } tempPoints.add(new Float(x)); tempPoints.add(new Float(y)); int length = tempPoints.size(); points = new float[length]; for(int i=0;i<length;i++) { points[i] = ((Float)tempPoints.get(i)).floatValue(); } if(x > maxX) { maxX = x; } if(y > maxY) { maxY = y; } if(x < minX) { minX = x; } if(y < minY) { minY = y; } findCenter(); calculateRadius(); pointsDirty = true; }
8
public Integer board(Integer newPassengers) throws TrainException { if (newPassengers < NO_PASSENGERS) { throw new TrainException( "The number of new train passengers must by positive"); } if (trainSeatsAbility == NO_SEATS) { throw new TrainException("There are no seats on the train."); } // If there will be leftover passengers after boarding all passenger // cars if ((newPassengers + passengersOnTrain) > trainSeatsAbility) { int unableBoarding = (newPassengers + passengersOnTrain) - trainSeatsAbility; passengersOnTrain = trainSeatsAbility; // Goes through each carriage on the train for (int index = 0; index < train.size(); index++) { RollingStock temporaryRollingStock = train.get(index); // If it is a a passenger car if (temporaryRollingStock instanceof PassengerCar) { // Board the car with number of available seats ((PassengerCar) temporaryRollingStock) .board(((PassengerCar) temporaryRollingStock) .numberOfSeats() - ((PassengerCar) temporaryRollingStock) .numberOnBoard()); } } return unableBoarding; // Else there won't be leftover passengers on the whole train } else { passengersOnTrain += newPassengers; // boolean done indicates if we have finished checking if a // particular passenger car will fill up boolean done = false; // Goes through each carriage on the train for (int index = 0; index < train.size() && !done; index++) { RollingStock temporaryRollingStock = train.get(index); // If it is a passenger car if (temporaryRollingStock instanceof PassengerCar) { // And if there will be leftover passengers from boarding it if ((newPassengers + ((PassengerCar) temporaryRollingStock) .numberOnBoard()) > ((PassengerCar) temporaryRollingStock) .numberOfSeats()) { // Set local variable getseat to the number of available // seats int getseat = (((PassengerCar) temporaryRollingStock) .numberOfSeats() - ((PassengerCar) temporaryRollingStock) .numberOnBoard()); // And board the passenger car with the number of // available seats ((PassengerCar) temporaryRollingStock).board(getseat); // The number of new passengers has now been reduced by // that number of available seats on the passenger car newPassengers -= getseat; // Else there won't be leftover passengers after // boarding this car } else { // Finished checking if a certain passenger car will // fill up done = true; // Board the rest of the new passengers ((PassengerCar) temporaryRollingStock) .board(newPassengers); } } } return NO_PASSENGERS; // There will be no passengers leftover from // boarding } }
9
private boolean checkForOutOfBoundsForPiece(Piece piece) { int x = piece.getX(); int y = piece.getY(); if (x > width || x < 0 || y < 0 || y > height) { return true; } return false; }
4
private void renderCurrentPlayer(Graphics2D graphics) { if (objectTron.getPlayerNumber(objectTron.getActivePlayer()) == 0) graphics.drawImage(playerRed, 41 + startPointXCoordinate, 41 + startPointYCoordinate, 40, 40, null); else graphics.drawImage(playerBlue, 41 + startPointXCoordinate, 41 + startPointYCoordinate, 40, 40, null); }
1
public String getCardStatusInformation() { String cardInfo = ""; // card value, card suit, x-position of the card, y-position of the card, the card has been removed boolean and, lastly, the card is face up boolean cardInfo = value + " " + suit + " " + cardArea.x + " " + cardArea.y + " " + hasBeenRemoved + " " + isFaceUp; return cardInfo; }
0
static String readAndValidate(File file) { StringBuilder source = new StringBuilder(); try { int lineNumber = 1; String line; int nestedLoops = 0; BufferedReader reader = new BufferedReader(new FileReader(file)); while ((line = reader.readLine()) != null) { int symbolNumber = 1; for (char c : line.toCharArray()) { if (TERMINAL_SYMBOLS.contains(c + "")) { source.append(c); if (c == '[') nestedLoops++; if (c == ']') nestedLoops--; /* if (nestedLoops < 0) throw new FuckedException("Unexpected ']' at line " + lineNumber + ", symbol " + symbolNumber);*/ } symbolNumber++; } lineNumber++; } /*if (nestedLoops != 0) throw new FuckedException("Unexpected EOF. No matching ']' found.");*/ } catch (FileNotFoundException e) { throw new FuckedException("File " + file.getName() + " not found"); } catch (IOException e) { throw new FuckedException("Error reading file " + file.getName()); } return source.toString(); }
7
public static Segment intersectionTrianglePlan(Face f, double z) { Point a = intersectionSegmentPlan(f.p1, f.p2, z); Point b = intersectionSegmentPlan(f.p2, f.p3, z); Point c = intersectionSegmentPlan(f.p3, f.p1, z); if (b != null && c != null) { return new Segment(b, c); } else if (a != null && c != null) { return new Segment(a, c); } else if (a != null && b != null) { return new Segment(a, b); } return null; }
6
private void doDestroy() throws Exception { serverStopListenerList = null; clientConnectListenerList = null; clientDisconnectListenerList = null; receiveDataOnServerListenerList = null; serverExceptionListenerList = null; setConnections(null); setInitial(false); }
0
public void deleteCourseByName(Scanner a_scan, Student s1) { for (int i = 0; i < test.getStudentList().size(); i++) { if (s1.equals(test.getStudentList().get(i))) { System.out.println("Please input course name: "); String courseName = a_scan.next().toLowerCase(); Course a_course = findCourse(courseName, s1); if (a_course != null) { test.getStudentList().get(i).deleteCourse(a_course); System.out.println(courseName + " was deleted from: " + s1.toString()); } else { System.out .println("Course may not exist in student record, " + "or was incorrectly entered"); } } } }
3
private int calcNumberOfNodes(double serialProb, double pow2Prob, double uLow, double uMed, double uHi, double uProb) { double u = random.nextDouble(); if (u <= serialProb) {// serial job return 1; } double par = twoStageUniform(uLow, uMed, uHi, uProb); if (u <= (serialProb + pow2Prob)) { // power of 2 nodes parallel job par = (int)(par + 0.5); // par = round(par) } int numNodes = (int)(Math.pow(2, par) + 0.5); // round(2^par) int maxNodes = (int)(Math.pow(2, uHi) + 0.5); return numNodes <= maxNodes ? numNodes : maxNodes; }
3
public WidgetUnits(List<core.GroupOfUnits> u1, List<core.GroupOfUnits> u2, core.Hero h1, core.Hero h2) { super(); units1 = u1; units2 = u2; hero1 = h1; hero2 = h2; setSizePolicy(Policy.Fixed, Policy.Fixed); left.setMaximumSize(32, 32); right.setMaximumSize(32, 32); split.setMaximumSize(32, 32); if (h2 == null) { left.setEnabled(false); right.setEnabled(false); split.setEnabled(false); list2.setEnabled(false); h2 = hero2 = new core.Hero("", null); u2 = units2 = new ArrayList<core.GroupOfUnits>(); } setLayout(layout); list1.setMaximumSize(150, 110); list2.setMaximumSize(150, 110); layout.addWidget(name1, 0, 0); layout.addWidget(list1, 1, 0, 4, 1); layout.addWidget(name2, 0, 2); layout.addWidget(list2, 1, 2, 4, 2); layout.addWidget(left, 1, 1); layout.addWidget(right, 2, 1); layout.addWidget(split, 3, 1); updateUnits(); left.clicked.connect(this, "moveLeft()"); right.clicked.connect(this, "moveRight()"); split.clicked.connect(this, "moveSplit()"); }
1
private PDFPage createPage(int pagenum, PDFObject pageObj) throws IOException { int rotation = 0; Rectangle2D mediabox = null; // second choice, if no crop Rectangle2D cropbox = null; // first choice PDFObject mediaboxObj = getInheritedValue(pageObj, "MediaBox"); if (mediaboxObj != null) { mediabox = parseNormalisedRectangle(mediaboxObj); } PDFObject cropboxObj = getInheritedValue(pageObj, "CropBox"); if (cropboxObj != null) { cropbox = parseNormalisedRectangle(cropboxObj); } PDFObject rotateObj = getInheritedValue(pageObj, "Rotate"); if (rotateObj != null) { rotation = rotateObj.getIntValue(); } Rectangle2D bbox = ((cropbox == null) ? mediabox : cropbox); return new PDFPage(pagenum, bbox, rotation, cache); }
4
public void printChildren(Graphics g) { }
0
public static void main (String[] args){ int beerNum = 99; String word = "bootles"; while (beerNum > 0 ){ if (beerNum == 1 ){ word = "bootles"; //no singular como em uma garrafa } System.out.println("beerNum "+ " word "+ "of beer on the wall");// O erro eram sinais ++ juntos ou repetidos System.out.println("beerNum "+ " word "+ "of beer "); System.out.println("Take on down"); System.out.println("pass it around"); beerNum = beerNum - 1; if (beerNum > 0){ System.out.println("beerNum " + " word " + "of beer on the wall"); }else{ System.out.println("No more bootles of beer on the wall"); }//fim do else } }
3
private int LoadMapFromFile(String mapFilename) { String s = ""; BufferedReader in = null; try { in = new BufferedReader(new FileReader(mapFilename)); int c; while ((c = in.read()) >= 0) { s += (char)c; } } catch (Exception e) { return 0; } finally { try { in.close(); } catch (Exception e) { // Fucked. } } return ParseGameState(s); }
3
public static void moveSelectedX(int x) { if (Main.selectedId != -1 && !Main.getSelected().locked) { RSInterface rsi = Main.getInterface(); if (rsi != null) { if (rsi.children != null) { rsi.childX.set(getSelectedIndex(), rsi.childX.get(getSelectedIndex()) + x); } } } }
4
private boolean versionCheck(String title) { if (this.type != UpdateType.NO_VERSION_CHECK) { final String localVersion = this.plugin.getDescription().getVersion(); if (title.split(delimiter).length == 3) { final String remoteVersion = title.split(delimiter)[2].split(" ")[0]; // Get the newest file's version number if (this.hasTag(localVersion) || !this.shouldUpdate(localVersion, remoteVersion)) { // We already have the latest version, or this build is tagged for no-update this.result = Updater.UpdateResult.NO_UPDATE; return false; } } else { // The file's name did not contain the string 'vVersion' final String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system"); this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'"); this.plugin.getLogger().warning("Please notify the author of this error."); this.result = Updater.UpdateResult.FAIL_NOVERSION; return false; } } return true; }
5
protected boolean isPrimitiveType(String typeSignature) { if (typeSignature == null) return true; if (typeSignature.equals("Ljava/lang/String;")) return true; if (typeSignature.equals("Ljava/lang/Integer;")) return true; if (typeSignature.equals("Ljava/lang/Double;")) return true; if (typeSignature.equals("Ljava/lang/Long;")) return true; if (typeSignature.equals("Ljava/lang/Boolean;")) return true; if (typeSignature.equals("Ljava/lang/Float;")) return true; if (typeSignature.equals("Ljava/lang/Short;")) return true; if (typeSignature.equals("Ljava/lang/Byte;")) return true; return false; }
9
public static String fastUnicode(String str) { byte[] bytes = str.getBytes(Charsets.UTF_16);// 转为UTF-16字节数组 int length = bytes.length; if (length > 2) { int i = 2; char[] chars = new char[(length - i) * 3]; int index = 0; boolean isOdd = false; for (; i < length; i++) { if (isOdd = !isOdd) { chars[index++] = '\\'; chars[index++] = 'u'; } chars[index++] = digits[bytes[i] >> 4 & 0xf]; chars[index++] = digits[bytes[i] & 0xf]; } return new String(chars); } else { return ""; } }
3
public void playSong(String song) { //Don't play a song if the jukebox has been muted if(muted) { return; } //If no song with that name exists if(!songs.containsKey(song)) { System.err.println("Breakout: No song called " + song + " exists"); return; } //Stops and rewinds the current song if(activeSong != null) { activeSong.loop(0);//Stop any looping activeSong.stop(); activeSong.setFramePosition(0); } //Get the new song activeSong = songs.get(song); //Start playing the new song activeSong.start(); }
3
public void testToDateTime_wrongChronoLocalTime_Zone() { LocalDate base = new LocalDate(2005, 6, 9, COPTIC_PARIS); // PARIS irrelevant LocalTime tod = new LocalTime(12, 13, 14, 15, BUDDHIST_TOKYO); try { base.toDateTime(tod, LONDON); fail(); } catch (IllegalArgumentException ex) {} }
1
public void turnRight() { handler.sendCommand("right"); }
0
@Override public void run() { for (final Xpp3Dom testCase : results.getChildren()) { apply(testCase); } }
1
public String getArrowDotSvek() { if (this == LinkDecor.NONE) { return "none"; } else if (this == LinkDecor.EXTENDS) { return "empty"; } else if (this == LinkDecor.COMPOSITION) { if (OptionFlags.NEW_DIAMOND) { return "empty"; } return "diamond"; } else if (this == LinkDecor.AGREGATION) { if (OptionFlags.NEW_DIAMOND) { return "empty"; } return "ediamond"; } else if (this == LinkDecor.ARROW) { return "open"; } else if (this == LinkDecor.PLUS) { return "empty"; } else { throw new UnsupportedOperationException(); } }
8