method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
7124cec0-9209-41bb-9028-756736c5c155
0
public int getAge() { return age; }
298d979c-673b-46e4-b15b-e6e620ff07e3
0
public int getNumBuffers() { return numBuffers; } // end getNumBuffers()
5729f2e6-fb78-4066-8867-afa2d422d519
7
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
809fcbfb-6561-4f1e-85f2-6cbda8963238
9
public static int findNumInRotatedArray(int[] array, int num) { int low = 0; int high = array.length - 1; int mid; while (low <= high) { mid = (low + high) / 2; if (array[mid] == num) { return mid; } else if (array[mid] > num) { if ((array[low] > array[mid]) || (array[low] < array[mid] && array[low] <= num)) { high = mid - 1; } else { low = mid + 1; } } else { if (array[high] < array[mid] || (array[high] > array[mid] && array[high] >= num)) { low = mid + 1; } else { high = mid - 1; } } } return -1; }
d2b073a8-d29a-49f7-b432-bc15f033f649
9
private static int play() { /** * Get a new deck of cards, and store a reference to it * in the variable <code>deck</code> */ Deck deck = new Deck(); /** * @param currentCard the current card, which user sees */ Card currentCard; /** * @param nextCard the next card in the deck. The user tries * to predict whether this is higher or lower than the current card */ Card nextCard; /** * @param correctGuesses The number of correct guesses the user * has made. At the end of the game, the will be the user's score. */ int correctGuesses; /** * @param guess The user's guess. 'H' if the user predicts that * the next card will be higher, 'L' if the user predicts that it will * be lower */ char guess; /** * shuffle the deck into a random order * before starting the game */ deck.shuffle(); correctGuesses = 0; currentCard = deck.dealCard(); System.out.println("The first card is the " + currentCard); /** * loop ends when the user's predicion is wrong */ while(true) { /** * Get the user's prediction, 'H' or 'L' ( or 'h' or 'l' ). */ System.out.print("Will the next card be higher(H) or lower(L)? "); do { guess = keyboard.next().charAt(0); guess = Character.toUpperCase(guess); if(guess != 'H' && guess != 'L') System.out.println("Pleas respond with H or L: "); } while (guess != 'H' && guess != 'L'); /** * get the next card and show it to the user */ nextCard = deck.dealCard(); System.out.println("The next card is: " + nextCard); /** * check the user's prediction */ if(nextCard.getValue() == currentCard.getValue()) { System.out.println("The value is the same as the previous card. "); System.out.println("You lose on ties. Sorry!"); break; // end the game } else if(nextCard.getValue() > currentCard.getValue()) { if (guess == 'H') { System.out.println("Your guess is correct!"); correctGuesses++; } else { System.out.println("Your guess was incorrect!"); break; } } else { if(guess == 'L') { System.out.println("Your guess is correct!"); correctGuesses++; } else { System.out.println("Your guess was incorrect!"); break; } } /** * To setup for the next iteration of the loop, the nextCard becomes * the currentCard, since the currentCard has to be the card the user * sees, and the nextCard will be set to the next card in the deck * after the user makes his guess */ currentCard = nextCard; System.out.println(); System.out.println("The card is " + currentCard); } // end of while loop System.out.println(); System.out.println("The game is over!"); System.out.println("You made " + correctGuesses + " correct predictions."); System.out.println(); return correctGuesses; } //end play
4e071fe7-ca87-49c5-a09c-356a4cc72795
9
public static boolean wordBreak(String s, Set<String> dict){ if(s==null||s.length() == 0){ return true; } boolean[][] resultHash = new boolean[s.length()][s.length()]; for(int len = 0;len<s.length();len++){ for(int i=0;i<s.length();i++){ if(i+len<s.length()){ if(dict.contains(s.substring(i,i+len+1))){ resultHash[i][len] = true; }else{ for(int k=i;k<i+len;k++){ if(resultHash[i][k-i] && resultHash[k+1][len-(k-i)-1]){ resultHash[i][len] = true; } } } } } } return resultHash[0][s.length()-1]; }
72ac6e80-b35a-4440-8b10-55bf723eafa1
9
@Override public boolean init(List<String> argumentList, DebuggerVirtualMachine dvm) { variablesWithOffsets = new LinkedHashMap<String, Integer>(); variablesWithNewValues = new HashMap<String, Integer>(); variableValues = new ArrayList<Integer>(); if (argumentList.size() % 2 != 0) { UserInterface.println("Invalid arguments."); HelpCommand.displayHelp(this); return false; } if (dvm.getFunctionName() == null) { UserInterface.println("There is no current function.\n"); return false; } for (Map.Entry<String, Object> e : dvm. getSymbolsFunctionEnvironmentRecord().entrySet()) { variablesWithOffsets.put(e.getKey(), (Integer) e.getValue()); } if (variablesWithOffsets.isEmpty()) { UserInterface.println("There are currently no local variables.\n"); return false; } String varName = null; for (int i = 0; i < argumentList.size(); i++) { if (i % 2 == 0) { varName = argumentList.get(i); if (!dvm.getSymbolsFunctionEnvironmentRecord().keySet().contains( varName)) { UserInterface.println(varName + " is not a valid variable name."); UserInterface.print("Valid variables are: "); for (String s : variablesWithOffsets.keySet()) { UserInterface.print(s + " "); } UserInterface.println("\n"); return false; } } else { try { Integer.parseInt(argumentList.get(i)); } catch (Exception ex) { UserInterface.println("Invalid new value for variable " + varName + "\n"); return false; } variablesWithNewValues.put(varName, Integer.parseInt(argumentList. get(i))); } } return true; }
f116eb2d-db81-464f-a5cf-93bc0f101309
4
@Test public void testLastVisitedSelection() throws BadConfigFormatException { // 3 possible targets one step from 5,8 ComputerPlayer player = new ComputerPlayer("test","yellow",board.getCellAt(board.calcIndex(5, 8))); player.setLastVisited('m'); // Pick a location with last visited room in target, just three targets board.calcTargets(5, 8, 1); int loc_4_8Tot = 0; int loc_5_9Tot = 0; int loc_5_7Tot = 0; // Run the test 100 times for (int i=0; i<100; i++) { BoardCell selected = player.pickLocation(board.getTargets()); if (selected == board.getCellAt(board.calcIndex(4, 8))) loc_4_8Tot++; else if (selected == board.getCellAt(board.calcIndex(5, 9))) loc_5_9Tot++; else if (selected == board.getCellAt(board.calcIndex(5, 7))) loc_5_7Tot++; else fail("Invalid target selected"); } // Ensure we have 100 total selections (fail should also ensure) assertEquals(100, loc_4_8Tot + loc_5_9Tot + loc_5_7Tot); // Ensure each target was selected more than once assertTrue(loc_4_8Tot > 10); assertTrue(loc_5_9Tot > 10); assertTrue(loc_5_7Tot > 10); }
e294e4f4-2ca8-4eb4-a627-486bb0dbc1e0
0
public boolean isEatable() { return true; }
e55cf1f4-675a-45f2-a130-a874626aa6e3
7
public static void main(String[] args) { Locale.setDefault(Locale.US); Scanner s = new Scanner(System.in); String op = s.nextLine(); double sum = 0; for(int i = 0; i <= 5; i++){ for(int j = 0; j < 12-i; j++){ s.nextDouble(); } for(int j = 12-i; j < 12; j++){ sum += s.nextDouble(); } } for(int i = 5; i >= 0; i--){ for(int j = 0; j < 12-i; j++){ s.nextDouble(); } for(int j = 12-i; j < 12; j++){ sum += s.nextDouble(); } } System.out.printf("%.1f\n", "S".equals(op) ? sum : sum/30); }
8cde71a6-80af-4dd4-a22f-e06f64e0fa7a
3
@Override public boolean isValid(LoginCredential loginCredential) { try { CryptedInputStream cryptedInputStream = new CryptedInputStream(new FileReader("crypted_" + loginCredential.getUserName() + ".txt")); int character; String cryptedPassword = ""; while ((character = cryptedInputStream.read()) >= 0) { cryptedPassword += (char) character; } cryptedInputStream.close(); if (cryptedPassword.equals(CryptedOutputStream.encrypt(loginCredential.getPassword()))) { return true; } } catch (IOException e) { e.printStackTrace(); } return false; }
6abd1cb3-7323-4df1-a125-97f7dbaf8a0b
0
public int getLineCountOffset() {return this.lineCountOffset;}
445fc1c8-c97f-4060-a43a-59b93543bcec
3
public void test_05_fastqReader() { String fastqFileName = "tests/fastq_test.fastq"; String txtFileName = "tests/fastq_test.txt"; // Read fastq file StringBuilder sb = new StringBuilder(); for( Fastq fq : new FastqFileIterator(fastqFileName, FastqVariant.FASTQ_ILLUMINA) ) sb.append(fq.getSequence() + "\t" + fq.getQuality() + "\n"); if( verbose ) System.out.println("Fastq test:\n" + sb); // Read txt file String txt = Gpr.readFile(txtFileName); // Compare if( txt.equals(sb.toString()) ) throw new RuntimeException("Sequences from fastq file does not match expected results:\n----- Fastq file -----" + sb + "\n----- Txt file -----" + txt + "-----"); }
b22e2145-5a6a-400b-99d9-fb4acd9e8da5
5
public static void combinationsCounter(int n, int k, int[] indexes, int d) { int i, iMin; if (d < k) { if (d == 0) { iMin = 1; } else { iMin = indexes[d-1]; } for (i = iMin; i < n; i++) { indexes[d] = i; if(sumElementsArray(indexes)<n) { combinationsCounter(n, k, indexes, d + 1); } else { i=n; combinationsCounter(n, k, indexes, d + 1); } } } else { if(sumElementsArray(indexes)==n) { combinations++; } } }
f32e64e7-02b2-45c8-aa1f-2ffa3539188a
2
public SignatureVisitor visitExceptionType() { if (state != RETURN) { throw new IllegalStateException(); } SignatureVisitor v = sv == null ? null : sv.visitExceptionType(); return new CheckSignatureAdapter(TYPE_SIGNATURE, v); }
59781272-1962-48d0-bed6-78489f25803f
7
public void maskRect(int x, int y, int w, int h, byte[] pix, byte[] mask) { int maskBytesPerRow = (w + 7) / 8; int stride = getStride(); for (int j = 0; j < h; j++) { int cy = y + j; if (cy >= 0 && cy < height_) { for (int i = 0; i < w; i++) { int cx = x + i; if (cx >= 0 && cx < width_) { int byte_ = j * maskBytesPerRow + i / 8; int bit = 7 - i % 8; if ((mask[byte_] & (1 << bit)) != 0) { data[cy * stride + cx] = pix[j * w + i]; } } } } } }
e7a7fb5c-9709-44c4-9437-fab0ecd3eac2
1
public void setToZeroPosition(){ for (int i = 0; i < beings.size(); i++){ beings.get(i).setPosition(zeroBeings.get(i).getX(), zeroBeings.get(i).getY()); } }
57fbeaa9-b7a4-4047-b72a-87b4a032b490
0
@Override public String toString() { return ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE); }
27ecdc29-5e50-4bdb-a89e-3de07a6f9ed4
1
public ByteVector putByte(final int b) { int length = this.length; if (length + 1 > data.length) { enlarge(1); } data[length++] = (byte) b; this.length = length; return this; }
527bbc00-b9f5-4b5e-a5a6-1d9406f6f5ac
6
public int calculateRangeAttack() { int attackLevel = c.playerLevel[4]; attackLevel *= c.specAccuracy; if (c.fullVoidRange()) attackLevel += c.getLevelForXP(c.playerXP[c.playerRanged]) * 0.1; if (c.prayerActive[3]) attackLevel *= 1.05; else if (c.prayerActive[11]) attackLevel *= 1.10; else if (c.prayerActive[19]) attackLevel *= 1.15; //dbow spec if (c.fullVoidRange() && c.specAccuracy > 1.15) { attackLevel *= 1.75; } return (int) (attackLevel + (c.playerBonus[4] * 1.95)); }
a745907e-f56a-4de0-8744-9ce48533bfdc
2
public void InsertarAudio(ArrayList datos) { // Cambiamos todos los datos, que se puedan cambiar, a minúsculas for(int i = 0 ; i < datos.size() ; i++) { try{datos.set(i, datos.get(i).toString().toLowerCase());} catch(Exception e){} } biblioteca.insertarRegistros("audio", datos); }
0fcb5c57-5c0d-46c8-a852-cef43fa6b4fa
3
private void initUI() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); questions[0] = new Question("File name for text file?", false); questions[1] = new Question("File name for tilesheet to use?", false); questions[1].GetTextField().setEditable(false); questions[1].GetTextField().setText(box.getSelectedName()); tilesheetFile = box.getSelectedFile(); for (int i = 0; i < questions.length; i++) { add(questions[i].GetLabel()); add(questions[i].GetTextField()); if (i == 0) { add(chooseTextFile); } else { add(chooseTilesheet); } } int result = JOptionPane.showConfirmDialog(null, this, "Enter in load information", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { running = false; } }
1513c7a6-fb5d-4476-92be-4a941adfdb7e
7
public void run() { Long time = System.currentTimeMillis(); Long sleep = System.currentTimeMillis() - (time+broadcastDelay); Long threshold; Set<Byte> keys; Iterator<Byte> i; Byte key; while (true) { // broadcast try { time = System.currentTimeMillis(); // -> networking.Networker.broadcast(); this.broadcast.invoke(new byte[0], Byte.valueOf((byte) 0), Boolean.FALSE, Boolean.FALSE, Boolean.TRUE); } catch (CallbackException e) { System.out.println(e.getLocalizedMessage()); } this.lock.lock(); // check for timeouts keys = this.activity.keySet(); i = keys.iterator(); threshold = System.currentTimeMillis() - dumpDelay; List<Byte> l = new LinkedList<Byte>(); while(i.hasNext()) { key = i.next(); // Keep-alive not received if (this.activity.get(key) <= threshold) { l.add(key); } } for(Byte b : l){ this.activity.remove(b); this.router.networkMessage(b, NetworkMessage.NOKEEPALIVE); } this.lock.unlock(); // sleep try { sleep = System.currentTimeMillis() - time + broadcastDelay; if (sleep > 50) Thread.sleep(sleep); } catch (InterruptedException e) {} } }
ef3dd797-9705-4092-9c47-4b6e9556a7a4
2
public void setProducts(ArrayList<Product> products, Basket basket) { if (basket != null) { for (Product product : products) { product.setInBasket(basket.isInBasket(product.getId())); } } this.products = products; removeSoldOutProducts(); }
bccdf364-1ff4-4f67-aa30-fa923aedca7e
7
private boolean loadEntities(String pathName, String productFile, String userFile){ boolean rtn = false; String productPath = confPath + productFileName; String userPath = confPath + userFileName; if(pathName != null && pathName.length() != 0){ if(productFile != null && productFile.length() != 0){ productPath = pathName + productFile; } if(userFile != null && userFile.length() != 0){ userPath = pathName + userFile; } } rtn = ItemList.getInstance().load(productPath); if(rtn){ rtn = UserList.getInstance().loadUsers(userPath); } return rtn; }
ad2368f5-77db-4be9-bf19-18da54708b76
9
protected void processKeyPressed(KeyEvent e) { if (!editable) return; if (selectedElement == null) return; int key = e.getKeyCode(); switch (key) { case KeyEvent.VK_UP: selectedElement.translateBy(0, -1); break; case KeyEvent.VK_DOWN: selectedElement.translateBy(0, 1); break; case KeyEvent.VK_LEFT: selectedElement.translateBy(-1, 0); break; case KeyEvent.VK_RIGHT: selectedElement.translateBy(1, 0); break; case KeyEvent.VK_DELETE: case KeyEvent.VK_BACK_SPACE: removeElement(selectedElement); break; case KeyEvent.VK_ENTER: showDialog(selectedElement); break; } repaint(); }
bf4521dd-ab31-4d14-a862-9bc370e4f46b
2
private void updateQuadTree() { q.clear(); for (Mob m : dots) { q.insert((Collidable)m); } // for (Mob m : lines) { // q.insert((Collidable)m); // } for (Mob m : polygons) { q.insert((Collidable)m); } }
e21084d1-e0b0-4e8c-b7c0-c2c8551121bb
6
@Override //Este metodo permite la eliminacion de un producto de la BBDD public boolean bajaProducto(int id) { boolean correcto=false; TransactionManager.obtenerInstanacia().nuevaTransaccion(); try { //Iniciamos la transsacion y bloqueamos la tabla a modificar TransactionManager.obtenerInstanacia().getTransaccion().start(); //buscamos el producto en la BBDD TProducto tProducto = FactoriaDAO.obtenerInstancia().getDAOProducto().mostrarProducto(id); //Si el producto existe lo damos de baja logica if(tProducto!=null) { // Si el producto esta activo lo intentamos dar de baja. if(tProducto.getActivo()) { //comprobamos si se introduce en la tabla o no if(FactoriaDAO.obtenerInstancia().getDAOProducto().bajaProducto(id)) { //confirmamos la transaccion try { TransactionManager.obtenerInstanacia().getTransaccion().commit(); correcto=true; } // Si falla el commit. catch(Exception e) { TransactionManager.obtenerInstanacia().getTransaccion().rollback(); correcto=false; } } } // else { correcto=false; TransactionManager.obtenerInstanacia().getTransaccion().rollback(); } } else { // Echamos para atras la transaccion TransactionManager.obtenerInstanacia().getTransaccion().rollback(); } //Eliminamos la transaccion TransactionManager.obtenerInstanacia().eliminaTransaccion(); } catch(Exception e) { try { TransactionManager.obtenerInstanacia().getTransaccion().rollback(); } catch (Exception ex) { ex.printStackTrace(); } TransactionManager.obtenerInstanacia().eliminaTransaccion(); } return correcto; }
2284cb04-5dc8-462f-a984-64c8f1e24ab7
0
private static void displayParams(long[] longValues, double[] doubleValues, int[] intValues) { System.out.println("Settings:"); System.out.println(" s: " + longValues[0]); System.out.println(" t: " + longValues[1]); System.out.println(" c1: " + doubleValues[0]); System.out.println(" c2: " + doubleValues[1]); System.out.println(" c3: " + doubleValues[2]); System.out.println(" dimension: " + intValues[0]); System.out.println(" threshold: " + intValues[1]); System.out.println(" initial temp: " + longValues[2]); }
0444a456-4a4f-4e79-a76d-9190ddbe1934
8
private BitSet selectImages(String str) { int n = view.getNumberOfInstances(ImageComponent.class); if (n == 0) return null; BitSet bs = new BitSet(n); if ("selected".equalsIgnoreCase(str)) { for (int i = 0; i < n; i++) { if (view.getImage(i).isSelected()) bs.set(i); } return bs; } if (selectFromCollection(str, n, bs)) { view.setImageSelectionSet(bs); return bs; } Matcher matcher = WITHIN_RECTANGLE.matcher(str); if (matcher.find()) { Rectangle2D area = getWithinArea(str); for (int i = 0; i < n; i++) { if (area.contains(view.getImage(i).getCenter())) { bs.set(i); } } view.setImageSelectionSet(bs); return bs; } out(ScriptEvent.FAILED, "Unrecognized expression: " + str); return null; }
9961dee0-5a30-4be0-b038-b10c8b85c4cf
9
public Tile getTile(int x, int y) { if (x < 0 || y < 0 || x >= width || y >= height) return Tile.voidTile; if (tiles[x + y * width] == Tile.col_spawn_floor) return Tile.spawn_floor; if (tiles[x + y * width] == Tile.col_spawn_grass) return Tile.spawn_grass; if (tiles[x + y * width] == Tile.col_spawn_hedge) return Tile.spawn_hedge; if (tiles[x + y * width] == Tile.col_spawn_wall1) return Tile.spawn_wall1; if (tiles[x + y * width] == Tile.col_spawn_wall2) return Tile.spawn_wall2; return Tile.voidTile; }
9da30dac-7275-431f-a697-a2df5bb4225d
7
public byte[] getNextFrame(int length) { byte[] output = new byte[length]; for (int i = 0; i < length; i++) { //convert the phase to an index by rounding int index = Math.round((WaveTable.TABLE_LENGTH - 1) * (phase / TWO_PI)); switch (mode) { case SINE: output[i] = WaveTable.SINE_TABLE[index]; break; case TRI: output[i] = WaveTable.TRI_TABLE[index]; break; case SAW: output[i] = WaveTable.SAW_TABLE[index]; break; case PULSE: if (phase < TWO_PI * pulseWidth) { output[i] = 127; } else { output[i] = -127; } break; } phase += phaseInc; if (phase >= TWO_PI) { phase -= TWO_PI; } } return output; }
ce5ac237-b004-451d-9424-dbe60dd4910c
6
private static LinkedList createNetworkFlow(BufferedReader buf) throws Exception { if (buf == null) { return null; } // create the Router objects first LinkedList routerList = createRouter(buf, NetworkReader.FLOW_ROUTER); int GB = 1000000000; // 1 GB in bits String line; String name1, name2; StringTokenizer str = null; Router r1, r2; Link tempLink = null; // creating the linking between two routers while ((line = buf.readLine()) != null) { str = new StringTokenizer(line); if (!str.hasMoreTokens()) { // ignore newlines continue; } // parse the name of the connected routers name1 = str.nextToken(); // router name if (name1.startsWith("#")) { // ignore comments continue; } name2 = str.nextToken(); // router name r1 = getRouter(name1, routerList); r2 = getRouter(name2, routerList); if (r1 == null || r2 == null) { System.out.println("NetworkReader.createNetworkFlow(): " + "Warning - unable to connect both "+name1+" and "+name2); continue; } // get baud rate of the link String baud = str.nextToken(); // bandwidth (Gbps) String propDelay = str.nextToken(); // latency (in millisec) String mtu = str.nextToken(); // link MTU (in byte) tempLink = new FlowLink(r1.get_name() + "_" + r2.get_name(), Double.parseDouble(baud) * GB, Double.parseDouble(propDelay), Integer.parseInt(mtu)); FIFOScheduler r1Sched = new FIFOScheduler(r1.get_name() + "_to_" + r2.get_name()); FIFOScheduler r2Sched = new FIFOScheduler(r2.get_name() + "_to_" + r1.get_name()); r1.attachRouter(r2, tempLink, r1Sched, r2Sched); } return routerList; }
b6a0b00a-c322-4934-9038-07f876c64c9d
8
public void construct(int[] treeNodes){ BinaryTree<Integer> root = null; if(treeNodes[0] != -1) { root = new BinaryTree<Integer>(treeNodes[0]); } Queue<BinaryTree> queue = new LinkedList<BinaryTree>(); queue.add(root); for(int i = 1; i < treeNodes.length;) { int noOfParents = i; for(int j = 1; j <= noOfParents; j++) { System.out.println(i + ":" + j); BinaryTree<Integer> node = queue.poll(); if(node != null) { if(i < treeNodes.length && treeNodes[i] != -1) { BinaryTree leftChild = new BinaryTree(treeNodes[i]); node.left = leftChild; queue.add(leftChild); } if (i < treeNodes.length && treeNodes[i+1] != -1) { BinaryTree rightChild = new BinaryTree(treeNodes[i + 1]); node.right = rightChild; queue.add(rightChild); } } i = i + 2; } } }
e5be0472-582e-4e00-b1d5-cd34131357ef
0
public void colorBlack() { myColor = BLACK; }
4fd7195b-c5d9-4c46-a17c-a9e5160d9232
4
@EventHandler(priority = EventPriority.NORMAL) public void onEntityDamagedDebug(EntityDamageEvent evt) { if( !(evt.getEntity() instanceof Player) ) { return; } Player jugador = (Player) evt.getEntity(); SpyAroundHere.logInfo("Entity attacked"); ItemMeta arma = jugador.getItemInHand().getItemMeta(); if(arma == null) { return; } if(arma.hasLore()) { StringBuilder log = new StringBuilder(); for(String valor_actual : arma.getLore()) { log.append(valor_actual); log.append("\n"); } SpyAroundHere.logInfo(log.toString()); } else { SpyAroundHere.logInfo("No LORE in WEAPON"); } }
bb286fd9-5753-4f58-8906-8ce7aabd96b5
4
@SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // tarkistetaan onko sessioon lisättynä tilausriveja ja haetaan ne ArrayList<Tilausrivi> tilausrivit = null; if (request.getSession().getAttribute("tilausrivit") != null) { tilausrivit = (ArrayList<Tilausrivi>) request.getSession() .getAttribute("tilausrivit"); } // otetaan formilta vastaan buttonin value String action = request.getParameter("btn"); // tarkistetaan onko kyseessä tilausrivin muokkaus vai poisto if (action.toLowerCase().contains("remove")) { // tilausrivin poisto String url = tallennaURL(request); tilausrivit = poistaTuote(tilausrivit, action); tallennaJaUudelleenohjaa(request, response, url, tilausrivit); } else if (action.toLowerCase().contains("edit")) { // tilausrivin muokkaus // haetaan muokattava tuote int numero = muokkaaTuote(tilausrivit, action); // asetetaan parametreiksi edit ja tuoteID String url = "ostoskori?action=edit&nro=" + numero; // uudelleenohjataan takaisin jsp-sivulle tallennaJaUudelleenohjaa(request, response, url, tilausrivit); } else if (action.toLowerCase().contains("save")) { // tilausrivin muokkaus tilausrivit = paivitaTuote(request, tilausrivit); String url = "ostoskori"; // lopuksi uudelleenohjataan takaisin ostoskoriin päivitetyillä tiedoilla tallennaJaUudelleenohjaa(request, response, url, tilausrivit); } }
a1f6e27b-d8a1-4e08-8ee2-55d999c6afba
8
protected void drawHorizontal(Graphics2D g2, Rectangle2D area) { Rectangle2D titleArea = (Rectangle2D) area.clone(); g2.setFont(this.font); g2.setPaint(this.paint); TextBlockAnchor anchor = null; float x = 0.0f; HorizontalAlignment horizontalAlignment = getHorizontalAlignment(); if (horizontalAlignment == HorizontalAlignment.LEFT) { x = (float) titleArea.getX(); anchor = TextBlockAnchor.TOP_LEFT; } else if (horizontalAlignment == HorizontalAlignment.RIGHT) { x = (float) titleArea.getMaxX(); anchor = TextBlockAnchor.TOP_RIGHT; } else if (horizontalAlignment == HorizontalAlignment.CENTER) { x = (float) titleArea.getCenterX(); anchor = TextBlockAnchor.TOP_CENTER; } float y = 0.0f; RectangleEdge position = getPosition(); if (position == RectangleEdge.TOP) { y = (float) titleArea.getY(); } else if (position == RectangleEdge.BOTTOM) { y = (float) titleArea.getMaxY(); if (horizontalAlignment == HorizontalAlignment.LEFT) { anchor = TextBlockAnchor.BOTTOM_LEFT; } else if (horizontalAlignment == HorizontalAlignment.CENTER) { anchor = TextBlockAnchor.BOTTOM_CENTER; } else if (horizontalAlignment == HorizontalAlignment.RIGHT) { anchor = TextBlockAnchor.BOTTOM_RIGHT; } } this.content.draw(g2, x, y, anchor); }
a0a296c8-07eb-4c09-aa0b-903bd9049f57
0
public LocalFileSystemFileProtocol() {}
c69f1a56-4986-4895-b502-6e61199b06de
1
protected String getName() { return name == null ? getClass().getSimpleName() : name; }
ab158a66-589b-4858-9252-11e4571e7b01
7
private void checkSettings() { // Check Region Size Integer regionSize = (Integer)regionSizeComboBox.getSelectedItem(); if(regionSize == null || regionSize == 0){ setError("Region Size cannot be null or zero!"); } // Build topology String[] intStrings = topologyField.getText().split("[, ]"); int[] intArray = new int[intStrings.length]; if(intStrings.length == 0 ) { setError("No topology specified!"); return; } for(int i = 0; i < intStrings.length; i++) { try{ intArray[i] = Integer.parseInt(intStrings[i]); } catch(NumberFormatException e) { setError("Topology Format Exception: " + e.getMessage()); return; } } // Check Training Directory if(directory == null || !directory.exists()) { setError("Training data directory not set!"); return; } this.regionSize = regionSize; this.topology = intArray; }
3d12c2a7-2218-41a6-b540-9d22050d883a
9
@Override public void keyPressed(Keys key) { switch (key) { case KEY_LEFT: player.getVelocity().x = -1; break; case KEY_RIGHT: player.getVelocity().x = 1; break; case KEY_UP: player.getVelocity().y = -1; break; case KEY_DOWN: player.getVelocity().y = 1; break; case KEY_SPACE: player.shootBullet(new Vector2F(player.lookX, player.lookY)); break; case KEY_W: player.yV = -3; break; case KEY_S: player.yV = 3; break; case KEY_A: player.xV = -3; break; case KEY_D: player.xV = 3; break; default: break; } }
b4b3fde1-c041-47b7-8228-9a8200cbf4c8
5
public JSONObject increment(String key) throws JSONException { Object value = this.opt(key); if (value == null) { this.put(key, 1); } else if (value instanceof Integer) { this.put(key, ((Integer) value).intValue() + 1); } else if (value instanceof Long) { this.put(key, ((Long) value).longValue() + 1); } else if (value instanceof Double) { this.put(key, ((Double) value).doubleValue() + 1); } else if (value instanceof Float) { this.put(key, ((Float) value).floatValue() + 1); } else { throw new JSONException("Unable to increment [" + quote(key) + "]."); } return this; }
70151256-f233-46d8-b0e7-4fc18339ec94
7
private static String removeTenantRoot(String tenantRoot, String path) { if (tenantRoot != null && tenantRoot.length() > 1 && path != null && path.startsWith(tenantRoot) && !path.startsWith(PUBLIC_ROOT)) { path = path.substring(tenantRoot.length()); if (path == null || path.isEmpty()) { path = "/"; } } return path; }
251e8869-47dd-4747-a090-85729a5e3e46
2
public Vector2 calculate() { if(behaviors.size() == 0) return new Vector2(0f, 0f); steeringForce = new Vector2(0f, 0f); for(IBehavior b : behaviors) { steeringForce.add(b.calculate(target)); } steeringForce = steeringForce.divideBy(behaviors.size()); //average return steeringForce; }
3f1ca4b2-b215-4ba3-9972-01f40b7ff2f5
8
public static Image getRightImage(int number) { if (number == 1) { return around; } else if (number == 2) { return unknown; } else if (number == 3) { return free; } else if (number == 4) { return nxt; } else if (number == 5) { return arrow_right; } else if (number == 6) { return arrow_down; } else if (number == 7) { return arrow_left; } else if (number == 8) { return arrow_up; } else { return blocked; } }
1886a197-ab14-43de-a2a2-678ff15132e0
6
private void parseInputToMaze(ArrayList<String> temp) { for (int y = 0; y < temp.size(); y++) { String line = temp.get(y); for (int x = 0; x < line.length(); x++) { if (line.substring(x, x + 1).equals("E")) { maze[y][x] = new MazeField(MazeField.FieldType.EMPTY); } else if (line.substring(x, x + 1).equals("W")) { maze[y][x] = new MazeField(MazeField.FieldType.WALL); } else if (line.substring(x, x + 1).equals("S")) { maze[y][x] = new MazeField(MazeField.FieldType.WALL, true, false); startPoint = new Point(x, y); } else if (line.substring(x, x + 1).equals("T")) { maze[y][x] = new MazeField(MazeField.FieldType.EMPTY, false, true); targetPoints.add(new Point(x, y)); } } } }
ff91529d-2a52-4ff0-a8cb-28bfb93d2501
9
public static void main(String[] args) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { // 日,一,二,三,四,五,六 String[] strCal = new String[42]; String[] destCal = new String[35]; // 只需要保存第一行的Calendar对象就可以了。 Calendar[] calArr = new Calendar[7]; Calendar cal = Calendar.getInstance(); // cal.set(Calendar.YEAR, 2014); // cal.set(Calendar.MONTH, Calendar.JULY); cal.set(Calendar.DAY_OF_MONTH, 1); // 周,1-7的整数,1为周日,7为周六 int dw = cal.get(Calendar.DAY_OF_WEEK); int startIndex = dw - 1; strCal[startIndex] = String.valueOf(cal.get(Calendar.DAY_OF_MONTH)); calArr[startIndex] = (Calendar) BeanUtils.cloneBean(cal); // 填充第一行当前日期之前的内容 for (int i = 0; i < startIndex; i++) { Calendar tmp = (Calendar) BeanUtils.cloneBean(calArr[startIndex]); tmp.add(Calendar.DAY_OF_MONTH, 0 - (startIndex - i)); calArr[i] = (Calendar) BeanUtils.cloneBean(tmp); strCal[i] = String.valueOf(calArr[i].get(Calendar.DAY_OF_MONTH)); } // 填充第一行当前日期之后的内容 for (int i = 6; i > startIndex; i--) { Calendar tmp = (Calendar) BeanUtils.cloneBean(calArr[startIndex]); tmp.add(Calendar.DAY_OF_MONTH, i - startIndex); strCal[i] = String.valueOf(tmp.get(Calendar.DAY_OF_MONTH)); calArr[i] = (Calendar) BeanUtils.cloneBean(tmp); } // 填充每一列 for (int i = 0; i < 7; i++) { Calendar tmpCal = calArr[i]; for (int j = 1; j < strCal.length / 7; j++) { tmpCal.add(Calendar.DAY_OF_MONTH, j * 7); strCal[j * 7 + i] = String.valueOf(tmpCal.get(Calendar.DAY_OF_MONTH)); tmpCal.add(Calendar.DAY_OF_MONTH, 0 - j * 7); } } // 处理日历需要5行显式还是6行显式的问题 int lastDay = Integer.parseInt(strCal[strCal.length - 8]); if (lastDay >= 29 && lastDay < Calendar.getInstance().getMaximum(Calendar.DAY_OF_MONTH)) { destCal = strCal; } else { System.arraycopy(strCal, 0, destCal, 0, destCal.length); } int num = 0; System.out.println("日,一,二,三,四,五,六"); for (String item : destCal) { num++; System.out.print(item); if (num != 0 && num % 7 == 0) { System.out.println(); } else { System.out.print(","); } } }
97f4a5ed-1a21-4065-8978-cd4f05153052
3
public double[] do200baudFSKHalfSymbolBinRequest (CircularDataBuffer circBuf,int start,int bin0,int bin1) { double vals[]=new double[2]; // Get the data from the circular buffer double samData[]=circBuf.extractDataDouble(start,20); double datar[]=new double[FFT_64_SIZE]; // Run the data through a Blackman window int a; for (a=0;a<datar.length;a++) { if ((a>=22)&&(a<42)) datar[a]=samData[a-22]; else datar[a]=0.0; datar[a]=windowBlackman(datar[a],a,datar.length); } fft64.realForward(datar); double spec[]=getSpectrum(datar); vals[0]=spec[bin0]; vals[1]=spec[bin1]; return vals; }
969cde7e-73b3-4f18-9a2d-9dc07e925cb0
8
private void tuRevertSame(final Character[] orig, final Character[] dest) { final TreeMap<Character,Character> origMap = new TreeMap<Character,Character>(); final TreeMap<Character,Character> destMap = new TreeMap<Character,Character>(); for (int i = 0; i < orig.length || i < dest.length; i++) { if (i < orig.length) { origMap.put(orig[i], orig[i]); } // end of if if (i < dest.length) { destMap.put(dest[i], dest[i]); } // end of if } // end of for tuRevert(origMap, destMap); final TreeMap<Character,Character> om = new TreeMap<Character,Character>(rcharComp); final TreeMap<Character,Character> dm = new TreeMap<Character,Character>(rcharComp); for (int i = 0; i < orig.length || i < dest.length; i++) { if (i < orig.length) { om.put(orig[i], orig[i]); } // end of if if (i < dest.length) { dm.put(dest[i], dest[i]); } // end of if } // end of for tuRevert(om, dm); } // end of tuRevertSame
a1725ac6-b989-42ec-86d9-51bd53654d2a
2
public void showSide(boolean showSideB) { showingSideB = showSideB; colorBar.setBackground(showingSideB ? colorB : colorA); String text = showingSideB ? sideB : sideA; contentLabel.setText(text); contentLabel.setFont(findBestFontSize(FONT, text)); }
803c7c1d-875d-4d9d-803a-3012d87bd8cf
6
static String urlize(String s, int length) { char[] charArray = s.toCharArray(); int start_strip = 0; for (int i = 0; i<s.length(); i++) { if (charArray[i] == ' ') { start_strip += 1; } else { break; } } int spaceCount = 0; for (int i = start_strip; i<length + start_strip; i++) { if (charArray[i] == ' ') { spaceCount += 1; } } char[] newCharArray = new char[length + 2*spaceCount]; for (int i = 0, j = start_strip; j < start_strip + length; j++) { if (charArray[j] == ' ') { newCharArray[i] = '%'; newCharArray[i+1] = '2'; newCharArray[i+2] = '0'; i += 3; } else { newCharArray[i] = charArray[j]; i += 1; } } return new String(newCharArray); }
70606c6f-5994-405f-b3a6-96c6261037fc
3
private Group readGroup(Class<? extends Group> type, List<ParsedParameter> params) { try { Group group = type.newInstance(); for (ParsedParameter param : params) { Field field = param.getParameter().getProperty(Properties.FIELD_HOLDER); field.set(group, param.getParsedValue()); } return group; } catch (InstantiationException | IllegalAccessException e) { throw new IllegalArgumentException(e); } }
ec55eb11-c718-4835-b627-11f549b20535
1
void writeClassfile(String classname, OutputStream out) throws NotFoundException, IOException, CannotCompileException { InputStream fin = openClassfile(classname); if (fin == null) throw new NotFoundException(classname); try { copyStream(fin, out); } finally { fin.close(); } }
9649cac6-f880-47e8-8837-daf5d8a9965e
3
private boolean isTargetKeyword(Token cur) { if (!cur.isKeyword()) return false; for (Keyword target: targetKeywords) { if (target.equals(cur.getKeyword())) return true; } return false; }
2dddb070-c161-42c2-8e07-72fb86bd6601
7
@Override public String getTypeDescription(File f) { String extension = Utils.getExtension(f); String type = null; if (extension != null) { if (extension.equals(Utils.jpeg) || extension.equals(Utils.jpg)) { type = "JPEG Image"; } else if (extension.equals(Utils.gif)){ type = "GIF Image"; } else if (extension.equals(Utils.tiff) || extension.equals(Utils.tif)) { type = "TIFF Image"; } else if (extension.equals(Utils.png)){ type = "PNG Image"; } } return type; }
171905b8-d466-45c4-a30e-9fc0e9d2b230
3
void iniciarJuego() { snake.inicializar(); while (!gameOver) { try { while (pausa) { Thread.sleep(10); } Thread.sleep(150); } catch (InterruptedException ex) { } snake.mover(); panel.repaint(); } }
dd8d2666-db40-4d7f-8cab-7e6098eab974
9
private Object optimizeFieldMethodProperty(Object ctx, String property, Class<?> cls, Member member) throws IllegalAccessException { Object o = ((Field) member).get(ctx); if (((member.getModifiers() & STATIC) != 0)) { // Check if the static field reference is a constant and a primitive. if ((member.getModifiers() & FINAL) != 0 && (o instanceof String || ((Field) member).getType().isPrimitive())) { o = ((Field) member).get(null); assert debug("LDC " + valueOf(o)); mv.visitLdcInsn(o); wrapPrimitive(o.getClass()); if (hasNullPropertyHandler()) { if (o == null) { o = getNullPropertyHandler().getProperty(member.getName(), ctx, variableFactory); } writeOutNullHandler(member, 0); } return o; } else { assert debug("GETSTATIC " + getDescriptor(member.getDeclaringClass()) + "." + member.getName() + "::" + getDescriptor(((Field) member).getType())); mv.visitFieldInsn(GETSTATIC, getInternalName(member.getDeclaringClass()), member.getName(), getDescriptor(returnType = ((Field) member).getType())); } } else { assert debug("CHECKCAST " + getInternalName(cls)); mv.visitTypeInsn(CHECKCAST, getInternalName(cls)); assert debug("GETFIELD " + property + ":" + getDescriptor(((Field) member).getType())); mv.visitFieldInsn(GETFIELD, getInternalName(cls), property, getDescriptor(returnType = ((Field) member) .getType())); } returnType = ((Field) member).getType(); if (hasNullPropertyHandler()) { if (o == null) { o = getNullPropertyHandler().getProperty(member.getName(), ctx, variableFactory); } writeOutNullHandler(member, 0); } currType = toNonPrimitiveType(returnType); return o; }
9c669587-337f-40d2-91fc-e5c182c87daa
2
private void updateRowColumnSizes(FlexGridData data) { if (data.mRowSpan == 1) { updateSizes(data.mRow, data.mSize.height, mRowHeights, data.mMinSize.height, mMinRowHeights, data.mMaxSize.height, mMaxRowHeights); } if (data.mColumnSpan == 1) { updateSizes(data.mColumn, data.mSize.width, mColumnWidths, data.mMinSize.width, mMinColumnWidths, data.mMaxSize.width, mMaxColumnWidths); } }
1037899d-563f-4057-83aa-ea9448e64056
2
private Sentence splitSentenceByWordsAndPunctuation(String sourceString) { ResourceBundle bundle; bundle = ResourceBundle.getBundle(ApplicationValue.BUNDLE_LOCATION); Pattern wordPattern = Pattern.compile(bundle.getString(ApplicationValue.WORD_PUNCUATION)); Matcher wordMatcher = wordPattern.matcher(sourceString); Sentence sentence = new Sentence(); while (wordMatcher.find()) { String sentencePartString = wordMatcher.group(); if (isPunctuation(sentencePartString)) { sentence.add(new Punctuation(sentencePartString)); } else { sentence.add(new Word(sentencePartString)); } } return sentence; }
1764f48b-576f-4a86-b30d-6642f32bbad6
2
private InfoNode SplitLeaf(String key, Integer value, Node node) { node.add(key, value); LeafNode sibling = new LeafNode(); int mid = (node.getSize()+1)/2; int loopTo = node.getSize(); for(int i = mid; i < loopTo;i++){ sibling.add(node.getKey(i), node.getValue(i)); } for(int i = mid; i < loopTo;i++){ node.remove(i); } sibling.nextLeaf = ((LeafNode) node).nextLeaf; ((LeafNode) node).nextLeaf = sibling; return new InfoNode(sibling.keys[0], sibling); }
2bb577de-7bdd-4b9f-ba6a-74de50788040
7
private void refreshRecursively(Object comp, boolean forceRefresh) { if (comp instanceof YIComponent) { YController controller = YUIToolkit.getController((YIComponent) comp); if (controller != null) { if (forceRefresh || (controller.getRefreshHelper().dirty && YUIToolkit.currentlyVisible((Component)comp))) { controller.refreshView(controller.getRefreshHelper().refreshData); controller.getRefreshHelper().dirty = false; } } } if (comp instanceof Container) { comp = YUIToolkit.getContentPane((Container)comp); // for JDialog or JFrame Component comps[] = ((Container) comp).getComponents(); for (int i=0; i < comps.length; i++) { Component child = comps[i]; refreshRecursively(child, forceRefresh); } } }
86d38ab6-c237-401f-846b-71f3f68ff796
3
public void draw(Graphics2D g2,int xOffset, int yOffset){ g2.setColor(Color.blue); if(skin==1){ g2.drawImage(Tile.zombie1[dire][timeVar],getX_Point()-xOffset, getY_Point()+yOffset,null); }else if (skin==2){ g2.drawImage(Tile.zombie2[dire][timeVar],getX_Point()-xOffset, getY_Point()+yOffset,null); }else if(skin==3){ g2.drawImage(Tile.zombie3[dire][timeVar],getX_Point()-xOffset, getY_Point()+yOffset,null); }else{ g2.drawImage(Tile.zombie4[dire][timeVar],getX_Point()-xOffset, getY_Point()+yOffset,null); } }
57e4d4c7-f9ae-4176-bf78-74149c683abe
6
public EndDisplay(Game game) { boolean test = false; if (test || m_test) { System.out.println("EndDisplay :: EndDisplay() BEGIN"); } final int YESGRIDX = 0; final int YESGRIDY = 0; final int YESPADY = 0; final double STATP1WEIGHTX = 0.5; final int STATP1WIDTH = 1; final int STATP1GRIDY = 1; final int STATP2GRIDX = 1; final int ENDLABELGRIDX = 0; final int ENDLABELGRIDY = 2; final int BUTTONPANELGRIDY = 3; final int BUTTONSIZEX = 100; final int BUTTONSIZEY = 30; final int FRAME_WIDTH = 250; final int FRAME_HEIGHT = 150; final String WINS = " Wins!"; final String DRAW = "The game was a draw"; setGame(game); GridBagLayout layout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); getContentPane().setPreferredSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT)); JLabel winner = new JLabel(); if (game.isWinner() == Game.PlayerTurn.PLAYER1) { winner.setText(game.getPlayer1().getPlayerName() + WINS); } else if (game.isWinner() == Game.PlayerTurn.PLAYER2) { winner.setText(game.getPlayer2().getPlayerName() + WINS); } else { winner.setText(DRAW); } OK_BUTTON.setPreferredSize(new Dimension(BUTTONSIZEX,BUTTONSIZEY)); getContentPane().setLayout(layout); c.gridy = YESGRIDY; c.gridx = YESGRIDX; c.gridwidth = GridBagConstraints.REMAINDER; c.ipady = YESPADY; layout.setConstraints(winner, c); getContentPane().add(winner); JPanel stats1 = statsPlayer1(game); c.weightx = STATP1WEIGHTX; c.gridwidth = STATP1WIDTH; c.gridy = STATP1GRIDY; layout.setConstraints(stats1, c); getContentPane().add(stats1); JPanel stats2 = statsPlayer2(game); c.gridx = STATP2GRIDX; layout.setConstraints(stats2, c); getContentPane().add(stats2); c.gridwidth = GridBagConstraints.REMAINDER; c.gridx = ENDLABELGRIDX; c.gridy = ENDLABELGRIDY; JPanel buttonPanel = new JPanel(); buttonPanel.add(OK_BUTTON); c.gridy = BUTTONPANELGRIDY; layout.setConstraints(buttonPanel, c); getContentPane().add(buttonPanel); OK_BUTTON.addActionListener(this); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); setVisible(true); if (test || m_test) { System.out.println("EndDisplay :: EndDisplay() END"); } }
761cca1d-c702-4e7a-8465-765a7ce5e734
2
@Override public int compareTo(Product o) { int res = 0; if (o.getProductCode()>this.getProductCode()) { res = 1; } if (o.getProductCode()<this.getProductCode()) { res=-1; } return res; }
6e259271-be5d-4d89-a207-abbb3ff2b96d
1
private void jButtonCommandeClientEntrepriseMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonCommandeClientEntrepriseMousePressed if (!(jTextFieldCmdDate.getText().trim().isEmpty()) ) { Entreprise entreprise = (Entreprise) this.jComboBoxCommandeClientEntreprise.getSelectedItem(); new VueCommandeClient(this.jTextFieldCmdDate.getText(),entreprise.getIdentreprise(),id_interlocuteur, id_commercial ).setVisible(true); } }//GEN-LAST:event_jButtonCommandeClientEntrepriseMousePressed
748c3f4a-f193-400d-9529-f2c81c6e622d
8
String anonymizeString(String input,String nameToBeAnonymized) { //extract name terms String nameTerms[] = nameToBeAnonymized.split(" "); String textTerms[] = input.split(" "); String output = null; //go through input, replace name term sequences with substitute boolean lastTermWasName = false; for(int i = 0; i < textTerms.length;i++) { boolean foundName = false; for(int j = 0; j < nameTerms.length;j++) { String processedTextTerm = textTerms[i].toLowerCase().replaceAll("[,.:;]+", ""); //System.out.println(processedTextTerm); if(processedTextTerm.compareTo(nameTerms[j].toLowerCase()) == 0) { foundName = true; } } if((foundName == true) && (anonymize == true)) { if(lastTermWasName == false) { if(output == null) { output = anonymousSubstituteName; } else { output = output + " " + anonymousSubstituteName; } } lastTermWasName = true; } else { if(output == null) { output = textTerms[i]; } else { output = output + " " + textTerms[i]; } lastTermWasName = false; } } return output; }
833727b8-3492-4628-94b6-241a62cc77fe
2
public String toString() { String x = ""; if (handlers != null) { for (int i = 0; i < handlers.length; i++) { x += "\n " + handlers[i]; } } /* * for (int i = 0; i < attrs.length; i++) { x += "\n " + attrs[i]; } */ return "(code " + maxStack + " " + maxLocals + " " + code.length + x + ")"; }
f458fd63-deb7-4fa9-8058-c8eb011ef5e7
7
public Copyable getVersion(Transaction me, ContentionManager manager) { while (true) { if (me != null && me.getStatus() == Status.ABORTED) { throw new AbortedException(); } switch (writer.getStatus()) { case ACTIVE: if (manager == null) { throw new PanicException("Transactional/Non-Tranactional race"); } manager.resolveConflict(me, writer); continue; case COMMITTED: return newVersion; case ABORTED: return oldVersion; default: throw new PanicException("Unexpected transaction state: " + writer.getStatus()); } } }
46507559-08c2-4505-8e7a-13585689ae21
4
public void loadFile() { JFileChooser chooser = new JFileChooser(executableDir); FileNameExtensionFilter filter = new FileNameExtensionFilter( "Pippin Executable Files", "pexe"); chooser.setFileFilter(filter); // CODE TO LOAD DESIRED FILE int openOK = chooser.showOpenDialog(null); if(openOK == JFileChooser.APPROVE_OPTION) { currentlyExecutingFile = chooser.getSelectedFile(); } if(currentlyExecutingFile != null && currentlyExecutingFile.exists()) { // CODE TO REMEMBER WHICH DIRECTORY HAS THE pexe FILES executableDir = currentlyExecutingFile .getAbsolutePath(); executableDir = executableDir.replace('\\','/'); int lastSlash = executableDir.lastIndexOf('/'); executableDir = executableDir.substring(0, lastSlash + 1); try { properties.setProperty("SourceDirectory", sourceDir); properties.setProperty("ExecutableDirectory", executableDir); properties.store(new FileOutputStream("propertyfile.txt"), "File locations"); } catch (Exception e) { System.out.println("Error writing properties file"); } } finalLoad_ReloadStep(); }
0a9706b6-170a-4d37-8b2b-4c64ffc04c51
5
public boolean getSimplicityofPN() throws BadLocationException { dialog.addMessageToLogger("Checking simplicity of a PN", 1); boolean simplicity = true; for (Arc a : getPn().getListOfArcs()) { if (!(a.getOutElement() instanceof Resource) && !(a.getInElement() instanceof Resource) && a.getCapacity() > 1) { simplicity = false; break; } } simpleNet = simplicity; if (simplicity) { dialog.addMessageToLogger("PN is simple", 1); } else { dialog.addMessageToLogger("PN isn't simple", 3); } return simplicity; }
1336d261-43ae-4342-9fa4-3b7be5ac5575
5
public void solve() throws SolvingInitialisiationException, WrongOptimisationOrderException{ if (possibleDecisions.isEmpty()) throw new SolvingInitialisiationException("DP decisions have not been initialized in "+this); Iterator<DPLotSizingDecision> it = possibleDecisions.iterator(); //Start of with the first decision as possible optimal decision this.optimalDecision = it.next(); if (this.optimalDecision.nextSetupPeriod.partialOptimalValue == null) throw new WrongOptimisationOrderException(); this.partialOptimalValue = this.optimalDecision.cost + this.optimalDecision.nextSetupPeriod.partialOptimalValue; //Iterate through the rest and see if there is a better decision while (it.hasNext()){ DPLotSizingDecision decision = it.next(); if (decision.nextSetupPeriod.partialOptimalValue == null) throw new WrongOptimisationOrderException(); if (this.partialOptimalValue > decision.cost + decision.nextSetupPeriod.partialOptimalValue){ this.optimalDecision = decision; this.partialOptimalValue = decision.cost + decision.nextSetupPeriod.partialOptimalValue; }; } // System.out.println("DEBUG: Solved "+this+". Next Setup Period is "+this.optimalDecision.nextSetupPeriod); }
099fb30d-86ad-402e-ae4d-c792687e2117
4
@Override public void run() { int buffersize=size; double datasize=30*buffersize*1024; byte toSend[] = new byte[buffersize]; byte toReceive[] = new byte[buffersize]; for (int i=0; i<buffersize; i++){ toSend[i] = (byte)2; }// TODO Auto-generated method stub DatagramPacket recivePacket; DatagramPacket sendPacket; InetAddress ipAddress; int port; for(int i=0;i<datasize;){ recivePacket=new DatagramPacket(toReceive, buffersize); try { socket.receive(recivePacket); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } toReceive=recivePacket.getData(); ipAddress=recivePacket.getAddress(); port=recivePacket.getPort(); sendPacket=new DatagramPacket(toSend, buffersize,ipAddress,port); try { socket.send(sendPacket); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } i=i+buffersize; } }
319cd57d-e0d8-469f-bbf5-6e7bc8f1c3a1
4
public void extractConfig(final String resource, final boolean replace) { final File config = new File(this.getDataFolder(), resource); if (config.exists() && !replace) return; this.getLogger().log(Level.FINE, "Extracting configuration file {1} {0} as {2}", new Object[] { resource, CustomPlugin.CONFIGURATION_SOURCE.name(), CustomPlugin.CONFIGURATION_TARGET.name() }); config.getParentFile().mkdirs(); final char[] cbuf = new char[1024]; int read; try { final Reader in = new BufferedReader(new InputStreamReader(this.getResource(resource), CustomPlugin.CONFIGURATION_SOURCE)); final Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(config), CustomPlugin.CONFIGURATION_TARGET)); while((read = in.read(cbuf)) > 0) out.write(cbuf, 0, read); out.close(); in.close(); } catch (final Exception e) { throw new IllegalArgumentException("Could not extract configuration file \"" + resource + "\" to " + config.getPath() + "\"", e); } }
03aab52a-9918-4f05-9eb1-2c53075c5b71
9
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(UserPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(UserPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(UserPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(UserPage.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() { try { new UserPage().setVisible(true); } catch(SQLException e) { System.err.println("SQL Error(s) as follows:"); while (e != null) { System.err.println("SQL Return Code: " + e.getSQLState()); System.err.println(" Error Message: " + e.getMessage()); System.err.println(" Vendor Message: " + e.getErrorCode()); e = e.getNextException(); } } catch(Exception e) { System.err.println(e); } } }); }
6e2e2e81-015b-4d24-a7f5-bdc8da55fd33
3
public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner in = new Scanner(System.in); int n = in.nextInt(); int k= in.nextInt(); int q= in.nextInt(); int[] arr=new int[n]; int [] indexArr=new int[q]; for(int count=0;count<n;count++){ arr[count]=in.nextInt(); } for(int count=0;count<q;count++){ indexArr[count]=in.nextInt(); } arr=shiftKTimes(arr,k); for(int count=0;count<q;count++){ System.out.println(arr[indexArr[count]]); } }
fdb3dcb7-29af-40d0-ad3d-661458ecc637
0
public long getIdConnection() { return idConnection; }
0be84ae8-a6ac-4a13-b656-dcf450002e30
1
public Class<? extends Command> getCls() { return cls; }
4db0221e-9e77-4f01-93f2-bbe8e5a6a399
8
public void testConstructor_int_int_int_int_Chronology() throws Throwable { LocalTime test = new LocalTime(10, 20, 30, 40, JULIAN_LONDON); assertEquals(JULIAN_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); try { new LocalTime(-1, 20, 30, 40, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(24, 20, 30, 40, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, -1, 30, 40, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 60, 30, 40, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, -1, 40, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, 60, 40, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, 30, -1, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, 30, 1000, JULIAN_LONDON); fail(); } catch (IllegalArgumentException ex) {} }
68e9a94c-fe8c-4971-b0f6-f68596c61f27
3
public void run() { //Guarda el tiempo actual del sistema tiempoActual = System.currentTimeMillis(); //Ciclo principal del JFrame. Actualiza y despliega en pantalla hasta que se acaben las vidas while (vidas > 0) { //si esta pausado no actualizas ni checas colision if (!pausa) { actualiza(); checaColision(); } repaint(); // Se actualiza el <code>JFrame</code> repintando el contenido. try { // El thread se duerme. Thread.sleep(80); } catch (InterruptedException ex) { System.out.println("Error en " + ex.toString()); } } }
db8b39f1-fde3-4c7c-9c76-2bd0152d74c4
4
public int getxattrsize(ByteBuffer path, ByteBuffer name, FuseSizeSetter sizeSetter) { if (xattrSupport == null) { return handleErrno(Errno.ENOTSUPP); } String pathStr = cs.decode(path).toString(); String nameStr = cs.decode(name).toString(); if (log != null && log.isDebugEnabled()) { log.debug("getxattrsize: path=" + pathStr + ", name=" + nameStr); } try { return handleErrno(xattrSupport.getxattrsize(pathStr, nameStr, sizeSetter), sizeSetter); } catch(Exception e) { return handleException(e); } }
6c2819ee-a030-4b03-a297-d581db43c2c3
1
public void suljeLohko() throws IllegalStateException { this.nykyinenLohko().paataLohko(); if (!this.eiAvoimiaLohkoja()) { lohkot.remove(lohkot.size() - 1); } }
d0c5499d-ea9a-4825-ae67-2b6897ead184
1
public void appendModifier(String type, String value) { for(TextSegment s : segments) { s.modifier.addModifier(type, value); } }
b72c80f5-72c5-42e9-8adf-db1e0dc92ea8
8
public void setComputerBoard() { int boardIter = shipSize; if (shipSize == 1) { boardIter = 3; } // System.out.println("BoardIter:" + boardIter); if (horizontal == false) { int yCoor = ship.getY(); while (boardIter > 0) { computerBoard[ship.getX()][yCoor] = shipSize; boardIter--; yCoor++; } } if (horizontal == true) { int xCoor = ship.getX(); while (boardIter > 0) { computerBoard[xCoor][ship.getY()] = shipSize; boardIter--; xCoor++; } } for (int col = 0; col < 10; col++) { for (int r = 0; r < 10; r++) { if (computerBoard[r][col] != 0) { computerBoard[r][col] = computerBoard[r][col]; } else { computerBoard[r][col] = 0; } // System.out.print(computerBoard[r][col] + " "); } // System.out.println(); } }
e9544e99-3c06-451b-b63c-861ed2124045
8
private ArrayList<Method> getAnnotatedMethodsRecursively(Class<?> klass) { if (klass == null || klass.equals(Class.class)) { annotatedMethodsByClass.put(klass, null); return null; } if (annotatedMethodsByClass.containsKey(klass)) { return annotatedMethodsByClass.get(klass); } ArrayList<Method> result = new ArrayList<Method>(); Method[] methods = klass.getDeclaredMethods(); if (methods == null) { annotatedMethodsByClass.put(klass, null); return null; } for (Method method : methods) { AEvent annotation = method.getAnnotation(AEvent.class); if (annotation != null) { method.setAccessible(true); result.add(method); } } ArrayList<Method> methodsFromSuperClass = getAnnotatedMethodsRecursively(klass.getSuperclass()); if (methodsFromSuperClass != null) { result.addAll(methodsFromSuperClass); } annotatedMethodsByClass.put(klass, result); return result; }
62a3d89f-27ff-42ca-b5ff-7bb2c9b8b44f
0
public Blog getBlogDetail(long pBlogId){ return blogModelBS.getBlogDetail(pBlogId); }
26b9a831-eb9c-4ce2-ac13-e65a28dc37d4
2
public static void main(String[] args) throws IOException, ClassNotFoundException { URLClassLoader urlClassLoader=new URLClassLoader(new URL[]{new URL("file:/tmp/")}); urlClassLoader.loadClass("Bulbs"); File file=new File("/tmp"); file.toURI().toURL(); FileChannel fcin=new FileInputStream("/tmp/test.txt").getChannel(); FileChannel fcout=new FileOutputStream("/tmp/test1.txt").getChannel(); ByteBuffer byteBuffer=ByteBuffer.allocate(1024); while (true){ byteBuffer.clear(); int cnt=fcin.read(byteBuffer); if(cnt==-1) break; byteBuffer.flip(); fcout.write(byteBuffer); } }
90d2191c-a515-4966-80e4-e35de4e0a0ab
3
public static <T extends DC> Set<Set<Pair<Pair<T,PT<Integer>>,Pair<T,PT<Integer>>>>> despatch(Pair<Pair<T,PT<Integer>>,Pair<T,PT<Integer>>> pair, Set<Set<Pair<Pair<T,PT<Integer>>,Pair<T,PT<Integer>>>>> sets) { if(pair==null) { return sets; } else { if(sets==null) { return new Set(new Set(pair,null),null); } else//pair!=null && sets!=null { if(sets.getNext()==null) { return new Set(sets.getFst().ins(pair),null); } else { return new Set(sets.getFst().ins(pair),despatch(pair,sets.getNext())); } } } }
35a8f104-7fdc-4b7c-9734-dfcdfcb6c87e
1
public String toString() { StringBuilder s = new StringBuilder(); for (Item item : this) s.append(item + " "); return s.toString(); }
9fa95ffd-28e7-44e2-b644-9dd103c91478
6
public static String firstName(byte fn, byte ln, boolean gender) { int[] N = {Calc.squeezeByte(fn, 0, SYL1.length),Calc.squeezeByte(ln, 0, SYL2.length)}; String p1 = SYL1[N[0]], p2 = SYL2[N[1]].get(gender); String suffix = ""; if (gender == Misc.FEMALE) { switch ((fn * ln) % 3) { case 0: suffix += "a"; break; case 1: suffix += "i"; break; case 2: suffix += "et"; break; case -1: suffix += "el"; break; case -2: suffix += "ra"; break; default: break; } } return p1 + p2 + suffix; }
63502cf5-c14b-4983-9f45-1f9b5cec2d43
0
protected void onMessage(String channel, String sender, String login, String hostname, String message) {}
d853e6c3-ba0b-42b2-bd4f-c49780e0eb16
7
@Override public Set<T> next(){ if(!hasNext()){ throw new NoSuchElementException(); } if(current == null){ current = new TreeSet<Integer>(); } else{ if(current.size() == 0){ current.add(1); } else{ part:{{ int iterations = 0; int tempIndex = current.last(); while(tempIndex == array.size() - iterations){ if(tempIndex == current.first()){ current.clear(); for(int i = 1; i < iterations + 3; i++){ current.add(i); } break part; } current.remove(tempIndex); tempIndex = current.lower(tempIndex); iterations++; } current.remove(tempIndex); for(int i = 0; i < iterations + 1; i++){ current.add(tempIndex + 1 + i); } }} } } return subsetWith(current); }
f09de4bb-df96-4746-85e7-91d07929a22d
5
public ArrayList<Flight> cancelFlightsCorrectly(String airport) { ArrayList<Flight> temp = deepCopy(flights); for (int i = temp.size() - 1; i >= 0; i--) { if (temp.get(i).getDepartureAirport().equals(airport) || temp.get(i).getArrivalAirport().equals(airport)) { /* find the flight ID which is canceled at airport */ String flightId = temp.get(i).getIdentifier(); /* remove the entire path when flight identifier equals flightId */ for (int j = temp.size() - 1; j >= 0; j--) { if (temp.get(j).getIdentifier().equals(flightId)) { temp.remove(j); } } i = temp.size(); // update i; } } return temp; }
18d98464-e071-49b5-8834-5588fc22f508
2
private static void expandMoveRecursivelyForBlack(Board board, Vector<Vector<Move>> outerVector, Vector<Move> innerVector, int r, int c){ Vector<Move> forcedMoves = Black.ObtainForcedMovesForBlack(r, c, board); if(forcedMoves.isEmpty()){ Vector<Move> innerCopy = (Vector<Move>)innerVector.clone(); outerVector.add(innerCopy); return; }else{ for(Move m:forcedMoves){ Board boardCopy = board.duplicate(); boardCopy.genericMakeBlackMove(m); innerVector.add(m); expandMoveRecursivelyForBlack(boardCopy, outerVector, innerVector, m.finalRow, m.finalCol); innerVector.remove(m); } } }
5fd52bde-2204-4be3-8261-fa193b056f88
3
public boolean setSerialProbability(int jobType, double prob) { if(jobType > BATCH_JOBS || jobType < INTERACTIVE_JOBS) { return false; } if(useJobType_) { serialProb[jobType] = prob; } else { serialProb[INTERACTIVE_JOBS] = serialProb[BATCH_JOBS] = prob; } return true; }
e75d75bc-78fe-48de-8a40-0a4f3a064b68
9
public K findKey (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { K[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != null && valueTable[i] == null) return keyTable[i]; } else if (identity) { for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return keyTable[i]; } else { for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return keyTable[i]; } return null; }
f9bdc6ec-b6d3-40bf-b64f-73779571a0ac
4
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: String codforn, codpedido, data; int qtd; codforn = txt_codforn.getText(); codpedido = txt_codpedido.getText(); data = txt_datapedido.getText(); qtd = (int) sp_qtdprod.getValue(); if(codforn.isEmpty()|| codpedido.isEmpty()|| data.isEmpty() || qtd==0){ JOptionPane.showMessageDialog(rootPane, "Por favor, preencha todos os campos!!"); } }//GEN-LAST:event_jButton1ActionPerformed
bf87ef1b-8817-47cb-aff7-e35c92d9b6b9
6
private void checkIfBuildable(int sizeX, int sizeY) { for (int i = 0; i < sizeX; i++) { for (int j = 0; j < sizeY; j++) { try { if (map.getTile(mouseTileCoords.x + i, mouseTileCoords.y + j) == null || !map.getTile(mouseTileCoords.x + i, mouseTileCoords.y + j).isPassable() || map.getTile(mouseTileCoords.x + i, mouseTileCoords.y + j).getEnemy() != null) { buildable = false; return; } } catch (IndexOutOfBoundsException e) { buildable = false; return; } } } buildable = true; }
212ed8a2-6af5-4e85-be98-2e1863357846
1
protected void btnRemoverEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverEmailActionPerformed if(JOptionPane.showConfirmDialog(rootPane, "Você tem certeza que deseja" + " Remover o item ? ","",JOptionPane.OK_CANCEL_OPTION) == 0){ this.listaEmail.remove(this.emailParaRemover); carregaTabelaEmails(listaEmail); } }//GEN-LAST:event_btnRemoverEmailActionPerformed
7553c3b4-75bc-4e9c-8a73-9bdca6ad098f
7
private Vector[] buildHeaders(JPanel panel, ColumnSet set, boolean blankOut, Vector[] refLabels) { int numParents = set.getNumParents(); int numChildren = getNumChildren(set); Vector[] headers = new Vector[2]; headers[0] = new Vector(); for (int i=0; i<set.getNumParents(); i++) { ColumnParent parent = set.getParent(i); JLabel columnLabel = new JLabel(); int numColumns = parent.getNumChildren(); String text = parent.getText(); Color foreground = parent.getColor(); if (blankOut) { foreground = columnLabel.getBackground(); columnLabel.setMaximumSize(new Dimension(32000, 2)); if (refLabels != null) { JLabel refLabel = (JLabel) refLabels[0].get(i); columnLabel.setPreferredSize(new Dimension(refLabel.getPreferredSize().width, 2)); } } columnLabel.setText(text); columnLabel.setForeground(foreground); columnLabel.setHorizontalAlignment(SwingConstants.CENTER); GridBagConstraints constraints = getParentConstraints(numColumns, (i == (numParents - 1))); gridbag.setConstraints(columnLabel, constraints); panel.add(columnLabel); headers[0].add(columnLabel); } int index = 0; headers[1] = new Vector(); for (int i=0; i<set.getNumParents(); i++) { ColumnParent parent = set.getParent(i); int numColumns = parent.getNumChildren(); for (int j=0; j<numColumns; j++) { ColumnChild child = parent.getChild(j); JLabel columnLabel = new JLabel(); String text = child.getText(); Color foreground = child.getColor(); if (blankOut) { foreground = columnLabel.getBackground(); columnLabel.setMaximumSize(new Dimension(32000, 2)); if (refLabels != null) { JLabel refLabel = (JLabel) refLabels[1].get(index); columnLabel.setPreferredSize(new Dimension(refLabel.getPreferredSize().width, 2)); } } columnLabel.setText(text); columnLabel.setForeground(foreground); columnLabel.setHorizontalAlignment(SwingConstants.CENTER); GridBagConstraints constraints = getChildConstraints(index == (numChildren - 1)); gridbag.setConstraints(columnLabel, constraints); panel.add(columnLabel); headers[1].add(columnLabel); index++; } } return headers; }