method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
e13fb9f2-e67e-4d06-a171-cc7a090c77c7
3
public void addANewRoute(String newIP, ArrayList<String> configurationFile){ element = new String[3]; for(int i=0; i<configurationFile.size(); i++){ for(int j=0; j<configurationFile.size(); j++){ element[0] = getAddress(configurationFile.get(i)); element[1] = getAddress(configurationFile.get(j)); if(configurationFile.get(i).equals(configurationFile.get(j))) { element[2] = getDistance(configurationFile.get(i)); }else{ element[2] = "99"; } node.add(element); } } routingTable.put(newIP, node); keys.add(newIP); }
523ac728-f723-414c-bfca-893fe1b96209
2
private static String getAttribute( Element e, String name, Object defaultValue ) throws IOException { String value = e.getAttribute( name ); if (value.isEmpty()) { if (defaultValue == null) { throw new IOException( "Required attribute '" + name + "' for element '" + e.getTagName() + "' missing." ); } value = defaultValue.toString(); } return value; }
4969c1cb-99f8-4e05-a186-c17f1a684ff9
7
private void removeStudentFromDB(Student student) throws ServerException { if (log.isDebugEnabled()) log.debug("Method call. Arguments: " + student); try { NodeList groups = document.getElementsByTagName("group"); Element group = getGroupNodeByNumber(groups, student.getGroupNumber()); if (group == null) { ServerException ex = new ServerException( "Can not remove student from DB"); log.error("Exception", ex); throw ex; } Element studentsNode = (Element) group.getElementsByTagName( "students").item(0); if (studentsNode == null) { ServerException ex = new ServerException("Can't remove student"); log.error("Exception", ex); throw ex; } NodeList students = studentsNode.getChildNodes(); for (int i = 0; i < students.getLength(); i++) { if (students.item(i).getAttributes() != null) { if (students.item(i).getAttributes().getNamedItem("id") .getNodeValue() .equals(new Integer(student.getId()).toString())) { studentsNode.removeChild(students.item(i)); break; } } } } catch (DOMException e) { ServerException ex = new ServerException("Can't remove student " + student + " from DB", e); log.error(ex); throw ex; } }
3c48c8e8-da04-4dd3-92d3-becc2bb67574
6
final int method1714(int i, int i_24_) { anInt5866++; if (Cache.method576(i_24_, 29)) { if (((Class348_Sub51) ((Class239) this).aClass348_Sub51_3136) .aClass239_Sub25_7271.method1830((byte) -97) && !Class151.method1210((byte) -113, ((Class348_Sub51) (((Class239) this) .aClass348_Sub51_3136)) .aClass239_Sub25_7271 .method1829(-32350))) return 3; if ((((Class348_Sub51) ((Class239) this).aClass348_Sub51_3136) .aClass239_Sub8_7254.method1751(-32350) ^ 0xffffffff) == -2) return 3; } if (i_24_ == i) return 3; if (Cache.method576(i_24_, i ^ 0x56)) return 2; return 1; }
d8e42e4e-0943-4cbe-99bc-14ae9a8628f3
9
public K findKey (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { K[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != null && valueTable[i] == null) return keyTable[i]; } else if (identity) { for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return keyTable[i]; } else { for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return keyTable[i]; } return null; }
ba3df472-7e26-49d4-b3d4-6620c1d70f78
0
public Section get(int id){ return this.section[id]; }
ab4e41bd-49e1-4eb9-a4c7-940ca87f03f5
6
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(RechecheOffre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RechecheOffre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RechecheOffre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(RechecheOffre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new RechecheOffre().setVisible(true); } }); }
434660d8-d52b-4544-830c-dc9b700bb93a
1
@Test public void deltaVectors_test() { try{ double []vec1= {1.0,2.0,3.0,1.0}; double []vec2= {2.0,1.0,1.0,3.0}; double result = FastICA.deltaVectors(vec1,vec2); double exp=1.5; Assert.assertEquals(result,exp,0.0); } catch (Exception e) { // TODO Auto-generated catch block fail("Not yet implemented"); } }
9d9f9557-b197-405a-851b-f5d4368c8629
6
public static String deFront(String str) { int len = str.length(); if (len == 0) { return str; } if (len == 1) { return str.charAt(0) == 'a' ? str : ""; } if (str.charAt(0) == 'a') { if (str.charAt(1) == 'b') { return str; } else { return "a" + str.substring(2); } } if (str.charAt(1) == 'b') { return str.substring(1); } return str.substring(2); }
25bbf1ae-3378-486d-b193-3418d8dd0802
0
public Attributes[] toArray() { Attributes[] result = new Attributes[size]; System.arraycopy(attributeLists, 0, result, 0, size); return result; }
bb7ce6d5-d0bc-47d2-a988-43230ef329d8
2
public void showError(Throwable t, String resource) { String text; try { text = resources.getString(resource + ".text"); } catch (MissingResourceException e) { text = resources.getString("error.text"); } String title; try { title = resources.getString(resource + ".title"); } catch (MissingResourceException e) { title = resources.getString("error.title"); } String reason = resources.getString("error.reason"); String message = text + "\n" + MessageFormat.format(reason, new Object[] { t }); JOptionPane.showMessageDialog(this, message, title, JOptionPane.ERROR_MESSAGE); }
fb0e4672-007a-432c-9b77-a760b8fc11cf
4
public static void removeCardFromCurrentlyOpenCardViewer(String cardID) { if (!mostRecentCardViewer.isShowing()) { return; } Card previous; for (Card e : mostRecentCardViewer.cards) { previous = e; if (e.getID().equals(cardID)) { mostRecentCardViewer.cards.remove(e); mostRecentCardViewer.showCards(previous); String x = mostRecentCardViewerLabel.getText(); if (x.contains(" cards)")) { int value = Integer.parseInt( x.substring(x.lastIndexOf("(") + 1, x.lastIndexOf(" "))); mostRecentCardViewerLabel.setText( x.substring(0, x.lastIndexOf("(") + 1) + (value - 1) + " cards)"); } break; } } }
b305b9fb-7f76-4dac-8fc6-11c03d610887
3
public double findClosestValue(int nums, double sumBudgets, List<PriceBean> beans, List<SelectedPrice> result) { int numberSize = 0; for (int i = 0; i < beans.size(); i++) { if (beans.get(i).getName() > sumBudgets) { numberSize = i; break; } } int[] numbers = new int[numberSize]; double[] prices = new double[numberSize]; double closetValue = 0; for (int i = 0; i < numberSize; i++) { numbers[i] = beans.get(i).getCount(); prices[i] = beans.get(i).getName(); } closetValue = multiKnapsack(sumBudgets, nums, numbers, prices, result); return closetValue; }
73f218d1-ae86-4bd5-9548-6ceeb946eb56
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; PrefixQuery other = (PrefixQuery) obj; if (prefix == null) { if (other.prefix != null) return false; } else if (!prefix.equals(other.prefix)) return false; return true; }
a2972d49-0012-41ce-9cc4-846c2ed1212b
1
public boolean setUsertileImageFrameHeight(int height) { boolean ret = true; if (height <= 0) { this.usertileImageFrame_Height = UISizeInits.USERTILE_IMAGEFRAME.getHeight(); ret = false; } else { this.usertileImageFrame_Height = height; } setUsertileImageOverlay_Height(this.usertileImageFrame_Height); somethingChanged(); return ret; }
5c11c239-fb65-45a3-8763-6cf5b83522d0
4
public static void packData(String from) throws Exception { logger.info("Starting to pack map data"); DatabaseConnection con = DatabaseManager.getSingleton().getConnection("info"); List<PreparedStatement> statements = new ArrayList<PreparedStatement>(); for (int i = 0; i < 16384; i++) { if (new File(from + i + ".txt").exists()) { int[] data = new int[4]; BufferedReader in = new BufferedReader(new FileReader(from + i + ".txt")); for (int j = 0; j < 4; j++) { data[j] = Integer.parseInt(in.readLine()); } PreparedStatement stat = con.getStatement("INSERT INTO mapdata VALUES("+i+", "+data[0]+", "+data[1]+", "+data[2]+", "+data[3]+");"); statements.add(stat); in.close(); } logger.info("Created statement for region "+i); } logger.info("Executing statements"); for(PreparedStatement s : statements) { s.execute(); } logger.info("Done!"); }
8537269f-f452-44fe-ad35-486ab4f7867d
0
public final void ban(String channel, String hostmask) { this.sendRawLine("MODE " + channel + " +b " + hostmask); }
e312e60d-3c96-440e-875e-99ae6f41abb0
2
private boolean applySelectedUpdates() { for(DBUpdate u : updates) { console.printf("Executing Update %s ... ", u.getFileName().toString()); if (db.executeScript(u.getPath())) { console.printf("done\n"); } else { //console.printf("failed!\n"); return false; } } return true; }
c99f87bd-ecf3-4b25-a1d4-fc73f4c51c71
9
@Override public void eliminar(Elemento e) { Integer aEliminar = e.get(); //Explicación. ConsolaManager.getInstance().escribirInfo(Messages.getString("HASH_ABIERTO_NOMBRE") + tipo, Messages.getString("HASH_ABIERTO_ELEMENTO_A_INSERTAR", new Object[]{aEliminar} )); //$NON-NLS-1$ //$NON-NLS-2$ //Se busca el balde. int baldeABuscar = h(aEliminar); //Explicación ConsolaManager.getInstance().escribirInfo(Messages.getString("HASH_ABIERTO_NOMBRE") + tipo,Messages.getString("HASH_ABIERTO_EXPLICACION_15", new Object[]{e.getNum(), baldeABuscar} )); //$NON-NLS-1$ //$NON-NLS-2$ if ( ! separadoSolo ) ConsolaManager.getInstance().escribirInfo(Messages.getString("HASH_ABIERTO_NOMBRE") + tipo, Messages.getString("HASH_ABIERTO_EXPLICACION_16")); //$NON-NLS-1$ //$NON-NLS-2$ //Si el balde encontrado < frontera entonces el elemento está en un balde particionado. if ( baldeABuscar < frontera ){ baldeABuscar = hprima(aEliminar); //Explicación ConsolaManager.getInstance().escribirInfo(Messages.getString("HASH_ABIERTO_NOMBRE") + tipo,Messages.getString("HASH_ABIERTO_EXPLICACION_17", new Object[]{e.getNum(), baldeABuscar} )); //$NON-NLS-1$ //$NON-NLS-2$ } //Referencia al elemento que se va a devolver. int posicionEncontrada = posicionElementoEnBalde(baldeABuscar,aEliminar); //Si lo encontre seteo como borrado y me fijo si tengo que hacer reasignaciones. if ( posicionEncontrada != -1 ){ //Seteo que se borro espacioDeAlmacenamiento.elementAt(baldeABuscar).elementAt(posicionEncontrada).setEstado(Celda.BORRADO); cantidadRegistros--; //Explicación ConsolaManager.getInstance().escribirInfo(Messages.getString("HASH_ABIERTO_NOMBRE") + tipo,Messages.getString("HASH_ABIERTO_EXPLICACION_18")); //$NON-NLS-1$ //$NON-NLS-2$ //Variable Auxiliar int borrados = 0; //Tengo que fijarme si el problema esta en las ranuras secundarias. int parado = 0; for ( int actual = ranuras ; actual < espacioDeAlmacenamiento.elementAt(baldeABuscar).size() ; actual ++){ //Si encuentro celdas borradas o virgenes aumento el contador de borrados. if (espacioDeAlmacenamiento.elementAt(baldeABuscar).elementAt(actual).getEstado() == Celda.BORRADO || espacioDeAlmacenamiento.elementAt(baldeABuscar).elementAt(actual).getEstado() == Celda.VIRGEN ){ borrados++; } //Aumento donde estoy parado dentro de una ranura secundaria. parado++; //Llegué al limite de la ranura secundaria. if ( parado == ranurasSecundarias){ //Vuelvo al principio. parado = 0; //Si estan todos vacios los debo eliminar. if ( borrados == ranurasSecundarias){ for ( int i = 0 ; i < ranurasSecundarias ; i++){ espacioDeAlmacenamiento.elementAt(baldeABuscar).removeElementAt(actual); actual--; } } //Reseteo el contador de borrados. borrados = 0; } } } ConsolaManager.getInstance().escribirInfo(Messages.getString("HASH_ABIERTO_NOMBRE") + tipo, Messages.getString("HASH_ABIERTO_ELEMENTO_ELIMINADO", new Object[]{aEliminar} )); //$NON-NLS-1$ //$NON-NLS-2$ //Se Agrega la captura agregarCaptura(); }
ee2159e1-e1a8-4bc5-ab66-260443869d55
2
public String getFingerPrint(){ if(hash==null) hash=genHash(); byte[] kblob=getPublicKeyBlob(); if(kblob==null) return null; return getKeySize()+" "+Util.getFingerPrint(hash, kblob); }
a43c389b-2fd9-4b89-a037-a4d0468e1078
2
public void setCategorieParent(Categorie categorie) { if (getCategorieParent() != null) { getCategorieParent().getSousCategories().remove(this); getCategorieParent().ajouterNbreSujets(-getNbreSujets()); getCategorieParent().ajouterNbreReponses(-getNbreReponses()); } categorieParent = categorie; if (!getCategorieParent().getSousCategories().contains(this)) { getCategorieParent().getSousCategories().add(this); getCategorieParent().ajouterNbreSujets(getNbreSujets()); getCategorieParent().ajouterNbreReponses(getNbreReponses()); } setJeuAssocie(getCategorieParent().getJeuAssocie()); }
693e5901-86ac-4705-8609-b72ad4c81fea
0
private boolean isValidInput(final String s) { return s.matches("[0-9]{4}[-][0-9]{1,2}"); }
8803151c-a8f2-4f55-a5c7-ca75b899e94a
5
private void buttonComputeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonComputeActionPerformed String errorMessage = ""; boolean error = true; try { loanCalculate.setMonthlyInterest(Float.parseFloat(textInterest.getText())); } catch(Exception e) { error = false; } try{ loanCalculate.setPrincipalBalance(Float.parseFloat(textPrincipal.getText())); } catch(Exception r) { error = false; } loanCalculate.setTotalNumberOfPayment(1); Date grantdt = new Date(); currentDate = grantdt; if(error) { principal = Float.parseFloat(textPrincipal.getText()); interest = loanCalculate.getInterest(); interestrt = Float.parseFloat(textInterest.getText()); totalPayment = loanCalculate.getCashloan(); totInterest = totalPayment - principal; labelTotalPayment.setText(Float.toString(totalPayment)); labelTotalInterest.setText(Float.toString(totInterest)); labelTotalPrincipal.setText(Float.toString(principal)); checkNo = textCheckNo.getText(); currentdtString = df.format(currentDate); if(textEndDate.getText().length() != 0) { String dateToFormatEnd = textEndDate.getText(); try { enddt = df.parse(dateToFormatEnd); finalEndString = df.format(enddt); } catch (ParseException ex) { Logger.getLogger(AddCashloan.class.getName()).log(Level.SEVERE, null, ex); } } buttonConfirm.setEnabled(true); buttonCompute.setEnabled(false); } }//GEN-LAST:event_buttonComputeActionPerformed
aeaf935a-52b8-4936-b6e6-74642566b56a
1
protected void initializeHttpClient(HttpClient aaHTTPClient) { if (aaHTTPClient == null) { this.caHTTPClient = createHttpClient(); setSocketTimeout(DEFAULT_SOCKET_TIMEOUT); setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT); } else { this.caHTTPClient = aaHTTPClient; } }
df4c3ce6-cf77-4876-af18-1957ac47d29c
4
public static boolean checkFor0Points(Data myData) { //0 points only allowed in "none" semesters for(Subject thisSubject:myData.subjects){ for(Semester thisSemester:thisSubject.semesters){ if (thisSemester.mark==0 && thisSemester.usedState!=UsedState.none) return false; } } return true; }
000ff46d-64b4-412c-9a1d-925dbaaa869a
1
public float fruitOccuranceMLE(int fruit) { float sum = 0f; for (int i = 0; i < occuranceHist[fruit].length; i++){ sum += occuranceHist[fruit][i] * i; } return sum / occuranceHist[0].length; }
911422bc-de2b-43a6-bc2c-460fd9a2e5ed
0
public static String getRandomGrid(){ Random rand = new Random(); int max = 50; int randomNum = rand.nextInt(max); System.out.println(randomNum); return possibleGrids[randomNum]; }
b71a397a-52c1-4d8b-9a96-6811a0dfdf80
2
public static CubicSpline[] oneDarray(int n, int m){ if(m<3)throw new IllegalArgumentException("A minimum of three data points is needed"); CubicSpline[] a =new CubicSpline[n]; for(int i=0; i<n; i++){ a[i]=CubicSpline.zero(m); } return a; }
488cc161-a613-4f84-8efc-903faa2fb7ca
8
private String makeDurationString(Duration dur) { Dur d = VEventHelper.durationToICALDur(dur); String out = ""; int days = d.getDays(); if (days > 0) out += days + " " + (days == 1 ? ApplicationSettings.getInstance().getLocalizedMessage("lvip.day") : ApplicationSettings.getInstance().getLocalizedMessage("lvip.days")); int hrs = d.getHours(); if (hrs > 0) { if (out.length() > 0) out += ", "; out += +hrs + " " + (hrs == 1 ? ApplicationSettings.getInstance().getLocalizedMessage("lvip.hr") : ApplicationSettings.getInstance().getLocalizedMessage("lvip.hrs")); } int mins = d.getMinutes(); if (mins > 0) { if (out.length() > 0) out += ", "; out += mins + " " + (mins == 1 ? ApplicationSettings.getInstance().getLocalizedMessage("lvip.min") : ApplicationSettings.getInstance().getLocalizedMessage("lvip.mins")); } return out; }
afd158e7-df9b-4102-a05f-2f427a98f353
1
@Override public void initializeLanguage() { Array<Letter> lettersAvailable = this.getLanguage().getLettersAvailable(); char[] letterDistribution = new char[] { 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'n', 'n', 'n', 'n', 'n', 'n', 'r', 'r', 'r', 'r', 'r', 'r', 't', 't', 't', 't', 't', 't', 'l', 'l', 'l', 'l', 's', 's', 's', 's', 'u', 'u', 'u', 'u', 'd', 'd', 'd', 'd', 'g', 'g', 'g', 'b', 'b', 'c', 'c', 'm', 'm', 'p', 'p', 'f', 'f', 'h', 'h', 'v', 'v', 'w', 'w', 'y', 'y', 'k', 'j', 'x', 'q', 'z' }; for (int i = 0; i < letterDistribution.length; i++) { Random random = new Random(); Letter letter = new Letter(letterDistribution[i], i + random.nextInt()*random.nextInt()*random.nextInt()); lettersAvailable.add(letter); } this.getLanguage().setDictionaryPath(Constants.ENGLISH_WORD_LIST_PATH); WordListParser.getInstance().parse(this);// TODO: think a better way // where to put it }
a9ff7fc1-d33e-4fd7-aac0-159d9b7ee529
2
public static Clientes sqlLeer(Clientes cli){ String sql="SELECT * FROM clientes WHERE idclientes = '"+cli.getId()+"'"; if(!BD.getInstance().sqlSelect(sql)){ return null; } if(!BD.getInstance().sqlFetch()){ return null; } cli.setRut(BD.getInstance().getInt("rut")); cli.setDv(BD.getInstance().getString("dv").charAt(0)); cli.setNombre(BD.getInstance().getString("nombre")); cli.setApe_paterno(BD.getInstance().getString("ape_paterno")); cli.setApe_materno(BD.getInstance().getString("ape_materno")); cli.setEmail(BD.getInstance().getString("email")); cli.setFecha_nac((BD.getInstance().getString("fecha_nac")) ); cli.setTelefono(BD.getInstance().getString("telefono")); cli.setSexo(BD.getInstance().getString("sexo").charAt(0)); cli.setDireccion(BD.getInstance().getString("direccion")); return cli; }
f89023b2-cc7e-40c9-880c-4b0e715269c8
5
@Deprecated private void flipMap(){ LogicalTile[][] map = worldMap; LogicalTile[][] fliped = new LogicalTile[map.length][map[0].length]; int newX; int newY =0; for(int y = map.length-1;y>=0 ;y--){ newX = 0; for(int x = map.length-1;x >=0;x--){ fliped[newY][newX] = map[y][x]; //System.out.println(newY+":"+newX+"<--"+y+":"+x); newX++; } newY++; } worldMap = fliped; for(int x = 0; x < worldMap.length; x++) for(int y = 0; y <worldMap[x].length;y++) if(gameBoard[x][y] != null) gameBoard[x][y].curLocation = new Point(x,y); }
7eaaea64-3d26-4474-881b-0359d9cc474c
5
private void updateWaitTimes(double timestep) { if (this.timeSinceRTL != -1) { this.timeSinceRTL += timestep; } for (Message m: sentMessageDuration.keySet()) { double time = sentMessageDuration.get(m); sentMessageDuration.put(m, time + timestep); } this.timeSinceHeartbeat += timestep; if(this.children.size() > 0) { this.timeToHeartbeat -= timestep; } if ((this.parent == -1) && (this.hasService == false)) { this.timeWithoutConnection += timestep; } }
7657b4da-2870-41ba-bb52-dfc39eb96f82
9
public void checkInputs(List inputs) throws IllegalArgumentException { Object [] list = inputs.toArray(); // first off, check that we got the right number of paramaters if (list.length != 3) throw new IllegalArgumentException("requires three inputs"); // now, try to cast the first element into a function Function function = null; if (list[0] instanceof Function) { function = (Function)(list[0]); } else if (list[0] instanceof VariableReference) { Expression xpr = ((VariableReference)(list[0])). getReferencedDefinition().getExpression(); if (xpr instanceof Function) function = (Function)xpr; } if (function == null) throw new IllegalArgumentException("first arg to higher-order " + " function must be a function"); // check that the function returns a boolean if (! function.getReturnType().toString(). equals(BooleanAttribute.identifier)) throw new IllegalArgumentException("higher-order function must " + "use a boolean function"); // get the two inputs Evaluatable eval1 = (Evaluatable)(list[1]); Evaluatable eval2 = (Evaluatable)(list[2]); // the first arg might be a bag if (secondIsBag && (! eval1.returnsBag())) throw new IllegalArgumentException("first arg has to be a bag"); // the second arg must be a bag if (! eval2.returnsBag()) throw new IllegalArgumentException("second arg has to be a bag"); // finally, we need to make sure that the given type will work on // the given function List args = new ArrayList(); args.add(eval1); args.add(eval2); function.checkInputsNoBag(args); }
45ee66db-10b3-45b2-8acc-429b90b5c88a
7
public boolean searchMatrix(int[][] matrix, int target) { int low; int high; int mid; low = 0; high = matrix.length - 1; while (low <= high) { mid = (low + high) >>> 1; int value = matrix[mid][0]; if (target < value) high = mid - 1; else if (target > value) low = mid + 1; else return true; } if (low == 0) return false; int[] arr = matrix[low - 1]; low = 0; high = arr.length - 1; while (low <= high) { mid = (low + high) >>> 1; int value = arr[mid]; if (target < value) high = mid - 1; else if (target > value) low = mid + 1; else return true; } return false; }
27e48d35-c1cb-4bf1-9696-63c9229d4f7d
0
public final void show() { StackPane parentRoot = (StackPane) ((Stage) stage.getOwner()) .getScene().getRoot(); parentRoot.getChildren().add(mask); stage.show(); }
fc3e7e09-3b5e-4d15-ac02-fa13990c6913
0
public DriverThread(Vector<File> imageQueue) { this.imageQueue = imageQueue; }
32f5547d-47fc-412d-b2b7-64ab3530eac4
1
public void testFactory_standardWeeksIn_RPeriod() { assertEquals(0, Weeks.standardWeeksIn((ReadablePeriod) null).getWeeks()); assertEquals(0, Weeks.standardWeeksIn(Period.ZERO).getWeeks()); assertEquals(1, Weeks.standardWeeksIn(new Period(0, 0, 1, 0, 0, 0, 0, 0)).getWeeks()); assertEquals(123, Weeks.standardWeeksIn(Period.weeks(123)).getWeeks()); assertEquals(-987, Weeks.standardWeeksIn(Period.weeks(-987)).getWeeks()); assertEquals(1, Weeks.standardWeeksIn(Period.days(13)).getWeeks()); assertEquals(2, Weeks.standardWeeksIn(Period.days(14)).getWeeks()); assertEquals(2, Weeks.standardWeeksIn(Period.days(15)).getWeeks()); try { Weeks.standardWeeksIn(Period.months(1)); fail(); } catch (IllegalArgumentException ex) { // expeceted } }
187a2d40-a524-45bf-9cc1-dbbfe8ecb004
0
public Artikel getArtikel() { return artikel; }
55e3d883-64aa-4026-a728-3f71a8b18e52
1
public void testConstructorEx3_TypeArray_intArray() throws Throwable { try { new Partial(new DateTimeFieldType[] {DateTimeFieldType.dayOfYear()}, null); fail(); } catch (IllegalArgumentException ex) { assertMessageContains(ex, "must not be null"); } }
5cd6562e-2772-4963-94e8-16f517f8d041
1
public static double sumRow(int[][] matrix, int u) { double a = 0.0D; for(int m = 0; m < matrix[u].length; m++) { a += matrix[u][m]; } return a; }
37b14a61-5194-414f-889f-5dfa4606acda
9
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Pair other = (Pair) obj; if (this.first == null) { if (other.first != null) { return false; } } else if (!this.first.equals(other.first)) { return false; } if (this.second == null) { if (other.second != null) { return false; } } else if (!this.second.equals(other.second)) { return false; } return true; }
459bb2d2-79cd-4122-9fb8-783ec1602146
8
public static void main(String[] args) { Scanner sc = new Scanner(System.in); String login; boolean bb = false; while(!bb){ System.out.println("Input your Login"); login = sc.nextLine(); if(valid(login)){ bb = true; if(showInfo("/S/"+login+".txt")){ boolean b = false; while(!b){ System.out.println("Input your Password"); String password = sc.nextLine(); User user = (User) Deserialize("/S/"+login+".txt"); if(password.equals(user.password)){ b = true; SimpleDateFormat sdf = new SimpleDateFormat(); System.out.println( sdf.format(user.lastlogintime) );// old date user.lastlogintime = new Date(); System.out.println(); System.out.println( sdf.format(user.lastlogintime) );// now Serialize(user, "/S/"+login+".txt"); }else{ System.out.println(); System.out.println("You input wrong password!"); } } }else{ boolean b = false; while(!b){ System.out.println("Input your Password"); String password = sc.nextLine(); if(password.length() > 3 && password.length() < 40){ b = true; Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(); System.out.println(sdf.format(date)); User user = new User(login, password, date); Serialize(user, "/S/"+login+".txt"); }else{ System.out.println("Error Password. Password must contain 3 - 40 numbers!"); } } } } } }
5ab30be3-d8aa-47cb-a8b7-f14dd1d0fcc0
8
public pagingAction(int currentPage, int totalCount, int blockCount, int blockPage) { this.blockCount = blockCount; this.blockPage = blockPage; this.currentPage = currentPage; this.totalCount = totalCount; // 전체 페이지 수 totalPage = (int) Math.ceil((double) totalCount / blockCount); if (totalPage == 0) { totalPage = 1; } // 현재 페이지가 전체 페이지 수보다 크면 전체 페이지 수로 설정 if (currentPage > totalPage) { currentPage = totalPage; } // 현재 페이지의 처음과 마지막 글의 번호 가져오기. startCount = (currentPage - 1) * blockCount; endCount = startCount + blockCount - 1; // 시작 페이지와 마지막 페이지 값 구하기. startPage = (int) ((currentPage - 1) / blockPage) * blockPage + 1; endPage = startPage + blockPage - 1; // 마지막 페이지가 전체 페이지 수보다 크면 전체 페이지 수로 설정 if (endPage > totalPage) { endPage = totalPage; } // 이전 block 페이지 pagingHtml = new StringBuffer(); if (currentPage > blockPage) { pagingHtml.append("<a href=listAction.action?currentPage=" + (startPage - 1) + ">"); pagingHtml.append("이전"); pagingHtml.append("</a>"); } pagingHtml.append("&nbsp;|&nbsp;"); //페이지 번호.현재 페이지는 빨간색으로 강조하고 링크를 제거. for (int i = startPage; i <= endPage; i++) { if (i > totalPage) { break; } if (i == currentPage) { pagingHtml.append("&nbsp;<b> <font color='red'>"); pagingHtml.append(i); pagingHtml.append("</font></b>"); } else { pagingHtml .append("&nbsp;<a href='listAction.action?currentPage="); pagingHtml.append(i); pagingHtml.append("'>"); pagingHtml.append(i); pagingHtml.append("</a>"); } pagingHtml.append("&nbsp;"); } pagingHtml.append("&nbsp;&nbsp;|&nbsp;&nbsp;"); // 다음 block 페이지 if (totalPage - startPage >= blockPage) { pagingHtml.append("<a href=listAction.action?currentPage=" + (endPage + 1) + ">"); pagingHtml.append("다음"); pagingHtml.append("</a>"); } }
55a1f003-c9dd-4b3a-9d62-3765f2763d8a
8
public BigDecimal getAvailability() { LinkedHashSet<PhysicalLink> uniqPhysicalLinks = new LinkedHashSet<PhysicalLink>(); LinkedHashSet<PhysicalNode> uniqIntermediaryNodes = new LinkedHashSet<PhysicalNode>(); for(VirtualLink virtualLink : linksMapping.keySet()) { PhysicalNode sourcePhysicalNode = getHostingNodeFor( (VirtualNode) virtualLink.getSourceNode()); PhysicalNode destinyPhysicalNode = getHostingNodeFor( (VirtualNode) virtualLink.getDestinyNode()); ArrayList<PhysicalLink> hostingLinks = linksMapping.get(virtualLink); for(PhysicalLink hostingLink : hostingLinks) { uniqPhysicalLinks.add(hostingLink); PhysicalNode hostingLinkSourceNode = (PhysicalNode) hostingLink.getSourceNode(); PhysicalNode hostingLinkDestinyNode = (PhysicalNode) hostingLink.getDestinyNode(); PhysicalNode[] hostingLinkNodes = { hostingLinkSourceNode, hostingLinkDestinyNode }; for(PhysicalNode hostingLinkNode : hostingLinkNodes) { if(!hostingLinkNode.equals(sourcePhysicalNode) && !hostingLinkNode.equals(destinyPhysicalNode)) { uniqIntermediaryNodes.add(hostingLinkNode); } } } } BigDecimal availability = new BigDecimal(1); for(PhysicalNode hostingNode : uniqPhysicalNodes()) { availability = availability.multiply(hostingNode.getNodeAvailability(), MathContext.DECIMAL64); } for(PhysicalLink hostingLink : uniqPhysicalLinks) { availability = availability.multiply(hostingLink.getAvailability(), MathContext.DECIMAL64); } for(PhysicalNode intermediaryNode : uniqIntermediaryNodes) { availability = availability.multiply(intermediaryNode. getIntermediaryNodeAvailability(), MathContext.DECIMAL64); } return availability; }
c86c8505-f552-4ed2-a24e-ff8bc18c7072
9
@Override public ArrayList<BERoleTime> readRoleTime() throws SQLException { ArrayList<BERoleTime> res = new ArrayList<>(); Statement stm = m_connection.createStatement(); stm.execute("select * from [Role/Time] " + "inner join Incident " + "on [Role/Time].incidentId = Incident.id " + "inner join Fireman " + "on [role/time].firemanId = fireman.id " + "where Incident.isDone = 0 " + "order by [Role/Time].vehicleOdinNumber, fireman.firstName, Fireman.lastName"); ResultSet result = stm.getResultSet(); while (result.next()) { int incidentid = result.getInt("incidentId"); BEIncident refIncident = null; for (BEIncident be : readRecentIncidents()) { if (be.getM_id() == incidentid) { refIncident = be; } } int firemanid = result.getInt("firemanId"); BEFireman refFireman = null; for (BEFireman be : readFiremen()) { if (be.getM_id() == firemanid) { refFireman = be; } } boolean isOnStation = result.getBoolean("isOnStation"); int roleid = result.getInt("roleId"); BERole refRole = null; for (BERole be : readRoles()) { if (be.getM_id() == roleid) { refRole = be; } } int vehicleodinnumber = result.getInt("vehicleOdinNumber"); BEVehicle refVehicle = null; for (BEVehicle be : readVehicles()) { if (be.getM_odinNumber() == vehicleodinnumber) { refVehicle = be; } } int hours = result.getInt("hours"); BERoleTime be = new BERoleTime(refIncident, refFireman, isOnStation, refRole, refVehicle, hours); res.add(be); } return res; }
d9c50e23-2072-4287-b147-0f0019d9a9c7
4
@Override public void validate() { if (platform == null) { addActionError("Please Select Platorm"); } if (location == null) { addActionError("Please Select Location"); } if (gender == null) { addActionError("Please Select Gender"); } if (age == null) { addActionError("Please Select Age"); } }
83fa14a1-2c9f-4f3f-b174-a523e51ccfbd
0
public void showAllPorts() { model.showAllData(); }
11566910-6848-49c4-81a6-e573c627eff6
7
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final LicenciaConductor other = (LicenciaConductor) obj; if (this.numero != other.numero) { return false; } if (!Objects.equals(this.categoria, other.categoria)) { return false; } if (!Objects.equals(this.vencimiento, other.vencimiento)) { return false; } if (!Objects.equals(this.restriccion, other.restriccion)) { return false; } if (!Objects.equals(this.departamento, other.departamento)) { return false; } return true; }
5cce5491-5de0-4469-9cc3-a08bc627df56
1
@Override public int top() { if (amount != 0) { return stack[0]; } else return error; }
4b5dac56-5e9c-4ff1-a266-a7ed92dc387b
9
protected ToggleButton createToggleButton(final Object[] args) { String tip = new String(); String text = new String(); try{ tip = ((args.length > 0) && (args[0] != null)) ? args[0].toString() : null; } catch(final Throwable exp) { System.out.println(exp.getMessage()); } try{ text = ((args.length > 1) && (args[1] != null)) ? args[1].toString() : null; } catch(final Throwable exp) { System.out.println(exp.getMessage()); } final Object imageArg = args[2]; final Dimension size = ((args.length > 3) && (args[3] instanceof Dimension)) ? (Dimension) args[3] : new Dimension(-1, -1); final ToggleButton retval = new ToggleButton( tip, (imageArg == null) ? text : null, imageArg, size, false); retval.setActionCommand(tip); toggleButtonList.addElement(retval); return retval; }
b0227250-8313-48d1-a0f1-a10199193ef3
0
public static void main(String[] args) { Originator o = new Originator(); o.createMemento(); o.modifyState(80); // 获取备份 o.getMemento(); }
41f291c8-8e46-4a6a-8126-0226f9c5d9b5
1
public CodeEntry(byte[] buf) { int[] off = new int[1]; off[0] = 0; while (off[0] < buf.length) { pe.put(Utils.strd(buf, off), Utils.strd(buf, off)); } }
e065bc1b-714c-4fca-adf8-f1dc0512caf2
4
public void checkCharacterCollision(){ for(Character c1 : characters){ for(Character c2 : characters){ if( !c1.equals(c2) ){ if(c1.getBounds().intersects(c2.getBounds())){ moveBack(c1); } } } } }
747a9cd7-cca0-4669-800b-a2e416ef4678
2
private boolean wrapNonInfixIfCondition(IfStatement parent, AstNode node) { if (parent.getCondition() != node) return false; else if (node instanceof ParenthesizedExpression) return false; else return true; }
4cc6db12-a02a-43e0-bcbe-1b763c008c9a
2
@Override public void draw(Graphics2D g) { bg.draw(g); p.draw(g); op.draw(g); Rectangle rect = p.getRectangle(); g.draw(rect); Rectangle rect2 = new Rectangle(p.getx() - (p.getWidth() / 2), p.gety() - (p.getHeight() / 2), p.getWidth(), p.getHeight()); g.draw(rect2); // health1 g.drawImage(Images.hud.getSubimage(0, 50, Math.max(p.health, 1), 50), 0, 0, Math.max(p.health, 1), 50, null); // health2 g.drawImage(Images.hud.getSubimage(0, 50, Math.max(op.health, 1), 50), 320, 0, Math.min(-op.health, 1), 50, null); // health bar contour g.drawImage(Images.hud.getSubimage(0, 0, 320, 50), 0, 0, 320, 50, null); // shield g.drawImage(Images.hud.getSubimage(50, 100, 50, 50), (320 / 2) - 25, 0, 50, 50, null); int xc = 70; int yx = 95; g.setFont(maximilien); g.setColor(Color.BLACK); g.drawString(endResult, xc + 2, yx + 2); g.setColor(Color.ORANGE); g.drawString(endResult, xc, yx); g.setColor(Color.BLACK); g.setFont(new Font("Maximilien", Font.PLAIN, 15)); g.drawString(getDiff() == 0 ? "Easy" : getDiff() == 1 ? "Normal" : "Hard", 143, 28); }
56fe3a29-7dae-4cca-a779-dca3d2355619
3
public void speelMuziek(Soundtracks huidigeSoundtrack){ if(this.huidigeSoundtrack != huidigeSoundtrack){ if(this.huidigeSoundtrack != null) this.huidigeSoundtrack.getGeluid().stop(); this.huidigeSoundtrack = huidigeSoundtrack; if(this.huidigeSoundtrack != null) huidigeSoundtrack.getGeluid().loop(); } }
f33ba30b-89da-4693-a40a-acb950b85979
8
public String toString() { switch(t) { case FAILURE: return "FAILURE " + node; case START: return "START " + node; case EXIT: return "EXIT"; case COMMAND: return "COMMAND " + node + " executes " + command; case ECHO: return "ECHO " + msg; case TIME: return "TIME " + msg; case DELIVERY: return "DELIVERY " + p; case TIMEOUT: return "TIMEOUT " + to; default: return "UNKNOWN EVENT TYPE " + t; } }
9fce16e9-0f02-4a23-bee7-0e99055085a0
7
public static boolean isStaff(CommandSender sender) { if(sender instanceof ConsoleCommandSender) { return true; } Player player = (Player) sender; if(!StaffChat.getStaffChat().isVaultPresent()) { return false; } if(StaffChat.getStaffChat().isPermissionsPresent()) { if(StaffChat.getStaffChat().getPermission().hasGroupSupport()) { for(String playerGroup : StaffChat.getStaffChat().getPermission().getPlayerGroups(player)) { for(String staffGroup : StaffChat.getStaffChat().getConfiguration().getStaffGroups()) { if(staffGroup.equalsIgnoreCase(playerGroup)) { return true; } } } } } return false; }
02d20826-7089-4026-902e-0971ad563067
6
public String getQuad() { String stt = "0"; //search for 4 equal cards... if (cards[0].getRank() == cards[1].getRank() && cards[1].getRank() == cards[2].getRank() && cards[2].getRank() == cards[3].getRank()) { stt = Character.toString(cards[0].getCharCard()) + cards[4].getCharCard(); return stt; } if (cards[1].getRank() == cards[2].getRank() && cards[2].getRank() == cards[3].getRank() && cards[3].getRank() == cards[4].getRank()) { stt = Character.toString(cards[1].getCharCard()) + cards[0].getCharCard(); } return stt; }
6632a654-40fb-4cfb-ae10-fbcae9fef449
5
private void respawnPlayer() { long time = System.currentTimeMillis(); try { for (Player p : players) { if (p.getTimeDied() != 0 && time - p.getTimeDied() > RESPAWN_TIME) { p.respawn(); Server.sendToAll(5, p.getName()); } } } catch (NullPointerException e) { e.getMessage(); } catch (ConcurrentModificationException e) { e.getMessage(); } }
54983974-1e17-4fbe-9289-0992c9970b87
5
public static void main(String args[]){ Game game = new ConnectFour(); ConnectFourAI C4AI; ConnectFourAI C4AI2; C4AI2 = new ConnectFourAI(game, "test1",Color.blue); C4AI = new ConnectFourAI(game,"test2",Color.red); if(C4AI.getGame() == game) System.out.println("Set Game Success"); if(C4AI.getPlayerName() == "test2") System.out.println("Name Set"); if(C4AI.getPlayerColour() == Color.red) System.out.println("Color Ok"); C4AI = new ConnectFourAI(game, "test3",Color.yellow); C4AI = new ConnectFourAI(game); System.out.println(C4AI.setAIMove()); Coordinate cord = new Coordinate(C4AI.GAME_WIDTH,C4AI.GAME_HEIGHT, Game.PlayerTurn.PLAYER1); C4AI.SetTime(C4AI.GAME_WIDTH); if(C4AI.getTime() == C4AI.GAME_WIDTH) System.out.println("Time edited"); C4AI.SetRun(true); if(C4AI.getRun() == true) System.out.println("Game Running"); }
c83b57a1-bb86-4654-a752-c78c6d268f3e
3
@Override public void updateMedicine(MedicineDTO medicine) throws SQLException { Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.update(medicine); session.getTransaction().commit(); } catch (Exception e) { System.err.println("Error while updating a medicine!"); } finally { if (session != null && session.isOpen()) session.close(); } }
5f450821-5264-4aab-ba98-b513cbd33f8d
4
public void maintainBounderies(float pf_width, float pf_height) { /*Check if the rectangle is outside the canvas bounderies and move it inside if that is the case*/ if(x < 0) { setXPos(0); } else if((x + width) > pf_width) { setXPos(pf_width - width); } if(y < Breakout.STATUS_FIELD_HEIGHT) { setYPos(Breakout.STATUS_FIELD_HEIGHT); } else if((y + height) > pf_height) { setYPos(pf_height - height); } }
6be37902-d539-4fa2-aad7-cb563e451bf6
0
@XmlElement public void setName(String name) { this.name = name; }
0c9a5e93-380b-42e1-9c38-30bea3f5281b
9
public void updateThisPlayerMovement(Stream str) { synchronized(this) { if(mapRegionDidChange) { str.createFrame(73); str.writeWordA(mapRegionX+6); str.writeWord(mapRegionY+6); } if(didTeleport) { str.createFrameVarSizeWord(81); str.initBitAccess(); str.writeBits(1, 1); str.writeBits(2, 3); str.writeBits(2, heightLevel); str.writeBits(1, 1); str.writeBits(1, (updateRequired) ? 1 : 0); str.writeBits(7, currentY); str.writeBits(7, currentX); return ; } if(dir1 == -1) { // don't have to update the character position, because we're just standing str.createFrameVarSizeWord(81); str.initBitAccess(); isMoving = false; if(updateRequired) { // tell client there's an update block appended at the end str.writeBits(1, 1); str.writeBits(2, 0); } else { str.writeBits(1, 0); } if (DirectionCount < 50) { DirectionCount++; } } else { DirectionCount = 0; str.createFrameVarSizeWord(81); str.initBitAccess(); str.writeBits(1, 1); if(dir2 == -1) { isMoving = true; str.writeBits(2, 1); str.writeBits(3, Misc.xlateDirectionToClient[dir1]); if(updateRequired) str.writeBits(1, 1); else str.writeBits(1, 0); } else { isMoving = true; str.writeBits(2, 2); str.writeBits(3, Misc.xlateDirectionToClient[dir1]); str.writeBits(3, Misc.xlateDirectionToClient[dir2]); if(updateRequired) str.writeBits(1, 1); else str.writeBits(1, 0); } } } }
7d7819e7-8aae-4d45-aeb2-e651605ef278
9
void compress( int init_bits, OutputStream outs ) throws IOException { int fcode; int i /* = 0 */; int c; int ent; int disp; int hsize_reg; int hshift; // Set up the globals: g_init_bits - initial number of bits g_init_bits = init_bits; // Set up the necessary values clear_flg = false; n_bits = g_init_bits; maxcode = MAXCODE( n_bits ); ClearCode = 1 << ( init_bits - 1 ); EOFCode = ClearCode + 1; free_ent = ClearCode + 2; char_init(); ent = nextPixel(); hshift = 0; for ( fcode = hsize; fcode < 65536; fcode *= 2 ) ++hshift; hshift = 8 - hshift; // set hash code range bound hsize_reg = hsize; cl_hash( hsize_reg ); // clear hash table output( ClearCode, outs ); outer_loop: while ( (c = nextPixel()) != EOF ) { fcode = ( c << maxbits ) + ent; i = ( c << hshift ) ^ ent; // xor hashing if ( htab[i] == fcode ) { ent = codetab[i]; continue; } else if ( htab[i] >= 0 ) // non-empty slot { disp = hsize_reg - i; // secondary hash (after G. Knott) if ( i == 0 ) disp = 1; do { if ( (i -= disp) < 0 ) i += hsize_reg; if ( htab[i] == fcode ) { ent = codetab[i]; continue outer_loop; } } while ( htab[i] >= 0 ); } output( ent, outs ); ent = c; if ( free_ent < maxmaxcode ) { codetab[i] = free_ent++; // code -> hashtable htab[i] = fcode; } else cl_block( outs ); } // Put out the final code. output( ent, outs ); output( EOFCode, outs ); }
d75cceef-edd9-4b79-b451-8ed8b213c3c7
6
public static Boolean isPrime(Long n) { boolean prime = true; for (long i = 3; i <= Math.sqrt(n); i += 2){ if (n % i == 0) { prime = false; break; } } if ((n % 2 != 0 && prime && n > 2) || n == 2) { return true; } else { return false; } }
3e9ad998-eeef-4e96-893c-e55d55195d5e
5
@Override public boolean run() { if (verbose) Timer.showStdErr("Calculating ACAT score on input: " + vcfFile); countByAcat = new CountByType(); countByEff = new CountByType(); VcfFileIterator vcf = new VcfFileIterator(vcfFile); for (VcfEntry ve : vcf) { if (vcf.isHeadeSection()) { addHeader(vcf); // Add header lines System.out.println(vcf.getVcfHeader()); // Show header } acat(ve); // Annotate ACAT t2dGenes(ve); // Annotate T2D-Genes // Show line if (!quiet) System.out.println(ve); } if (verbose) { System.err.println(countByAcat); System.err.println(countByEff); Timer.showStdErr("Done."); } return true; }
2d9a1b74-0c21-4092-9d05-4aa811f7834a
1
@Override public void run() { if (this.ID != null) { search (this.ID); } this._view.init(); }
aa27c15e-3020-4b6a-8345-b46d372d8347
7
@SuppressWarnings("deprecation") public boolean insertar(FaltaVO entrada){ Statement consulta = Conexion.getConexion().hacerConsulta(); boolean bandera = false; String columna = "INSERT INTO faltas("; String valores = "VALUES ("; if(entrada.getAlumno() != null){ columna += "alumno, "; valores += entrada.getAlumno() +", "; bandera = true; } if(entrada.getFecha() != null){ Date fecha = entrada.getFecha(); columna += "fecha, "; valores += "'" + fecha.getYear() + "-" +fecha.getMonth()+ "-" + fecha.getDay() +"', "; bandera = true; } if(entrada.getIdFalta() != null){ columna += "idFalta, "; valores += entrada.getIdFalta() +", "; bandera = true; } if(entrada.getJustificante() != null){ columna += "justificante, "; valores += entrada.getJustificante() +", "; bandera = true; }else{ } if(entrada.getMateria() != null){ columna += "materia, "; valores += entrada.getIdFalta() +", "; bandera = true; } if(bandera){ columna = columna.substring(0, columna.length()-2) +") "; valores = valores.substring(0, valores.length()-3) +");"; try{ consulta.executeQuery(columna + valores); consulta.close(); return true; }catch(Exception e){ return false; } }else{ return false; } }
91613b73-84c8-455e-a367-6eda22985fce
4
@EventHandler public void onPrepareItemEnchantEvent(PrepareItemEnchantEvent e) { if (e.getEnchanter() != null) { if (!plugin.getLevels().containsKey(e.getEnchanter().getName())) return; if (!plugin.getThreads().containsKey(e.getEnchanter().getName()) && plugin.getLevels().containsKey(e.getEnchanter().getName())) { EnchantmentGiver thr = new EnchantmentGiver(e, plugin, plugin.getMinLevel(e.getEnchanter().getName()), plugin.getMaxLevel(e.getEnchanter().getName())); plugin.getThreads().put(e.getEnchanter().getName(), thr); Bukkit.getScheduler().scheduleAsyncDelayedTask(plugin, thr); } } }
a2ced0fa-0add-4a33-889c-d0aec44f2e1f
2
public void sort() { for (String key : map.keySet()) { List<PathPattern<U>> list = map.get(key); if (list != null) { Collections.sort(list); } } }
90411ec9-3d81-4fc6-aeaf-4b7e5843657a
2
public String notation() { return this.from != null && this.to != null ? this.from.toString() + this.to.toString() : null; }
71baa47a-784e-444c-b6dd-4dbf0b5ddd25
1
public void hide() { for(RadioButton rb : btns) rb.hide(); }
dc99aac0-62b5-4287-a5ed-c2d15342a1f1
4
public void takeAttack(AttackBox incoming){ switch (incoming.getType()) { case 'p': if(stats.naturalAR > 0){ stats.damageHP((int) (100.0 / (100 + stats.naturalAR) * incoming.getForce()) ); }else{ stats.damageHP((int) (2 - (100.0 / (100 - stats.naturalAR))) * incoming.getForce() ); } break; case 'm': if(stats.naturalMR > 0){ stats.damageHP((int) (100.0 / (100 + stats.naturalMR) * incoming.getForce()) ); }else{ stats.damageHP((int) (2 - (100.0 / (100 - stats.naturalMR))) * incoming.getForce() ); } break; default: stats.damageHP(incoming.getForce()); break; } }
e04772a0-4b7a-482b-959b-2d6d3e336339
2
public boolean equals(Object production) { if (production instanceof Production) { Production p = (Production) production; return getRHS().equals(p.getRHS()) && getLHS().equals(p.getLHS()); } return false; }
9470f205-70a8-466e-8491-a0f4c15aac68
4
private void addMines(double x, double y) { for(int i = 0; i < 75; i++) { double tx = x + random.nextGaussian() * 6; double ty = y + random.nextGaussian() * 6; StoneMine sm = new StoneMine(tx,ty); if(isEmpty(sm)) { entities.add(sm); } else { sm = null; } } for(int i = 0; i < 200; i++) { double tx = x + random.nextGaussian() * 6; double ty = y + random.nextGaussian() * 6; GoldMine sm = new GoldMine(tx,ty); if(isEmpty(sm)) { entities.add(sm); } else { sm = null; } } }
c3e23dac-a49f-41a4-84ab-0186ade587e6
9
public static int requestDecision(Team team, String msg) { if(!team.isOnline()) { return team.getIndexOfStrength(Team.WEAKEST); } team.setLastInput(null); sendMsg(team, msg); long start = System.currentTimeMillis(); boolean maxTimeout = false; boolean avgTimeout = false; while((maxTimeout = (System.currentTimeMillis() - start < MILLISTOTIMEOUT)) && team.getLastInput() == null) { team.setLastInput(team.read().substring(0, 1)); } team.registerReactionTime(System.currentTimeMillis() - start); if((avgTimeout = (team.getAvgReactionTime() > ALLOWEDAVGREACTION))) { team.setOnline(false); } String s = team.getLastInput().toLowerCase(); switch (s) { case "l": return 0; case "m": return 1; case "r": return 2; default: if(maxTimeout || avgTimeout) { Logger.log(team.getName() + ": Maximum timeout: " + maxTimeout + "\tAverage timeout: " + avgTimeout, team, Logger.SERVER); } else { Logger.log(team.getName() + ": no valid decision. Sent 'l', 'm' or 'r' after receiving '" + SHOOT + "' or '" + KEEP + "'.", team, Logger.COMMUNICATION); } //Logger.log(team.getName() + ": Timeout", team, Logger.SERVER); team.setOnline(false); return requestDecision(team, msg); } }
8642981c-29e8-4ce2-8d56-d0547f2a66f8
7
public static void main(String[] args) throws Exception { ArrayList<Integer> list = new ArrayList<Integer>(); ArrayList<Integer> even = new ArrayList<Integer>(); ArrayList<Integer> multipleOf3 = new ArrayList<Integer>(); ArrayList<Integer> others = new ArrayList<Integer>(); BufferedReader br = new BufferedReader( new InputStreamReader(System.in) ); for (int i = 0; i < N; i++) { list.add( Integer.parseInt(br.readLine()) ); } for (Integer x : list) { if (x % 3 == 0) { multipleOf3.add(x); } else if (x % 2 == 0) { even.add(x); } else { others.add(x); } } for (Integer x : multipleOf3) { System.out.println(x); } System.out.println(); for (Integer x : even) { System.out.println(x); } System.out.println(); for (Integer x : others) { System.out.println(x); } }
ba22e439-dc59-449e-8878-5f260b5a0e60
1
public static InputSource getFromHTTP(String adresse){ //String result = ""; URL url = null; System.out.println("downloading..."); try{ url = new URL(adresse.replace(" ", "%20")); HttpURLConnection client = (HttpURLConnection) url.openConnection(); client.setRequestProperty("User-Agent", "Xenos"); client.setRequestProperty("Accept-Encoding", "gzip, deflate"); client.setRequestProperty("Accept", "application/xml"); client.setRequestMethod("GET"); //String line; //BufferedReader rd = new BufferedReader( new InputStreamReader(client.getInputStream())); return new InputSource(client.getURL().openStream()); //while ((line = rd.readLine()) != null){ // result += line; //} } catch (Exception e){ e.printStackTrace(); return null; } //System.out.println("downloaded"); }
0a17a9e5-6b28-4a45-bdc8-f6ab5b0e5a4d
1
public Image loadImage (String file) // this method reads and loads the image { try { InputStream m = this.getClass().getResourceAsStream(file); return (ImageIO.read (m)); } catch (IOException e) { System.out.println ("Error: File " + file + " not found."); return null; } }
7c1d56d1-ca01-412d-8a6f-548d969e68da
0
@Override public String toString() { return String.format( "isAssignableTo(%s)", this.superclassOrInterface.getSimpleName() ); }
73e8cb28-4f89-4e8c-bb26-39e7471f9e10
3
public void visitLdcInsn(final Object cst) { if (cst instanceof Long || cst instanceof Double) { minSize += 3; maxSize += 3; } else { minSize += 2; maxSize += 3; } if (mv != null) { mv.visitLdcInsn(cst); } }
dc643f5a-dbde-4d5c-9dbe-6876e9f757a6
0
@Override public void restoreCurrentToDefault() {cur = def;}
44f6aa6a-81b4-4410-9bbf-a07dbe16ba4a
8
public static <GInput, GValue> Field<GInput, GValue> conditionalField(final Filter<? super GInput> condition, final Field<? super GInput, GValue> accept, final Field<? super GInput, GValue> reject) throws NullPointerException { if (condition == null) throw new NullPointerException("condition = null"); if (accept == null) throw new NullPointerException("accept = null"); if (reject == null) throw new NullPointerException("reject = null"); return new Field<GInput, GValue>() { @Override public GValue get(final GInput input) { return condition.accept(input) ? accept.get(input) : reject.get(input); } @Override public void set(final GInput input, final GValue value) { if (condition.accept(input)) { accept.set(input, value); } else { reject.set(input, value); } } @Override public String toString() { return Objects.toInvokeString("conditionalField", condition, accept, reject); } }; }
c3245813-9825-4f8e-b55a-7f6bd6a9af64
2
public User getCurrentUser() { for(PinochlePlayer player : players) { if(player.getPosition() == currentTurn) { return player.getUser(); } } return null; }
f7b3539f-15d3-42b7-8d38-58cd29ed8ff2
9
public void augment(Edge[] path) { // find the bottleneck capacity delta on path P float delta = Float.MAX_VALUE; for (int i = 0; i < path.length; i++) { float tempWeight = path[i].getWeight(); if (tempWeight < delta) { delta = tempWeight; } } // update the residual graph by pushing Delta flow through the path P for (int i = 0; i < path.length; i++) { Edge edge = path[i]; edge.setWeight(edge.getWeight() - delta); Edge residualEdge = graph.getEdge(edge.getTarget(), edge.getSource()); if (residualEdge == null) { residualEdge = new Edge(edge.getTarget(), edge.getSource(), delta); graph.addEdge(residualEdge); } else { residualEdge.setWeight(residualEdge.getWeight() + delta); } if (edge.getWeight() <= 0) { Vertex p = edge.getSource(); Vertex q = edge.getTarget(); if (tree(p) == S && tree(q) == S) { q.setParent(null); orphans.add(q); } if (tree(p) == T && tree(q) == T) { p.setParent(null); orphans.add(p); } } } }
a73ebb83-c9a2-4c67-95db-36bdf8a4feea
8
@Override public TableData checkIfColumnExist(String tableName, String columnName) throws IllegalArgumentException{ if(connexion == null && path == null) return new TableData(ApiResponse.MYAPI_NOT_INITIALISE,null); DatabaseMetaData databaseMeta = null; try { if(connect == null || connect.isClosed()) return new TableData(ApiResponse.DATABASE_NOT_CONNECT,false); if(tableName == null || columnName == null) throw new IllegalArgumentException("An argument is null."); databaseMeta = connect.getMetaData(); ResultSet rs = null; rs = databaseMeta.getColumns(null, null, tableName, columnName); return (rs.next()?new TableData(ApiResponse.SUCCESS,true):new TableData(ApiResponse.SUCCESS,false)); } catch (SQLException e) { e.printStackTrace(); return new TableData(ApiResponse.ERROR,false); } }
ae11f6ff-1553-4806-9bb9-4402bf945d42
9
protected PairVector<MOB,String> getAllPlayersHere(Area area, boolean includeLocalFollowers) { final PairVector<MOB,String> playersHere=new PairVector<MOB,String>(); MOB M=null; Room R=null; for(final Session S : CMLib.sessions().localOnlineIterable()) { M=S.mob(); R=(M!=null)?M.location():null; if((R!=null)&&(R.getArea()==area)&&(M!=null)) { playersHere.addElement(M,getExtendedRoomID(R)); if(includeLocalFollowers) { MOB M2=null; final Set<MOB> H=M.getGroupMembers(new HashSet<MOB>()); for(final Iterator<MOB> i=H.iterator();i.hasNext();) { M2=i.next(); if((M2!=M)&&(M2.location()==R)) playersHere.addElement(M2,getExtendedRoomID(R)); } } } } return playersHere; }
69b73901-66d8-403b-a29a-b94cafdcf84a
4
@Override public String toString() { String format = "\t%-20s: \"%s\"\n"; StringBuilder sb = new StringBuilder(); sb.append("Feature (line " + lineNum + "): '" + type // + "' [ " + start + ", " + end + " ]\t" // + (complement ? "complement" : "") // + "\n" // ); // More coordinates? if (featureCoordinates != null) { sb.append(String.format(format, "coordinates", "join")); for (FeatureCoordinates fc : featureCoordinates) sb.append(String.format(format, "", fc)); } for (Entry<String, String> e : qualifiers.entrySet()) sb.append(String.format(format, e.getKey(), e.getValue())); return sb.toString(); }
17e2f684-2f6a-4d44-b3bc-e50eeb1c9b30
0
public FloatResource(float value) { this.value = value; }
0937dd9a-3fca-4d58-887e-bdc41754f7cb
1
@Override public int getRowCount() { if (dfa != null) return dfa.getStates().size(); else return 0; }
922b09ed-56f0-43df-8651-ecdc2c235d02
0
@Override public void desenhar(Graphics2D g) { // TODO Auto-generated method stub Shape s = new Ellipse2D.Double(getPosX(), getPosY(), raio/2, raio/2); g.draw(s); }
4572c5ac-afad-4623-b4e5-b22ab23933d9
7
private void resetPosition(Tile current, int row, int col){ if(current == null) return; int x = getTileX(col); int y = getTileY(row); int distX = current.getX() - x; int distY = current.getY() - y; if(Math.abs(distX) < Tile.SLIDE_SPEED){ current.setX(current.getX() - distX); } if(Math.abs(distY) < Tile.SLIDE_SPEED){ current.setY(current.getY() - distY); } if(distX < 0){ current.setX(current.getX() + Tile.SLIDE_SPEED); } if(distY < 0){ current.setY(current.getY() + Tile.SLIDE_SPEED); } if(distX > 0){ current.setX(current.getX() - Tile.SLIDE_SPEED); } if(distY > 0){ current.setY(current.getY() - Tile.SLIDE_SPEED); } }
864cfbbc-bf67-47ad-94c0-220652cda15c
0
public boolean isAlive() { return alive; }
6790d8a8-f407-49c2-b74a-0768a220718a
1
public void setR(Route r)throws IllegalArgumentException { if(r == null) throw new IllegalArgumentException("Er is geen route"); this.r = r; }
56e1b5b9-6b32-4490-8749-c392d76bb82f
0
private void displayInfo(){ String txt = typingArea.getText(); displayArea.append(txt + "\n"); displayArea.setCaretPosition(displayArea.getDocument().getLength()); }
5a1540df-7b15-456e-9da1-dcc957022a87
5
public static void main(String[] arguments) { Dimension aDimension = Toolkit.getDefaultToolkit().getScreenSize(); Robot aRobot = null; try { aRobot = new Robot(); } catch (Exception anException) { System.err.println(anException); throw new RuntimeException(anException.toString()); } BufferedImage anImage = aRobot.createScreenCapture(new Rectangle(aDimension)); Model aModel = new Model(); for (int index = 0; index < 3; index++) { View aView; JFrame aWindow; aView = new View(aModel); aWindow = new JFrame("MVC-" + Integer.toString(index + 1)); aWindow.getContentPane().add(aView); aWindow.setMinimumSize(new Dimension(400, 300)); aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); aWindow.setSize(800, 600); aWindow.setLocation((200 + (index * 80)), (100 + (index * 60))); aWindow.setVisible(true); } for (int index = 0; index < 11; index++) { try { Thread.sleep(1000); } catch (InterruptedException anException) { System.err.println(anException); throw new RuntimeException(anException.toString()); } if (index % 2 == 0) { aModel.picture(anImage); } else { aModel.picture(null); } aModel.changed(); } return; }
eb2b887b-940a-4f6b-b6e3-699203e14a25
2
private void updateContainerInfo() { try { int total = ImageUtils.calculatePossibleDataSpace(new File(edContainerFile.getText()), edBoardCode.getText()); int used = EncryptionProvider.SHA_256_HASH_SIZE_BYTES * 2 + "{ \"timestamp\": 0000000000000, \"postText\": \"\" }".length() + txtPostText.getText().length(); File attach = new File(edAttachFile.getText()); if (attach.exists()) { used += attach.length(); } lblCapacity.setText(String.format("%s bytes total, %s used", total, used)); pbCapacity.setMaximum(total); pbCapacity.setValue(used); } catch (IOException ex) { lblCapacity.setText("invalid container file"); pbCapacity.setMaximum(0); pbCapacity.setValue(0); } }