method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
d609634c-e06f-494c-a19d-6e27aeffe6ff
2
public static void loadFonts(){ try { resource = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/fonts.png")); } catch (IOException e) { e.printStackTrace(); } try { texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/background/sand.png")); } catch (IOException e) { e.printStackTrace(); } }
ef6ef649-1d15-4c89-a215-89e16f269666
1
public void applyPreserveRule(IdentifierMatcher preserveRule) { if (loadOnDemand) loadMatchingClasses(preserveRule); super.applyPreserveRule(preserveRule); }
c63aed86-f621-409a-9ad7-b98a5d55e26f
0
@Override public void componentResized(ComponentEvent e) { // 根据panel自适应大小,调整scrollpane和textArea的位置 scrollPane.setBounds(0, 0, this.getWidth(), this.getHeight()); textArea.setSize(scrollPane.getSize()); // 调整滚动条到随后 textArea.selectAll(); // 去掉全选效果 textArea.setCaretPosition(textArea.getDocument().getLength()); // JScrollBar bar = scrollPane.getVerticalScrollBar(); // bar.setValue(bar.getMaximum()); // scrollPane.getVerticalScrollBar().setValue(scrollPane.getVerticalScrollBar().getMaximum()); // System.out.println("componentResized: bounds:" + this.getBounds() + // ", size=" + this.getSize()); // System.out.println("textArea bounds=" + textArea.getBounds() + // ", caret pos=" + textArea.getCaretPosition()); // System.out.println("scrollPane bounds=" + scrollPane.getBounds()); // // System.out.println("bar pos=" + bar.getValue() + ", maxpos=" + // bar.getMaximum()); // System.out.println("========"); }
75ec7a17-72a3-4d4b-944f-030709dea392
0
public LocalDate getEndDate() { return this._endDate; }
14ebf1a1-788c-42da-8927-9c38ed8918fd
0
@OneToMany(mappedBy="car") public List<Participant> getPassengers() { return passengers; }
7248fdf9-ee1b-4852-88ce-0d8505a2ad0e
3
void replaceAllocStmt(Unit u){//Set<Unit> set){ String classname = null; /* Iterator it = u.getDefBoxes().iterator(); while(it.hasNext()){ Value v = ((ValueBox)it.next()).getValue(); if(v instanceof Local){ Local l = (Local)v ; classname = l.getType().toString(); } } */ StringBuilder sb = new StringBuilder("void initializePoolObject"); Value v = u.getDefBoxes().get(0).getValue(); Unit spclInvk = b.getUnits().getSuccOf(u); if(spclInvk instanceof InvokeStmt){ InvokeExpr invExpr = ((InvokeStmt) spclInvk).getInvokeExpr(); if(invExpr instanceof SpecialInvokeExpr){ String s = invExpr.getMethod().toString(); //does it yield full method name along with classname and parameters passed? int i = s.indexOf("("); sb.append(s.substring(i, s.length()-1)); int j = s.indexOf(":"); classname = s.substring(1, j); } } Unit u_succ = b.getUnits().getSuccOf(u); Unit insert_before = null; if(u_succ instanceof InvokeStmt){ insert_before = b.getUnits().getSuccOf(u_succ); } Local bool = Jimple.v().newLocal("flag", BooleanType.v()); b.getLocals().add(bool); Stmt check = Jimple.v().newAssignStmt(bool, Jimple.v().newVirtualInvokeExpr(buf_l, bufPool.getMethod("boolean isObjInPool(java.lang.String)").makeRef(), StringConstant.v(classname))); b.getUnits().insertBefore(check, u); Local savedObj = Jimple.v().newLocal("savedObj", RefType.v(Scene.v().getSootClass("java.lang.Object"))); b.getLocals().add(savedObj); Stmt ifStmt = Jimple.v().newIfStmt( Jimple.v().newEqExpr(bool, IntConstant.v(0)), u); b.getUnits().insertAfter(ifStmt, check); Stmt toCall = Jimple.v().newAssignStmt(savedObj, Jimple.v().newVirtualInvokeExpr(buf_l, bufPool.getMethod("java.lang.Object getObject(java.lang.String)").makeRef(), StringConstant.v(classname))); b.getUnits().insertAfter(toCall, ifStmt); Stmt castStmt = Jimple.v().newAssignStmt(v , Jimple.v().newCastExpr(savedObj, RefType.v(Scene.v().getSootClass(classname)))); b.getUnits().insertAfter(castStmt, toCall); Stmt s = Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr((Local) v, Scene.v().getSootClass(classname).getMethod(sb.toString()).makeRef())); b.getUnits().insertAfter(s, castStmt); b.getUnits().insertAfter(Jimple.v().newGotoStmt(insert_before), s); }
381c811b-f931-485b-93f1-0d719689093a
0
public void setPcaIdElemento(int pcaIdElemento) { this.pcaIdElemento = pcaIdElemento; }
26805530-e4fd-44c1-86e5-977ac697921e
3
private static boolean doesPatternExist(Map<Byte, byte[]> haystack, byte[] needle) { if (needle == null) return false; for (Byte key : haystack.keySet()) { if (Arrays.equals(haystack.get(key), needle)) { return true; } } return false; }
c30c9741-29e9-4504-85af-a90147091096
8
private void loadingStages() { if(lowMem && loadingStage == 2 && ObjectManager.anInt131 != plane) { aRSImageProducer_1165.initDrawingArea(); aTextDrawingArea_1271.drawText(0, "Loading - please wait.", 151, 257); aTextDrawingArea_1271.drawText(0xffffff, "Loading - please wait.", 150, 256); aRSImageProducer_1165.drawGraphics(4, super.graphics, 4); loadingStage = 1; aLong824 = System.currentTimeMillis(); } if(loadingStage == 1) { int j = method54(); if(j != 0 && System.currentTimeMillis() - aLong824 > 0x57e40L) { signlink.reporterror(myUsername + " glcfb " + aLong1215 + "," + j + "," + lowMem + "," + decompressors[0] + "," + onDemandFetcher.getNodeCount() + "," + plane + "," + anInt1069 + "," + anInt1070); aLong824 = System.currentTimeMillis(); } } if(loadingStage == 2 && plane != anInt985) { anInt985 = plane; method24(plane); } }
80a7eb66-aa9d-4f1d-b8d5-06d659bf3ac5
7
@Override public int worldAging(int age) { //between 4000BC and 100BC if(age < -100){ return age + 100; } //Around birth of Christ else if(age == -100){ return age = -1; } else if(age == -1){ return age = 1; } else if(age == 1){ return age = 50; } //between 50 AD and 1750 AD else if(age < 1750){ return age + 50; } //between 1750 AD and 1900 AD else if(age < 1900){ return age + 25; } //between 1900 AD and 1970 AD else if(age < 1970){ return age + 5; } //After 1970 AD return age + 1; }
817b4f1c-53db-493b-bfff-751603fadf94
5
private void multiplyTempo() { String txt = tempoField.getText(); if (txt != null) { int num = 1; try { num = Integer.parseInt(txt); } catch (NumberFormatException e) { return; } if (num <= 1) return; ArrayList<StaffNoteLine> s = theStaff.getSequence().getTheLines(); ArrayList<StaffNoteLine> n = new ArrayList<StaffNoteLine>(); for (int i = 0; i < s.size(); i++) { n.add(s.get(i)); for (int j = 0; j < num - 1; j++) n.add(new StaffNoteLine()); } s.clear(); s.addAll(n); StateMachine.setTempo(theStaff.getSequence().getTempo() * num); theStaff.updateCurrTempo(); theStaff.getControlPanel().getScrollbar() .setMax(s.size() - Values.NOTELINES_IN_THE_WINDOW); } }
e6b0dc3d-c1ea-4971-8e62-8ade8bb4a4a9
4
public void verifyType(String inMsg, BufferedReader in) throws Exception{ String welcomeMsg = WELCOME_CONSTANT + "\n"; String[] splitter = inMsg.split(":"); if ((splitter[0] + ":").equals(FROM_CONSTANT )){ if (!splitter[1].isEmpty()){ String ipReceived = splitter[1]; System.out.println("<CLIENT> DEBUGGING: " + ipReceived); if (adyacentIp.equals(ipReceived)){ System.out.println("<CLIENT> DEBUGGING IP RECIVED:" + ipReceived); String type = in.readLine(); //Revisar si es WELCOME System.out.println("<CLIENT> TYPE IS:" + type); if (type.equals(WELCOME_CONSTANT)){ System.out.println("<CLIENT>\n Starting to send DV"); } } } } }
e9ee21af-6e32-4b38-afbe-d48959cebf6e
0
@Override public void greeting(Context ctx) { System.out.println("Hello !! " + LoggerUtils.getSig()); ctx.setState(new ConcreteState_Night()); }
dd9e4f43-e2cd-4e94-8c59-b5455267088c
4
public boolean deleteFile(String filename, int resID) { // check for errors first if (resID == -1 || filename == null) { return false; } Object[] packet = new Object[2]; packet[0] = filename; packet[1] = myID_; // send the event super.send(super.output, 0, DataGridTags.FILE_DELETE_REPLICA, new IO_data(packet, DataGridTags.PKT_SIZE, resID)); // wait for ACK int tag = DataGridTags.FILE_DELETE_REPLICA_RESULT; FilterDataResult type = new FilterDataResult(filename, tag); Sim_event ev = new Sim_event(); super.sim_get_next(type, ev); boolean result = false; try { packet = (Object[]) ev.get_data(); String resName = GridSim.getEntityName(resID); int msg = ((Integer) packet[1]).intValue(); if (msg == DataGridTags.FILE_DELETE_SUCCESSFUL) { result = true; System.out.println(super.get_name() + ".deleteFile(): " + filename + " has been deleted from " + resName); } else { System.out.println(super.get_name() + ".deleteFile(): " + "There was an error in deleting " + filename + " from " + resName); } } catch (Exception e) { System.out.println(super.get_name() + ".deleteFile(): Exception"); result = false; } return result; }
f67dd151-b3cd-4586-80df-dcb671302f89
4
@SuppressWarnings("unchecked") @Override public String displayQuestionWithAnswer(int position, Object userAnswer) { ArrayList<String> questionList = (ArrayList<String>) question; String questionStr = questionList.get(0) + "_____________" + questionList.get(1); ArrayList<String> answerList = (ArrayList<String>) answer; String userAnswerStr = (String) userAnswer; boolean correct = false; if (getScore(userAnswer) == score) correct = true; StringBuilder sb = new StringBuilder(); sb.append("<span class=\"dominant_text\">Feedback for Question " + position + " (Score: " + Math.round(getScore(userAnswer)*100)/100.0 + "/" + Math.round(score*100)/100.0 + ")" + ":</span><br /><br />\n"); sb.append("<span class=\"quiz_title\">\n"); sb.append(questionStr + "\n"); sb.append("</span><br /><br />\n"); sb.append("<p class=\"answer\">Your answer is :\n"); if (correct) { sb.append("<span class=\"correct answer\">" + userAnswerStr + "&#160;&#160;</span>"); sb.append("<img class=\"small\" src=\"images/right.png\"></p><br /><br />"); } else { sb.append("<span class=\"wrong answer\">" + userAnswerStr + "&#160;&#160;</span>"); sb.append("<img class=\"small\" src=\"images/wrong.png\"><span class=\"wrong\">incorrect</span></p><br />\n"); sb.append("<p class=\"answer\">Correct answer : <span class=\"correct answer\">"); for (int i = 0; i < answerList.size(); i++) { sb.append(answerList.get(i)); if (i < answerList.size() - 1) sb.append(" OR "); } sb.append("</span></p>\n"); } return sb.toString(); }
2bf69ccc-154e-4c85-b8b0-84309a37a3b9
0
public void setSaveEncoding(String saveEncoding) { this.saveEncoding = saveEncoding; }
e457742c-7ad8-49f7-bf9b-19682d91c82e
7
public static List<Flow> getFlows(String dpid) throws IOException, JSONException { List<Flow> flows = new ArrayList<Flow>(); // If JSONObject is not supplied, get it. try { obj = (JSONObject) Deserializer.readJsonObjectFromURL("http://" + IP + ":8080/wm/core/switch/" + dpid + "/flow/json").get(5, TimeUnit.SECONDS); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TimeoutException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (!obj.isNull(dpid)) { json = obj.getJSONArray(dpid); for (int i = 0; i < json.length(); i++) { obj = (JSONObject) json.get(i); Flow flow = new Flow(dpid); flow.setActions(ActionJSON.getActions(obj .getJSONArray("actions"))); flow.setMatch(MatchJSON.getMatch(obj.getJSONObject("match"))); flow.setPriority(String.valueOf(obj.getInt("priority"))); if (obj.getInt("idleTimeout") != 0) flow.setIdleTimeOut(String.valueOf(obj .getInt("idleTimeout"))); if (obj.getInt("hardTimeout") != 0) flow.setHardTimeOut(String.valueOf(obj .getInt("hardTimeout"))); flow.setDurationSeconds(String.valueOf(obj .getInt("durationSeconds"))); flow.setPacketCount(String.valueOf(obj.getInt("packetCount"))); flow.setByteCount(FormatLong.formatBytes(obj.getLong("byteCount"),false,false)); flows.add(flow); } } return flows; }
1161c1f5-5505-4df0-8b05-a86b2825950a
5
public static boolean getFileWithHttp(String address, String localFileName) { OutputStream out = null; URLConnection conn = null; InputStream in = null; try { // create local folders new File(localFileName).getParentFile().mkdirs(); // get file URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } } catch (Exception e) { e.printStackTrace(); return false; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { ioe.printStackTrace(); return false; } } return true; }
bddf0b67-532e-4339-92c6-203c709a6488
8
@Override public void affectPhyStats(Physical affected, PhyStats affectableStats) { super.affectPhyStats(affected,affectableStats); if(affected instanceof MOB) { affectableStats.setSensesMask(affectableStats.sensesMask()|PhyStats.CAN_SEE_HIDDEN); if(ticksSinceLoss>30) affectableStats.setDisposition(affectableStats.disposition()|PhyStats.IS_HIDDEN); } else { if(unLocatable) affectableStats.setSensesMask(affectableStats.sensesMask()|PhyStats.SENSE_UNLOCATABLE); if(affected instanceof Item) { if((((Item)affected).owner() instanceof Room) &&((!(affected instanceof Container)) ||(!((Container)affected).hasADoor()) ||(!((Container)affected).isOpen()))) affectableStats.setDisposition(affectableStats.disposition()|PhyStats.IS_HIDDEN); } else affectableStats.setDisposition(affectableStats.disposition()|PhyStats.IS_HIDDEN); } }
fc2623d6-6e0d-4d3d-b9af-e4cd24098a58
4
static protected void FillBuff() throws java.io.IOException { int i; if (maxNextCharInd == 4096) maxNextCharInd = nextCharInd = 0; try { if ((i = inputStream.read(nextCharBuf, maxNextCharInd, 4096 - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { if (bufpos != 0) { --bufpos; backup(0); } else { bufline[bufpos] = line; bufcolumn[bufpos] = column; } throw e; } }
fd12150b-2fe1-4429-8582-f2c573251274
3
public static boolean conflitoLinha(int posicaox, int posicaoy, int valorteste, Celula[][] sudoku){ int linhateste = posicaox; for(int i=0;i<=8;i++){ if(i==posicaoy){ continue; } Celula celulatestar = sudoku[linhateste][i]; if(celulatestar.getNumero()==valorteste){ return true; } } return false; }
10d4c19a-232e-4b0b-886d-f0ae5c104111
1
@Test public void shouldThrowErrorWhenFileSizeTooBig() throws IOException { //given File tmpFile = folder.newFile(FILENAME); String filePathString = tmpFile.getAbsolutePath(); Path filePath = Paths.get(filePathString); byte[] bytes = new byte[260000]; Files.write(filePath, bytes, StandardOpenOption.APPEND); //when try { FileParser fileParser = new FileParser(filePathString); fileParser.parse(); } catch (GOLException e) { //then String msg = "Dateigröße darf maximal 250kb betragen."; assertEquals(msg, e.getMessage()); } }
50c3e627-f17a-4055-b0e8-7bf510cf6c6c
4
public void setWrap(int a){ switch(a){ case 0: mainBrain.setXYwrap(false, false); break; case 1: mainBrain.setXYwrap(true, false); break; case 2: mainBrain.setXYwrap(false, true); break; case 3: mainBrain.setXYwrap(true, true); break; } }
561e7383-e636-4dd0-914e-74dbf726bf5f
7
public void run() { while(true){ if(client.isConnected()){ while(!client.isGameStarted()) { //listens to server for the go signal client.listenToServer(); } // // game components revealed // setButton.setVisible(true); lblNumberOfCards.setVisible(true); numberOfCardsInDeck.setVisible(true); playersPointsPane.setVisible(true); playersPane.setVisible(true); addCardsButton.setVisible(true); // // title components hidden // start.setVisible(false); startGamePane.setVisible(false); lblTitle.setVisible(false); nameField.setVisible(false); validate(); updateGUI(); //visual update while(client.isGameStarted() && client.isConnected()){ //constantly listens to server and refreshes until game ends if (client.isCanCallSet()) { updateGUI(); client.listenToServer(); updateGUI(); } } reset("" + client.getWinner()); //resets game when finished }else{ try { //if not connected, will wait until checking again Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); //should never happen } } } }
6884a537-8a57-4f27-bb18-083994ddc1a9
2
public static void main(String[] args) { ArrayList arrayList1 = new ArrayList(); arrayList1.add("Hello"); arrayList1.add("world"); arrayList1.add("world"); arrayList1.add("welcome!"); String s1 = (String)arrayList1.get(0); String s2 = (String)arrayList1.get(1); String s3 = (String)arrayList1.get(2); String s4 = (String)arrayList1.get(3); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); System.out.println("--------------"); for(int i = 0;i < arrayList1.size(); i++) { System.out.println(arrayList1.get(i)); } //arrayList1.clear(); System.out.println(arrayList1.size()); System.out.println(arrayList1.isEmpty()); arrayList1.remove(0); //remove(object o) arrayList1.remove("welcome!"); //remove(object o) System.out.println("-----------"); for(int i = 0; i < arrayList1.size(); i++) { System.out.println(arrayList1.get(i)); } arrayList1.add("aaa"); arrayList1.add("bbb"); System.out.println(arrayList1.indexOf("worlddd")); System.out.println(arrayList1.indexOf("bbb")); }
bd5d74d8-82b6-4b52-94b8-807084006797
8
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, String> fouten = new HashMap<>(); String gebruikersnaam = request.getParameter("gebruikersnaam"); String paswoord = request.getParameter("paswoord"); if (gebruikersnaam == null || gebruikersnaam.isEmpty()) { fouten.put("gebruikersnaam", "Gebruikersnaam is een verplicht veld"); } if (paswoord == null || paswoord.isEmpty()) { fouten.put("paswoord", "Paswoord is een verplicht veld"); } Klant klant = klantDAO.getBestaandeKlant(gebruikersnaam, paswoord); if (klant==null){ if (fouten.containsKey("paswoord")||fouten.containsKey("gebruikersnaam")){ //foutmelding(en) van paswoord en/of van gebruikersnaam zitten al in lijst } else { fouten.put("klant", "Verkeerde gebruikersnaam of paswoord"); } } if (fouten.isEmpty()) { request.setAttribute("klant", klant); request.getSession().setAttribute("klant", klant); RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW); dispatcher.forward(request, response); } else { request.setAttribute("fouten", fouten); RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW); dispatcher.forward(request, response); } }
d05ce029-0674-4dd4-a23c-5407400b2d0f
7
protected FrameDecoder retrieveDecoder(Header header, Bitstream stream, int layer) throws DecoderException { FrameDecoder decoder = null; // REVIEW: allow channel output selection type // (LEFT, RIGHT, BOTH, DOWNMIX) switch (layer) { case 3: if (l3decoder==null) { l3decoder = new LayerIIIDecoder(stream, header, filter1, filter2, output, OutputChannels.BOTH_CHANNELS); } decoder = l3decoder; break; case 2: if (l2decoder==null) { l2decoder = new LayerIIDecoder(); l2decoder.create(stream, header, filter1, filter2, output, OutputChannels.BOTH_CHANNELS); } decoder = l2decoder; break; case 1: if (l1decoder==null) { l1decoder = new LayerIDecoder(); l1decoder.create(stream, header, filter1, filter2, output, OutputChannels.BOTH_CHANNELS); } decoder = l1decoder; break; } if (decoder==null) { throw newDecoderException(UNSUPPORTED_LAYER, null); } return decoder; }
a0299c52-7d66-4ed0-954f-e04e6e48301f
6
public static void setPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (pixels == null || w == 0 || h == 0) { return; } else if (pixels.length < w * h) { throw new IllegalArgumentException("pixels array must have a length" + " >= w*h"); } int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { WritableRaster raster = img.getRaster(); raster.setDataElements(x, y, w, h, pixels); } else { // Unmanages the image img.setRGB(x, y, w, h, pixels, 0, w); } }
84df6835-e216-4de6-9867-9938c4ab584e
0
@Test public void testNextInt() { System.out.println("nextInt"); RandomInt instance = new RandomInt(); int expResult = 0; int result = instance.nextInt(1); assertEquals(expResult, result); expResult = 0; result = instance.nextInt(2); assertEquals(expResult, result); expResult = 6; result = instance.nextInt(10); assertEquals(expResult, result); expResult = 5575; result = instance.nextInt(8754); assertEquals(expResult, result); expResult = 100; result = instance.nextInt(8754); assertEquals(expResult, result); instance = new RandomInt(); expResult = 7193; result = instance.nextInt(16385); assertEquals(expResult, result); expResult = 2932; result = instance.nextInt(16385); assertEquals(expResult, result); expResult = 10386; result = instance.nextInt(16385); assertEquals(expResult, result); expResult = 5575; result = instance.nextInt(16385); assertEquals(expResult, result); expResult = 100; result = instance.nextInt(16385); assertEquals(expResult, result); expResult = 15976; result = instance.nextInt(16385); assertEquals(expResult, result); expResult = 430; result = instance.nextInt(16385); assertEquals(expResult, result); expResult = 9740; result = instance.nextInt(16385); assertEquals(expResult, result); expResult = 9449; result = instance.nextInt(16385); assertEquals(expResult, result); expResult = 1636; result = instance.nextInt(16385); assertEquals(expResult, result); }
b0ecb4e0-939f-4e45-b81a-f0fd3384ad98
3
public void inicio(Local local) throws Exception { salvar = new JButton("Salvar"); id = new JTextInt(local.getId()); id.setEditable(false); id.setEnabled(false); cidade = new JTextField(local.getCidade() == null ? "" : local.getCidade()); estado = new JTextField(local.getEstado() == null ? "" : local.getEstado()); descricao = new JTextField(local.getDescricao() == null ? "" : local.getDescricao()); JPanel pp = new JPanel(); DesignGridLayout layout = new DesignGridLayout(pp); layout.row().grid(new JLabel("ID:")).add(id); layout.row().grid(new JLabel("Cidade:")).add(cidade); layout.row().grid(new JLabel("Estado:")).add(estado); layout.row().grid(new JLabel("Descrição:")).add(descricao); layout.row().grid().add(salvar, 1); getContentPane().add(new JScrollPane(pp)); pack(); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); }
f3478929-78cd-4244-8cf7-b653cd8ba269
1
public static void insertActionCom(String typelibelle) throws SQLException { String query = ""; try { query = "INSERT INTO ACTION_TYPE (TYP_LIB) VALUES (?); "; PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query); pStatement.setString(1, typelibelle.toUpperCase()); pStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(RequetesActionType.class.getName()).log(Level.SEVERE, null, ex); } }
4c42330f-8804-457a-91d5-e85abacf5f4c
0
public void setjButtonPrec(JButton jButtonPrec) { this.jButtonPrec = jButtonPrec; }
c1341cc5-3eb5-48d8-ad07-390605df7066
2
private static int trySwapTimes(int[] a, int times){ if(times == 0) return maxSum(a); int max = Integer.MIN_VALUE; for(int i=0;i<allSwaps.size();i++){ Point p = allSwaps.get(i); swap(a, p.x, p.y); allSwaps.remove(i); max = Math.max(max, trySwapTimes(a, times-1)); allSwaps.add(i, p); } return max; }
b7301e65-1eab-43b9-ac59-25c1d4fadbbb
6
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Vector3d vector3d = (Vector3d) o; if (x == vector3d.x && y == vector3d.y && z == vector3d.z) { return true; } return false; }
45f95bc4-8fd2-479c-9cd6-8bf797693adb
1
@Override public String getText() { String typed = super.getText(); return typed.equals(hint) ? "" : typed; }
05212c8d-70eb-4690-a540-8f0fd51dd561
0
public void setName(String name) { this.name = name; }
c8c023d7-fafe-4baa-91e5-638ea22a2a27
0
public String getHostname() { return _hostname; }
1c50537b-fab9-4b34-9c2f-d9586f0f41c0
5
public static void parseQueryString(String queryString, Map<String, String> params) { if (queryString == null || params == null) { return; } if (queryString.length() > 0) { String token; int offset; StringTokenizer tokenizer = new StringTokenizer(queryString, "&"); while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if ((offset = token.indexOf("=")) > 0) { params.put(urlDecode(token.substring(0, offset)), urlDecode(token.substring(offset + 1))); } else { params.put(urlDecode(token), null); } } } }
1d23a336-d686-4e9e-b076-86c2d0be4738
0
public int getFloorDistance() { return floorDistance; }
2d0e8429-81d8-4883-8739-297af2baa21c
8
public static void main(String[] args) { int port = 4444; // default port // Check for and parse command line arguments Queue<String> arguments = new LinkedList<String>(Arrays.asList(args)); try { while ( ! arguments.isEmpty()) { String flag = arguments.remove(); try { if (flag.equals("--port")) { port = Integer.parseInt(arguments.remove()); if (port < 0 || port > 65535) { throw new IllegalArgumentException("port " + port + " out of range"); } } else { throw new IllegalArgumentException("unknown option: \"" + flag + "\""); } } catch (NoSuchElementException nsee) { throw new IllegalArgumentException("missing argument for " + flag); } catch (NumberFormatException nfe) { throw new IllegalArgumentException("unable to parse number for " + flag); } } } catch (IllegalArgumentException iae) { System.err.println(iae.getMessage()); System.err.println("usage: Server [--port PORT]"); return; } // Try to launch the server try { Server server = new Server(4444); server.serve(); } catch (IOException e) { System.out.println("Error in starting server."); e.printStackTrace(); } }
56fdad5a-211d-4e2d-a0a6-abd3676a3b0f
6
private void handleMouseInput() { if (Mouse.getDX() != 0 || Mouse.getDY() != 0) { if (isMouseOnSelection(SELECTION.YES) && !currentSelection.equals(SELECTION.YES)) { Sounds.get().playCursor(); currentSelection = SELECTION.YES; } else if (isMouseOnSelection(SELECTION.NO) && !currentSelection.equals(SELECTION.NO)) { Sounds.get().playCursor(); currentSelection = SELECTION.NO; } } }
e2bfe0cd-f02a-4b53-bf8c-928bcbf96b90
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(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { MainJFrame a = new MainJFrame(); a.setVisible(true); re_calc.setVisible(false); recoverFiles.setVisible(false); a.getDrives(a.DriveSelector); } }); }
f7136356-115e-432a-9b13-cbe76af16503
4
public Grid getGrid() { boolean test = false; if (test || m_test) { System.out.println("GameBoardGraphics :: getGrid() BEGIN"); } if (test || m_test) { System.out.println("GameBoardGraphics :: getGrid() END"); } return m_grid; }
54c57672-6936-4f65-a7fd-0f243fd6ccd9
3
public int size() { if(empty){ return 0; }else if(begin < end){ return end-begin; }else if(begin > end){ return MAX-begin+end; }else{ return MAX; } }
d563f97b-18ba-4357-9b4c-5b8594c0a2ef
6
private void loadLanguage() { try { BufferedReader reader = new BufferedReader(new FileReader(new File(GameApplication.getGameDir() + File.separator + "resources" + File.separator + "lang" + File.separator + langFileName + ".glf"))); String cur; while ((cur = reader.readLine()) != null) { if (cur.equals("")){ continue; } String current = ""; String[] var = cur.split("\\|"); for (String s : var) { int i = Integer.parseInt(s); char c = (char) i; current += c; } String[] vars = current.split("="); if (vars.length <= 1) { continue; } String var0 = vars[0]; String var1 = vars[1]; langValues.put(var0, var1); } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
ce405841-c8e0-484a-97b4-4a8a58350d73
8
public static int minCut(String s) { boolean [][] isPal = new boolean[s.length()][s.length()]; int[][] cost = new int[s.length()][s.length()]; // for single letter palindromes for( int i = 0; i< s.length(); i++) { isPal[i][i] = true; cost[i][i] = 0; } // for 2 and more lettered string for( int l = 2; l<= s.length(); l++) { for(int i = 0; i< s.length()-l+1; i++) { int j = l+i -1; // for length 2 if(l ==2) { isPal[i][j] = s.charAt(i) == s.charAt(j); } else { // for length 3+ isPal[i][j] = s.charAt(i) == s.charAt(j) && isPal[i+1][j-1]; } if(isPal[i][j]) { cost[i][j] = 0; } else { // if not palindrome ..then try all the potential cuts with minimum cost which can make it palindromic cost[i][j] = Integer.MAX_VALUE; for( int k = i; k<j; k++) { if(cost[i][j] > cost[i][k]+ cost[k+1][j] + 1) { // here +1 defines a cost of a cut cost[i][j] = cost[i][k]+ cost[k+1][j] + 1; } } } } } return cost[0][s.length()-1]; }
ab7e1a27-cbe6-477a-ba90-d81a85d94dfe
4
public static void main(String[] args) { SequentialSearchST<String, Integer> st = new SequentialSearchST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } // print keys for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); for (String s : st.keys()) st.delete(s); if (st.isEmpty()) System.out.println("Successfully deleted all items"); else System.out.println("Unsuccessful in deleting all items"); }
67035bd2-32b4-4629-8142-4bd81cf52d8a
9
private int validMove(int x, int y) { if ((x >= 0) && (x < 10) && (y >= 0) && (y < 10)) { if (this.playerIntBoard[x][y] > -2) return 1; } else if ((x < 0) || (x >= 10) || (y < 0) || (y >= 10)) { return -5; } return this.playerIntBoard[x][y]; }
9c46c4af-f1dd-4c9b-8af5-1f704ab4a618
3
public Map<String, TableDescription> getTablesInDataBaseDescription() { Map<String, TableDescription> result = new HashMap<String, TableDescription>(); for (DataBase db : databases.values()) { for (TableDescription td : db.getTablesDescriptions()) { String tableName = td.getName(); if (!result.containsKey(tableName)) { result.put(tableName, td); } } } return result; }
9de6f6fd-6b1f-449c-9d7c-172a418aa2c3
3
public List<QcTestCase> getTestCases(List<Long> testcaseIds) throws Exception { List<QcTestCase> testCases = new ArrayList<QcTestCase>(); for (Long testcaseId : testcaseIds) { QcRequest qcRequest = new QcRequest(QcConstants.QC_ENDPOINT_URL + "/test-case/" + testcaseId); try { XMLConfiguration config = restClient.get(qcRequest); testCases.add(QcXmlConfigUtil.getTestcase(config)); } catch (NotFound notFound) { log.warn("No testcase found for testCase id: " + testcaseId); } } return testCases.size() > 0 ? testCases : null; }
9e421a68-42d8-4864-b4f8-8babfe4cf94b
5
@Override public void update() { super.update(); Projectile projectile = null; ArrayList deadProjectiles = new ArrayList(); try { for (String key : projectiles.keySet()) { projectile = (Projectile) projectiles.get(key); projectile.update(); if (projectile.isDirty()) { projectile.cleanUp(); deadProjectiles.add(key); } } if (deadProjectiles.size() > 0) { for (int i = 0; i < deadProjectiles.size(); i++) { projectiles.remove((String) deadProjectiles.get(i)); } } } catch (ConcurrentModificationException concEx) { //another thread was trying to modify projectiles while iterating //we'll continue and the new item can be grabbed on the next update } }
35b465b7-c22a-4c22-8ed4-e1de4b2c805d
8
@Override public boolean keyUp(int keycode) { switch (keycode) { case Keys.UP: moving.remove(Dir.North); return true; case Keys.DOWN: moving.remove(Dir.South); return true; case Keys.RIGHT: moving.remove(Dir.East); return true; case Keys.LEFT: moving.remove(Dir.West); return true; case Keys.Z: A = false; return true; case Keys.X: B = false; return true; case Keys.ENTER: start = false; return true; case Keys.SHIFT_RIGHT: select = false; return true; } return false; }
bb82db59-5326-473b-b063-24fe42be133b
9
void rehash() { int oldCapacity = table.length; Entry oldMap[] = table; int i; for (i = oldCapacity; --i >= 0;) { Entry e, next, prev; for (prev = null, e = oldMap[i]; e != null; e = next) { next = e.next; Object obj = e.ref.get(); if ((obj == null || db.isDeleted(obj)) && e.dirty == 0) { count -= 1; e.clear(); if (prev == null) { oldMap[i] = next; } else { prev.next = next; } } else { prev = e; } } } if (count <= (threshold >>> 1)) { return; } int newCapacity = oldCapacity * 2 + 1; Entry newMap[] = new Entry[newCapacity]; threshold = (int)(newCapacity * loadFactor); table = newMap; for (i = oldCapacity; --i >= 0 ;) { for (Entry old = oldMap[i]; old != null; ) { Entry e = old; old = old.next; int index = (e.oid & 0x7FFFFFFF) % newCapacity; e.next = newMap[index]; newMap[index] = e; } } }
7b1cd388-e228-40f3-8a9a-2c0959f1cf47
0
public static Session fromNanoCookie(NanoHTTPD.CookieHandler cookie) { return fromSessionId(cookie.read(COOKIE_KEY)); }
d8616391-5388-4359-807d-83bde3c17077
9
private void RenderFrame() { int i = 0; glBegin(GL_LINES); glColor3d(1, 1, 1); boolean draw = true; for(i = 0; i < 8; i++){ for (int j = 0; j < 8; j++){ for (int l=0; l<8; l+=2){ if((i == opposites[l] && j == opposites[l+1]) || i == getExcludedVertex() || j == getExcludedVertex()){ draw = false; break; }else { draw = true; } } if(i<j && draw){ drawPointFromArray(i); drawPointFromArray(j); } } } i = 0; glEnd(); }
491ee47a-642d-4944-8515-80ffec0d7b77
2
public void moveBullets() { for (int i=0; i<MAX_BULLETS; i++) { if (bullets[i].getVisibility()) { bullets[i].moveForward(); } } }
57de9dd6-dd8d-4440-bf64-97e7aa8cec71
4
public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); switch(key) { case KeyEvent.VK_W: p.setMoveUp(true); break; case KeyEvent.VK_S: p.setMoveDown(true); break; case KeyEvent.VK_A: p.setMoveLeft(true); break; case KeyEvent.VK_D: p.setMoveRight(true); break; } }
067fbe9c-e216-4712-82e7-1ce047579e09
2
public int getBytesDownloaded(){ int total = 0; for(int i : pieces.keySet()){ Piece p = pieces.get(i); if(p==null) continue; total += p.bytesCompleted(); } return total; }
1df5a818-54d7-4aad-a1b3-2c5185fd6c89
7
public static String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
b65ca8df-9d9b-46fc-a80a-fca6a67ab3ba
8
private static void deleteCompetitor(Scanner scan){ //If there are some competitors in table. while (!ds.getAllCompetitor().isEmpty()) { //Display all competitor for conveniently picking a name. ds.printCompetitors(ds.getAllCompetitor()); System.out.println("please input the name of competitor whom you want to delete:\n"+ goMainMenu); String name = scan.next(); //If user doesn't want to go back to main menu. if (!name.equalsIgnoreCase(mainMenuCmd)) { //Checking if it is a valid name. if (ds.checkExistingOfCompetitor(name)) { //While loop for giving more chances to user ensuring the deleting. while (true) { System.out.println("Deleting this competitor will also delete him from competition."); System.out.println("Are you sure you want to delete this competitor?\n" + " \"y\" for yes, \"n\" for going backward, " + goMainMenu); String conf = scan.next(); //If user doesn't want to go back to main menu. if (!conf.equalsIgnoreCase(mainMenuCmd)) { //If user input "y". if (conf.equalsIgnoreCase("y")) { //Delete competitor from competitor table first by name user input. ds.deleteCompetitorFromCompetitorTable(name); System.out.println("Deleting from competitor table successful."); System.out.println(); //If there are any records in competition table about this student. if (ds.checkExistingOfCompetition(name)) { //Delete them as well by student name. ds.deleteCompetitorFromCompetitionTable(name); System.out.println("Deleting from competition table successful."); System.out.println(); } else{ //If there is no record of competition about this student. System.out.println("There is no record of this competitor in competition table."); System.out.println(); } //Print all competitors again to show user the process worked. ds.printCompetitors(ds.getAllCompetitor()); } else if (conf.equalsIgnoreCase("n")) { break;//If user regretted then the program will go backward. } else { System.out.println("please input valid command."); } } else { return; } } } else{ System.out.println("The name you input does not exist in competitor table, please check it again."); System.out.println(); } } else{ return; } } System.out.println("There is no any competitor in yet."); }
cdca374d-b242-4f8a-bdce-fce7ef78e3a2
1
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); final int dID = Integer.parseInt(request.getParameter("dID")); PrintWriter out = response.getWriter(); if (new Control(-1).startParsing(dID)) { out.print("true"); } else { out.print("false"); } out.close(); }
527b348c-efb6-4ee0-8404-93dec8bc9de9
0
public Integer getEmailsCount() { return emails.size(); }
67fa6dd7-2f29-41c0-9005-7095a2669ed0
4
public static String[] readMap(int stage){ String[] array = new String[Constant.MAP_Array_SIZE]; File file = new File("source/stages/stage" + stage + ".txt"); BufferedReader bur = null ; try { FileReader fr = new FileReader(file); bur = new BufferedReader(fr); String str = null; int i = 0 ; while((str = bur.readLine()) != null){ array[i] = str ; i ++; } } catch (Exception e) { e.printStackTrace(); }finally{ if( bur != null ) try { bur.close(); } catch (IOException e) { e.printStackTrace(); } } return array ; }
7e54325e-bfba-49e3-8ae1-9f801444e8f2
1
public void setSelectionPointer(String pointerName) { this.pointer = new SelectionPointer(pointerName); if(selection != -1) { pointer.setPositionAt(get(selection)); } }
36cc92ba-13cc-48b6-bdae-bf44a93cfdd8
3
public void act(){ if (clicked){ if (counter >= 10){ counter = 0; clicked = false; } else{ counter++; this.setImage (bg[2]); } } else if (selected){ selected = false; this.setImage (bg[1]); } else{ this.setImage (bg[0]); } }
e06d1f74-fd45-479a-a5ad-748580e92ecb
0
public void restoreTemporaryToCurrent() { lineEnd.restoreTemporaryToCurrent(); saveEncoding.restoreTemporaryToCurrent(); saveFormat.restoreTemporaryToCurrent(); ownerName.restoreTemporaryToCurrent(); ownerEmail.restoreTemporaryToCurrent(); applyFontStyleForComments.restoreTemporaryToCurrent(); applyFontStyleForEditability.restoreTemporaryToCurrent(); applyFontStyleForMoveability.restoreTemporaryToCurrent(); useCreateModDates.restoreTemporaryToCurrent(); createModDatesFormat.restoreTemporaryToCurrent(); }
15ef8730-6dbc-4e3d-83f0-01eb1cb899da
1
void checkEndCode() { if (endCode) { throw new IllegalStateException( "Cannot visit instructions after visitMaxs has been called."); } }
815aec73-d53d-4f1a-b05f-83447572595a
6
public static void main(String[] args) { /* wap to print following pattern * *** ***** ******* ***** *** * */ for(int i=0;i<=3;i++) { for(int j=3;j>=i;j--){ System.out.print(" "); } for(int j=i;j>=1;j--){ System.out.print("**"); } System.out.print("*"); System.out.println(" "); } for(int i=1;i<=3;i++) { for(int j=i;j>=0;j--){ System.out.print(" "); } for(int j=i;j<=2;j++){ System.out.print("**"); } System.out.print("*"); System.out.println(" "); } }
fbe49c15-c3cf-47bd-afbf-72d54a7406f3
3
private static ResourceUserList createGridUser(GridletList list) { ResourceUserList userList = new ResourceUserList(); userList.add(0); // user ID starts from 0 userList.add(1); userList.add(2); int userSize = userList.size(); int gridletSize = list.size(); int id = 0; // assign user ID to particular Gridlets for (int i = 0; i < gridletSize; i++) { if (i != 0 && i % userSize == 0) id++; ( (Gridlet) list.get(i) ).setUserID(id); } return userList; }
7cdc032c-135d-47e2-9871-3db21910eda3
4
@Override public String getUsername() throws RemoteException { { try { String name = JOptionPane.showInputDialog(null, "Please, enter your nickname!"); if (name != null && name.trim().length() > 0) { nickname = name; return name; } else if (name == null) { System.exit(0); } else { JOptionPane.showMessageDialog(null, "Please choose a nickname with more than one letter!"); getUsername(); } } catch (RemoteException ex) { ex.printStackTrace(); System.exit(0); } return null; } }
0c632824-46df-4247-a2d5-cdf5da00b434
0
public static Hand TwoPair(Rank firstPairRank, Rank secondPairRank, Rank firstKicker) { return new Hand(HandRank.TwoPair, null, firstPairRank, secondPairRank, firstKicker, Rank.Null, Rank.Null); }
af4fd1c9-e01c-43a6-b020-93f258c5c6fe
6
public Behaviour jobFor(Actor actor) { if ((! structure.intact()) || (! personnel.onShift(actor))) return null ; final Choice choice = new Choice(actor) ; final Delivery d = Deliveries.nextDeliveryFor( actor, this, services(), 10, world ) ; if (d != null && personnel.assignedTo(d) < 1) { //d.nextStepFor(actor) ; //I.sayAbout(this, "next delivery: "+d) ; choice.add(d) ; } final Delivery c = Deliveries.nextCollectionFor( actor, this, services(), 10, null, world ) ; if (c != null && personnel.assignedTo(c) < 1) choice.add(c) ; choice.add(new Supervision(actor, this)) ; return choice.weightedPick() ; }
40e4f297-a392-4b76-b42d-5447a9b01801
8
public CRLGen() { super(); try { crlM=new CRLManager(); //Certificat à révoquer } catch (InvalidKeyException e) { // TODO Bloc catch généré automatiquement e.printStackTrace(); } catch (KeyStoreException e) { // TODO Bloc catch généré automatiquement e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Bloc catch généré automatiquement e.printStackTrace(); } catch (CertificateException e) { // TODO Bloc catch généré automatiquement e.printStackTrace(); } catch (NoSuchProviderException e) { // TODO Bloc catch généré automatiquement e.printStackTrace(); } catch (SignatureException e) { // TODO Bloc catch généré automatiquement e.printStackTrace(); } catch (CRLException e) { // TODO Bloc catch généré automatiquement e.printStackTrace(); } catch (IOException e) { // TODO Bloc catch généré automatiquement e.printStackTrace(); } }
f7e9c16a-cf36-4b0b-b2c6-c2156609c630
1
public void update(GameContainer c, StateBasedGame s, int d) throws SlickException { GameScreen.time += d; if (c.getInput().isKeyPressed(Input.KEY_SPACE)){ s.enterState(1); } }
1d499a81-d624-493f-9807-d58fd0ff76e6
9
private static Result toResult(Object xml) throws IOException { if(xml==null) throw new IllegalArgumentException("no XML is given"); if (xml instanceof String) { try { xml=new URI((String)xml); } catch (URISyntaxException e) { xml=new File((String)xml); } } if (xml instanceof File) { File file = (File) xml; return new StreamResult(file); } if (xml instanceof URI) { URI uri = (URI) xml; xml=uri.toURL(); } if (xml instanceof URL) { URL url = (URL) xml; URLConnection con = url.openConnection(); con.setDoOutput(true); con.setDoInput(false); con.connect(); return new StreamResult(con.getOutputStream()); } if (xml instanceof OutputStream) { OutputStream os = (OutputStream) xml; return new StreamResult(os); } if (xml instanceof Writer) { Writer w = (Writer)xml; return new StreamResult(w); } if (xml instanceof Result) { return (Result) xml; } throw new IllegalArgumentException("I don't understand how to handle "+xml.getClass()); }
4fa20972-e81a-46b6-8339-66aa01eb055c
6
@Override public PlayerAbilities swapAbilityScores(int strength, int intelligence, int wisdom, int dexterity, int constitution, int charisma) { List<Integer> scores = new ArrayList<Integer>(); scores.add(abilities.getStrength()); scores.add(abilities.getIntelligence()); scores.add(abilities.getWisdom()); scores.add(abilities.getDexterity()); scores.add(abilities.getConstitution()); scores.add(abilities.getCharisma()); PlayerAbilities swappedAbilities = new PlayerAbilities(); if (scores.contains(strength)) { swappedAbilities.setStrength(strength); scores.remove(new Integer(strength)); } else { throw new RuntimeException("Can only swap one of the existing scores."); } if (scores.contains(intelligence)) { swappedAbilities.setIntelligence(intelligence); scores.remove(new Integer(intelligence)); } else { throw new RuntimeException("Can only swap one of the existing scores."); } if (scores.contains(wisdom)) { swappedAbilities.setWisdom(wisdom); scores.remove(new Integer(wisdom)); } else { throw new RuntimeException("Can only swap one of the existing scores."); } if (scores.contains(dexterity)) { swappedAbilities.setDexterity(dexterity); scores.remove(new Integer(dexterity)); } else { throw new RuntimeException("Can only swap one of the existing scores."); } if (scores.contains(constitution)) { swappedAbilities.setConstitution(constitution); scores.remove(new Integer(constitution)); } else { throw new RuntimeException("Can only swap one of the existing scores."); } if (scores.contains(charisma)) { swappedAbilities.setCharisma(charisma); scores.remove(new Integer(charisma)); } else { throw new RuntimeException("Can only swap one of the existing scores."); } abilities = swappedAbilities; return abilities; }
0b1fe7a3-b4f6-4bec-889c-3991c1dc7bd2
3
@Override public Dimension getMinimumSize(JComponent c) { if ((JOptionPane) c == optionPane) { Dimension ourMin = getMinimumOptionPaneSize(); LayoutManager lm = c.getLayout(); if (lm != null) { Dimension lmSize = lm.minimumLayoutSize(c); if (ourMin != null) { return new Dimension(Math.max(lmSize.width, ourMin.width), Math.max(lmSize.height, ourMin.height)); } return lmSize; } return ourMin; } return null; }
84d769fb-f302-40af-93b3-54371f4d4845
3
@Override public Move findBestMove(int[][] board) { while(true) { String s = in.next(); for (Move move : Move.ALL) { if(move.arrow.equals(s)) { int[][] newBoard = makeMove(board, move); copyBoard(board, newBoard); return move; } } } }
dd87637a-8d89-405c-b679-39034246f411
2
public static void main(String[] args) throws Exception { final Runner runner = new Runner(); Thread t1 = new Thread(new Runnable() { public void run() { try { runner.firstThread(); } catch (InterruptedException ignored) {} } }); Thread t2 = new Thread(new Runnable() { public void run() { try { runner.secondThread(); } catch (InterruptedException ignored) {} } }); t1.start(); t2.start(); t1.join(); t2.join(); runner.finished(); }
bf0a8cf4-5397-41ad-be41-64eb1f7308ea
2
@Override public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception { Contexto oContexto = (Contexto) request.getAttribute("contexto"); oContexto.setVista("jsp/entrada/form.jsp"); EntradaBean oEntradaBean; EntradaDao oEntradaDao; oEntradaBean = new EntradaBean(); EntradaParam oEntradaParam = new EntradaParam(request); oEntradaBean = oEntradaParam.loadId(oEntradaBean); oEntradaDao = new EntradaDao(oContexto.getEnumTipoConexion()); try { oEntradaBean = oEntradaDao.get(oEntradaBean); } catch (Exception e) { throw new ServletException("EntradaController: Update Error: Phase 1: " + e.getMessage()); } try { oEntradaBean = oEntradaParam.load(oEntradaBean); } catch (NumberFormatException e) { oContexto.setVista("jsp/mensaje.jsp"); return "Tipo de dato incorrecto en uno de los campos del formulario"; } return oEntradaBean; }
0b42347f-a127-4821-a193-80d5bbb9f45f
8
public String KonversiKwitansi (double doubleAngka){ String [] bil ={"","satu","dua","tiga","empat","lima","enam","tujuh","delapan","sembilan","sepuluh","sebelas"}; String x=" "; int intAngka = (int) doubleAngka; if (doubleAngka<12){ x = bil[intAngka] + " "; } else if(doubleAngka<20){ x = KonversiKwitansi(doubleAngka-10) + "belas "; } else if(doubleAngka<100){ x = KonversiKwitansi(doubleAngka/10) + "puluh " + KonversiKwitansi(doubleAngka%10); } else if(doubleAngka<200){ x = "seratus" + KonversiKwitansi(doubleAngka-100); } else if(doubleAngka<1000){ x = KonversiKwitansi(doubleAngka/100) + "ratus " + KonversiKwitansi(doubleAngka%100); } else if(doubleAngka<2000){ x = "seribu "+ KonversiKwitansi(doubleAngka-1000); } else if(doubleAngka<1000000){ x = KonversiKwitansi(doubleAngka/1000) + "ribu " + KonversiKwitansi (doubleAngka%1000); } else if(doubleAngka<1000000000){ x = KonversiKwitansi(doubleAngka/1000000)+ "juta " + KonversiKwitansi (doubleAngka%1000000); } else { x = KonversiKwitansi(doubleAngka/1000000000) + "milyat " + KonversiKwitansi(doubleAngka%1000000000); } return x; }
d12b6efc-122e-4899-b9af-5e75ad5b27e3
5
* @return a bitset with all specified versions set */ public BitSet convertVersions( String spec ) { BitSet set = new BitSet(); if ( spec.toLowerCase().equals("all") ) { for ( int i=1;i<=versions.size();i++ ) set.set(i); } else { HashMap<String,Short> map = new HashMap<String,Short>(); for ( int i=0;i<versions.size();i++ ) { Version v = versions.get( i ); String vid = v.versionID(groups); map.put( vid, (short)(i+1) ); } StringTokenizer st = new StringTokenizer(spec,","); while ( st.hasMoreTokens() ) { String token = st.nextToken(); if ( map.containsKey(token) ) set.set( map.get(token).shortValue() ); else System.out.println("couldn't find version "+token +" (ignored)"); } } return set; }
c5f5e642-fd3a-466b-9e03-b11c16192c9f
3
public static void main (String args[]) throws Exception{ ConnectionFrames playerWindow = new ConnectionFrames(); playerWindow.run(); Ball ball = new Ball(); while(playerWindow.connectionType == null); System.out.println(playerWindow.connectionType); //ball.run(); while(playerWindow.connectionType.equals("server")){ System.out.println("APP: Im now a Server"); playerWindow.sleep(1000); } while(playerWindow.connectionType.equals("client")){ System.out.println("APP: Im now a Client"); playerWindow.sleep(1000); } }
85c3e852-a240-4fe8-9b0a-538bb6cad575
4
public void addComment(String value) { if (value != null) // we have something { String trimmed = value.trim() ; if (trimmed.length() > 0) { if (trimmed.charAt(0) == '#' ) // comment sign { comment.add( value ) ; after = 0 ; return ; } else { Logger.global.warning("no comment! >" + value ) ; } } } // not a comment -> empty line, increment the counters if (comment.size() > 0) { after++ ; } else { before++ ; } }
a59a02dc-ec76-4a85-abf0-4cc43720bcf3
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(Brillo_Contraste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Brillo_Contraste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Brillo_Contraste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Brillo_Contraste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ /* java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Brillo_Contraste().setVisible(true); } });*/ }
d3d8fbf3-d7b0-4948-9f87-2c0c77a24271
4
public int getMachineIndexByName(String machineFileName){ ArrayList machines = getEnvironment().myObjects; if(machines == null) return -1; for(int k = 0; k < machines.size(); k++){ Object current = machines.get(k); if(current instanceof Automaton){ Automaton cur = (Automaton)current; if(cur.getFileName().equals(machineFileName)){ return k; } } } return -1; }
3efb6482-ce74-469b-9f0e-dd515f703ea0
8
@Override public Iterable<Token> determineMostLikelyTags(Iterable<Token> sentence) { List<Map<String, Double>> matrix = new ArrayList<>(); Map<String, List<String>> paths = createPath(); Iterator<Token> tokenIter = sentence.iterator(); // initialize base cases (t == 0) String firstToken = tokenIter.next().getText(); for (String tag : tagSet) { double startProb = languageModel.beginningOfSentenceTagProbability(tag); double emitProb = languageModel.tokenProbability(firstToken, tag); put(matrix, 0, tag, Math.log(startProb * emitProb)); paths.get(tag).add(tag); } // run Viterbi for t > 0 int i = 0; while (tokenIter.hasNext()) { String token = tokenIter.next().getText(); i++; Map<String, List<String>> newPaths = createPath(); for (String tag : tagSet) { double maxProbLog = Double.NEGATIVE_INFINITY; String prevTagWithMaxProb = null; for (String prevTag : tagSet) { double prevProbLog = matrix.get(i-1).get(prevTag); double transProb = languageModel.tagTransitionProbability(prevTag, tag); double emitProb = languageModel.tokenProbability(token, tag); double overallProbLog = prevProbLog + Math.log(transProb * emitProb); if (overallProbLog > maxProbLog) { maxProbLog = overallProbLog; prevTagWithMaxProb = prevTag; } } put(matrix, i, tag, maxProbLog); List<String> extended = new ArrayList<>(paths.get(prevTagWithMaxProb)); extended.add(tag); newPaths.put(tag, extended); } paths = newPaths; } double maxProbLog = Double.NEGATIVE_INFINITY; String lastTagForMaxState = null; for (String tag : tagSet) { double probLog = matrix.get(i).get(tag); if (probLog > maxProbLog) { maxProbLog = probLog; lastTagForMaxState = tag; } } List<String> path = paths.get(lastTagForMaxState); List<Token> result = new ArrayList<>(); i = 0; for (Token oldToken : sentence) { Token newToken = new Token(path.get(i), oldToken.getText()); result.add(newToken); i++; } return result; }
12b98af1-cec1-4cf1-80b3-85ead86510c2
7
private static int parseArgs(String[] args, HamaConfiguration conf, BSPJob bsp) { conf.set(inputMatrixAPathString, args[0]); conf.setInt(inputMatrixARows, Integer.parseInt(args[1])); conf.setInt(inputMatrixACols, Integer.parseInt(args[2])); conf.set(inputMatrixBPathString, args[3]); conf.setInt(inputMatrixBRows, Integer.parseInt(args[4])); if (Integer.parseInt(args[2]) != Integer.parseInt(args[4])) { System.out.println("Matrices size do not match."); return 1; } conf.setInt(inputMatrixBCols, Integer.parseInt(args[5])); bsp.setOutputPath(new Path(args[6])); conf.set(inputMatrixCPathString, args[6]); if (args.length > 7) { bsp.setNumBspTask(Integer.parseInt(args[7])); if (args.length > 8) { int n = Integer.parseInt(args[8]); if ((n & (n - 1)) != 0) { System.out.println("The block size must be a power of two"); return 1; } conf.setInt(blockSizeString, n); } else { /* * set the size of blocks depending on the number of peers and * matrices sizes */ /* * let's assume square matrices : nbTasks = * (PaddedRowSize/sizeBlock)^3 , */ int rows = conf.getInt(inputMatrixARows, 4); int n = 2; /* set n as the largest power of two smaller than row/2 */ while (n < rows / 2) { n *= 2; } n /= 2; int nbPeers = Integer.parseInt(args[7]); /* * lower the block size to make sure every peer has at least a * task */ while (Math.pow(rows / n, 3) < nbPeers) { n /= 2; } /* taking the future padding into account */ n *= 2; System.out.println("block size :" + n); conf.setInt(blockSizeString, n); } } else { /* * set the size of blocks depending on the number of peers and * matrices sizes */ /* * let's assume square matrices : nbTasks = * (PaddedRowSize/sizeBlock)^3 , */ int rows = conf.getInt(inputMatrixARows, 4); int n = 2; /* set n as the largest power of two smaller than row/4 */ while (n < rows / 4) { n *= 2; } conf.setInt(blockSizeString, n); int tasks = (int) Math.pow((int) (rows / n), 3); System.out.println("block size :" + n); System.out.println("peers :" + tasks); bsp.setNumBspTask(tasks); } return 0; }
b8670bfe-5735-47aa-aba3-eb4f4bc7fa8b
5
public static void createColumn(CyTable table, String columnName, Class type, Class elementType) { CyColumn column = table.getColumn(columnName); if (column != null) { if (!column.getType().equals(type)) throw new RuntimeException("Column "+columnName+" already exists, but has a different type"); if (column.getType().equals(List.class) && !column.getListElementType().equals(elementType)) throw new RuntimeException("List column "+columnName+" already exists, but has a different element type"); return; } if (type.equals(List.class)) table.createListColumn(columnName, elementType, false); else table.createColumn(columnName, type, false); return; }
050ea1dc-fec0-4bf9-82f5-9c7b915ee532
7
@Override public void action() { //System.out.println("Executando comportamento esperarReputacao"); ACLMessage mensagem = this.agenteReputacao.receive(); if(mensagem != null){ System.out.println("Recebi Mensagem"); ACLMessage mensagemDeRetorno = mensagem.createReply(); AID agenteEmissorAid = mensagem.getSender(); if(mensagem.getPerformative() == ACLMessage.INFORM){ // O agente esta informando uma reputacao try { Reputacao reputacao = (Reputacao) mensagem.getContentObject(); agenteReputacao.addReputacao(reputacao); } catch (UnreadableException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if(mensagem.getPerformative() == ACLMessage.REQUEST){ try { AID agenteAid = (AID) mensagem.getContentObject(); RepositorioReputacaoAgente repositorioReputacao = this.agenteReputacao.getRepositorioReputacao(agenteAid); Reputacao reputacao = repositorioReputacao.pegarReputacao(); if(reputacao == null){ reputacao = new Reputacao(agenteAid, -1); } mensagemDeRetorno.setContentObject(reputacao); mensagemDeRetorno.setPerformative(ACLMessage.INFORM); this.agenteReputacao.send(mensagemDeRetorno); } catch (UnreadableException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else{ block(); } }
d754dea2-0be1-4e1f-91db-7e43c40288be
3
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Produk other = (Produk) obj; if (!Objects.equals(this.Pcode, other.Pcode)) { return false; } return true; }
2fed591a-2f16-400c-b109-9779422c4d9d
8
protected void setupMouseControls(){ // right click to set the color addMouseListener(new MouseInputAdapter() { public void mouseClicked(MouseEvent e) { if( e.getButton() == MouseEvent.BUTTON1 || e.getButton() == MouseEvent.BUTTON3){ int xPos = e.getX(); if(xPos < 0 || xPos > CHR_PIXEL_WIDTH*tile.getWidth()){ // ignore it return; } int yPos = e.getY(); if(yPos < 0 || yPos > CHR_PIXEL_HEIGHT*tile.getHeight()){ // ignore it return; } int relX = xPos / CHR_PIXEL_WIDTH; int relY = yPos / CHR_PIXEL_HEIGHT; int index = (relY * tile.getWidth()) + relX; if( e.getButton() == MouseEvent.BUTTON1){ processLeftClick(index); } if( e.getButton() == MouseEvent.BUTTON3){ processRightClick(index); } } } }); addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { processMouseDragged(e); } public void mouseMoved(MouseEvent e) { processMouseMoved(e); } } ); }
6dccae49-0bce-43c9-8f07-37decb9eef07
6
public void insert(ListNode node, int index) { ListNode currentNode = root; ListNode beforeNode = root; int currentIndex = 0; if (!isEmpty() && index >= 0 && index <= size()) { // iterate to index while (currentNode != null && currentIndex != index) { beforeNode = currentNode; currentNode = currentNode.next; currentIndex++; } // insert if (index == 0) { root = node; node.next = currentNode; } else { beforeNode.next = node; node.next = currentNode; } } }
64e3d6dd-fc41-4e8c-88a0-5a14806cbe43
5
private String getCorrection(String word) { String res = corrections.get(word); if (res != null) { return res; } for (String u : getMisspelled(word)) { String s = corrections.get(u); if (s != null && ((word.length() >= DOUBLE_CORRECTION_TRESHOLD) || isKnown(u))) { return s; } } return res; }
252d0198-4b8b-4abb-9947-339e862febd4
7
public static void main(String[] args) throws Exception { Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40); analyzer = new WhitespaceAnalyzer(Version.LUCENE_40); String index_path = "D:/code_respo/index"; String data_path = "D:/code_respo/respo"; String query_path = "D:/code_respo/query.py"; String search_path = "D:/code_respo/tornado"; IndexBuilder ib = new IndexBuilder(data_path); Directory index; File index_file = new File(index_path); if (index_file.exists()) { System.out.println("load index!"); index = FSDirectory.open(index_file); } else { System.out.println("build index!"); index = ib.buildIndex(analyzer, index_path); } System.out.println("index complete!"); // =========================================================== ExtractMethod em = new ExtractMethod(); File datadir = new File(search_path); List<File> file_list = Util.travelDir(datadir); for (File file : file_list) { if (Util.fileFileter(file)) { System.out.println("-----prepare method of " + file.getCanonicalPath()); em.processFile(file); } } List<CodeMethod> code_collection = em.getFilteredCode_collection(50); // ============================================================ Searcher searcher = new Searcher(index, analyzer); int score[] = { 0, 0, 0, 0 }; Scanner in = new Scanner(System.in); int count = 0; for (CodeMethod cm : code_collection) { count++; FileWriter fw = new FileWriter(query_path); PrintWriter pw = new PrintWriter(fw); fw.write(em.commentToString(cm)); fw.write(em.methodToString(cm)); String q = em.methodToString(cm); searcher.doSearch(QueryParser.escape(q), searcher.searcher .getIndexReader().maxDoc()); searcher.printResult(0.3, pw);// set threshold to print System.out.print("No." + count + " please score the result(0-3): "); int tmp = in.nextInt(); if (tmp == -1) { break; } if (tmp == -2) { continue; } score[tmp]++; fw.close(); } System.out.print("score : "); for (int i = 0; i < score.length; i++) { System.out.print(" " + score[i]); } System.out.println(); searcher.close(); }
a4fa0d0b-5986-476e-87a2-e56e68e57fbb
2
@Override public void tick() { if (wait <= 3) { wait++; return; } if (getLevel().getTile(getX(), getY() - 1, getZ()).getVisableBlock() == 0) move(getX(), getY() - 1, getZ()); }
d2923253-1ac9-494a-8732-8eea09d495e7
0
@Override public void deleteEntity(T entity) throws DaoException { waitCompete(); getEntities().remove(entity); }
c9b9fee7-74cf-43d8-af1e-b79d27f00f46
3
public PodcastModel[] getSearchResult1(){ try{ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(_url.openStream()); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("outline"); //System.out.println("-----------------------"); PodcastModel[] podcastModels = new PodcastModel[nList.getLength()]; for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; PodcastModel tempPodcast = new PodcastModel(); tempPodcast.setName(getPodName("outline",eElement)); tempPodcast.setLink(getPodUrl("outline",eElement)); tempPodcast.setID(temp); podcastModels[temp] = tempPodcast; //System.out.println(podName[temp]+", "+podUrl[temp]); } } return podcastModels; } catch(Exception e){ e.printStackTrace(); logger.trace(e); return new PodcastModel[1]; } }
3a493262-be88-4896-ba13-1cd7f6c30047
0
public byte[] toBytes() { ByteBuffer buffer = ByteBuffer.allocate(BASE_SIZE + 4 + length); buffer.putInt(length) .put(Message.Type.PADDING.getTypeByte()) .put(data); return buffer.array(); }
cd5eb407-da73-4b36-b5e8-758cb3fbdc40
5
public Problem validate(final Object instance, final UpperCase annotation, final Object target, final CharSequence value) { if (value == null || value.length() < 1) { if (annotation.required()) { return new Problem(instance, annotation, target, value); } return null; } for(int i = 0, length = value.length(); i < length; ++i) { char c = value.charAt(i); if(!Character.isUpperCase(c)) { return new Problem(instance, annotation, target, value); } } return null; }