method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
365ff292-493f-40a2-b6ef-bc07fb7caafe
5
public RandomListNode copyRandomList(RandomListNode head) { if (head == null) return null; RandomListNode p = head, p1; while (p != null) { p1 = new RandomListNode(p.label); p1.next = p.next; p.next = p1; p = p1.next; } p = head; while (p != null) { p1 = p.next; if (p.random != null) { p1.random = p.random.next; } p = p1.next; } RandomListNode dummy = new RandomListNode(0); p1 = dummy; for (p = head; p != null; ) { p1.next = p.next; p1 = p1.next; p = p1.next; } return dummy.next; }
c27be95f-ecca-4c38-9b42-34c62f493856
6
public List<java.util.LinkedList<Integer>> createDepthLinkedLists(TreeNode node){ if(node==null){ return null; } List<java.util.LinkedList<Integer>> linkedListList = new ArrayList<java.util.LinkedList<Integer>>(); Queue<TreeNode> nodeQueue = new ArrayDeque<TreeNode>(); nodeQueue.add(node); while(!nodeQueue.isEmpty()){ java.util.LinkedList<Integer> list = new java.util.LinkedList<Integer>(); Queue<TreeNode> innerQueue = new ArrayDeque<TreeNode>(); while(!nodeQueue.isEmpty()){ innerQueue.add(nodeQueue.poll()); } while(!innerQueue.isEmpty()){ TreeNode currentNode = innerQueue.poll(); list.add(currentNode.value); if(currentNode.left!=null){ nodeQueue.add(currentNode.left); } if(currentNode.right!=null){ nodeQueue.add(currentNode.right); } } linkedListList.add(list); } return linkedListList; }
8e75045c-5ac9-4922-a2b6-fb1fd5d2d5e0
5
public MatchResult match(EvaluationCtx context) { MatchResult result = null; // before matching, see if this target matches any request if (matchesAny()) return new MatchResult(MatchResult.MATCH); // first, try matching the Subjects section result = subjectsSection.match(context); if (result.getResult() != MatchResult.MATCH) { logger.finer("failed to match Subjects section of Target"); return result; } // now try matching the Resources section result = resourcesSection.match(context); if (result.getResult() != MatchResult.MATCH) { logger.finer("failed to match Resources section of Target"); return result; } // next, look at the Actions section result = actionsSection.match(context); if (result.getResult() != MatchResult.MATCH) { logger.finer("failed to match Actions section of Target"); return result; } // finally, match the Environments section result = environmentsSection.match(context); if (result.getResult() != MatchResult.MATCH) { logger.finer("failed to match Environments section of Target"); return result; } // if we got here, then everything matched return result; }
25cc50e8-dc15-4769-8311-4392d1f476f7
7
public Object [] getResultTypes() { int addm = (m_AdditionalMeasures != null) ? m_AdditionalMeasures.length : 0; int overall_length = RESULT_SIZE+addm; overall_length += NUM_IR_STATISTICS; overall_length += NUM_WEIGHTED_IR_STATISTICS; overall_length += NUM_UNWEIGHTED_IR_STATISTICS; if (getAttributeID() >= 0) overall_length += 1; if (getPredTargetColumn()) overall_length += 2; Object [] resultTypes = new Object[overall_length]; Double doub = new Double(0); int current = 0; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; // IR stats resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; // Unweighted IR stats resultTypes[current++] = doub; resultTypes[current++] = doub; // Weighted IR stats resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; // Timing stats resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; // sizes resultTypes[current++] = doub; resultTypes[current++] = doub; resultTypes[current++] = doub; // Prediction interval statistics resultTypes[current++] = doub; resultTypes[current++] = doub; // ID/Targets/Predictions if (getAttributeID() >= 0) resultTypes[current++] = ""; if (getPredTargetColumn()){ resultTypes[current++] = ""; resultTypes[current++] = ""; } // Classifier defined extras resultTypes[current++] = ""; // add any additional measures for (int i=0;i<addm;i++) { resultTypes[current++] = doub; } if (current != overall_length) { throw new Error("ResultTypes didn't fit RESULT_SIZE"); } return resultTypes; }
d8aad6e0-132d-4c03-b6fb-17f1e8ab1ec2
1
public boolean isFull() { return mChildren[0] != null && mChildren[1] != null; }
2acb7024-0e0d-4ca8-a220-0ba005f8522e
4
private static BufferedImage deriveBufferedImageFromTIFFBytes( InputStream in, Library library, int compressedBytes, int width, int height) { BufferedImage img = null; try { library.memoryManager.checkMemory(compressedBytes); /* com.sun.media.jai.codec.SeekableStream s = com.sun.media.jai.codec.SeekableStream.wrapInputStream( in, true ); ParameterBlock pb = new ParameterBlock(); pb.add( s ); javax.media.jai.RenderedOp op = javax.media.jai.JAI.create( "tiff", pb ); */ Object com_sun_media_jai_codec_SeekableStream_s = ssWrapInputStream.invoke(null, new Object[]{in, Boolean.TRUE}); ParameterBlock pb = new ParameterBlock(); pb.add(com_sun_media_jai_codec_SeekableStream_s); Object javax_media_jai_RenderedOp_op = jaiCreate.invoke(null, new Object[]{"tiff", pb}); /* * This was another approach: TIFFDecodeParam tiffDecodeParam = new TIFFDecodeParam(); // tiffDecodeParam.setDecodePaletteAsShorts(true); ImageDecoder dec = ImageCodec.createImageDecoder("TIFF", s, tiffDecodeParam ); NullOpImage op = new NullOpImage( dec.decodeAsRenderedImage(0), null, null, OpImage.OP_IO_BOUND ); // RenderedImage img = dec.decodeAsRenderedImage(); // RenderedImageAdapter ria = new RenderedImageAdapter(img); // BufferedImage bi = ria.getAsBufferedImage(); */ if (javax_media_jai_RenderedOp_op != null) { library.memoryManager.checkMemory( Math.max(compressedBytes * 60, (int) (width * height * 0.15))); // This forces the image to decode, so we can see if that fails, // and then potentially try a different compression setting /* op.getTile( 0, 0 ); */ RenderedImage ri = (RenderedImage) javax_media_jai_RenderedOp_op; Raster r = ri.getTile(0, 0); // Calling op.getAsBufferedImage() causes a spike in memory usage // For example, for RenderedOp that's 100KB in size, we spike 18MB, // with 1MB remaining and 17MB getting gc'ed // So, we try to build it piecemeal instead //System.out.println("Memory free: " + Runtime.getRuntime().freeMemory() + ", total:" + Runtime.getRuntime().totalMemory() + ", used: " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())); if (r instanceof WritableRaster) { library.memoryManager.checkMemory(1024); ColorModel cm = ri.getColorModel(); img = new BufferedImage(cm, (WritableRaster) r, false, null); } else { library.memoryManager.checkMemory((int) (width * height * 2.5)); /* img = op.getAsBufferedImage(); */ img = (BufferedImage) roGetAsBufferedImage.invoke(javax_media_jai_RenderedOp_op, new Object[]{}); } } } catch (Throwable e) { img = null; logger.log(Level.FINE, "deriveBufferedImageFromTIFFBytes() : Could not derive image from data bytes: ", e); } finally { try { in.close(); } catch (IOException e) { } } return img; }
915bb894-8a9b-427a-8ec8-f58da9b34556
6
public List<Integer> rightSideView(TreeNode root) { if (root == null) return new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); List<Integer> ret = new ArrayList<>(); while (!queue.isEmpty()) { int size = queue.size(); for (int i=0; i<size; i++) { TreeNode t = queue.remove(); if (i==0) ret.add(t.val); if (t.right != null) queue.add(t.right); if (t.left != null) queue.add(t.left); } } return ret; }
58509a3b-6dbc-4d19-886c-7cc9f3ad386f
2
public void Start() { ServerSocket serverSocket = null; Socket socket = null; try { serverSocket = new ServerSocket(7777); System.out.println(" ۵Ǿϴ."); ServerSender sender = new ServerSender(); // sender sender.start(); // ϳ ϱ . (receiver Ŭ̾Ʈ ŭ ) while (true) { socket = serverSocket.accept(); // Ŭ̾Ʈ û ٸ ServerReceiver receiver = new ServerReceiver(socket); // , Ŭ̾Ʈ ϳ . receiver.start(); } } catch (Exception e) { e.printStackTrace(); } } // start()
60f9e09e-ebe4-430b-a994-0c2efc8b2d73
0
public void popReturnAddrs() { pc = returnAddrs.pop(); }
ac4a7e64-8ce6-48e9-af95-cff1f0e7fdb5
0
public static void setUsers(Map<String, UserEntity> users) { Scheduler.users = users; }
a1a48dab-0430-4dd2-9117-e25bb167b112
9
private void postPlugin(final boolean isPing) throws IOException { // The plugin's description file containg all of the plugin data such as name, version, author, etc final PluginDescriptionFile description = plugin.getDescription(); // Construct the post data final StringBuilder data = new StringBuilder(); data.append(encode("guid")).append('=').append(encode(guid)); encodeDataPair(data, "version", description.getVersion()); encodeDataPair(data, "server", Bukkit.getVersion()); encodeDataPair(data, "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)); encodeDataPair(data, "revision", String.valueOf(REVISION)); // If we're pinging, append it if (isPing) { encodeDataPair(data, "ping", "true"); } // Acquire a lock on the graphs, which lets us make the assumption we also lock everything // inside of the graph (e.g plotters) synchronized (graphs) { final Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { final Graph graph = iter.next(); for (Plotter plotter : graph.getPlotters()) { // The key name to send to the metrics server // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME final String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName()); // The value to send, which for the foreseeable future is just the string // value of plotter.getValue() final String value = Integer.toString(plotter.getValue()); // Add it to the http post data :) encodeDataPair(data, key, value); } } } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(plugin.getDescription().getName()))); // Connect to the website URLConnection connection; // Mineshafter creates a socks proxy, so we can safely bypass it // It does not reroute POST requests so we need to go around it if (isMineshafterPresent()) { connection = url.openConnection(Proxy.NO_PROXY); } else { connection = url.openConnection(); } connection.setDoOutput(true); // Write the data final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data.toString()); writer.flush(); // Now read the response final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final String response = reader.readLine(); // close resources writer.close(); reader.close(); if (response == null || response.startsWith("ERR")) { throw new IOException(response); //Throw the exception } else { // Is this the first update this hour? if (response.contains("OK This is your first update this hour")) { synchronized (graphs) { final Iterator<Graph> iter = graphs.iterator(); while (iter.hasNext()) { final Graph graph = iter.next(); for (Plotter plotter : graph.getPlotters()) { plotter.reset(); } } } } } }
7d125a2c-1edd-486e-9666-4989eead2197
5
public void send(DataOutputStream outputStream)throws Exception{ //send tanks Tank s; //outputStream.writeUTF("$tank$"); outputStream.writeInt(tanks.size()); for(Map.Entry<Integer, Tank> entry : tanks.entrySet()){ s = entry.getValue(); outputStream.writeInt(entry.getKey()); //it's a id of the tank which we send outputStream.writeInt(s.id_tank); outputStream.writeInt(s.id_armor); outputStream.writeInt(s.id_engine); outputStream.writeInt(s.id_first_weapon); outputStream.writeInt(s.id_second_weapon); outputStream.flush(); } outputStream.flush(); //send armor //outputStream.writeUTF("$armor$"); outputStream.writeInt(armorsID.size()); for(Integer entry : armorsID){ outputStream.writeInt(entry); } outputStream.flush(); //send engine //outputStream.writeUTF("$engine$"); outputStream.writeInt(enginesID.size()); for(Integer entry : enginesID){ outputStream.writeInt(entry); } outputStream.flush(); //send first weapon //outputStream.writeUTF("$first_weapon$"); outputStream.writeInt(firstWeaponID.size()); for(Integer entry : firstWeaponID){ outputStream.writeInt(entry); } outputStream.flush(); //send second weapon //outputStream.writeUTF("$second_weapon$"); outputStream.writeInt(secondWeaponID.size()); for(Integer entry : secondWeaponID){ outputStream.writeInt(entry); } outputStream.flush(); }
43246730-9996-4e1c-a32d-98cb5b261227
0
@Override public void applyTemporaryToCurrent(){cur = new Color(tmp.getRGB());}
6c2dc72f-ef05-43b7-843c-0930a4bc6438
3
private void btnSwitchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSwitchActionPerformed AdministradorCRUD adao = new AdministradorCRUD(MyConnection.getConnection()); if(btnSwitch.getText().equals("Actualizar")){ Administrador admin = new Administrador( edtUserName.getText().toString(), jtxtPass.getText().toString(), edtDNI.getText().toString() ); if(adao.update(admin)){ JOptionPane.showMessageDialog( this, "Registro Guardado Con exito!!!", "Notificación", JOptionPane.INFORMATION_MESSAGE ); } }else{ Administrador admin = new Administrador( edtUserName.getText().toString(), jtxtPass.getText().toString(), edtDNI.getText().toString() ); if(adao.add(admin)){ JOptionPane.showMessageDialog( this, "Registro Guardado Con exito!!!", "Notificación", JOptionPane.INFORMATION_MESSAGE ); clearForm(); } } }//GEN-LAST:event_btnSwitchActionPerformed
6f6e778f-1c55-41fe-8343-4d852556c61d
9
public static boolean confirmChanges(List<Path> filesToCopy, List<Path> filesToDelete, int charsToDisplay, Path outputPath) { if (filesToCopy.isEmpty() && filesToDelete.isEmpty()) { System.out.println("There are no changes."); return true; } else { System.out.println("There are changes to sync "); if (filesToCopy.isEmpty()) { System.out.println("There are no files to copy"); } else { System.out.println("Files to copy: "); for(Path path: filesToCopy) { String filePath = HelperMethods.truncate(charsToDisplay, path); System.out.println(filePath); } } if (filesToDelete.isEmpty()) { System.out.println("There are no files to delete"); } else { System.out.println("Files to delete: "); for(Path path: filesToDelete) { Path relativePath = outputPath.relativize(path); String filePath = HelperMethods.truncate(charsToDisplay, relativePath); System.out.println(filePath); } } System.out.println("There are total " +filesToCopy.size()+" file(s) to copy and " + filesToDelete.size()+" file(s) to delete" ); System.out.println("Execute changes? [Y/N] ..."); char input = 0; do { try { input = (char) System.in.read(); } catch (IOException e) { e.printStackTrace(); } } while (!"Y".equalsIgnoreCase(String.valueOf(input)) && !"N".equalsIgnoreCase(String.valueOf(input))); return "y".equalsIgnoreCase(String.valueOf(input)); } }
eca759f7-d4cb-4f65-bebe-1ad4696888e8
1
@Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Add Keyword")) { } }
485bcb12-91c6-48ee-b1cc-9c32b760bd82
7
public static int connect(int a[], int al, int ar, int b[], int bl, int br) { int max = 0; for (int i = al; i <= ar; i++) { int j = find(b, bl, br, a[i]); if (j == -1) continue; int n = 0; if (i - 1 >= 0 && j - 1 >= 0) n += connect(a, al, i - 1, b, bl, j - 1); if (i + 1 < a.length && j + 1 < b.length) n += connect(a, i + 1, ar, b, j + 1, br); if (max < n + 1) max = n + 1; } return max; }
3ee4a833-c0f7-49ef-ae6e-ba4728518e3e
0
public void setPersonApplicantions(PersonApplication personApplicantions) { PersonApplications.add(personApplicantions); }
f063e70e-907e-4e72-bb42-7e7d761d1f9c
4
@Override public <T> void deleteObject(Class<T> clazz, Long id) { Session session = null; try{ session = sessionFactory.getCurrentSession(); session.beginTransaction(); T obj = (T)session.get(clazz, id); session.delete(obj); session.getTransaction().commit(); }catch(RuntimeException e){ try{ session.getTransaction().rollback(); }catch(RuntimeException rbe){ } throw e; } finally{ if (session != null && session.isOpen()){ session.close(); } } }
c5aaf454-264e-4a75-936d-0222e5b1606c
2
public void filtrarEstrategias(){ for(int i=0;i<contenedorEstrategia.getEstrategias().size();i++){ System.out.println(contenedorEstrategia.getEstrategias().get(i).server+" "+serverTF.getText()); if(!contenedorEstrategia.getEstrategias().get(i).server.equals(serverTF.getText())){ contenedorEstrategia.getEstrategias().remove(i); i--; } } }
0965e91f-6513-443d-ba25-2449f8540b8c
0
protected int processSortInfo (byte[] sortInfo) { // TBD // if (Outliner.DEBUG) { System.out.println("\tStan_Debug:\tPdbReaderWriter:processSortInfo"); } return SUCCESS ; } // end protected method processSortInfo;
1009828d-72d9-46ca-a4dd-2dff37d77359
3
private BitSet checkArcs( ListIterator<Arc> iter, String type ) throws MVDException { BitSet bs = new BitSet(); while ( iter.hasNext() ) { Arc a = iter.next(); BitSet v = a.versions; for ( int i=v.nextSetBit(0);i>=0;i=v.nextSetBit(i+1) ) { if ( bs.nextSetBit(i)==i ) throw new MVDException("Version " +i+" present twice in "+type+" set"); bs.set( i ); } } return bs; }
5b8723f9-09a1-4b57-9d4d-cb2cdb4308e2
4
public void setColumnData(int i, Object value) throws Exception { if (i == 0) personID = (String) value; else if (i == 1) name = (String) value; else if (i == 2) projectID = (String) value; else if (i == 3) role = (String) value; else throw new Exception("Error: invalid column index in courselist table"); }
0827164d-1b70-4353-a24d-9f310b4109a9
8
private Point fisica(float dt, float x, float y, int diametro) { x += vx; y += vy; if (vx < 0 && x <= 0 || vx > 0 && x + diametro >= getWidth()) vx = -vx; if (vy < 0 && y < 0 || vy > 0 && y + diametro >= getHeight()) vy = -vy; return new Point(Math.round(x), Math.round(y)); }
086f7dd9-6838-43ec-b6c3-5e7183edb594
7
public static Field randomReachableField(Field from, HashMap<Field, ArrayList<Object>> conflictingHashMap, ArrayList<Field> shouldGetCleared) { LinkedList<Field> frontier = new LinkedList<Field>(); frontier.add(from); ArrayList<Field> closedSet = new ArrayList<Field>(); Field currentField = frontier.poll(); closedSet.add(currentField); while(currentField != null){ for (Field neighbour : currentField.neighbors) { if(neighbour != null && !closedSet.contains(neighbour) && (!conflictingHashMap.containsKey(neighbour) || (conflictingHashMap.containsKey(neighbour) && conflictingHashMap.get(neighbour).contains(from)))){ frontier.add(neighbour); closedSet.add(neighbour); } } currentField = frontier.poll(); } Random rand = new Random(); return closedSet.get(rand.nextInt(closedSet.size())); }
260fe62c-f96f-4a3d-ad00-dce2cd04709d
8
public void drawObjects(Graphics g){ g.drawImage(bg, 0, 0); int x=75; int y=50; for(int j=0; j<4; j++){ for(int i=0; i<10; i++){ if((j*10)+i < objectList.size()){ if( objectList.get((j*10)+i) != null){ if(objectList.get((j*10)+i).itemClass==1){ g.drawImage(objectList.get((j*10)+i).getImg(), x+5, y+5); if(((Equipable)objectList.get((j*10)+i)).equipped){ g.drawImage(equip, x,y); } }else{ g.drawImage(objectList.get((j*10)+i).getImg(), x+5, y+5); } } } if(selected==(j*10)+i){ if(isSelected){ g.drawImage(inBox3,x,y); }else{ g.drawImage(inBox2,x,y); } }else{ g.drawImage(inBox,x,y); } x+=50; } x=75; y+=50; } }
89a12466-a609-46ff-bf03-f7e270a22374
5
public void printTopTerms(int n) { List<String> seen = new ArrayList<String>(); for (int i=0; i<n; i++) { double highest = 0; String base = ""; for (Map.Entry<String, Double> e : termScore.entrySet()) { if (!seen.contains(e.getKey()) && e.getValue() > highest) { highest = e.getValue(); base = e.getKey(); } } seen.add(base); } for (String term: seen) { System.out.println(term); } }
b62c31dd-4309-4a61-ac83-9789881929fb
0
public void test(){ System.out.println("HeadCount : "+getH()+" TailCount : "+getT()); }
25009eaf-f10a-4de2-a2f6-4a5e309a2ba1
7
public List<String> userService(String userName, String userType) { List<String> serviceList = new Vector<String>(); String currentLine; StringTokenizer strTk; BufferedReader br = getFileReader(); if(br == null) { System.err.println("Error opening file"); System.exit(1); } try { //Read until the end of file while ((currentLine = br.readLine()) != null) { if(currentLine.isEmpty()) break; strTk = new StringTokenizer(currentLine); //read services only for the received user if (strTk.nextElement().equals(userName)) { if(!strTk.nextElement().equals(userType)) { break; } while (strTk.hasMoreTokens()) { serviceList.add(strTk.nextToken()); } break; } } br.close(); } catch (IOException e) { System.err.println("Error reading database file"); e.printStackTrace(); } return serviceList; }
240261f0-8ba7-40b3-bbee-f5d9cbf4a8cc
3
@Override public boolean getDebugMode() { Object[] buttons = {"Debug mode", "Play Normally"}; int userInput = JOptionPane.showOptionDialog(null, "Would you like to use debug mode? \n (This will display all game-states at every update.)", "Quantum Werewolves", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, buttons, buttons[1]); switch(userInput){ case JOptionPane.YES_OPTION : return true; case JOptionPane.NO_OPTION : return false; case JOptionPane.CLOSED_OPTION : System.exit(0); return false; } return false; }
6efbbc9e-cf92-48e8-ac8a-15524cdd7246
0
@After public void tearDown() { }
22f0b074-25fa-49d7-a5d3-786c9f09e92b
8
public void onKeyPressed(KeyEvent e) { switch (e.getKeyCode()) { case VK_UP: case VK_W: directions.add(Direction.UP); break; case VK_DOWN: case VK_S: directions.add(Direction.DOWN); break; case VK_RIGHT: case VK_D: directions.add(Direction.RIGHT); break; case VK_LEFT: case VK_A: directions.add(Direction.LEFT); break; } }
ffe10595-7f14-4d95-acbd-6094a132d5d7
4
public static void main(String[] args) { final int MAX_STUDENTS = 50, MAX_SUBJECTS = 3; int[][] marks = new int[MAX_STUDENTS][MAX_SUBJECTS]; // generate data into the marks for (int studentID = 0; studentID < MAX_STUDENTS; studentID++) { for (int subjectID = 0; subjectID < MAX_SUBJECTS; subjectID++) { marks[studentID][subjectID] = (int) (Math.random() * 20); } } // print marks for (int studentID = 0; studentID < MAX_STUDENTS; studentID++) { System.out.println("Student #" + studentID); for (int subjectID = 0; subjectID < MAX_SUBJECTS; subjectID++) { System.out.println("\tSubject # " + subjectID + " : " + marks[studentID][subjectID]); } } }
91797e76-d9cc-4286-9cc8-acba56122494
4
@Override public Value evaluate(Value... operands) throws Exception { // we need two operands if (operands.length != input()) throw new EvalException("Error: wrong number of operands"); // get operands Value l = operands[0]; Value r = operands[1]; // if they are identical if (l.getType().isNumeric() && r.getType().isNumeric()) { // perform OR return new Value(new Boolean(l.getDouble() != r.getDouble())); } // if they are identical if (l.getType() == r.getType()) { // perform OR return new Value(new Boolean(!l.getData().equals(r.getData()))); } return new Value(new Boolean(true)); }
ed104cda-d91b-4ec7-9910-37212aecc0e5
5
static void move(int[][] board, int x, int y, int dx, int dy, int n, int m) { while (true) { if (board[x][y] == 0) { break; } int tox = x + dx; int toy = y + dy; if (!inside(tox, toy, n, m)) { break; } if (board[tox][toy] == 0) { board[tox][toy] = board[x][y]; board[x][y] = 0; x = tox; y = toy; } else if (board[tox][toy] == board[x][y]) { board[tox][toy] = -board[x][y] * 2; board[x][y] = 0; break; } else { break; } } }
65882fe1-c920-46ae-a703-3dabacda5422
6
public boolean assignUser(int idUser) { Action pick = new Action(idUser, true); Action drop = new Action(idUser, false); if (size() == 0) { // Agregarse a sí mismo add(pick); add(drop); } else { // Agregar otros usuarios add(1, pick); //Agregar la recogida del nuevo como primer paso int carrying = 1; for (int i = 2; i < size(); ++i) { carrying += (get(i).isPickup ? 1 : -1); if (i == (size() -1) || carrying == 4) { add(i, drop); break; } } } if (!updateDistance()) { deassignUser(idUser); return false; } return true; }
f7f15694-6ef9-49e1-997d-f8ec9d38afb2
1
@Test public void RussianName() throws Exception { LoginCheck logCh = new LoginCheck(); name = "Вася585"; if (kesh.containsKey(name)) { assertFalse(kesh.get(name)); } else { boolean result = logCh.validate(name); kesh.put(name, result); assertFalse(result); } }
0924b0b7-af67-4684-94ef-82f3ee426253
4
@Override public void undo() { if (prevSpeed == CeilingFan.HIGH) { ceilingFan.high(); } if (prevSpeed == CeilingFan.MEDIUM) { ceilingFan.medium(); } if (prevSpeed == CeilingFan.LOW) { ceilingFan.low(); } if (prevSpeed == CeilingFan.OFF) { ceilingFan.off(); } }
799601cf-2c6a-4165-9c20-0d725e0df8a2
3
public Command getCommand() { String inputLine; // will hold the full input line String word1 = null; String word2 = null; System.out.print("> "); // print prompt inputLine = reader.nextLine(); // Find up to two words on the line. Scanner tokenizer = new Scanner(inputLine); if(tokenizer.hasNext()) { word1 = tokenizer.next(); // get first word if(tokenizer.hasNext()) { word2 = tokenizer.next(); // get second word // note: we just ignore the rest of the input line. } } // Now check whether this word is known. If so, create a command // with it. If not, create a "null" command (for unknown command). if(commands.isCommand(word1)) { return new Command(word1, word2); } else { return new Command(null, word2); } }
630bdbad-a6af-4ce7-b58d-023d4b05e491
4
@Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) { this.rotation = CharRotation.UP; Helper.moveIfPossible(this, x, y - 1); Helper.eatFlowerIfCollided(this); } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { this.rotation = CharRotation.DOWN; Helper.moveIfPossible(this, x, y + 1); Helper.eatFlowerIfCollided(this); } else if (e.getKeyCode() == KeyEvent.VK_LEFT) { this.rotation = CharRotation.LEFT; Helper.moveIfPossible(this, x - 1, y); Helper.eatFlowerIfCollided(this); } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { this.rotation = CharRotation.RIGHT; Helper.moveIfPossible(this, x + 1, y); Helper.eatFlowerIfCollided(this); } }
e3ca9151-fb55-405c-a293-c31510aafc1f
3
public void sortScoreInfo() { int i = 0, j = 0; String temp = ""; for(i = 0; i < users.size(); i++) { for(j = i; j < users.size(); j++) { if(Double.parseDouble(highScores.get(i)) < Double.parseDouble(highScores.get(j)) ) { temp = users.get(i); users.set(i, users.get(j)); users.set(j, temp); temp = highScores.get(i); highScores.set(i, highScores.get(j)); highScores.set(j, temp); temp = times.get(i); times.set(i, times.get(j)); times.set(j, temp); temp = difficulties.get(i); difficulties.set(i, difficulties.get(j)); difficulties.set(j, temp); temp = sizes.get(i); sizes.set(i, sizes.get(j)); sizes.set(j, temp); } } } }
644b9c51-675a-4c7b-8a57-afc4c890e3b6
9
public void testClosedPoolBehavior() throws Exception { final ObjectPool pool; try { pool = makeEmptyPool(new MethodCallPoolableObjectFactory()); } catch (UnsupportedOperationException uoe) { return; // test not supported } Object o1 = pool.borrowObject(); Object o2 = pool.borrowObject(); pool.close(); try { pool.addObject(); fail("A closed pool must throw an IllegalStateException when addObject is called."); } catch (IllegalStateException ise) { // expected } try { pool.borrowObject(); fail("A closed pool must throw an IllegalStateException when borrowObject is called."); } catch (IllegalStateException ise) { // expected } // The following should not throw exceptions just because the pool is closed. if (pool.getNumIdle() >= 0) { assertEquals("A closed pool shouldn't have any idle objects.", 0, pool.getNumIdle()); } if (pool.getNumActive() >= 0) { assertEquals("A closed pool should still keep count of active objects.", 2, pool.getNumActive()); } pool.returnObject(o1); if (pool.getNumIdle() >= 0) { assertEquals("returnObject should not add items back into the idle object pool for a closed pool.", 0, pool.getNumIdle()); } if (pool.getNumActive() >= 0) { assertEquals("A closed pool should still keep count of active objects.", 1, pool.getNumActive()); } pool.invalidateObject(o2); if (pool.getNumIdle() >= 0) { assertEquals("invalidateObject must not add items back into the idle object pool.", 0, pool.getNumIdle()); } if (pool.getNumActive() >= 0) { assertEquals("A closed pool should still keep count of active objects.", 0, pool.getNumActive()); } pool.clear(); pool.close(); }
a8eddc21-d352-44de-b8ee-3936675a7e29
0
public List<String> getPermissionCommand() { return config.getStringList("ArenaOption.PermissionCommands"); }
66b487c3-6c74-41b5-8f12-0268b6b82827
0
public String getSintoma() { return sintoma; }
c6144a1e-fa60-4129-b7e3-50b399bc11a1
1
@Override public void run() { for (i=0; i <= aantal; i++){ System.out.print(letter); } }
30a6b619-6efb-4202-9286-485e5c9edad4
3
@Test @Ignore public void testCycles() { if (jdepend.containsCycles()) { StringBuilder sb = new StringBuilder( "The following packages contain cycles which should be removed."); for (Object element : jdepend.getPackages()) { JavaPackage pack = (JavaPackage) element; if (pack.containsCycle()) { /* * Append chars to avoid instantiating strings. * * Micro-optimisation in a test class _is_ ridiculous, don't * you think? You are allowed to laugh at me on this one. */ sb.append('\n').append('\t').append(pack.getName()); } } log.warn(sb.toString()); fail(); } else { log.info("No package cycle detected."); } }
e6cdf145-3d54-4560-ad2c-6419b686e7aa
7
public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYSeries)) { return false; } if (!super.equals(obj)) { return false; } XYSeries that = (XYSeries) obj; if (this.maximumItemCount != that.maximumItemCount) { return false; } if (this.autoSort != that.autoSort) { return false; } if (this.allowDuplicateXValues != that.allowDuplicateXValues) { return false; } if (!ObjectUtilities.equal(this.data, that.data)) { return false; } return true; }
f1f08485-d5b0-49cc-904e-40c5f42b8283
9
private ArrayList<ServerMessage> updateConvo(String message) { ArrayList<ServerMessage> messageList = new ArrayList<ServerMessage>(); //Parse the message data into appropriate fields boolean convo_id = false; StringBuilder ci = new StringBuilder(); boolean user = false; StringBuilder un = new StringBuilder(); boolean text = false; StringBuilder msg = new StringBuilder(); for (String token: message.split(" ")) { //find convo_id tokens and make the convo-id if (convo_id && !token.equals("-u")) { ci.append(token); ci.append(" "); //find username token } else if (user && !token.equals("-t")) { un.append(token); //find text tokens and make the message String } else if (text) { msg.append(token); msg.append(" "); } //start looking for convo_id if (token.equals("-c")) { convo_id = true; //start looking for username } else if (token.equals("-u")) { convo_id = false; user = true; //start looking for text } else if (token.equals("-t")) { user = false; text = true; } } messageList.add(new ServerMessage(everyoneInConvoButMe(ci.toString(), un.toString()), message, this)); return messageList; }
f41eeb5f-6174-43bf-bf72-d0d848cf07b2
2
public int reduceHealth(int damage) { health = health - damage; if(health <= 0) { health = 0; dead = true; } if(health > maxHealth) { health = maxHealth; } return health; }
8576b302-a4d3-4ed2-b7d3-4003e1be231f
8
private static int pivot(int[] a, int low, int high) { int i1 = low, i2 = high - 1, i3 = (low + high) / 2; int a1 = a[i1], a2 = a[i2], a3 = a[i3]; int n = (a1 > a2) ? a1 : a2; int m = (a2 > a3) ? a2 : a3; if (m > n) { return (a1 > a2) ? i1 : i2; } else if (n > m) { return (a2 > a3) ? i2 : i3; } else if (n == m) { return (a1 > a3) ? i1 : i3; } return -1; }
e92f6e09-cbbe-4fdb-bef5-9c059dca0509
8
private Map<String, Element> gatherCCSSResults() { Map<String, Element> results = new HashMap<>(); String sql = "SELECT " + " MSP.projectID " + ", MSP.siteID, BS.disname, BS.schname " + ", BC.gradeLevel " + ", BC.subjectArea " + "FROM `bank_collector` AS BC " + "LEFT JOIN `map_sample_collector` AS MSC ON MSC.collectorID = BC.id " + "LEFT JOIN map_collector_site MCS ON MCS.collectorID = MSC.collectorID " + "LEFT JOIN map_site_project MSP ON MSP.siteID = MCS.siteID " + "LEFT JOIN bank_site AS BS ON BS.id = MSP.siteID " + "WHERE BS.active = 'y' " + "AND MSP.active = 'y' " + "AND MCS.active = 'y' " + "AND MSC.active = 'y' " + "AND BC.active = 'y' " + "AND MSP.projectID = 23401520791814151 " + "GROUP BY BS.disname, BS.schname, BC.gradeLevel, BC.subjectArea " + "ORDER BY BS.disname, BS.schname, BC.gradeLevel, BC.subjectArea "; ResultSet rs = DM.Execute(sql); String curSiteID = ""; String curGradeLevel = ""; String curSubjectArea = ""; String curProjectID = ""; boolean start = false; Element curSchool = null; Element curGrade = null; Element curSubject = null; Element holder = base.CreateSection("School Results"); try { rs.beforeFirst(); while (rs.next()) { curProjectID = rs.getString("projectID"); // Initial NULL cases if (curSchool == null) { curSiteID = rs.getString("siteID"); curSchool = base.CreateSection(rs.getString("schname")); curSchool.appendChild(base.PullExternal(props.getProperty("file.inbase") + "insert_files/CCSS_filler.txt")); System.out.println("\nSchool: " + rs.getString("schname")); } if (curGrade == null) { curGradeLevel = rs.getString("gradeLevel"); curGrade = base.CreateSection("Grade " + rs.getString("gradeLevel")); curGrade.setAttribute("bump", "true"); curGrade.appendChild(base.PullExternal(props.getProperty("file.inbase") + "insert_files/grade_filler.txt")); System.out.println("\tGrade: " + rs.getString("gradeLevel")); curGrade.appendChild( base.Base().ImportFragmentString( createChart( "Grade Level Analysis" , curProjectID , curSiteID , curGradeLevel , "gla" ) ) ); curGrade.appendChild( base.Base().ImportFragmentString( createTable( curProjectID , curSiteID , curGradeLevel , curSubjectArea ) ) ); } if (curSubject == null) { curSubjectArea = rs.getString("subjectArea"); curSubject = base.CreateSection(rs.getString("subjectArea")); curSubject.appendChild(base.PullExternal(props.getProperty("file.inbase") + "insert_files/subject_filler.txt")); System.out.println("\tSubject: " + rs.getString("subjectArea")); } // Running checks if (!curSubjectArea.equals(rs.getString("subjectArea"))) { curGrade.appendChild(curSubject); curSubject = base.CreateSection(rs.getString("subjectArea")); curSubject.appendChild(base.PullExternal(props.getProperty("file.inbase") + "insert_files/subject_filler.txt")); System.out.println("\t\tSubject area: " + rs.getString("subjectArea")); System.out.println("\t\t[Generate CR for " + rs.getString("subjectArea") +"]"); curGrade.appendChild( base.Base().ImportFragmentString( createChart( String.format("Cognitive Rigor: %s (Grade %s)",curSubjectArea , curGradeLevel) , curProjectID , curSiteID , curGradeLevel , curSubjectArea) ) ); curGrade.appendChild( base.Base().ImportFragmentString( createTable( curProjectID , curSiteID , curGradeLevel , curSubjectArea ) ) ); } if (!curGradeLevel.equals(rs.getString("gradeLevel"))) { curGrade.appendChild(curSubject); curSchool.appendChild(curGrade); curGrade = base.CreateSection("Grade " + rs.getString("gradeLevel")); curGrade.setAttribute("bump", "true"); curGrade.appendChild(base.PullExternal(props.getProperty("file.inbase") + "insert_files/grade_filler.txt")); System.out.println("\tGrade level: " + rs.getString("gradeLevel")); curGrade.appendChild( base.Base().ImportFragmentString( createChart( "Grade Level Anlaysis" , curProjectID , curSiteID , curGradeLevel , "gla") ) ); curGrade.appendChild( base.Base().ImportFragmentString( createTable( curProjectID , curSiteID , curGradeLevel , curSubjectArea ) ) ); } if (!curSiteID.equals(rs.getString("siteID"))) { curGrade.appendChild(curSubject); curSchool.appendChild(curGrade); holder.appendChild(curSchool); curSchool = base.CreateSection(rs.getString("schname")); curSchool.appendChild(base.PullExternal(props.getProperty("file.inbase") + "insert_files/CCSS_filler.txt")); curSchool.setAttribute("bump", "true"); System.out.println("\nSchool: " + rs.getString("schname")); } curSiteID = rs.getString("siteID"); curGradeLevel = rs.getString("gradeLevel"); curSubjectArea = rs.getString("subjectArea"); } curGrade.appendChild(curSubject); curSchool.appendChild(curGrade); holder.appendChild(curSchool); } catch (SQLException ex) { Logger.getLogger(CCSS_builder.class.getName()).log(Level.SEVERE, null, ex); } results.put("data", holder); return results; }
ebf3a586-20be-4714-aa03-e284a005dda0
7
public void DBUpdateFollowers(MOB mob) { if((mob==null)||(mob.Name().length()==0)) return; final List<DBPreparedBatchEntry> statements=new LinkedList<DBPreparedBatchEntry>(); statements.add(new DBPreparedBatchEntry("DELETE FROM CMCHFO WHERE CMUSERID='"+mob.Name()+"'")); for(int f=0;f<mob.numFollowers();f++) { final MOB thisMOB=mob.fetchFollower(f); if((thisMOB!=null) &&(thisMOB.isMonster()) &&(!thisMOB.isPossessing()) &&(CMLib.flags().isSavable(thisMOB))) { CMLib.catalog().updateCatalogIntegrity(thisMOB); final String sql="INSERT INTO CMCHFO (CMUSERID, CMFONM, CMFOID, CMFOTX, CMFOLV, CMFOAB" +") values ('"+mob.Name()+"',"+f+",'"+CMClass.classID(thisMOB)+"',?," +thisMOB.basePhyStats().level()+","+thisMOB.basePhyStats().ability()+")"; statements.add(new DBPreparedBatchEntry(sql,thisMOB.text()+" ")); } } DB.updateWithClobs(statements); }
2b44fe77-82fd-4b1f-8f43-a7e3dd60f804
5
public static String checkBanned(String ip) throws UnknownHostException { String query = "SELECT * FROM `" + mysql_db +"`.`banlist`"; try (Connection con = getConnection(); PreparedStatement pst = con.prepareStatement(query)) { ResultSet r = pst.executeQuery(); while (r.next()) { String decIP = r.getString("ip"); if (decIP.contains("*")) { if (Functions.inRange(ip, decIP)) return decIP; } else if (decIP.equals(ip)) return decIP; } return null; } catch (SQLException e) { e.printStackTrace(); logMessage(LOGLEVEL_IMPORTANT, "Could not check ban."); return null; } }
acae2ae9-04f3-496f-9688-e778f2a0cce4
7
@Override public void doPost( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException { String gameIdString = req.getParameter( "gameid" ); String playerIdString = req.getParameter( "playerid" ); BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); Map<String, List<BlobKey>> blobs = blobstoreService.getUploads( req ); List<BlobKey> keys = blobs.get("photo"); Map<String, List<BlobInfo>> blobInfos = blobstoreService.getBlobInfos( req ); List<BlobInfo> infos = blobInfos.get( "photo" ); boolean succeeded = false; if( null != keys && keys.size() > 0 ) { Long gameId = Long.parseLong( gameIdString ); Long playerId = Long.parseLong( playerIdString ); AutoChallengeGameEndpoint gameEndpoint = new AutoChallengeGameEndpoint(); AutoChallengeGame game = gameEndpoint.getAutoChallengeGame( gameId ); String fileName; if( null != infos && infos.size() > 0 ) { fileName = infos.get( 0 ).getFilename(); } else { fileName = gameId + "_" + String.valueOf(System.currentTimeMillis()); } BlobKey blobKey = keys.get( 0 ); for( Challenge oneChallenge : game.getChallenges() ) { if( playerId.equals( oneChallenge.getPlayerId() ) ) { oneChallenge.setResponseBlobKey( blobKey ); oneChallenge.setResponseBucketName( BlobUtil.BUCKET_NAME_CHALLENGE_RESPONSES ); oneChallenge.setResponseFileName( fileName ); oneChallenge.setResponseSourceUrl( null ); oneChallenge.setResponseSourceTitle( null ); break; } } gameEndpoint.updateAutoChallengeGame( game ); succeeded = true; } if( succeeded ) { resp.setStatus( HttpServletResponse.SC_OK ); } else { resp.sendError( 400, "Photo uplaod cannot be handled" ); } }
04601fb4-9efe-4723-a1c0-0fc29065e259
7
public void SmartIDCardInserted(CardActionEvents ce) { System.out.println("Inserted SmartID card."); long timeElapsed = 0; try { BasicService service = ce.getService(); service.open(); Reader reader = new Reader(); if (service != null) { PasswdEnterDialog passwd = new PasswdEnterDialog(reader, "SmartID card Reader"); timeElapsed = System.currentTimeMillis(); byte[] s = passwd.getBACString(); service.addAPDUListener(reader); if (s != null) { service.doBAC(s); } reader.setVisible(true); if (s != null) { reader.getStatusBar().setBACOK(); } else { reader.getStatusBar().setBACNotChecked(); } reader.setSmartID(new SmartID(service)); if (reader.getSmartID().hasEAC()) { if (reader.getSmartID().wasEACPerformed()) { reader.getStatusBar().setEACOK(); } else { reader.getStatusBar().setEACFail("TODO get reason"); } } else { reader.getStatusBar().setEACNotChecked(); } // Make the frame visible only after a successful BAC if (reader.getCOMFile() == null) { InputStream in = reader.getSmartID() .getInputStream(BasicService.EF_COM); reader.setCOMFile(new DG_COM(in)); reader.readData(); reader.verifySecurity(service); } timeElapsed = System.currentTimeMillis() - timeElapsed; System.out.println("Reading time: " + (timeElapsed / 1000) + " s."); } } catch (Exception e) { e.printStackTrace(); } }
eb9963df-d2f0-45d2-849a-348966b442cb
0
public void createNewPizzaProduct() { pizza = new Pizza(); }
0040de97-9e81-4b49-aa2e-48bc8c4ca7cf
6
public void generate(Land[][] world, float heightThreshold, float lakeLevel){ this.lakeLevel = lakeLevel; this.world = world; ArrayList<Land> startOptions = new ArrayList<Land>(); ArrayList<Land> riverStarts = new ArrayList<Land>(); for(int i = 0; i < world.length; i++){ for(int j = 0; j < world[0].length; j++){ if(world[i][j].height>=heightThreshold){ startOptions.add(world[i][j]); j+=10; i+=2; } } } int numRivers = (int) (Math.random()*startOptions.size()); System.out.println(numRivers); int rand = 0; for(int i = 0; i < numRivers; i++){ rand = (int) (Math.random()*startOptions.size()); if(rand == startOptions.size()){ rand--; } riverStarts.add(startOptions.get(rand)); startOptions.remove(rand); } for(int i = 0; i<riverStarts.size(); i++){ startRiver(riverStarts.get(i)); } }
f018466e-b988-47a3-a1cb-5a1e7fdaed41
4
public TableModel Update() { String columnNames[] = { "Liste Filiere"}; DefaultTableModel defModel = new DefaultTableModel(); defModel.setColumnIdentifiers(columnNames); SequenceController seq_classe= new SequenceController(); seq_classe.CreateSequence("SEQ_FILIERE"); try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS); if (con == null) System.out.println("con classe ko "); else System.out.println("con classe ok "); Statement statement = con.createStatement(); if (statement == null) System.out.println("statement classe ko "); else System.out.println("statement classe ok "); //System.out.println("test1 : " + SaisieNom.getText()); ResultSet rs = statement.executeQuery("select * from \"FILIERE\" order by LIBFILIERE" ); //ResultSet rs = statement.executeQuery("select * from \"classe\" where nom='"+SaisieNom.getText()+"'" ); //ResultSet rs = statement.executeQuery("SELECT table_name FROM user_tables" ); //String codeCLasse = ""; String LibFiliere = ""; //String CodeFiliere = ""; while (rs.next()) { //codeCLasse= "N.A"; LibFiliere=rs.getString("LIBFILIERE"); defModel.addRow(new Object [] {LibFiliere} ); } rs.close(); statement.close(); con.close(); } catch (SQLException ex) { Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); } return defModel; }
d6920ff5-0028-452e-86aa-0edaae70e08f
0
public int getBlood() { return blood; }
fa89d229-ef29-479f-9672-72ed9e080a6c
3
private void updateTrainingBall() { if (ballY >= 0.95 || ballY <= -0.95) { ballYSpeed = -ballYSpeed; } //Left Paddle (AI) if (ballX <= -0.9) { stateList.learnAll((ballY+1)/2, AI); stateList.reset(); resetRandomBall(); } stateList.add(ballX, ballY, ballYSpeed); ballX += ballXSpeed; ballY += ballYSpeed; updateAIPaddle(); }
0df894af-5de8-4570-babf-ba624011d965
5
private Graph<TypedVerTex, DefaultEdge> generateGraph(Tuple<double[][], String[][]> params) throws UserError { double[][] data1=params.getKey(); //String [][]data2=params.getValue(); int noTypes=(int)data1[0][0]; int noNoRels=(int)data1[0][1]; //------------ BuildHeteGraph x=new BuildHeteGraph(); //get all types port for (int i = 1; i <= noTypes; i++) { ExampleSet exampleSet=exset[i]; String vertexType=exampleSet.getSource().replace("Retrieve ", "").trim(); x.addVertex(exampleSet,ObjectTypeOfGraph.VERTEX,vertexType); } //get All relation ports for (int i = noTypes+1; i <= noTypes+noNoRels; i++) { ExampleSet exampleSet=exset[i]; String vertexType=exampleSet.getSource().replace("Retrieve ", "").trim(); System.out.println("---reading relation exampleset "+vertexType); //split to types String []ss=vertexType.split("_"); String fromType=ss[0]; String toType=ss[1]; //navigate through data set Iterator<Example> itor = exampleSet.iterator(); while(itor.hasNext()){ Example ex = itor.next(); Attributes atts = ex.getAttributes(); Iterator<Attribute> it = atts.iterator(); Attribute from=it.next(); Attribute to=it.next(); String fromVal=ex.getValueAsString(from); String toVal=ex.getValueAsString(to); TypedVerTex v1 = x.findVertex(fromVal, fromType); TypedVerTex v2 = x.findVertex(toVal, toType); System.out.print("<"+v1+"-->"+v2+">;"); if(v1!=null && v2!=null){ //create state vertex and add to graph TypedVerTex state=new TypedVerTex("state", ex); x.addVertex(state); //add edge from v1->state x.addEdge(v1, state); //add edge from v2->state x.addEdge(v2, state);///state-->v2???? } } System.out.println(); } return x.getGraph(); }
a1882883-edba-4d8d-92af-495c88a185b4
4
protected List<Integer> getAllPrimes() { boolean[] sito = new boolean[N]; for (int i = 1; i < sito.length; i++) { sito[i] = true; } ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < sito.length; i++) { if (sito[i]) { int i1 = i + 1; list.add(i1); int x = 2; int j = (i1 * x); while (j <= N) { sito[j - 1] = false; x++; j = (i1 * x); } } } return list; }
32a982a5-6f51-41a1-8ce2-6e75cf081ddc
3
public static void main(String[] args) throws InterruptedException { PoolingClientConnectionManager pool = new PoolingClientConnectionManager(); final HttpClient httpClient = new DefaultHttpClient(); ForkJoinPool forkJoinPool = new ForkJoinPool(); ArrayList<FutureTask<Object>> futureTasks = new ArrayList<FutureTask<Object>>(); // futureTasks.add(new FutureTask<Object>()); // forkJoinPool.invokeAll(args) ThreadGroup threadGroup = new ThreadGroup("http-test"); for (int i = 0; i < 30; i++) { new Thread(threadGroup, new Runnable() { public void run() { HttpGet httpGet = null; Log4JStopWatch watch = new Log4JStopWatch(log); watch.start(); try { httpGet = new HttpGet("http://www.terra.com.br/"); HttpResponse response = httpClient.execute(httpGet, new BasicHttpContext()); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); } catch (Exception e) { httpGet.abort(); } watch.stop(); } }, "thread-" + i).start(); } while(threadGroup.activeCount() > 1) { Thread.currentThread().sleep(2000); } System.out.println("Hello World!"); }
4fd4bd68-e5b9-4a83-a031-b66d94961107
3
public static String getJsonFromData(Data data){ ObjectMapper mapper = new ObjectMapper(); StringWriter writer = new StringWriter() ; try { mapper.writeValue(writer, data) ; } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return writer.toString() ; }
df73854b-b64e-489a-8d67-53a66255c660
4
@Override public void run() { WordNode current_node; if((current_node = this.the_words.getHead()) == null) return; for(int i=0; i < this.the_words.getSize(); ++i){ if(isFormable(current_node)){ this.formable_words.add(current_node.copy()); // Keep largest words next to each other if(current_node.getWord().length() >= this.formable_words.getHead().getWord().length()) this.formable_words.updateHead(this.formable_words.getHead().getPrevious()); } current_node = current_node.getNext(); } }
292900ec-72e3-415a-b3f6-f79b20479410
8
public String toString(){ StringBuffer sb = new StringBuffer(); switch(type){ case TYPE_VALUE: sb.append("VALUE(").append(value).append(")"); break; case TYPE_LEFT_BRACE: sb.append("LEFT BRACE({)"); break; case TYPE_RIGHT_BRACE: sb.append("RIGHT BRACE(})"); break; case TYPE_LEFT_SQUARE: sb.append("LEFT SQUARE([)"); break; case TYPE_RIGHT_SQUARE: sb.append("RIGHT SQUARE(])"); break; case TYPE_COMMA: sb.append("COMMA(,)"); break; case TYPE_COLON: sb.append("COLON(:)"); break; case TYPE_EOF: sb.append("END OF FILE"); break; } return sb.toString(); }
44b37b2e-9393-49d7-8ce5-78559e9e79d5
4
public HelpFrame() { this.setTitle("Syntaxilizer Help"); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setSize(Main.WIDTH - 200, Main.HEIGHT - 100); this.setResizable(true); this.setLocationRelativeTo(null); //center window on screen helpPane = new JEditorPane(); helpPane.setMargin(new Insets(10, 10, 10, 10)); helpPane.setEditable(false); helpPane.setEditorKit(JEditorPane.createEditorKitForContentType("text/html")); helpPane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(e.getURL().toURI()); } catch (Exception e1) { e1.printStackTrace(); } } } } }); try { helpPane.setPage((new File("resources\\help.html")).toURI().toURL()); } catch (Exception e) { helpPane.setText("Cannot load help file from resources\\help.html"); e.printStackTrace(); } helpPane.setFont(Main.normalFont.deriveFont(13.0f)); JScrollPane scrollPane = new JScrollPane(helpPane); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); scrollPane.setPreferredSize(new Dimension(250, 145)); scrollPane.setMinimumSize(new Dimension(10, 10)); this.add(scrollPane); this.setVisible(true); }
dc0bd3d7-4439-4b63-9719-a7dbc5b740a7
7
@Override public String getJSONString() { StringBuilder json = new StringBuilder() .append("{") .append(super.getJSONBaseString()); if(this.getRepeat() != null) { json.append("\"repeat\":{"); for(int i=0;i<7;i++) { json.append("\"").append(Daily.days[i]).append("\": ").append(this.getRepeat()[i]).append(","); } json =json.deleteCharAt(json.length()-1); json.append("},"); } json.append("\"streak\":").append(this.getStreak()).append(","); json.append("\"completed\":" + (this.isCompleted() ? "true":"false")); json.append(",") .append("\"checklist\":["); if(this.getChecklist() != null && !this.getChecklist().getItems().isEmpty()) { for(ChecklistItem item : this.getChecklist().getItems()) { json.append("{") .append("\"text\":").append(JSONObject.quote(item.getText())).append(",") .append("\"id\":").append(JSONObject.quote(item.getId())).append(",") .append("\"completed\":").append(item.isCompleted() ? "true" : "false") .append("},"); } json.deleteCharAt(json.length()-1); } json.append("]") .append("}"); return json.toString(); }
f7ac5a7e-90c8-40ec-9cad-61d2e8b1eeea
2
public BufferedImage getImage() { if (image == null) { try { return ImageIO.read(new File("res/default.png")); } catch (IOException ex) { return null; } } else { return image; } }
69b88c5d-5249-4c8a-8868-d9af6bc1ab0d
2
private void mapRawData(String[] tickers) { System.out.println("total number of tickers: " + tickers.length); int counter = 0; // (" 2 36 44 9 9 9 9 9 9 9 9 9 9 1 1 1"); for (String tk : tickers) { StringBuilder saveAsText = new StringBuilder(); saveAsText.append(cnnForecast(tk).trim()); saveAsText.append(" "); saveAsText.append(analystEstimates(tk)); saveAsText.append(" "); saveAsText.append(keyBasedData(yahoobase + "/ks?s=" + tk, keykeys)); saveAsText.append(" "); saveAsText.append(limitToTen(pastPrices(tk))); saveAsText.append(" "); saveAsText.append(optionsCount(tk)); // System.out.println(tk); if (!printQuickCount(saveAsText)) System.out.println("\n--> " + saveAsText); rawMap.put(tk, saveAsText.toString()); } }
c3a78aad-e61a-4136-babb-892257a7dfa5
0
public int[] getMessageTimestamps() { return messageTimestamps; }
b62cce5d-dcd6-41d8-aa28-5e1447766f27
3
public boolean onCommand(CommandSender sender, String[] args) { // get the groups PermissionGroup[] groups = plugin.permissions.getGroups(); // create a comparator Comparator<PermissionGroup> rankComparator = new RankComparator(); // and sort the groups Arrays.sort(groups, rankComparator); // print out the ranks String ranks = "&fRanks in order of least to greatest: "; for(int i = 0; i < groups.length - 1; i++) { // exclude unranked groups if(groups[i].getOptionInteger("rank", "", 9999) != 9999) { ranks += groups[i].getPrefix() + groups[i].getName() + "&f, "; } } // don't add a comma to the last one if(groups.length > 0) { ranks += groups[groups.length - 1].getPrefix() + groups[groups.length - 1].getName(); } // and send! MCNSARanksCommandExecutor.returnMessage(sender, ranks); return true; }
ead1f11c-1abf-426e-b680-51662c6d0a09
0
public String getAccessToken_secret() { return accessToken_secret; }
cd4c43b1-3d5e-4baf-ad18-1659cfc7f5e4
8
final public void start(BlockStatement node) throws ParseException { label_1: while (true) { assign(node); jj_consume_token(SEMICOLON); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case SEMICOLON: case STATEMENT: case PRINT: case READ: case TYPE: case ID: ; break; default: jj_la1[0] = jj_gen; break label_1; } } jj_consume_token(0); }
73bed854-9190-4bd4-9a41-ab48d2f85485
0
public String getGoTo() { return goTo; }
d9039f30-7086-4a59-a132-9b40ed08515f
2
private String decodeAuthCookieSafely(Cookie cookie) { if (cookie == null) { return null; } String decodedCookieValue = null; try { decodedCookieValue = Base64Utils.decode(cookie.getValue()); } catch (Base64Exception e) { LOGGER.log(Level.WARNING, e.getMessage()); } return decodedCookieValue; }
47528f42-fcb5-4591-814a-56d4becbabb0
4
public boolean playerHasItem2(int itemID) { for (int i= 0; i < playerItems.length; i++) { if (playerItems[i] == itemID+1) { playerAxe = itemID; return true; } } for (int i2 = 0; i2 < playerEquipment.length; i2++) { if (playerEquipment[i2] == itemID) { playerAxe = itemID; return true; } } return false; }
18c24651-ce24-4a52-b157-3eeaa1546f49
6
public void addStateMarker(int state, double time) { plot.addDomainMarker(new ValueMarker(time, Color.BLUE, new BasicStroke((float) 2.5))); switch(state) { case 2: XYTextAnnotation text = new XYTextAnnotation("Armed", time, 500); text.setFont(new Font("SansSerif", Font.PLAIN, 9)); plot.addAnnotation(text); break; case 3: XYTextAnnotation text2 = new XYTextAnnotation("Profile", time, 510); text2.setFont(new Font("SansSerif", Font.PLAIN, 9)); plot.addAnnotation(text2); break; case 4: XYTextAnnotation text3 = new XYTextAnnotation("Ramp", time, 520); text3.setFont(new Font("SansSerif", Font.PLAIN, 9)); plot.addAnnotation(text3); break; case 5: XYTextAnnotation text4 = new XYTextAnnotation("Constant", time, 530); text4.setFont(new Font("SansSerif", Font.PLAIN, 9)); plot.addAnnotation(text4); break; case 6: XYTextAnnotation text5 = new XYTextAnnotation("Recovery", time, 540); text5.setFont(new Font("SansSerif", Font.PLAIN, 9)); plot.addAnnotation(text5); break; case 7: XYTextAnnotation text6 = new XYTextAnnotation("Retrieve", time, 550); text6.setFont(new Font("SansSerif", Font.PLAIN, 9)); plot.addAnnotation(text6); break; } }
46f4667e-057f-489a-8e14-37ca33c1b625
6
private void stop() { if (isMovingRight() == false && isMovingLeft() == false) { speedX = 0; } if (isMovingRight() == false && isMovingLeft() == true) { moveLeft(); } if (isMovingRight() == true && isMovingLeft() == false) { moveRight(); } }
412e7d6f-923b-4c9b-883e-170ace61102d
8
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //¶Ӧı,ĽȷĽ request.setCharacterEncoding("gbk"); response.setContentType("text/html;charset=gbk"); //ĬϵϢ String searchPath = "D:\\Bingo_Index"; //ȡûȡĹؼ String keyWords = (String) request.getParameter("keyWords"); //ServletContextʵ ServletContext sc = getServletContext(); /** * ؼΪգתerrorҳ * Ҳjavascript valadition֤ */ if(keyWords==null){ RequestDispatcher rd = sc.getRequestDispatcher("/error.jsp"); rd.forward(request, response); return; } //ûж //ԲͬIJѯͣȥͬĿ¼¼ String searchType = request.getParameter("searchType"); if(!searchType.equals("webPage") && (searchType != null)) { searchPath = SearchType.getSearchType(searchType); } //ҳ String startLocationTemp = request.getParameter("startLocation"); if(startLocationTemp != null) { //parseInt int startLocation = Integer.parseInt(startLocationTemp); System.out.println(startLocation); } //ִ Analyzer analyzer = null; //ҳ Highlighter highlighter = null; /** * DocumentLuceneҪ */ List<Document> list = new ArrayList<Document>(); Integer totalCount = null; try { IndexSearcher indexSearch = new IndexSearcher(searchPath); analyzer = new MMAnalyzer(); String[] field = { "title", "content", "link"}; // Map<String, Float> boosts = new HashMap<String, Float>(); boosts.put("title", 3f); QueryParser queryParser = new MultiFieldQueryParser(field, analyzer, boosts); Filter filter = null; try { /** * ǾIJѯʵ * queryParserLuceneҪIJѯ */ Query query = queryParser.parse(keyWords); TopDocs topDocs = indexSearch.search(query, filter, 1000, new Sort(new SortField("size"))); totalCount = new Integer(topDocs.totalHits); SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter( "<font color='red'>", "</font>"); // highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(query)); highlighter.setTextFragmenter(new SimpleFragmenter(70)); for (int i = 0; i < topDocs.totalHits; i++) { ScoreDoc scoreDoc = topDocs.scoreDocs[i]; int docSn = scoreDoc.doc; // ĵڲ Document doc = indexSearch.doc(docSn); // ݱȡӦĵ list.add(doc); } } catch (ParseException e) { e.printStackTrace(); } } catch (CorruptIndexException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } RequestDispatcher rd = sc.getRequestDispatcher("/result.jsp"); request.setAttribute("keyWords", keyWords); request.setAttribute("totalCount", totalCount); request.setAttribute("docList", list); request.setAttribute("analyzer", analyzer); request.setAttribute("highlighter", highlighter); /** * RequestDispatcherṩforwardinclude */ rd.forward(request, response); }
fc733a09-395a-4ec1-b27f-098070d55a26
2
public static double absDiff(double[] obs, double[] sim, double missingValue) { sameArrayLen(obs, sim); double abs = 0; for (int i = 0; i < obs.length; i++) { if (obs[i] > missingValue) { abs += Math.abs(obs[i] - sim[i]); } } return abs; }
e35518b0-7244-45b2-a270-68762a832948
8
private static void processToken(String token, Stack<String> operators, Vector<String> postfix) { if(token.matches("\\p{Alpha}+")) // If is an ID puts it on the vector { postfix.add(token); } else if(token.equals(")")) // If ")" pop until find matching "(" { while(!operators.empty()) { String top = operators.pop(); if(top.equals("(")) break; postfix.add(top); } } else if(token.equals("(")) { operators.push(token); } else// if is an operator token pop until find operator of lower precedence, then push { while (!operators.empty() && !operators.peek().equals('(')) { String top = operators.peek(); if (precedence(top) < precedence(token)) break; postfix.add(operators.pop()); } operators.push(token); } }
3e9fcec2-a3a7-4f54-b8f5-ae44e0dba618
3
public List<String>delNickName(String nickName) throws NickNameNotExist { if(!nickNameAlreadyExist(nickName)) throw new NickNameNotExist(); for (Personne p : listPer) { if(p.getListNickName().contains(nickName)) { int rang = p.getListNickName().indexOf(nickName); p.getListNickName().remove(rang); break; } } return app.appValid(); }
3ac179b4-b9ee-4f6b-b44b-7a4253d65466
4
private boolean valueSearchNonNull(Entry n, Object value) { // Check this node for the value if (value.equals(n.value)) return true; // Check left and right subtrees for value return (n.left != null && valueSearchNonNull(n.left, value)) || (n.right != null && valueSearchNonNull(n.right, value)); }
fba5addc-acdb-4cc5-9900-1a03cda215cf
7
static final void method106() { IndexLoader.anInt669 = 0; for (int i = 0; i < Class150.anInt2057; i++) { Npc class318_sub1_sub3_sub3_sub1 = (((Class348_Sub22) (Class348_Sub22) Class282.aClass356_3654 .get((long) EntityPacket.anIntArray1233[i])) .aClass318_Sub1_Sub3_Sub3_Sub1_6859); if ((((Mob) class318_sub1_sub3_sub3_sub1) .aBoolean10309) && class318_sub1_sub3_sub3_sub1.method2425(-1) != -1) { int i_20_ = ((class318_sub1_sub3_sub3_sub1.method2436((byte) 119) - 1) * 256 + 252); int i_21_ = (((Class318_Sub1) class318_sub1_sub3_sub3_sub1).xHash - i_20_) >> 9; int i_22_ = (((Class318_Sub1) class318_sub1_sub3_sub3_sub1).anInt6388 - i_20_) >> 9; Mob class318_sub1_sub3_sub3 = Class84.method817(252, i_21_, (((Class318_Sub1) class318_sub1_sub3_sub3_sub1) .heightLevel), i_22_); if (class318_sub1_sub3_sub3 != null) { int i_23_ = (((Mob) class318_sub1_sub3_sub3) .localId); if (class318_sub1_sub3_sub3 instanceof Npc) i_23_ += 2048; if ((((Mob) class318_sub1_sub3_sub3) .anInt10261) == 0 && class318_sub1_sub3_sub3.method2425(-1) != -1) { Class258_Sub4.anIntArray8557[IndexLoader.anInt669] = i_23_; Class268.anIntArray3432[IndexLoader.anInt669] = i_23_; IndexLoader.anInt669++; ((Mob) class318_sub1_sub3_sub3) .anInt10261++; } Class258_Sub4.anIntArray8557[IndexLoader.anInt669] = i_23_; Class268.anIntArray3432[IndexLoader.anInt669] = ((Mob) class318_sub1_sub3_sub3_sub1).localId + 2048; IndexLoader.anInt669++; ((Mob) class318_sub1_sub3_sub3) .anInt10261++; } } } Class34.method347(Class268.anIntArray3432, Class258_Sub4.anIntArray8557, 0, -22222, IndexLoader.anInt669 - 1); }
7b81061e-77da-4b29-872d-816a66fe9093
7
public void equipBraves(IndianSettlement is) { final Specification spec = getSpecification(); List<Unit> units = is.getUnitList(); units.addAll(is.getTile().getUnitList()); roles: for (Role r : new Role[] { Role.DRAGOON, Role.SOLDIER, Role.SCOUT }) { List<EquipmentType> e = r.getRoleEquipment(spec); while (!units.isEmpty()) { Unit u = units.get(0); for (EquipmentType et : e) { if (u.canBeEquippedWith(et) && !is.canProvideEquipment(et)) { continue roles; } } if (u.getRole() != Role.DRAGOON && u.getRole() != r) { getAIUnit(u).equipForRole(r, false); } units.remove(0); } } }
3c9dcd78-c0a5-4a9f-9264-a37969f9e8b1
9
public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getActionCommand() == "Exit") { this.exitButtonActionPerformed(e); } else if (e.getActionCommand() == "Sort!") { startSortButtonActionPerformed(e); } else if (e.getActionCommand() == "Source Dir") { sourceDirUpdate(); } else if (e.getActionCommand() == "Target Dir") { targetBrowseButtonActionPerformed(e); } else if (e.getActionCommand() == "Properties") { this.setPropertiesMenuItemActionPerformed(e); } else if (e.getActionCommand() == "Help on Usage") { this.usageHelpMenuItemActionPerformed(e); } else if (e.getActionCommand() == "About") { this.aboutHelpMenuItemActionPerformed(e); } else if (e.getActionCommand() == "Help on Database") { this.dbHelpMenuItemActionPerformed(e); } else if (e.getActionCommand() == "Ok") { jd.setVisible(false); jd = null; } }
baa25fca-2b0b-4748-bf31-778d1b66d5f0
2
private void programmerAutosaveButton(java.awt.event.ActionEvent evt) { try { List<String> userInput = Arrays.asList(programmerText.getText().split("\n")); PrintWriter out; DateFormat dateFormat = new SimpleDateFormat("dd_MMM_HH_mm_ss"); Date date = new Date(); String fileName1; fileName1 = "KarelCode_"; fileName1 += dateFormat.format(date); fileName1 += ".txt"; out = new PrintWriter(fileName1); for(int loop = 0; loop < userInput.size(); loop++) { out.println(userInput.get(loop)); } out.close(); } catch (FileNotFoundException ex) { Logger.getLogger(World.class.getName()).log(Level.SEVERE, null, ex); } }
e17e1529-3759-4a4f-9ab6-af082e1a1f47
9
private String httpRequest(Map<String, String> param, String method) { Log.d("httpRequest", "start to send http request"); // 添加其他默认需要的参数 param.put("method", method); if (!param.containsKey("v")){ param.put("v", Ver); } if (!param.containsKey("appKey")){ param.put("appKey", AppKey); } if (!param.containsKey("uzone_token") && UzoneToken != null){ param.put("uzone_token", UzoneToken); } // 生成请求用户的参数 Map<String, String> nameValuePairs = this.buildRequestParam(param); String url = this.buildRequestUri(nameValuePairs, RestServer); String response = ""; HttpClient client = new HttpClient(); InputStream in = null; BufferedReader reader = null; try{ HttpMethod getMethod = new GetMethod(url); client.executeMethod(getMethod); in = getMethod.getResponseBodyAsStream(); reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String temp = ""; while((temp = reader.readLine()) != null){ sb.append(temp); } response = sb.toString(); // 关闭链接 getMethod.releaseConnection(); }catch (Exception e) { // TODO: handle exception }finally{ try{ if(in != null){ in.close(); } if(reader != null){ reader.close(); } }catch (IOException e) { // TODO: handle exception } } Log.d("httpRequest", "Server Resonse: " + response); return response; }
fd618a42-338e-464f-80b0-ccb9ddd6f836
0
public static float getYawByF(int f) { return f * 360.0f / 4.0f; }
1c0a42c5-ad2a-4446-9130-ae8c1a3523c7
9
@Override public void step(PulsatioGame game, float delta) { stage.act(delta); stage.draw(); heartbeatTimer += delta; if (heartbeatTimer >= 12) { heartbeatTimer = 0; game.assets.get("sound/GGJ13_Theme.wav", Sound.class).play(adrenalineteam0*3f); } if (placementPhase && player0placed && player1placed) { leavePlacement(); } if ((team0units.size() == 0 || team1units.size() == 0) && (player0placed && player1placed && !placementPhase)) { Log.info("Game over"); Gdx.app.exit(); } SpriteBatch b = stage.getSpriteBatch(); b.begin(); drawUi(b); b.end(); }
c92dec40-601c-46eb-b879-1e278c08cb35
8
private void handleInput() { //Toggle debug screen if(in.getKeypress(debugButton)) { debugMenu=!debugMenu; } //Toggle music if(in.getKeypress(music)) { AudioManager.epic.toggle(); } //Toggle flying if(in.getKeypress(fly)) { this.cam.fly=!this.cam.fly; this.grounded=false; } //Host a server if(in.getKeypress(host) && s==null) { s = new Server(this, new ServerPlayer(this.world), true); } //Join a server if(in.getKeypress(join) && s==null) { s = new Server(this, new ServerPlayer(this.world), false); } //Set position of light 0 of the world to player position if (Keyboard.isKeyDown(Keyboard.KEY_Q)) { this.world.lights[0].move(this.position); } }
5a19b5e5-8251-4421-8c04-a44972720994
2
public List<Planet> NeutralPlanets() { List<Planet> r = new ArrayList<Planet>(); for (Planet p : planets) { if (p.Owner() == 0) { r.add(p); } } return r; }
8b053b7d-4347-4950-b553-a093e87d7d97
8
public List<Long> getLongList(String path) { List<?> list = getList(path); if (list == null) { return new ArrayList<Long>(0); } List<Long> result = new ArrayList<Long>(); for (Object object : list) { if (object instanceof Long) { result.add((Long) object); } else if (object instanceof String) { try { result.add(Long.valueOf((String) object)); } catch (Exception ex) { } } else if (object instanceof Character) { result.add((long) ((Character) object).charValue()); } else if (object instanceof Number) { result.add(((Number) object).longValue()); } } return result; }
9459c1c1-dfaa-4990-b788-47c897f19bda
0
private static ImageProcessor xGradient(ImageProcessor ip){ ImageProcessor result = ip.duplicate(); int[] Gx = {-1, 0, 1, -2, 0, 2, -1, 0, 1}; result.convolve3x3(Gx); return result; }
00f0576b-a5cc-4a0f-8493-ab5af8d7b801
9
public int compareTo(CHRTile tile){ if(tile.tileWidth != tileWidth){ return ((tile.tileWidth < tileWidth) ? 1 : -1); } if(tile.tileHeight != tileHeight){ return ((tile.tileHeight < tileHeight) ? 1 : -1); } if(IMAGE_SIMILARITY_THRESHOLD > 0) { // double RMS_THRESHOLD = IMAGE_SIMILARITY_THRESHOLD / 100.0; int rms_error = calculateRMS(tile.rgb, IMAGE_SIMILARITY_THRESHOLD/100.0); if(rms_error ==0) { return 0; } } /* if(IMAGE_SIMILARITY_THRESHOLD > 0) { int diffCount = 0; // do pixel by pixel check for(int i=0;i<pix.length;i++){ if(tile.pix[i] != pix[i]){ diffCount++; if(diffCount> IMAGE_SIMILARITY_THRESHOLD) return ((tile.pix[i]< pix[i]) ? 1 : -1); } } } else { */ // do mask check for(int i=0;i<mask.length;i++){ if(tile.mask[i] != mask[i]){ return ((tile.mask[i]< mask[i]) ? 1 : -1); } } // } return 0; }
e8823b07-bc8f-46f2-9187-ecd872ba57a6
2
public static int fac(int k) { if (k < 0) return 0; int kfac = 1; while (k > 1) { kfac = kfac * k; k = k - 1; } return kfac; }
da0313ca-668a-4d3e-986b-9269aed782d1
7
public void saveScoreStats() { File file = new File("Scores.txt"); boolean flag = false; FileWriter writer; ArrayList<String> scoreData = new ArrayList<String>(); ListIterator<String> iterator; try { Scanner s = new Scanner(file); while(s.hasNextLine()) { scoreData.add(s.nextLine()); } s.close(); iterator = scoreData.listIterator(); while(iterator.hasNext()) { if(iterator.next().equals(user.getUsername())) { iterator.next(); iterator.set(String.valueOf(user.getScore().getHighScore()) + " " + String.valueOf(user.getScore().getBestTime()) + " " + user.getScore().getBestDifficulty() + " " + user.getScore().getBestSize() + " " + user.getScore().getCurrentScore() + " " + String.valueOf(user.getScore().getCurrentTime()) + " " + user.getScore().getLastDifficulty() + " " + user.getScore().getLastSize()); flag = true; break; } } if(flag == false) { scoreData.add(user.getUsername()); scoreData.add(String.valueOf(user.getScore().getHighScore()) + " " + String.valueOf(user.getScore().getBestTime()) + " " + user.getScore().getBestDifficulty() + " " + user.getScore().getBestSize()); } writer = new FileWriter("Scores.txt"); iterator = scoreData.listIterator(); while(iterator.hasNext()) { writer.write(iterator.next()); writer.write("\n"); } writer.close(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "Could not find Scores. Contact system administrator.", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Could not update Scores. Contact system administrator.", "Error", JOptionPane.ERROR_MESSAGE); } }
1c6b336b-c7aa-4711-a5fd-1caad74e2034
1
public void removePush() { if (stack != null) instr = stack.mergeIntoExpression(instr); }
45698a6e-00ac-484e-82de-5b6db8b1f998
6
@RequestMapping(value="inserirDisciplina",method = RequestMethod.POST) public String inserir(@Valid Disciplinas disciplina, BindingResult result, final RedirectAttributes redirectAttributes) { if(disciplina.getCodDisciplina()==null || disciplina.getCodDisciplina().equals("")) { System.out.println("Erro"); return "index"; } if(disciplina.getNomeDisciplina()==null || disciplina.getNomeDisciplina().equals("")){ System.out.println("Erro"); return "index"; } if(result.hasErrors()) return "index"; if(ds.pesquisar(disciplina.getCodDisciplina(), disciplina.getNomeDisciplina())==null){ ds.inserir(disciplina); System.out.println("Disciplina adicionada com sucesso"); return "redirect:disciplina-adicionada"; }else{ redirectAttributes.addFlashAttribute("message", "Disciplina não pode ser adicionada pois já existe semelhante registrada"); return "redirect:/"; } }