method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
7fff4f24-e55e-4152-ac1e-aa185bb6f799
3
private void broadcast(Command command) { List<ICallbackClient> m_clients = m_subscriber.getClients(); for (int i = 0; i < m_clients.size(); ++i) { try { m_clients.get(i).pushMessage(command); } catch (RemoteException e ){ e.printStackTrace(); } catch(InterruptedException e){ e.printStackTrace(); } } }
90f8205f-5728-4876-8e03-c41df489e976
0
public static void main(String[] args) { double above = 0.7, below = 0.4; float fabove = 0.7f, fbelow = 0.4f; System.out.println("(int)above: " + (int)above); System.out.println("(int)below: " + (int)below); System.out.println("(int)fabove: " + (int)fabove); System.out.println("(int)fbelow: " + (int)fbelow); }
d656729f-4189-4534-86a3-71faace5bd92
1
public void testEra() { assertEquals(1, CopticChronology.AM); try { new DateTime(-1, 13, 5, 0, 0, 0, 0, COPTIC_UTC); fail(); } catch (IllegalArgumentException ex) {} }
d3991a6e-58da-4b60-9ef1-9e28aac8e534
1
static void destroy(Object instance) { Class<? extends Object> clazz = instance.getClass(); invokeMethodWithAnnotation(clazz, instance, PreDestroy.class ); }
eb1a9878-192a-4769-b100-731a46b202ae
1
@Test public void dijkstraSimplePossible() { Graph g = testGraph1(); Vertex[] expected = new Vertex[2]; for (int i = 0; i < expected.length; i++) { expected[i] = g.getVertices().get(i); } Vertex[] actual = new Vertex[2]; }
9f666fb5-82f4-4961-bb33-b4ec889ab0e8
3
@Override public boolean verifier() throws SemantiqueException { super.verifier(); if(gauche.isBoolean()){ setBoolean(); if(!droite.isBoolean()) GestionnaireSemantique.getInstance().add(new SemantiqueException("Expression droite arithmetique, booleenne attendue pour le OU ligne:"+line+" colonne:"+col)); }else if(droite.isBoolean()) GestionnaireSemantique.getInstance().add(new SemantiqueException("Expression droite booléenne, arithmetique attendu pour Somme ligne:"+line+" colonne:"+col)); return true; }
7e3f8dda-f7b5-42fa-953f-f62a90739283
1
public static pgrid.service.corba.PeerReference[] read (org.omg.CORBA.portable.InputStream istream) { pgrid.service.corba.PeerReference value[] = null; int _len0 = istream.read_long (); value = new pgrid.service.corba.PeerReference[_len0]; for (int _o1 = 0;_o1 < value.length; ++_o1) value[_o1] = pgrid.service.corba.PeerReferenceHelper.read (istream); return value; }
d670d826-c3e7-4000-9846-4bb71b279965
2
@Override public String toString(){ String toReturn = ""; for(int i = 0; i<this.size;i++){ toReturn += DNSDB.IPToString(this.keys[i]); toReturn+= " -> "; toReturn += this.values[i]; toReturn+= "\n"; } if(this.nextLeaf != null){ toReturn+= this.nextLeaf.toString(); } return toReturn; }
f6522786-5e14-465d-8191-942553611ef8
8
private boolean alg_s1() { switch (alg_pos) { case 0: return alg_set(0, 0); case 1: if (alg_get(1, 1) != 0) { return alg_set(2, 2); } if (alg_get(0, 1) != 0 || alg_get(0, 2) != 0) { return alg_set(2, 0); } return alg_set(0, 2); case 2: if (alg_get(2, 0) != 0 || (alg_get(0, 1) == alg_get(1, 0))) { return alg_set(2, 2); } return alg_set(2, 0); default: return false; } }
8d723833-e3ec-43f3-9a6d-1ce82182f72e
5
public void run() { File file = new File(outputLoc.getAbsolutePath() + File.separatorChar + audio.getFileName()); File fileTmp = new File(outputLoc.getAbsolutePath() + File.separatorChar + audio.getFileName() + ".vkadl"); if (file.exists()) { System.out.println("Skipping " + audio.getFileName()); return; } if (fileTmp.exists()) { fileTmp.delete(); } URL audioUrl = null; try { audioUrl = new URL(audio.getFileUrl()); } catch (MalformedURLException ex) { ex.printStackTrace(); } System.out.println("Downloading:\t" + audio.getFileName()); try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileTmp)); BufferedInputStream in = new BufferedInputStream(audioUrl.openStream())) { byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer, 0, buffer.length)) >= 0) { out.write(buffer, 0, read); } fileTmp.renameTo(file); } catch (IOException ex) { ex.printStackTrace(); } System.out.println("Done:\t" + audio.getFileName()); }
972d9c7d-6a21-48b4-9eee-86072b9e5165
5
public String buscarProspectoPorNombre(String name){ //##########################CARGA_BASE DE DATOS############# tablaDeProspectos(); //##########################INGRESO_VACIO################### if(name.equals("")){ name = "No busque nada"; resultBusqueda = "Debe ingresar datos a buscar"; } //##########################CONVIRTIENDO A MAYUSCULA################################ cadena = name.substring(0,1).toUpperCase() + name.substring(1, name.length()); int longitud = datos.size(); for(int i = 0; i<longitud;i++){ String NombreBuscado = datos.get(i).getName(); if (NombreBuscado.equals(cadena)){ db_Temp.add(datos.get(i)); resultBusqueda = datos.get(i).getName(); } } if (db_Temp.size()>0){ for (int j=0; j<db_Temp.size();j++){ System.out.println("SU BÚSQUEDA POR NOMBRE MUESTRA LOS SIGUIENTES RESULTADOS\t" + "\n"); mostrar(j); } }else{ resultBusqueda = "No se encontraron registros para los filtros ingresados"; } return resultBusqueda; }
f41f3ad5-e54c-4309-848f-1b1a3c5c9e28
5
public Descriptor compile(SymbolTable symbolTable) { // prevent overriding of constants if (key instanceof IdentNode && symbolTable.descriptorFor(((IdentNode) key).getIdentName()) instanceof IntConstDescriptor) { throw new CompilerException("Constant " + ((IdentNode) key).getIdentName() + " cannot be overriden"); } Descriptor rightDescr = value.compile(symbolTable); if (rightDescr instanceof RecordDescriptor || rightDescr instanceof ArrayDescriptor) { Descriptor leftDescr = key.compile(symbolTable); if (!leftDescr.equals(rightDescr)) { throw new CompilerException("left type (" + leftDescr + ") is not compatible with right type (" + rightDescr + ")"); } write("ASSIGN, " + rightDescr.size()); } else { key.compile(symbolTable); write("ASSIGN, 1"); } return null; }
36830757-026a-4e3c-9f72-dd133ed0165e
3
private static Method getMethod(Class<?> cl, String method) { for (Method m : cl.getMethods()) { if (m.getName().equals(method)) { return m; } } return null; }
bb0db7fc-3832-4bb6-8314-21da9c8df497
2
public Integer getInteger() { Object gotValue=getValue(); if (gotValue != null) { if (!Integer.class.isAssignableFrom(gotValue.getClass())) { throw new ClassCastException("don't know how to convert " +gotValue.getClass().getName()+" to Integer"); } } return (Integer)gotValue; }
688c29e3-bdc6-4e3d-bf49-d7144ab4cc4b
6
public void actionPerformed(ActionEvent e) { if (e.getSource() == valide) { joueur1 = new Joueur(jtf1.getText(), Pion.JOUEUR1); joueur2 = new Joueur(jtf2.getText(), Pion.JOUEUR2); gestionnaireScore = new Score(joueur1, joueur2); model = new PartieIHM(joueur1, joueur2, gestionnaireScore); demande.setVisible(false); tabMorpion.setVisible(true); } else if (e.getSource() == rejouer) { fenetreFinTour.dispose(); tabMorpion.dispose(); //Mettre en place la solution pour refaire une partie } else if (e.getSource() == quitter) { fenetreFinTour.dispose(); tabMorpion.dispose(); } else { BCase bcase = (BCase) e.getSource(); if (bcase.obtenirPion() == Pion.LIBRE) { bcase.poserPion((tour)%2,model); tour++; if (model.victoire() == true || tour == 9) { fenetreFinTour(); } } } }
77634e66-4a22-4d0b-89b4-0a5dcde6dd3d
4
public void askRemoveInventoryItem(Command command) { int inventoryItem; if(!command.hasSecondWord()) { // if there is no second word, we don't know what to remove System.out.println("Verwijder wat?"); return; } //Try if input if numeric try { inventoryItem = Integer.parseInt(command.getSecondWord()) - 1; if(inventoryItem <= player.getInventorySize()) { if(player.getInventoryItem(inventoryItem).getItemValue() == 0) { checkRemoveInventoryItem(conversation.askQuestionInput("Weet je zeker dat je wilt " + player.getInventoryItem(inventoryItem).getItemName() + " verwijderen? ja/nee"), inventoryItem); }else { System.out.println("Je kunt dit voorwerp niet weg gooien, quest voorwerp!"); } }else { System.out.println("Item wat je wil verwijderen bestaat niet.."); } }catch(Exception e) { System.out.println("Het item wat je opgaf is ongeldig, dit moet numeriek zijn!"); } }
61a08f14-b1c5-4039-9061-e077adb9c913
5
public static String trimWhitespace(String str) { if (!hasLength(str)) { return str; } StringBuilder sb = new StringBuilder(str); while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { sb.deleteCharAt(0); } while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); }
c96e8b5c-2b0e-4c7b-bec6-03b4f31b05da
7
public void execute() { String line = null; try { dout.runQueue(); } catch (Exception e) { log.catching(Level.WARN, e); } Thread.interrupted(); dout.setEnabled(true); try { line = reader.readLine("> ", null); } catch (IOException e) { if (e.getCause() instanceof InterruptedException) { try { System.out.write(new byte[] {0x08, 0x08}); } catch (IOException e1) { log.catching(Level.WARN, e1); } } else log.catching(Level.WARN, e); return; } finally { dout.setEnabled(false); } if (line.length() == 0) return; try { parser.execute(line); } catch (ExecutionException e) { if (e.getMessage().equals("No command matches.")) System.err.println("Command '" + line + "' not found"); else log.catching(Level.WARN, e); } }
fa400c6b-e6a4-4f40-948e-e01b1bc992c9
8
@Override public void doAlgorithm() { GraphModel g = graphData.getGraph(); step("start the algorithm."); String str = JOptionPane.showInputDialog(null, "Enter the homomorphism map size: ", "Homomorphism Size", 1); int mapSize = Integer.parseInt(str); Vertex[] vs = new Vertex[2*mapSize]; GraphPoint[] directions = new GraphPoint[mapSize]; for(int i=0;i<2*mapSize;i=i+2) { vs[i] = requestVertex(g, "select the" + i + "th vertex."); vs[i+1] = requestVertex(g, "select the" + i + "th vertex."); if(g.isEdge(vs[i],vs[i+1])) {step("The vertices have edge together.");return;} GraphPoint directionVector = GraphPoint.sub(vs[i].getLocation(), vs[i+1].getLocation()); directions[i/2] = GraphPoint.div(directionVector, directionVector.norm()); } boolean[] isThere = new boolean[mapSize]; int numOfThere = 0; for(int i=0;i < mapSize;i++) isThere[i]=false; for(int j=0;j < 100;j++) { if(numOfThere == mapSize) break; step(j+"th step"); for(int i=0;i<2*mapSize;i=i+2) { if(isThere[i/2]) continue; vs[i].setLocation(new GraphPoint( vs[i].getLocation().getX()-directions[i/2].getX() * 10, vs[i].getLocation().getY()+directions[i/2].getY() * 10)); System.out.println(vs[i].getLocation().distance(vs[i+1].getLocation())); if(vs[i].getLocation().distance(vs[i+1].getLocation()) < 10) { isThere[i/2] = true; numOfThere++; } } } step("the end of the algorithm."); }
ea9b40ea-8a2d-40bd-9986-722cca4b8f56
3
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { LinkedList<String> paramList = new LinkedList<String>(); Utils.addArrayToList(paramList, args); Iterator<String> it = paramList.iterator(); if("db".equalsIgnoreCase(cmd.getName())) { if(!it.hasNext()) { return false; } String par = it.next().toLowerCase(); if(!commands.containsKey(par)) { return false; } return executeCommand(par, sender, it); } return false; }
fe1c18f2-6437-4c85-8537-6a4adb39b075
8
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Produto other = (Produto) obj; if (this.Id != other.Id) { return false; } if (!Objects.equals(this.Nome, other.Nome)) { return false; } if (Double.doubleToLongBits(this.Valor_comp) != Double.doubleToLongBits(other.Valor_comp)) { return false; } if (Double.doubleToLongBits(this.Valor_vend) != Double.doubleToLongBits(other.Valor_vend)) { return false; } if (!Objects.equals(this.Descricao, other.Descricao)) { return false; } if (this.Estoque != other.Estoque) { return false; } return true; }
f9c46093-9d3f-4673-a6d2-28fdcea71d77
5
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); ListNode p = dummy; while(l1 != null && l2 != null){ if(l1.val < l2.val){ p.next = l1; l1 = l1.next; }else{ p.next = l2; l2 = l2.next; } p = p.next; } if(l1 != null) p.next = l1; if(l2 != null) p.next = l2; return dummy.next; }
7a62afc4-8d34-44c3-bc2f-9c87446c0c4c
6
public void generateVerticalCorridor(MapRegion room1, MapRegion room2, String[][] dungeon) { // Etäisyys lähekkäimpien seinien välillä int distance = room2.getY1() - room1.getY2(); // Valitaan alku- ja loppukoordinaatit siten, että polku ei koskaan kulje huoneen kulmasta int startX = Main.rand.nextInt(room1.getX2() - room1.getX1() - 2) + room1.getX1() + 1; int endX = Main.rand.nextInt(room2.getX2() - room2.getX1() - 2) + room2.getX1() + 1; int x = startX, y = room1.getY2(); // Kuljetaan ensin pystysuunnassa puoleen väliin for(int i = 0; i < distance/2; i++) dungeon[x][y++] = "."; // Jos tarvii, siirrytään vaakasuunnassa endX:n määrittämään x-koordinaattiin if (startX < endX) while (x != endX) dungeon[x++][y] = "."; else if (startX > endX) while (x != endX) dungeon[x--][y] = "."; // Siirrytään loppuun asti pystysuunnassa while(y != room2.getY1()) dungeon[x][y++] = "."; }
8154d03c-dcc1-4b3a-9059-b8bf8cb88cf4
3
public static byte[] encryptBloc(byte[] in) { byte[] tmp = new byte[in.length]; byte[][] state = new byte[4][Nb]; for (int i = 0; i < in.length; i++) state[i / 4][i % 4] = in[i%4*4+i/4]; state = AddRoundKey(state, w, 0); for (int round = 1; round < Nr; round++) { state = SubBytes(state); state = ShiftRows(state); state = MixColumns(state); state = AddRoundKey(state, w, round); } state = SubBytes(state); state = ShiftRows(state); state = AddRoundKey(state, w, Nr); for (int i = 0; i < tmp.length; i++) tmp[i%4*4+i/4] = state[i / 4][i%4]; return tmp; }
c67c99c4-344d-43df-b768-66c4f818a5dd
8
protected void gmcpSaySend(String sayName, MOB mob, MOB target, CMMsg msg) { if((mob.session()!=null)&&(mob.session().getClientTelnetMode(Session.TELNET_GMCP))) { mob.session().sendGMCPEvent("comm.channel", "{\"chan\":\""+sayName+"\",\"msg\":\""+ MiniJSON.toJSONString(CMLib.coffeeFilter().fullOutFilter(null, mob, mob, target, null, CMStrings.removeColors(msg.sourceMessage()), false)) +"\",\"player\":\""+mob.name(target)+"\"}"); } final Room R=mob.location(); if(R!=null) for(int i=0;i<R.numInhabitants();i++) { final MOB M=R.fetchInhabitant(i); if((M!=null)&&(M!=msg.source())&&(M.session()!=null)&&(M.session().getClientTelnetMode(Session.TELNET_GMCP))) { M.session().sendGMCPEvent("comm.channel", "{\"chan\":\""+sayName+"\",\"msg\":\""+ MiniJSON.toJSONString(CMLib.coffeeFilter().fullOutFilter(null, M, mob, target, null, CMStrings.removeColors(msg.othersMessage()), false)) +"\",\"player\":\""+mob.name(target)+"\"}"); } } }
6bab42df-63cd-4903-b54c-f1429069e7a1
9
protected boolean[] datasetIntegrity( boolean nominalPredictor, boolean numericPredictor, boolean stringPredictor, boolean datePredictor, boolean relationalPredictor, boolean multiInstance, int classType, boolean predictorMissing, boolean classMissing) { print("kernel doesn't alter original datasets"); printAttributeSummary( nominalPredictor, numericPredictor, stringPredictor, datePredictor, relationalPredictor, multiInstance, classType); print("..."); int numTrain = getNumInstances(), numClasses = 2, missingLevel = 20; boolean[] result = new boolean[2]; Instances train = null; Kernel kernel = null; try { train = makeTestDataset(42, numTrain, nominalPredictor ? getNumNominal() : 0, numericPredictor ? getNumNumeric() : 0, stringPredictor ? getNumString() : 0, datePredictor ? getNumDate() : 0, relationalPredictor ? getNumRelational() : 0, numClasses, classType, multiInstance); if (missingLevel > 0) addMissing(train, missingLevel, predictorMissing, classMissing); kernel = Kernel.makeCopies(getKernel(), 1)[0]; } catch (Exception ex) { throw new Error("Error setting up for tests: " + ex.getMessage()); } try { Instances trainCopy = new Instances(train); kernel.buildKernel(trainCopy); compareDatasets(train, trainCopy); println("yes"); result[0] = true; } catch (Exception ex) { println("no"); result[0] = false; if (m_Debug) { println("\n=== Full Report ==="); print("Problem during building"); println(": " + ex.getMessage() + "\n"); println("Here is the dataset:\n"); println("=== Train Dataset ===\n" + train.toString() + "\n"); } } return result; }
5cdab1c9-be1e-435b-82bc-ff646f320e99
0
public Block(Color color, boolean isSolid) { this.color = color; this.isSolid = isSolid; }
5765a86d-fadb-4d05-847d-ef4839b48422
1
public void updateSubTypes() { if (!staticFlag) subExpressions[0].setType(Type.tSubType(classType)); }
b9fc27ec-9043-435c-97a8-0a4c6c449112
2
private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed //codigo guardar if (principal != null) { if (fichero == null) { guardarComo(); } else { guardar(); } } }//GEN-LAST:event_btnGuardarActionPerformed
c1a1194d-a0ab-43e4-818e-df9287ed907c
6
public List<ConversionMessage> run(PageLayout layout, boolean checkOnly) { List<ConversionMessage> messages = new ArrayList<ConversionMessage>(); //Regions for (ContentIterator it = layout.iterator(null); it.hasNext(); ) { Region reg = (Region)it.next(); //Primary and secondary Script if (reg.getType().equals(RegionType.TextRegion)) { Variable v = reg.getAttributes().get("primaryScript"); if (v != null && v.getValue() != null) convertScript((StringValue)v.getValue(), checkOnly, messages); v = reg.getAttributes().get("secondaryScript"); if (v != null && v.getValue() != null) convertScript((StringValue)v.getValue(), checkOnly, messages); } } return messages; }
e33baf3b-a681-4508-84aa-a11aebc8aab5
9
public String itsHere(MOB mob, Room R) { if(R==null) return ""; if((okMaterials()!=null)&&(okMaterials().length>0)) { for(int m=0;m<okMaterials().length;m++) { if((R.myResource()&RawMaterial.MATERIAL_MASK)==okMaterials()[m]) return L("You sense @x1 here.", RawMaterial.CODES.NAME(R.myResource()).toLowerCase()); } } if((okResources()!=null)&&(okResources().length>0)) { for(int m=0;m<okResources().length;m++) { if(R.myResource()==okResources()[m]) return L("You sense @x1 here.",RawMaterial.CODES.NAME(R.myResource()).toLowerCase()); } } return ""; }
cd545070-e01a-4dcb-9e65-7abed42ad52d
7
private float calculAngle(float x, float y, float xCursor, float yCursor) { float a = xCursor - x, b = yCursor - y; float mod = (float) Math.sqrt(a*a + b*b); double angleRadian = Math.acos(a / mod); if (a == 0) { if (b > 0) angleRadian = 3 * Math.PI / 2; else if (b < 0) angleRadian = Math.PI / 2; } else if (b == 0) { if (a < 0) angleRadian = Math.PI; else angleRadian = 0; } else if (b < 0) angleRadian *= -1; float arg = (float) ((angleRadian * 360) / (2 * Math.PI)); if (arg < 0) arg += 360; return arg; }
7930f5a7-9369-423d-af8c-9c6c59782bd6
6
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { Class<?> rawType = type.getRawType(); final boolean skipSerialize = excludeClass(rawType, true); final boolean skipDeserialize = excludeClass(rawType, false); if (!skipSerialize && !skipDeserialize) { return null; } return new TypeAdapter<T>() { /** The delegate is lazily created because it may not be needed, and creating it may fail. */ private TypeAdapter<T> delegate; @Override public T read(JsonReader in) throws IOException { if (skipDeserialize) { in.skipValue(); return null; } return delegate().read(in); } @Override public void write(JsonWriter out, T value) throws IOException { if (skipSerialize) { out.nullValue(); return; } delegate().write(out, value); } private TypeAdapter<T> delegate() { TypeAdapter<T> d = delegate; return d != null ? d : (delegate = gson.getDelegateAdapter(Excluder.this, type)); } }; }
ae4e9774-c642-4770-bffa-5dd67ee4fd91
2
private void startProcessDistribute(){ while(noStopRequested){ try{ workers.take().processResponse(this.readPool.take()); }catch(Exception e){ e.printStackTrace(); } } }
b0626a70-b977-4e88-9ca5-af40849b7cee
7
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked if(evt.getButton() == 1){ jTextField2.setEnabled(true); jTextArea1.setEnabled(true); jTextArea2.setEnabled(true); jTextArea3.setEnabled(true); if(sslclientSocket == null) { try{ sslclientSocket = new ClientSocket(jTextField3.getText(), Integer.parseInt(jTextField4.getText())); sslclientSocket.sendMessage(BP01.sUsername); try { userList = (ArrayList<String>) new ObjectInputStream(sslclientSocket.getClient().getInputStream()).readObject(); System.out.println("object recieved"); for(String s : userList) jTextArea3.append(s); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(BPMain.class.getName()).log(Level.SEVERE, null, ex); } jLabel9.setForeground(new Color(51, 153, 0)); }catch(NumberFormatException e){ jLabel9.setForeground(new Color(153, 51, 0)); chatUpdating = false; jTextArea1.setEnabled(false); jTextArea1.setEnabled(false); jTextArea1.setEnabled(false); jTextField2.setEnabled(false); sslclientSocket = null; }finally{ if(!chatUpdate.isAlive()) chatUpdate.start(); if(sslclientSocket != null) { jTextArea1.setEnabled(true); jTextArea1.setEnabled(true); jTextArea1.setEnabled(true); jTextField2.setEnabled(true); chatUpdating = true; } } } jLabel4.dispatchEvent(new MouseEvent(jPanel1.getComponentAt(172, 71), MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(), MouseEvent.NOBUTTON, 172,71, 1, false)); } }//GEN-LAST:event_jButton2MouseClicked
64fd8754-30e3-4fb3-ab8b-627657789be5
9
public static void DFSTest(WUGraph g, WUGraph t, DFSVertex[] vertArray) { int[][] maxOnPath; Neighbors neigh; int i, j; System.out.println("Testing the tree."); maxOnPath = new int[VERTICES][VERTICES]; for (i = 0; i < VERTICES; i++) { for (j = 0; j < VERTICES; j++) { vertArray[j].visited = false; } DFS(t, vertArray[i], null, maxOnPath[i], -MAXINT); for (j = 0; j < VERTICES; j++) { if (!vertArray[j].visited) { tree = false; } } if (!tree) { return; } } // for (i = 0; i < vertArray.length; i++) { // for (j = 0; j < vertArray.length; j++) { // System.out.print(" " + maxOnPath[i][j]); // } // System.out.println(); // } for (i = 0; i < VERTICES; i++) { neigh = g.getNeighbors(vertArray[i]); if (neigh != null) { for (j = 0; j < neigh.neighborList.length; j++) { int v = ((DFSVertex) neigh.neighborList[j]).number; if (neigh.weightList[j] < maxOnPath[i][v]) { minTree = false; } } } } }
eb92bd41-c09c-4a01-875a-302597f7c3bf
2
@Override int makeTurn() { System.out.print("You choose: "); int number; do { number = in.nextInt(); } while(number < Game.MIN_CHOICE || number > Game.MAX_CHOICE); return number; }
0718a786-00fc-402f-a030-d43f8f316fd1
8
public void setImgPath_UserlistImage(Path img, Imagetype type) { switch (type) { case MOUSEFOCUS: this.imgUserlist_MFoc = handleImage(img, UIResNumbers.USERLIST_IMAGEFRAME_MFOC.getNum()); if (this.imgUserlist_MFoc == null) { this.imgUserlist_MFoc = UIDefaultImagePaths.USERLIST_IMAGEFRAME_MFOC.getPath(); deleteImage(UIResNumbers.USERLIST_IMAGEFRAME_MFOC.getNum()); } break; case SELECTED: this.imgUserlist_Sel = handleImage(img, UIResNumbers.USERLIST_IMAGEFRAME_SEL.getNum()); if (this.imgUserlist_Sel == null) { this.imgUserlist_Sel = UIDefaultImagePaths.USERLIST_IMAGEFRAME_SEL.getPath(); deleteImage(UIResNumbers.USERLIST_IMAGEFRAME_SEL.getNum()); } break; case FOCUSSELECTED: this.imgUserlist_FocSel = handleImage(img, UIResNumbers.USERLIST_IMAGEFRAME_FOCSEL.getNum()); if (this.imgUserlist_FocSel == null) { this.imgUserlist_FocSel = UIDefaultImagePaths.USERLIST_IMAGEFRAME_FOCSEL.getPath(); deleteImage(UIResNumbers.USERLIST_IMAGEFRAME_FOCSEL.getNum()); } break; case DEFAULT: this.imgUserlist_Def = handleImage(img, UIResNumbers.USERLIST_IMAGEFRAME_DEF.getNum()); if (this.imgUserlist_Def == null) { this.imgUserlist_Def = UIDefaultImagePaths.USERLIST_IMAGEFRAME_DEF.getPath(); deleteImage(UIResNumbers.USERLIST_IMAGEFRAME_DEF.getNum()); } break; default: throw new IllegalArgumentException(); } somethingChanged(); }
d6ad375d-3228-43de-9fae-d4b38868b75b
8
public static void main(String[] args) { ConsistentGlobalProblemSetInitialisation starter = new ConsistentGlobalProblemSetInitialisation(); starter.initLanguage(new char[] { '0', '1' }, 10, "(0|101|11(01)*(1|00)1|(100|11(01)*(1|00)0)(1|0(01)*(1|00)0)*0(01)*(1|00)1)*"); int solutionFoundCounter = 0; int noSolutionFound = 0; List<Long> cycleCount = new LinkedList<Long>(); long tmpCycle; long timeStamp; int[] problemCount = new int[25]; int[] candidatesCount = new int[1]; int[] noCycles = new int[2]; problemCount[0] = 3; problemCount[1] = 6; problemCount[2] = 9; problemCount[3] = 12; problemCount[4] = 15; problemCount[5] = 18; problemCount[6] = 21; problemCount[7] = 24; problemCount[8] = 27; problemCount[9] = 30; problemCount[10] = 33; problemCount[11] = 36; problemCount[12] = 39; problemCount[13] = 42; problemCount[14] = 45; problemCount[15] = 48; problemCount[16] = 51; problemCount[17] = 54; problemCount[18] = 57; problemCount[19] = 60; problemCount[20] = 63; problemCount[21] = 66; problemCount[22] = 69; problemCount[23] = 72; problemCount[24] = 75; candidatesCount[0] = 100; noCycles[0] = 250; noCycles[1] = 500; int pc = 0; int cc = 0; int nc = 0; for (int x = 0; x < 2; x++) { System.out.println("x:"+x); for (int n = 0; n < 25; n++) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss"); Logger l = new Logger("C_G_PS_" + df.format(new Date()) + ".log", true); pc = problemCount[n]; cc = candidatesCount[0]; nc = noCycles[1]; l.log("Problem Count: " + pc); l.log("CandidatesCount: " + cc); l.log("Max Cycles: " + nc); solutionFoundCounter = 0; noSolutionFound = 0; cycleCount = new LinkedList<Long>(); for (int i = 0; i < 100; i++) { timeStamp = System.currentTimeMillis(); starter.initProblems(pc); starter.initCandidates(cc); tmpCycle = starter.startEvolution(nc); l.log(i + ": finished (" + (System.currentTimeMillis() - timeStamp) + "ms, " + tmpCycle + "cycles)"); if (starter.getWinner() != null) { GraphvizRenderer.renderGraph(starter.getWinner().getObj(), "winner.svg"); solutionFoundCounter++; cycleCount.add(tmpCycle); l.log(i + ": Solution found."); } else { noSolutionFound++; l.log(i + ": No solution found."); } } long max = 0; long min = 10000; long sum = 0; for (long no : cycleCount) { sum += no; max = (no > max ? no : max); min = (no < min ? no : min); } l.log("Solution Found: " + solutionFoundCounter); l.log("Avg cycles: " + (cycleCount.size() > 0 ? sum / cycleCount.size() : '0')); l.log("Max cycles: " + max); l.log("Min cycles: " + min); l.log("No solution found: " + noSolutionFound); l.finish(); } } }
33b6993b-33aa-48e7-b51b-b07abbae5dd1
8
private String msgchk(String chk, String msg) throws InterruptedException, FileNotFoundException, UnsupportedEncodingException{ String broken[]; if (chk.endsWith(ghosts)){ ghost=1; } if (chk.endsWith(nonstop)){ if (cnt == 0){ dataOut.print("n\b"); dataOut.flush(); } cnt++; } if (chk.endsWith("Room error")){ return "Room error"; } if (msg.endsWith("just entered the Realm.")){ broken=msg.split(" "); for (int i=0;i<broken.length;i++ ) { if (broken[i].equals("just")){ player=broken[i-1]; } } GosLink.gb.enter(player.trim(),mynum); } if (chk.endsWith(hangup)){ GosLink.dw.append("BBS shutdown detected!"); loggedin=0; return "!OffLINE+02"; } return null; }
8f800c56-98bd-4a30-9656-b056dbaab07c
5
public static boolean objIsSitting(int objId) { synchronized (glob.oc) { for (Gob gob : glob.oc) { if (gob.id == objId) { Layered lay = gob.getattr(Layered.class); if (lay != null) { for (Entry<Indir<Resource>, Sprite> s : lay.sprites .entrySet()) { if (s.getValue().res.name.contains("gfx/borka/body/sitting/")) { return true; } } } } } } return false; }
13b24fde-88fb-4b43-8fdf-cdcc048da975
5
@SuppressWarnings("unchecked") public static void extractZIP(LauncherAPI api, GameFile source, File file, File dest, int min, int max) throws Exception { final ZipFile zip = new ZipFile(file); Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries(); int total = 0; while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { total += entry.getSize(); } } entries = (Enumeration<ZipEntry>) zip.entries(); final int current = 0; while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { final File dir = new File(dest, entry.getName()); if (!dir.exists()) { dir.mkdirs(); } } else { final File e = new File(dest, entry.getName()); copyStream(api, source, zip.getInputStream(entry), new FileOutputStream(e), current, total, min, max); } } zip.close(); }
9902f79a-d70d-40d2-9332-1ba3e962b2fa
7
private void setCalorimetery(String s ) throws Exception { String[] splits = s.split("\t"); if( splits.length != 3) throw new Exception("No " + splits); if( splits[1].equals("1") && this.calorimetryData1 != null) throw new Exception("No"); if( splits[1].equals("2") && this.calorimetryData2 != null) throw new Exception("No"); if( splits[1].equals("1")) this.calorimetryData1 = Double.parseDouble(splits[2]); else if( splits[1].equals("2")) this.calorimetryData2 = Double.parseDouble(splits[2]); else throw new Exception("No"); }
c30159ba-d0a3-460b-b92c-2e3ec5c70289
6
public String nextCDATA() throws JSONException { char c; int i; StringBuilder sb = new StringBuilder(); for (;;) { c = next(); if (end()) { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { sb.setLength(i); return sb.toString(); } } }
2deddfdc-c69e-4820-bc7f-f60fe31b1939
4
public int getMinRecur(int front, int rear){ //base case if(front == rear||rear-front==1) { if(arr[front] > arr[rear]){ System.out.println("min: "+arr[rear]); }else{ System.out.println("min: "+arr[front]); } return -1; } int middle = (rear+front)/2; if(arr[front] > arr[middle]){ //min in the left part, including middle getMin(front,middle); }else{ //right part getMin(middle,rear); } return -1; }
af317e0b-b8e9-467d-9f1e-4d2fd22964c2
1
private List<IntKeyValuePair> getKVPs() { List<IntKeyValuePair> kvpArray = new ArrayList<IntKeyValuePair>(); for(int i = 0; i < size; i++) { kvpArray.addAll(map[i].getKeyValuePairs()); } Collections.sort(kvpArray); return kvpArray; }
150bcd87-be7a-4da0-8069-323f0e12e4d2
0
public Constraint usingValidator(final GeneralValidator validator) throws IllegalArgumentException, IllegalStateException { validator.validate(this.paramValue, this.value); return new Constraint(this); }
dc97c34c-7146-45bc-88c0-2d734adef11b
5
public void promotionClicked(int y) { if (!selectingPromotion) return; y-=100; y /= 50; if (y == 0) { promotionPiece = new Queen(promotionColor); } else if (y == 1) { promotionPiece = new Bishop(promotionColor); } else if (y == 2) { promotionPiece = new Knight(promotionColor); } else if (y == 3) { promotionPiece = new Rook(promotionColor); } synchronized (this) { this.notifyAll(); } }
5248f338-93a2-4236-80e0-886280a6b6fb
9
private void toForester( final Writer writer ) throws IOException { final int longest = getLengthOfLongestState() + 5; writer.write( "Identifiers: " ); writer.write( String.valueOf( getNumberOfIdentifiers() ) ); writer.write( ForesterUtil.LINE_SEPARATOR ); writer.write( "Characters : " ); writer.write( String.valueOf( getNumberOfCharacters() ) ); writer.write( ForesterUtil.LINE_SEPARATOR ); writer.write( ForesterUtil.pad( "", 20, ' ', false ).toString() ); writer.write( ' ' ); for( int character = 0; character < getNumberOfCharacters(); ++character ) { final String c = getCharacter( character ); writer.write( c != null ? ForesterUtil.pad( c, longest, ' ', false ).toString() : ForesterUtil .pad( "", longest, ' ', false ).toString() ); if ( character < getNumberOfCharacters() - 1 ) { writer.write( ' ' ); } } writer.write( ForesterUtil.LINE_SEPARATOR ); for( int identifier = 0; identifier < getNumberOfIdentifiers(); ++identifier ) { if ( getIdentifier( identifier ) != null ) { writer.write( ForesterUtil.pad( getIdentifier( identifier ), 20, ' ', false ).toString() ); writer.write( ' ' ); } for( int character = 0; character < getNumberOfCharacters(); ++character ) { final S state = getState( identifier, character ); writer.write( state != null ? ForesterUtil.pad( state.toString(), longest, ' ', false ).toString() : ForesterUtil.pad( "", longest, ' ', false ).toString() ); if ( character < getNumberOfCharacters() - 1 ) { writer.write( ' ' ); } } if ( identifier < getNumberOfIdentifiers() - 1 ) { writer.write( ForesterUtil.LINE_SEPARATOR ); } } }
290c8fd8-9c2e-4231-a2b7-f27dfce39bc9
6
public Card dealCard() { numCards = deckCount * 52; if (dealt >= numCards) { throw new IllegalStateException("No Cards Left In The Deck"); } else { cardsRemaining = numCards - dealt; switch (cardsRemaining) { case 15: System.out.println("15 cards remaining in the shoe"); break; case 5: System.out .println("5 cards remaining in the shoe, adding cards " + "to shoe "); Shoe.clear(); for (int h = 0; h < deckCount; h++) { for (int i = 1; i < 14; i++) { for (int j = 1; j < 4; j++) { Shoe.add(new Card(i, j)); Collections.shuffle(Shoe); } } } break; } dealt++; return Shoe.get(dealt - 1); } }
831a1b35-9c5e-4fdd-8bc8-35ff5e1b3224
9
public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) { try { String line = value.toString(); //got one event information with first field as: Venue_ID BufferedReader inCandidateFile = new BufferedReader(new FileReader(localPath[1].toString())); while((line = inCandidateFile.readLine()) != null) //create list of all venue_IDs so we do not make this as a bottleneck to read files again & again { //V0-001-003699774-0|E0-001-036995779-6|...|2011-03-05 20:00:00|2011-03-05 20:00:00|...|39.491188|-84.32839|" "|music|" "|...|concert,music,reverbnationcom|V0-001-003699774-0 StringTokenizer eventTokens = new StringTokenizer(line, "|"); if(eventTokens.hasMoreTokens()) { String venue_id = eventTokens.nextToken(); venueData.add(venue_id); } } inCandidateFile.close(); //file reading is over so close file reader object! line = value.toString(); StringTokenizer eventTokens = new StringTokenizer(line, "|"); if(eventTokens.hasMoreTokens()) //find tags for this venue { //ACTUAL: id|title|start_time|stop_time|venue_name|latitude|longitude|description|category|recur_string|created|modified|owner|url|tags|venue_id|gotvenue //USED: id|title|start_time|stop_time|venue_name|latitude|longitude|description|category|recur_string|url|tags|venue_id for(int i=0; i < 14; i++) //skip fields till 'tags' field arrives eventTokens.nextToken(); String tags = eventTokens.nextToken(); String venue_id = eventTokens.nextToken(); if(venueData.contains(venue_id) && (tags != null && tags.length() > 1) ) //if this is a venue from candidate events list { StringTokenizer tagTokens = new StringTokenizer(tags, ","); while(tagTokens.hasMoreElements()) //process the tags to find trend { venueID.set(venue_id + "|" +tagTokens.nextToken().trim()); output.collect(venueID, one); } } } } catch(Exception e) { System.out.println("Caught Exception: "+e); e.printStackTrace(); } }
5efebdca-1c68-4f0b-8d6d-76c3df058e27
3
@Override public int compareTo(Object o) { try{ Pair p = (Pair)o; //if(p.first == this.first && p.second == this.second) if(p.first.equals(this.first) && p.second.equals(this.second)) return 0; }catch(ClassCastException e) { //Whatever this is, this is not a Pair. So, not equal at all. return -1; } return -1; //Not sure what would the order be, so always -1. }
27514f81-1efb-4b9f-a780-7c3f3fd7b5a1
3
@Override public void draw(Graphics2D g2) { g2.drawImage(background, 0, 0, GamePanel.WIDTH, GamePanel.HEIGHT, null); for (int i = 0; i < items; i++) { Rectangle rect = new Rectangle((GamePanel.WIDTH / 2) - (90 / 2), (GamePanel.HEIGHT / 2) + (20 + i * 50), 90, 46); if (i == selectedItem) { g2.drawImage(buttons[i][0], rect.x, rect.y, rect.width, rect.height, null); } else { g2.drawImage(buttons[i][1], rect.x, rect.y, rect.width, rect.height, null); } if (i == pressedItem) { g2.drawImage(buttons[i][2], rect.x, rect.y, rect.width, rect.height, null); } } }
1a97f6b2-3882-4eca-943e-1500443f25e6
7
private int[][] fillHeight(int[][] map) { int length = map.length / 2; //fill center tile map[(map.length - 1) / 2][(map[0].length - 1) / 2] = (map[0][0] + map[0][map[0].length - 1] + map[map.length - 1][0] + map[map.length - 1][map[0].length - 1]) / 4 + random(); while (length > 0) { //do diamond step for(int i = 0; i < map.length / 2 / length; i++) { for(int j = 0; j < map.length / 2 / length; j++) { map = diamond(map, length + (j * 2 * length), length + (i * 2 * length), length); } } //do square step for(int i = 0; i < map.length / 2 / length; i++) { for(int j = 0; j < map.length / 2 / length; j++) { if(length > 1) map = square(map, length + (j * 2 * length), length + (i * 2 * length), length); } } if(length == 1)length = 0; length -= length / 2; } return map; }
17110fcb-cad5-4216-9bab-9f8107d29862
4
@Test public void testRegistreerGebruiker() throws Exception { File f = new File("C:/Users/Jacky/Dropbox/Themaopdracht 4/CSVTestdata/RegistreerGebruikerTest.csv"); if (f.exists() && f.isFile()) { String naam; String wachtwoord; String wachtwoord2; String adres; String postcode; String woonplaats; String telefoonnummer; String emailadres; String emailadres2; FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { Scanner sc = new Scanner(line); sc.useDelimiter(";"); while (sc.hasNext()) { naam = sc.next(); wachtwoord = sc.next(); wachtwoord2 = sc.next(); adres = sc.next(); postcode = sc.next(); woonplaats = sc.next(); telefoonnummer = sc.next(); emailadres = sc.next(); emailadres2 = sc.next(); driver.get(baseUrl + "/ATD-Windows/index.jsp"); driver.findElement(By.name("naam")).clear(); driver.findElement(By.name("naam")).sendKeys("admin@ikbendeadmin.nl"); Thread.sleep(4000L); driver.findElement(By.name("wachtwoord")).clear(); driver.findElement(By.name("wachtwoord")).sendKeys("admin"); Thread.sleep(4000L); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); Thread.sleep(4000L); WebElement mnuElement; mnuElement = driver.findElement(By.id("registreren")); mnuElement.click(); Thread.sleep(4000L); driver.get("http://localhost:8080/ATD-Windows/registreer.jsp"); Thread.sleep(4000L); driver.get("http://localhost:8080/ATD-Windows/registreer.jsp"); Thread.sleep(4000L); driver.findElement(By.name("naam")).clear(); driver.findElement(By.name("naam")).sendKeys(naam); Thread.sleep(2000L); driver.findElement(By.name("wachtwoord")).clear(); driver.findElement(By.name("wachtwoord")).sendKeys(wachtwoord); Thread.sleep(2000L); driver.findElement(By.name("wachtwoord2")).clear(); driver.findElement(By.name("wachtwoord2")).sendKeys(wachtwoord2); Thread.sleep(2000L); driver.findElement(By.name("adres")).clear(); driver.findElement(By.name("adres")).sendKeys(adres); Thread.sleep(2000L); driver.findElement(By.name("postcode")).clear(); driver.findElement(By.name("postcode")).sendKeys(postcode); Thread.sleep(2000L); driver.findElement(By.name("woonplaats")).clear(); driver.findElement(By.name("woonplaats")).sendKeys(woonplaats); Thread.sleep(2000L); driver.findElement(By.name("telefoonnummer")).clear(); driver.findElement(By.name("telefoonnummer")).sendKeys(telefoonnummer); Thread.sleep(2000L); driver.findElement(By.name("emailadres")).clear(); driver.findElement(By.name("emailadres")).sendKeys(emailadres); Thread.sleep(2000L); driver.findElement(By.name("emailadres2")).clear(); driver.findElement(By.name("emailadres2")).sendKeys(emailadres2); Thread.sleep(2000L); new Select(driver.findElement(By.name("rol_id"))).selectByVisibleText("Garagemedewerker"); Thread.sleep(4000L); driver.findElement( By.cssSelector("div > input[type=\"submit\"]")).click(); Thread.sleep(4000L); driver.findElement(By.cssSelector("input[type=\"submit\"]")).click(); Thread.sleep(4000L); } line = br.readLine(); sc.close(); } br.close(); } }
28ea69ab-c6bc-47f0-888c-0013170c7b61
1
public boolean isRead() { /* if it is part of a += operator, this is a read. */ return parent != null && parent.getOperatorIndex() != ASSIGN_OP; }
83b774de-e541-42fb-84e0-1163c17f0f3b
7
public void gfxPlayRound(int myXCoor, int myYCoor, int targXCoor, int targYCoor) { previousBoard = DeltaBoard.cloneBoard(board); // Checks if user's king is in check before moving if (isChecked(userColor, getXOfKing(userColor), getYOfKing(userColor), true)){ // Check whether the user's king is in check prior to user's turn System.out.println("Your King is in check!"); } kingPreviouslyChecked = ((King)board.get(getXOfKing(userColor),getYOfKing(userColor))).isChecked(); // Keeps track of whether the user's king was checked before this turn this.myXCoor = myXCoor; this.myYCoor = myYCoor; this.targXCoor = targXCoor; this.targYCoor = targYCoor; chosen = board.get(myXCoor, myYCoor); target = board.get(targXCoor, targYCoor); // handleCastle() returns boolean signifying if iteration of the loop should be skipped if (handleCastle()){ return; } // handleEnPassant() returns boolean signifying if iteration of the loop should be skipped if (handleEnPassant()){ return; } // handlePawnJump() returns boolean signifying if iteration of the loop should be skipped if (handlePawnJump()){ return; } // Regular Move: Checks if king is in check after move if (validMove(myXCoor, myYCoor, targXCoor, targYCoor, userColor, true)) { // Case when the resulting position does NOT result in a check on the user's king if (chosen.getType().equals("PAWN")){ handlePawnPromotion(targXCoor, targYCoor); } if (target == null) { // Print feedback information to user System.out.println(clearScreen() + "Successful move: " + chosen + " (" + myXCoor + "," + myYCoor + ") to (" + targXCoor + "," + targYCoor + ").\n"); } else { // Print feedback information to user System.out.println(clearScreen() + "Successful kill: " + chosen + " (" + myXCoor + "," + myYCoor + ") takes " + target + " (" + targXCoor + "," + targYCoor + ").\n"); } advanceRound(); } else{ loopRound(); } }
f4e2ac2e-b0ff-4f22-a1dc-11e3c59f0732
5
private void initPanel(){ panel.setBackground(Color.black); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(Box.createRigidArea(new Dimension(30, 50))); panel.add(label); panel.add(Box.createRigidArea(new Dimension(30, 50))); panel.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if (sb.length() <= MAX_LENGTH) { if (String.valueOf(e.getKeyChar()).matches("[a-zA-Z0-9]")) { sb.append(e.getKeyChar()); } } label.setText(sb.toString()); if (e.getKeyCode() == KeyEvent.VK_ENTER) { quit(); } if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); label.setText(sb.toString()); } } } }); panel.setFocusable(true); }
5ed513fe-5c3d-479c-9ab5-628fc10faa67
7
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int quizID = Integer.parseInt(request.getParameter("quizID")); HttpSession session = request.getSession(); int position = 0; Quiz quiz = Quiz.getQuizByQuizID(quizID); session.setAttribute("ispractice", true); session.setAttribute("isfeedback", quiz.opFeedback); ArrayList<Question> questions = quiz.getQuestions(); ArrayList<Integer> indices = new ArrayList<Integer>(); ArrayList<Object> userAnswers = new ArrayList<Object>(); for (int i = 0; i < questions.size(); i++) userAnswers.add(null); for (int i = 0; i < questions.size(); i++) indices.add(new Integer(i)); if (quiz.isRandom) { Random random = new Random(0); for (int i = 0; i < questions.size(); i++) { int j = (int) Math.floor(random.nextDouble() * (questions.size() - i)); Integer temp = indices.get(i); indices.set(i, indices.get(j)); indices.set(j, temp); } } boolean isPractice = (Boolean) session.getAttribute("ispractice"); if (isPractice) { ArrayList<Integer> correctCount = new ArrayList<Integer>(); for (int i = 0; i < questions.size(); i++) correctCount.add(new Integer(0)); session.setAttribute("correct_count", correctCount); session.setAttribute("total_correct_count", 0); } boolean isFeedBack = (Boolean) session.getAttribute("isfeedback"); if (isFeedBack) { session.setAttribute("feedback_position", -1); } //DEBUG quiz.isOnepage = false; position++; session.setAttribute("quiz", quiz); session.setAttribute("position", position); session.setAttribute("questions", questions); session.setAttribute("indices", indices); session.setAttribute("userAnswers", userAnswers); session.setAttribute("start_time", new Date().getTime()); RequestDispatcher dispatch = request.getRequestDispatcher("take_quiz.jsp"); dispatch.forward(request, response); }
91eaff5c-919d-4dfb-8281-3bbe8b9423e5
1
public Row getLastSelectedRow() { int index = getLastSelectedRowIndex(); return index == -1 ? null : getRowAtIndex(index); }
94efbd36-0e80-4a46-9b43-94b7be836516
5
public ListNode partition(ListNode head, int x) { if (head == null) return head; if (head.val < x) { head.next = partition(head.next, x); return head; } ListNode p = head.next, q = head;; while (p!=null && p.val >= x) { q = q.next; p =p.next; } if (p == null) return head; q.next = p.next; p.next = partition(head,x); return p; }
bf9c5c56-94a6-4cc4-a921-0e00da9a770a
4
private boolean readNumber( boolean fireEvent, StringBuffer b ) throws IOException, JSONSyntaxException { // Detect any sequence of digits while( this.readChar() && this.isDigit(this.currentChar) ) b.append( this.currentChar ); // Floating point following? if( this.currentChar == '.' ) { b.append( this.currentChar ); this.readFloatingNumberFrac( false, b ); } if( fireEvent ) this.fireNumberRead( b.toString() ); return (this.currentValue != -1); }
e681015a-ea96-4bdd-bd4a-0fde71ae094d
4
@SuppressWarnings("unchecked") public static void printList(AbstractList list, int depth) { final Iterator i = list.iterator(); Object o = null; for (int k = 0; k < depth; k++) System.out.print(" "); System.out.println("List: "); while (i.hasNext() && (o = i.next()) != null) { for (int k = 0; k < depth; k++) System.out.print(" "); System.out.print(" +"); print(o, depth); } }
b503df7d-6d53-49fe-9bc0-e3951180c3da
5
List<String> events(Subscribe subscriber) { final String event2 = subscriber.value(); String[] eventz = subscriber.events(); List<String> events = new ArrayList<String>(); if (event2 != null && !event2.isEmpty()) { events.add(event2); } for (String e : eventz) { if (e != null && !e.isEmpty()) { events.add(e); } } return events; }
366ffd64-0d7c-4f20-8eb5-1242fb521b47
4
private static double getGreatestDistance(JadeNode inNode) { double distance = 0.0; if (inNode.isInternal()) { if (inNode.isTheRoot()) { distance = inNode.getBL(); } double posmax = 0.0; for (int i = 0; i < inNode.getChildCount(); i++) { double posmax2 = getGreatestDistance(inNode.getChild(i)); if (posmax2 > posmax) posmax = posmax2; } distance += posmax; return distance; } else return inNode.getBL(); }
c30ae1c2-5917-43db-ac8f-2ee81ef659c4
3
private void createMap() { Node node; map = new ArrayList<ArrayList<Node>>(); for (int x = 0; x < mapWith; x++) { map.add(new ArrayList<Node>()); for (int y = 0; y < mapHeight; y++) { node = new Node(x, y); if (obstacleMap[x][y] == 1) { node.setObstical(true); } map.get(x).add(node); } } }
eeee15f3-8252-4833-8911-9782a5be3de0
2
public void loadLegendConfig() throws FileNotFoundException, BadConfigFormatException { cellTypes = new HashMap<Character, String>(); FileReader reader = new FileReader(legend); Scanner s = new Scanner(reader); String infoString; char abbreviation; String cellName; while (s.hasNextLine()) { // grab line infoString = s.nextLine(); // ensure line contains comma if (infoString.charAt(1) != ',') { throw new BadConfigFormatException("Bad Legend File"); } abbreviation = infoString.charAt(0); // 3 is where the string starts with a space in between comma and // string cellName = infoString.substring(3); cellTypes.put(abbreviation, cellName); } }
3fbf12f4-b855-400d-9a6c-cbd601ce3283
0
public int getPage() { return page; }
7b36684c-71de-4512-acb5-04e93acbf00e
5
private void buildAddress() { FileReader inetSaves = null; int numAdd = 0; numAddress=0; try { byteCount = (new File("IPAddressBank.rcf")).length(); byteCount = (long) 1.25*byteCount; inetSaves = new FileReader("IPAddressBank.rcf"); //Check the file header if(!readTill(';',inetSaves).equals("IP Address Bank")) { System.err.println("Invalid header for IP address bank"); inetSaves = null; } //Find the number of inet addresses in the file while(!newLine(inetSaves).equals("end")) { if(byteCount < 0) { System.err.println("Important return"); inetSaves.close(); saveAddress(); needReset = true; return; } numAdd++; } inetSaves.close(); byteCount = (new File("IPAddressBank.rcf")).length(); byteCount = (long) 1.25*byteCount; inetSaves = new FileReader("IPAddressBank.rcf"); //Fill the Inet list int cnt = 0; while(cnt<numAdd) { newLine(inetSaves); readTill('/',inetSaves); addAddress(InetAddress.getByName(readTill(';',inetSaves))); cnt++; } inetSaves.close(); setCanConnect(); } catch(IOException e) { System.err.println("Fatal error in the IP address file"); } }
f74d2eff-ddfc-474f-bb57-52e3adb40739
0
public AbstractPlay get(int number) { return super.get(number); }
4ddd0838-fb46-477d-b9c6-f5dd85aff5a5
8
public static void main(String[] args){ long t = 1; long p = 1; long h = 1; long T=2, P=3, H=4; boolean firstTime=true; while(true){ if (T<= P && T<=H){ t++; T=t*(t+1)/2; } else if (P <= T && P <= H){ p++; P=p*(3*p-1)/2; } else { h++; H=h*(2*h-1); } if (T == P && P == H){ if (!firstTime) break; firstTime=false; } // // System.out.println(P); } System.out.println(T); }
8528d173-2280-4b50-9f02-81ea539e5e2d
5
public void insert(MazeCell item, MazeCell current){ int j; if(item == null) System.out.println("PROBLEEEEEEEEEM"); if(rear == maxSize-1){ // deal with wraparound rear = -1; //System.out.println("PROBLEEEEEEEEEM2"); } if (nItems==0){ queArray[++rear]= item; //System.out.println("yoo"); nItems++; //System.out.printf("rear is now %d\n",rear); } else{ //System.out.println("PROBLEEEEEEEEEM3"); //System.out.printf("j is %d\n",rear); for(j=rear; j>=front; j--){ //System.out.println("PROBLEEEEEEEEEM4"); //System.out.printf("j is %d\n",j); if(calculateDistance(item,current)<calculateDistance(queArray[j],current)){//epeidh ola ta kelia ston laburintho exoun apostasi ena System.out.println("Let's give priority to the closer ones!"); queArray[j+1]=queArray[j]; //ousiastika den tha ekteleitai pote auto to if } //dhladh h UCS se auth th periptvsh tha douleuei san BFS. else{ //System.out.println("PROBLEEEEEEEEEM6"); break; } } //System.out.println("yoo2"); queArray[++rear]=item; nItems++; } }
a597b020-1960-4d43-99e5-67a1d815f827
8
protected Object readObjectImpl(Class cl) throws IOException { try { Object obj = cl.newInstance(); if (_refs == null) _refs = new ArrayList(); _refs.add(obj); HashMap fieldMap = getFieldMap(cl); int code = read(); for (; code >= 0 && code != 'z'; code = read()) { _peek = code; Object key = readObject(); Field field = (Field) fieldMap.get(key); if (field != null) { Object value = readObject(field.getType()); field.set(obj, value); } else { Object value = readObject(); } } if (code != 'z') throw expect("map", code); // if there's a readResolve method, call it try { Method method = cl.getMethod("readResolve", new Class[0]); return method.invoke(obj, new Object[0]); } catch (Exception e) { } return obj; } catch (IOException e) { throw e; } catch (Exception e) { throw new IOExceptionWrapper(e); } }
5c368259-3a7b-444c-a0ab-7b4ad277df51
6
SortGraphics(){ JFrame frame = new JFrame("Sorting Algorithms"); canvas.setForeground(Color.black); canvas.setBackground(Color.white); Sort.setPointNumber(300); // calls init frame.getContentPane().add(canvas); frame.getContentPane().validate(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400,450); JMenuBar menubar = new JMenuBar(); JMenu initMenu = new JMenu("Initialization"); JMenuItem randomItem = new JMenuItem("Random"); JMenuItem randomUniqueItem = new JMenuItem("Random, unique"); JMenuItem backwardsItem = new JMenuItem("Sorted, decreasing"); JMenuItem sortedItem = new JMenuItem("Sorted, increasing"); JMenuItem reuseItem = new JMenuItem("Start over without init"); initMenu.add(randomItem); initMenu.add(randomUniqueItem); initMenu.add(backwardsItem); initMenu.add(sortedItem); initMenu.add(new JSeparator()); initMenu.add(reuseItem); randomItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Sort.initRandom(new Random().nextInt() ); Dimension d = canvas.getSize(); if( d == null ) return; canvas.repaint(0,0,d.width,d.height); } }); randomUniqueItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // TODO: initRandomUnique not implemented yet!! Sort.initRandom(new Random().nextInt() ); Dimension d = canvas.getSize(); if( d == null ) return; canvas.repaint(0,0,d.width,d.height); } }); backwardsItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Sort.initBackwards(); Dimension d = canvas.getSize(); if( d == null ) return; canvas.repaint(0,0,d.width,d.height); } }); sortedItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Sort.initSorted(); Dimension d = canvas.getSize(); if( d == null ) return; canvas.repaint(0,0,d.width,d.height); } }); reuseItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Sort.initOldNumbers(); Dimension d = canvas.getSize(); if( d == null ) return; canvas.repaint(0,0,d.width,d.height); } }); sortMenu = new JMenu("Sorting Algorithms"); JMenuItem stopSort = new JMenuItem("Stop Sorting"); sortMenu.add(stopSort); stopSort.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if( sortT == null ) return; sortT.stop(); // destroy the current thread } }); sortMenu.add(new JSeparator()); menubar.add(initMenu); menubar.add(sortMenu); frame.setJMenuBar(menubar); frame.pack(); frame.setVisible(true); }
4996b4cb-27db-40e4-bada-c2d03d0f0245
9
public void keyReleased(KeyEvent e) { switch(e.getKeyCode()) { case 37: left = false; leftReleased = true; break; case 39: right = false; rightReleased = true; break; case 65: a = false; aReleased = true; break; case 68: d = false; dReleased = true; break; case 10: enter = false; enterReleased = true; break; case 38: up = false; upReleased = true; break; case 40: down = false; downReleased = true; break; case KeyEvent.VK_W: w = false; wReleased = true; break; case KeyEvent.VK_S: s = false; sReleased = true; break; } }
55d785f3-f49f-4ecb-8618-6928a850e0be
1
private BeanstreamApiException mappedException(int status, BeanstreamResponse bsRes) { if (bsRes != null) { return BeanstreamApiException.getMappedException(status, bsRes); } return BeanstreamApiException.getMappedException(status); }
2f4632d1-4449-467e-9700-0dda6bd17f34
9
public Token scanForNextToken() { if (!matcher.find()) return null; String tokenstring = matcher.group(); String type = null; if (Pattern.compile(SPECIAL_SYMBOL).matcher(tokenstring).matches()) type = "specialsymbol"; else if (Pattern.compile(KEYWORD).matcher(tokenstring).matches()) type = "keyword"; else if (Pattern.compile(SYMBOL).matcher(tokenstring).matches()) type = "symbol"; else if (Pattern.compile(WORD).matcher(tokenstring).matches()) type = "word"; else if (Pattern.compile(NUMBER).matcher(tokenstring).matches()) type = "number"; else if (Pattern.compile(BOOLEAN).matcher(tokenstring).matches()) type = "boolean"; else if (Pattern.compile(CHARACTER).matcher(tokenstring).matches()) type = "character"; else if (Pattern.compile(STRING).matcher(tokenstring).matches()) type = "string"; else type = "unknown"; return new Token(tokenstring, type); }
af1832d4-85a7-4499-a3f0-c47671f5ad22
5
@Override public String toString() { StringBuilder sb = new StringBuilder(""); for (int x=size-1; x >= 0; x--) { for (int y=0; y < size; y++) { switch (grid[x][y]) { case UNSAFE: sb.append(" X "); break; case OCCUPIED: sb.append(" Q "); break; case EMPTY: sb.append(" _ "); break; default: break; } } sb.append('\n'); } return sb.toString(); }
220ef58e-f3d1-48e8-9895-c23a3b2d6007
6
public RTT.corba.CSendHandle sendOperation (String operation, org.omg.CORBA.Any[] args) throws RTT.corba.CNoSuchNameException, RTT.corba.CWrongNumbArgException, RTT.corba.CWrongTypeArgException, RTT.corba.CCallInterrupted { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("sendOperation", true); $out.write_string (operation); RTT.corba.CAnyArgumentsHelper.write ($out, args); $in = _invoke ($out); RTT.corba.CSendHandle $result = RTT.corba.CSendHandleHelper.read ($in); return $result; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); if (_id.equals ("IDL:RTT/corba/CNoSuchNameException:1.0")) throw RTT.corba.CNoSuchNameExceptionHelper.read ($in); else if (_id.equals ("IDL:RTT/corba/CWrongNumbArgException:1.0")) throw RTT.corba.CWrongNumbArgExceptionHelper.read ($in); else if (_id.equals ("IDL:RTT/corba/CWrongTypeArgException:1.0")) throw RTT.corba.CWrongTypeArgExceptionHelper.read ($in); else if (_id.equals ("IDL:RTT/corba/CCallInterrupted:1.0")) throw RTT.corba.CCallInterruptedHelper.read ($in); else throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { return sendOperation (operation, args ); } finally { _releaseReply ($in); } } // sendOperation
f6723658-1951-4069-bbe6-d12aaa4f3205
7
@Override public void run() { int frames = 0; double unprocessedSeconds = 0; long lastTime = System.nanoTime(); double secondsPerTick = 1 / 60.0; int tickCount = 0; requestFocus(); while (running) { long now = System.nanoTime(); long passedTime = now - lastTime; lastTime = now; if (passedTime < 0) passedTime = 0; if (passedTime > 100000000) passedTime = 100000000; unprocessedSeconds += passedTime / 1000000000.0; boolean ticked = false; while (unprocessedSeconds > secondsPerTick) { tick(); unprocessedSeconds -= secondsPerTick; ticked = true; tickCount++; if (tickCount % 60 == 0) { System.out.println(frames + " fps"); lastTime += 1000; frames = 0; } } if (ticked) { render(); frames++; } else { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }
861cadbf-8dcc-4d06-9ee5-dc474cb6557a
0
public String getMsgID() { return msgID; }
351bbd97-8e64-421a-a2a9-adb427b16bd8
9
int at(long x){ long L=0, R=0; int k; for(k=17;k>=0;k--)if(endK[k] < x){ L = ten[k]; R = k==17?MAX_NUMBER:ten[k+1]; break; } for(;;){ long m = (R+L)/2; long p = endK[k]+1+(k+1)*(m-ten[k]); if(p<=x&&x<p+k+1){ String s = m+""; for(int i=0;i<s.length();i++)if(p+i==x)return s.charAt(i)-'0'; } else if(x < p)R=m; else L=m; } }
86a446ac-4700-4018-8d2e-ef5c37336362
4
@Override public void handle(HttpExchange exchange) throws IOException { System.out.println("In road building handler"); String responseMessage = ""; if(exchange.getRequestMethod().toLowerCase().equals("post")) { try { //TODO verify cookie method String unvalidatedCookie = exchange.getRequestHeaders().get("Cookie").get(0); CookieParams cookie = Cookie.verifyCookie(unvalidatedCookie, translator); BufferedReader in = new BufferedReader(new InputStreamReader(exchange.getRequestBody())); String inputLine; StringBuffer requestJson = new StringBuffer(); while ((inputLine = in.readLine()) != null) { requestJson.append(inputLine); } in.close(); System.out.println(requestJson); RoadBuildingDevRequest request = (RoadBuildingDevRequest) translator.translateFrom(requestJson.toString(), RoadBuildingDevRequest.class); exchange.getRequestBody().close(); ServerModel serverModel = this.movesFacade.roadBuilding(request, cookie); System.out.println("Request Accepted!"); // create cookie for user List<String> cookies = new ArrayList<String>(); // send success response headers exchange.getResponseHeaders().put("Set-cookie", cookies); exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); movesLog.store(new RoadBuildingCommand(movesFacade, request, cookie)); String name = serverModel.getPlayerByID(cookie.getPlayerID()).getName(); serverModel.getLog().addMessage(new LogEntry(name+ " played Road Building", serverModel.getPlayerByID(cookie.getPlayerID()).getName())); responseMessage = translator.translateTo(serverModel); } catch (InvalidCookieException | InvalidMovesRequest e) { // else send error message System.out.println("unrecognized / invalid road building(dev) request"); responseMessage = e.getMessage(); exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0); } } else { // unsupported request method responseMessage = "Error: \"" + exchange.getRequestMethod() + "\" is no supported!"; exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0); } //set "Content-Type: text/plain" header List<String> contentTypes = new ArrayList<String>(); String type = "text/plain"; contentTypes.add(type); exchange.getResponseHeaders().put("Content-type", contentTypes); if (!responseMessage.isEmpty()) { //send failure response message OutputStreamWriter writer = new OutputStreamWriter( exchange.getResponseBody()); writer.write(responseMessage); writer.flush(); writer.close(); } exchange.getResponseBody().close(); }
2a8e6a39-0699-476d-8af1-8d405aa489a0
6
public boolean test() { FileSystem fs; try { fs = new FileSystem("sample"); } catch (Exception e) { return false; } System.out.println(fs.toXMLString()); // make sure 'sample/foo/bar' is in the file system Tree<FileNode> rt = fs.getTree(); if(!rt.getLabel().getName().equals("CWD")) return false; Tree<FileNode> sampleT; try { sampleT = rt.findChild(new FileNode("sample",true)); if(sampleT == null) return false; Tree<FileNode> fooT = sampleT.findChild(new FileNode("foo",true)); if(fooT == null) return false; Tree<FileNode> barT = fooT.findChild(new FileNode("bar",true)); if(barT == null) return false; return true; } catch (InvalidOperationException e) { return false; // TODO Auto-generated catch block //e.printStackTrace(); } }
4ec8528f-87e9-4260-9a57-3f9d8239c952
1
public boolean hasPrefix(PGridPath path) { if (path == null) { throw new NullPointerException(); } return commonPrefix(path).length() == path.length(); }
a0d983df-f9af-49d8-8de7-48cafeeba671
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TestClass other = (TestClass) obj; if (component == null) { if (other.component != null) return false; } else if (!component.equals(other.component)) return false; if (value != other.value) return false; return true; }
937f413a-beac-41bd-861b-c2a69cfbdbc0
4
private void getCategoryContent(Map<String, Object> jsonrpc2Params) throws Exception { Map<String, Object> params = getParams(jsonrpc2Params, Constants.Param.Name.CATEGORY_ID, Constants.Param.Name.TYPE); int categoryId = (Integer) params.get(Constants.Param.Name.CATEGORY_ID); String type = (String) params.get(Constants.Param.Name.TYPE); if(type.equals(Constants.Param.Value.PUBLIC)){ Category category = em.getReference(Category.class, categoryId); if (category == null) { responseParams.put(Constants.Param.Status.STATUS, Constants.Param.Status.OBJECT_NOT_FOUND); return; } Collection<Thread> threadList = new LinkedList<Thread>(category.getThreads()); responseParams.put(Constants.Param.Name.THREADS, serialize(threadList)); }else if(type.equals(Constants.Param.Value.PRIVATE)){ PrivateCategory category = em.getReference(PrivateCategory.class, categoryId); if(category == null){ responseParams.put(Constants.Param.Status.STATUS, Constants.Param.Status.OBJECT_NOT_FOUND); return; } Collection<LinkedThread> threadList = new LinkedList<LinkedThread>(category.getLinkedThreads()); Collection<Note> notes = new LinkedList<Note>(category.getNotes()); responseParams.put(Constants.Param.Name.THREADS, serialize(threadList)); responseParams.put(Constants.Param.Name.THREADS, serialize(notes)); }else{ throwJSONRPC2Error(JSONRPC2Error.INVALID_PARAMS, Constants.Errors.PARAM_VALUE_NOT_ALLOWED, "Type: " + type); } responseParams.put(Constants.Param.Status.STATUS, Constants.Param.Status.SUCCESS); }
455e4a85-6e71-4423-bcfb-2865b6370030
2
@Override public boolean decrementLives() { if (lives == -1) return true; if (lives > 0) { lives--; return true; } return false; }
0ca2d9d4-53ea-49fb-a88b-ffa4aa8ad807
9
public long fillTables() { Iterator it = tables.listIterator(); // list of relevant source-tables String srctable=""; // holds name of current source-table long rowcount = 0; // add the database identifier into the SELECT statement queryStr = queryStr.replaceAll("databaseID", ""+databaseID); // iterate through all relevant source-tables while (it.hasNext()) { try { // extract data from source table and store it into remote temporary database srctable = (String)it.next(); rowcount += sourceDB.executeUpdate("INSERT IGNORE INTO "+tmpTable+" "+queryStr.replaceAll("#srctable#",srctable)); } catch (SQLException e) { // error, report to caller output += "Error while filling temporary database from source table "+srctable+"!"; output += "<p>"+e.getMessage()+"<p>"; success = false; return 0; } } // copy data from remote temporary table into local temporary table via mysqldump // (needs not be done if remote and local databases are the same) if (!dbIdentical) try { // different syntax for calling command line in windows and linux String os = System.getProperty("os.name").toLowerCase(); Runtime rt=Runtime.getRuntime(); String[] command = {"","",""}; if (os.indexOf("windows")>-1) { command[0] = "cmd.exe"; command[1] = "/c"; } else { command[0] = "/bin/sh"; command[1] = "-c"; } // build mysqldump-command // check if port was given String sourceHost = ""; String sourcePort = ""; if (sourceInfo.getHost().indexOf(":")>-1) { sourceHost = sourceInfo.getHost().split(":")[0]; sourcePort = "--port="+sourceInfo.getHost().split(":")[1]; } else sourceHost = sourceInfo.getHost(); String destHost = ""; String destPort = ""; if (destInfo.getHost().indexOf(":")>-1) { destHost = destInfo.getHost().split(":")[0]; destPort = "--port="+destInfo.getHost().split(":")[1]; } else destHost = destInfo.getHost(); if (sourceInfo.isUseSSH()) { // Version mit SSH command[2] = "ssh -q "+sourceHost+" mysqldump "+sourcePort+" --user="+sourceInfo.getUser() +" --password="+sourceInfo.getPassword()+" -t --compact --lock-tables=FALSE "+sourceInfo.getName() +" "+tmpTable; } else { // Version ohne SSH command[2] = "mysqldump --host="+sourceHost+" "+sourcePort+" --user="+sourceInfo.getUser() +" --password="+sourceInfo.getPassword()+" -t --compact --compress --lock-tables=FALSE "+sourceInfo.getName() +" "+tmpTable; } if (destInfo.isUseSSH()) { // Version mit SSH command[2] += " | ssh -q "+destHost+" mysql "+destPort+" --user="+destInfo.getUser() +" --password="+destInfo.getPassword()+" -C "+destInfo.getName(); } else { // Version ohne SSH command[2] += " | mysql --host="+destHost+" "+destPort+" --user="+destInfo.getUser() +" --password="+destInfo.getPassword()+" "+destInfo.getName(); } // execute command and wait for it to finish Process proc=rt.exec(command); /*BufferedInputStream bis = new BufferedInputStream(proc.getErrorStream()); int i=0; while ((i = bis.read())!=-1) { output+=(char)i; }*/ Thread.yield(); proc.waitFor(); } catch (Exception e) { // error, report to caller output += "Error while filling temporary database from source table "+srctable+" with mysqldump!"; output += "<p>"+e.getMessage()+"<p>"; success = false; return 0; } return rowcount; }
a448a773-abfd-4acf-9ff6-f9f6d8b99541
5
public void run() { try { if (isListener) { connection = listener.accept(); writeBuffer = new QueueBuffer<String>(connection.getOutputStream()); readBuffer = new BufferedReader(new InputStreamReader(connection.getInputStream())); handler.setState(State.CONNECTED); } while (true) { String in = readBuffer.readLine(); if (in == null) break; handler.fireRawTextEvent(in); Thread.yield(); } } catch (IOException e) { e.printStackTrace(); } finally { try { writeBuffer.close(); readBuffer.close(); connection.close(); listener.close(); } catch (IOException e) { e.printStackTrace(); } } }
f150ad83-418f-41dc-83e0-ad4f528c211e
1
public void visit_ldiv(final Instruction inst) { stackHeight -= 4; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += 2; }
d59f69ba-b111-460e-a317-6130d3ea8767
0
public JTextField getjTextFieldPrenom() { return jTextFieldPrenom; }
df47a53d-330a-4044-8dc8-7a9a9e266c58
0
public String getContents() { return buffer.toString(); }
a985fa07-cffb-4238-8225-69485c3ac9f5
0
public final String toString() { StringBuffer sb = new StringBuffer(); sb.append("{ " + super.toString()); sb.append(", distance=" + distance); sb.append(", position=(" + position.getX() + "," + position.getY() + ")"); sb.append(", lineWidth=" + lineWidth); sb.append(", incrementWidth=" + incrementWidth); sb.append(", angleChange=" + angleChange); sb.append(", color=" + color); sb.append(", polygonColor=" + polygonColor); sb.append(" }"); return sb.toString(); }
336fc641-7f45-4bc6-9500-32f87d811be1
9
public static byte[] getInverterType(String code) { byte[] invertercode = new byte[4]; if (code.equals("1700TL")) { invertercode[0] = 0x12; invertercode[1] = 0x1a; invertercode[2] = (byte) 0xd9; invertercode[3] = 0x38; //conf->ArchiveCode = 0x63; } if (code.equals("2100TL")) { invertercode[0] = 0x17; invertercode[1] = (byte) 0x97; invertercode[2] = 0x51; invertercode[3] = 0x38; //conf->ArchiveCode = 0x63; } if (code.equals("3000TL")) { invertercode[0] = 0x12; invertercode[1] = 0x1a; invertercode[2] = (byte) 0xd9; invertercode[3] = 0x38; invertercode[0] = 0x32; invertercode[1] = 0x42; invertercode[2] = (byte) 0x85; invertercode[3] = 0x38; //conf->ArchiveCode = 0x71; } if (code.equals("3000TLHF")) { invertercode[0] = 0x1b; invertercode[1] = (byte) 0xb1; invertercode[2] = (byte) 0xa6; invertercode[3] = 0x38; //conf->ArchiveCode = 0x83; } if (code.equals("4000TL")) { invertercode[0] = 0x78; invertercode[1] = 0x21; invertercode[2] = (byte) 0xbf; invertercode[3] = 0x3a; //conf->ArchiveCode = 0x4e; } if (code.equals("5000TL")) { invertercode[0] = 0x3f; invertercode[1] = 0x10; invertercode[2] = (byte) 0xfb; invertercode[3] = 0x39; //conf->ArchiveCode = 0x4e; } if (code.equals("7000")) { invertercode[0] = (byte) 0xcf; invertercode[1] = (byte) 0x84; invertercode[2] = (byte) 0x84; invertercode[3] = 0x3a; //conf->ArchiveCode = 0x63; } if (code.equals("10000TL")) { invertercode[0] = 0x69; invertercode[1] = 0x45; invertercode[2] = 0x32; invertercode[3] = 0x39; //conf->ArchiveCode = 0x80; } if (code.equals("XXXXTL")) { invertercode[0] = (byte) 0x99; invertercode[1] = 0x35; invertercode[2] = 0x40; invertercode[3] = 0x36; //conf->ArchiveCode = 0x4e; } return invertercode; }
88d5f8bd-5285-4c78-a88c-d98ed1712e91
6
public BitVector subset(int start, int end) { if (start < 0 || end > size() || end < start) throw new IndexOutOfBoundsException(); // Special case -- return empty vector is start == end if (end == start) return new BitVector(0); byte[] bits = new byte[((end - start - 1) >>> 3) + 1]; int s = start >>> 3; for (int i = 0; i < bits.length; i++) { int cur = 0xFF & this.bits[i + s]; int next = i + s + 1 >= this.bits.length ? 0 : 0xFF & this.bits[i + s + 1]; bits[i] = (byte) ((cur >>> (start & 7)) | ((next << (8 - (start & 7))))); } int bitsToClear = (bits.length * 8 - (end - start)) % 8; bits[bits.length - 1] &= ~(0xFF << (8 - bitsToClear)); return new BitVector(bits, end - start); }
6546214a-2280-4fa7-aec1-22c84d1018d0
3
@Override public ResultSet fillData(String command) { try { if (connection.isClosed()) Connect(server); } catch (SQLException e) { Connect(server); } try { return connection.prepareStatement(command).executeQuery(); } catch (SQLException e) { e.printStackTrace(); return null; } }
1fdb3b94-d2af-4c7b-b088-2bbda27cd6db
1
public void checkDatabaseConnection() { logger.info("Checking database connection..."); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); try { jdbcTemplate.queryForInt(SqlQueries.CHECK_DATABASE_QUERY); logger.info("Database is up!"); } catch (DataAccessException e) { logger.error("Database connection is down!", e); } }
590bf5a0-6f4d-46da-8153-77fabec53eca
2
public static void main(String[] args){ int average = 141; System.out.println(average); int invert=0; int help = average; while (help !=0) { invert=invert*10+help%10; help=help/10; } System.out.println(invert); if (average == invert) { System.out.println("it is a palindrome"); } else { System.out.println("it is not"); } }
54130c38-e6b8-474c-b82f-80c01878ec1b
3
protected void printFileHeader(PrintWriter writer) { writeToFile(HEADER_TIME, false); int nrOfClusters = clusters.size(); for (int i = 0; i < nrOfClusters; i++) { int nrOfElementsInCluster = clusters.get(i).getTimeSeriesIndexes().size(); for (int j = 0; j < nrOfElementsInCluster; j++) { if (isLastElement(nrOfClusters, i, nrOfElementsInCluster, j)) { writeToFile(getHeaderClusterString(i, j), true); } else { writeToFile(getHeaderClusterString(i, j), false); } } } }