method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
c5354ed5-e808-406d-ad6e-0559fba802e3
1
@Override public boolean matches(String inputExt, String outputExt) { return StringUtils.equalsIgnoreCase(inputExt, "xls") && StringUtils.endsWithIgnoreCase(outputExt, "properties"); }
e17fab94-142a-460f-b8fd-54ad9c15e54c
7
public Map getRecordByID(String table, String primaryKeyField, Object keyValue, boolean closeConnection) throws SQLException, Exception { Statement stmt = null; ResultSet rs = null; ResultSetMetaData metaData = null; final Map record=new HashMap(); // do this in an excpetion handler so that we can depend on the // finally clause to close the connection try { stmt = conn.createStatement(); String sql2; if(keyValue instanceof String){ sql2 = "= '" + keyValue + "'";} else { sql2 = "=" + keyValue;} final String sql="SELECT * FROM " + table + " WHERE " + primaryKeyField + sql2; rs = stmt.executeQuery(sql); metaData = rs.getMetaData(); metaData.getColumnCount(); final int fields=metaData.getColumnCount(); // Retrieve the raw data from the ResultSet and copy the values into a Map // with the keys being the column names of the table. if(rs.next() ) { for( int i=1; i <= fields; i++ ) { record.put( metaData.getColumnName(i), rs.getObject(i) ); } } } catch (SQLException sqle) { throw sqle; } catch (Exception e) { throw e; } finally { try { stmt.close(); if(closeConnection) conn.close(); } catch(SQLException e) { throw e; } // end try } // end finally return record; }
5a2178a8-7097-4ae4-b34b-df488ffd413b
2
@Override public void run() { while(run){ System.out.println( String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s", this.executor.getPoolSize(), this.executor.getCorePoolSize(), this.executor.getActiveCount(), this.executor.getCompletedTaskCount(), this.executor.getTaskCount(), this.executor.isShutdown(), this.executor.isTerminated())); try { Thread.sleep(seconds*1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
3d6e2b35-8667-4ce8-b757-085b6eb831e6
9
public void analyzeLine (String instr) { //clear the map for new input string tf_idf_map.clear(); core_words.removeAllElements(); non_core_words.removeAllElements(); System.out.println("analyzing..."); long start = System.currentTimeMillis(); //tokenization instr = getTokenized(instr); //regex Pattern p = Pattern.compile("([^\\ ]+)[\\ |.]"); Matcher m = p.matcher(instr); while(m.find()) { String word = m.group(1); //stemming: change the format of the words //e.g. making => make goes => go word = getStem(word); //filter the stop words if(stopmap.containsKey(word) == false && idfmap.containsKey(word)) { //update the tf if(tf_idf_map.containsKey(word)) { double freq = tf_idf_map.get(word); tf_idf_map.put(word, freq+1); } else tf_idf_map.put(word, 1.0); } } //sort the tf_idf_map on score List<Map.Entry<String, Double>> list = new ArrayList<Map.Entry<String, Double>>(tf_idf_map.entrySet()); for(int i = 0; i < list.size(); i++) { String key = list.get(i).getKey(); Double tf_idf = list.get(i).getValue() * idfmap.get(key); tf_idf_map.put(key, tf_idf); } Collections.sort(list, new Comparator<Map.Entry<String, Double>>() { public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) { //get idf score and multiply the tf double delta = o1.getValue() - o2.getValue(); if (delta > 0) return -1; else if (Math.abs(delta) < 0.00000001) return 0; else return 1; } }); //20% for core index int i; for(i = 0; i < list.size() * percentage; i++) core_words.add(list.get(i).getKey()); for(;i < list.size(); i++) non_core_words.add(list.get(i).getKey()); long end = System.currentTimeMillis(); System.out.println("analyzation done! Time(s): " + (end-start)/1000); /*for(i = 0; i < list.size(); i++) System.out.println(list.get(i).getKey()+"--"+list.get(i).getValue());*/ }
c7cd082f-a2c6-4eba-b6d8-e7105756e33f
1
private void init() { for (int i = 0; i < CAPACITY; i++) { arr[i] = null; } topPtr = CAPACITY; }
d3c0b20c-d90a-47e9-b095-0a3fa8ad9b63
3
private boolean startAlgorithm () { addToOpenedCells(startCell); while (true) { int selectedCellIndex = getNextCellIndex(); Point selectedCell = openedCells.get(selectedCellIndex); removeFromOpenedCells(selectedCellIndex); addToClosedCells(selectedCell); if (processAdjoiningCells(selectedCell)) { return true; } if (openedCells.isEmpty()) { return false; } delay(); } }
19f39987-3597-4702-b7cd-490192b79472
5
@Override public void add(String word) { // char[] lWord = word.toLowerCase().toCharArray(); if (this.root == null) { this.root = new WordNode(); this.nodeCount++; } WordNode currentNode = root; // for (char c : lWord) { // boolean nodeAdd = currentNode.add(c); // if (nodeAdd) { // this.nodeCount++; // } // if (currentNode.at(c) != null) { // currentNode = currentNode.at(c); // } // else { // System.out.printf("In WordTrie.add: Error occured at char %c for string %s.\n", c, word); // System.exit(0); // } // } for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); c = Character.toLowerCase(c); boolean nodeAdd = currentNode.add(c); if (nodeAdd) { this.nodeCount++; } if (currentNode.at(c) != null) { currentNode = currentNode.at(c); } else { System.out.printf("In WordTrie.add: Error occured at char %c for string %s.\n", c, word); System.exit(0); } } if (currentNode.getValue() < 1) { this.wordCount++; } currentNode.incrementValue(); }
72be2b20-c0aa-4148-b17b-a847ed2f055c
1
public void removeConstructor(CtConstructor m) throws NotFoundException { checkModify(); MethodInfo mi = m.getMethodInfo2(); ClassFile cf = getClassFile2(); if (cf.getMethods().remove(mi)) { getMembers().remove(m); gcConstPool = true; } else throw new NotFoundException(m.toString()); }
97d1f8c9-8563-48c0-8721-4c3404cddebf
1
private void setAttr(Attributes attr) { if (attr.getIndex("nome") >= 0) { this.nome = attr.getValue("nome"); } else { System.out.println("tabela: falta o atributo 'nome'"); } }
ba70f99a-2792-4eb0-b6ee-a7c1b4e1ebda
7
@Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ConnectionEvent that = (ConnectionEvent) o; if (!getClusterId().equals(that.getClusterId())) { return false; } if (!getServerAddress().equals(that.getServerAddress())) { return false; } if (!serverAddress.equals(that.serverAddress)) { return false; } return true; }
328f7ba8-ffa5-4b10-8c26-e9ab2f544d0f
8
public void setNspgStats(IntVO gap) { int v=gap.val(); switch (v) { case 0: //gap 0, 1 nspg0++; break; case 1: //gap 0, 1 nspg1++; break; case 2: case 3: case 4: case 5: case 6: case 7: //gap 2,3,4,5,6,7 nspg2++; break; default: //gap 2,3,4,5,6,7 nspg3++; break; } }
f3f3cf77-6854-45ec-9671-d985f263819b
0
public static void main(String[] args) { System.out.println(getLongValue("queryTime")); }
7efe5963-867d-4b6c-be95-34a1da60afb0
7
public boolean getInput() { while(Keyboard.next()) { if(Keyboard.getEventKeyState()) { onKeyDown(Keyboard.getEventKey()); } else { onKeyUp(Keyboard.getEventKey()); } } // mouse input //float mDX = Mouse.getDX() * 2.5f; // mouse sensitivity 2.5, testing stuff... //float mDY = -Mouse.getDY() * 2.5f; // invert y-axis to match all our coordinates //mouseX += mDX; //mouseY += mDY; float mDX = Mouse.getDX(); float mDY = -Mouse.getDY(); mouseX = Mouse.getX(); mouseY = Display.getHeight() - Mouse.getY(); /* if(mouseX < 0) { mouseX = 0; } else if(mouseX > Display.getWidth()) { mouseX = Display.getWidth(); } if(mouseY < 0) { mouseY = 0; } else if(mouseY > Display.getHeight()) { mouseY = Display.getHeight(); } * */ while(Mouse.next()) { int button = Mouse.getEventButton(); int mX = Mouse.getEventX(); int mY = Display.getHeight() - Mouse.getEventY(); // invert the y-axis to match all our coordinates if(button != -1) { // check that a state of a mouse button has changed if(Mouse.getEventButtonState()) { onMouseDown((int)mX, (int)mY, button); } else { onMouseUp((int)mX, (int)mY, button); } } } /* int mX = Mouse.getX(); int mY = Display.getHeight() - Mouse.getY(); // invert the y-axis to match all our coordinates //mouseX = mX; //mouseY = mY; int mDX = Mouse.getDX(); int mDY = -Mouse.getDY(); // invert y-axis yet again mouseX += mDX * 2.5f; mouseY += mDY * 2.5f; * */ if(mDX != 0 || mDY != 0) { onPointerMove((int)mouseX, (int)mouseY, (int)mDX, (int)mDY); } return false; }
99b636f0-ee72-441b-a176-65f52911d483
5
public void wdgmsg(Widget sender, String msg, Object... args) { if(sender == y) { ui.sess.close(); } else if(sender == n) { ui.destroy(this); } else if(sender == this) { if(msg == "close") ui.destroy(this); if(msg == "activate") ui.sess.close(); } else { super.wdgmsg(sender, msg, args); } }
5473a585-7455-4725-a361-a28155387bdb
2
public Scope getScope(Object obj, int scopeType) { int count = scopes.size(); for (int ptr = count; ptr-- > 0;) { Scope scope = (Scope) scopes.elementAt(ptr); if (scope.isScopeOf(obj, scopeType)) return scope; } return null; }
5c365154-6fcb-479d-98c9-73db1fd18ac8
2
private static String getVal(String[] lines, String field) { for (String line : lines) { String[] part = line.split(":", 0); if (part[0].equalsIgnoreCase(field)) return part[1]; } return "No value set for "+field; }
4bc798e3-595a-40ec-b1f9-53965875edee
0
public static GeneralNameValueConfig getVorbisConfigByField(String field) { return Registry.getConfigByField(field,vorbisFields); }
8056506a-5ca8-4199-8010-48ffcbcab8ec
1
public void addButton(BasicAction action) { JButton button = new JButton(action) { /** * */ private static final long serialVersionUID = -8635984393664103035L; public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); super.paintComponent(g2d); } }; button.setOpaque(false); button.setBorder(null); button.setHorizontalAlignment(JButton.LEFT); button.setForeground(new Color(70,47,47)); builder.add(button, cc.xy(2, inc)); inc += 2; if(centre != null) iFrame.remove(centre); centre = builder.getPanel(); centre.setBackground(Color.white); iFrame.add(BorderLayout.CENTER, centre); }
e869f553-be2f-4ca3-88e8-ee8352a17007
4
public void deleteMarkedEntities(){ for(Mob m:mobsToDelete) mobs.remove(m); for(Projectile p:projectilesToDelete) projectiles.remove(p); for(Explosion e:explosionsToDelete) explosions.remove(e); for(Particle p:particlesToDelete){ particles.remove(p); bgParticles.remove(p); } mobsToDelete.clear(); projectilesToDelete.clear(); explosionsToDelete.clear(); particlesToDelete.clear(); }
58125538-7c0a-4c93-8656-a6fb6f2954cb
2
public static void seq_ief(CompList<?> t) throws Exception { for (Compound c : t) { ComponentAccess.callAnnotated(c, Initialize.class, true); c.execute(); ComponentAccess.callAnnotated(c, Finalize.class, true); } }
2d4c9522-23d3-4e48-87d1-2cc42fe318b6
7
public void drawCard(PlayerClass pPlayer){ pPlayer.cout.printFerryClass(dobbelt); if(pPlayer.getPlayerPos() == 37 || pPlayer.getPlayerPos() == 3){ pPlayer.setPlayerPos(6); } else if(pPlayer.getPlayerPos() == 8){ pPlayer.setPlayerPos(16); } else if(pPlayer.getPlayerPos() == 18 || pPlayer.getPlayerPos() == 23){ pPlayer.setPlayerPos(26); } else if(pPlayer.getPlayerPos() == 34){ pPlayer.setPlayerPos(36); } if(dobbelt){ pPlayer.setDobbelt(true); } }
3e9ae05a-5a35-4228-8d93-2199392e5cff
4
@Override public boolean matches(List<Character> currentMatching) { if(currentMatching.size() > 1) return false; if(currentMatching.get(0).charValue() == '\n' || currentMatching.get(0).charValue() == '\r' || currentMatching.get(0).charValue() == '\t') return false; return currentMatching.get(0).charValue() <= 26; }
a67b6e50-61c8-49b0-bd3b-1793ff4f4576
7
public void enableBottomBar(boolean b) { if (moviePanel != null) remove(moviePanel); if (runPanel != null) remove(runPanel); if (b) { if (model.getRecorderDisabled()) { if (runPanel == null) createRunPanel(); add(runPanel, BorderLayout.SOUTH); } else { add(moviePanel, BorderLayout.SOUTH); } } else { if (model.getRecorderDisabled()) { if (runPanel == null) createRunPanel(); remove(runPanel); } else { remove(moviePanel); } } EventQueue.invokeLater(new Runnable() { public void run() { validate(); } }); view.updateSize(); }
de88183c-8f27-4d25-b207-f76a7aab59f6
8
private void renderScene(Scene scene) { long t = System.currentTimeMillis(); // HINT - always the getGraphics()-Method is called, // the background buffer will be cleared automatically Graphics2D g = canvas.getGraphics(); // enable anti aliasing g.addRenderingHints( ANTIALIAS ); // define the origin g.translate(canvas.getWidth() / 2, canvas.getHeight() / 2); // translate the scene to the point you have navigated to before g.translate(pModel.getViewOffsetX(), pModel.getViewOffsetY()); // zoom into the scene + invert y-axis g.scale(pModel.getZoom(), -pModel.getZoom()); // scale the stroke to ensure its contour has a one pixel width g.setStroke(new BasicStroke(1 / (float) pModel.getZoom())); if (grid != null) { grid.render(g); } if (scene.getGround() != null) { if (scene.getGround() instanceof IDrawable) { ((IDrawable) scene.getGround()).render(g); } else { System.err.println("cannot render " + scene.getGround()); } } orderedObjects.clear(); for (IDrawable decor : canvas.getDecorSet()) { orderedObjects.add(decor); } for (ObjectProperties obj : scene.getObjects()) { if (obj instanceof IDrawable) { ((IDrawable) obj).render(g); } else { System.err.println("Cannot render object: " + obj); } if (obj instanceof IDecorable) { orderedObjects.addAll(((IDecorable) obj).getDecorSet()); } } IDrawable decor; while (!orderedObjects.isEmpty()) { decor = orderedObjects.poll(); decor.render(g); } canvas.switchBuffers(); canvas.repaint(); DebugMonitor.getInstance().updateMessage("repaint", "" + (System.currentTimeMillis() - t)); }
0dd8d496-9da9-41b4-b85c-fc0839300116
1
public void delete() throws SQLException { Reminder.deleteByAppt(this.getId()); if (this.isJoint) { this.deleteArray("aWaitingId"); this.deleteArray("aRejectedId"); this.deleteArray("aAcceptedId"); } super.delete(); }
12507be1-ad8a-4466-9bf6-f9726a2b03ac
4
public static void main (String[] args) throws IOException, InterruptedException { final int port = 7000; final int writeBufferSize = 16384; final int objectBufferSize = 2048; final AtomicBoolean received = new AtomicBoolean(); // Creating server final Server server = new Server(writeBufferSize, objectBufferSize); server.bind(port); server.start(); System.out.println("Server listening on port " + port); // Creating client final Client client = new Client(writeBufferSize, objectBufferSize); client.start(); client.addListener(new Listener() { @Override public void received (Connection connection, Object object) { if (object instanceof String) { System.out.println("Received: " + object); received.set(true); } else System.err.println("Received unexpected object"); } }); client.connect(5000, "localhost", port); System.out.println("Client connected"); // Catching exception Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException (Thread t, Throwable e) { e.printStackTrace(); received.set(true); // Stopping it all System.out.println("Stopping client and server"); client.stop(); server.stop(); } }); // Sending small messages for (int i = 0; i < 5; i++) { String smallMessage = "RandomStringUtils.randomAlphanumeric(256)"; System.out.println("Sending: " + smallMessage); received.set(false); server.sendToAllTCP(smallMessage); while (!received.get()) { Thread.sleep(100); } } // Sending large message String bigMessage = "RandomStringUtils.randomAlphanumeric(532)RandomStringUtils.randomAlphanumeric(532)RandomStringUtils.randomAlphanumeric(532)RandomStringUtils.randomAlphanumeric(532)RandomStringUtils.randomAlphanumeric(532)RandomStringUtils.randomAlphanumeric(532)RandomStringUtils.randomAlphanumeric(532)"; bigMessage = bigMessage + bigMessage + bigMessage + bigMessage + bigMessage + bigMessage + bigMessage; System.out.println("Sending: " + bigMessage); received.set(false); server.sendToAllTCP(bigMessage); while (!received.get()) { Thread.sleep(100); } }
398ea0ee-f510-40e9-bb7a-22439f6b5dfe
9
static public ParseException generateParseException() { jj_expentries.removeAllElements(); boolean[] la1tokens = new boolean[17]; for (int i = 0; i < 17; i++) { la1tokens[i] = false; } if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 2; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } } } } for (int i = 0; i < 17; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.addElement(jj_expentry); } } int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = (int[])jj_expentries.elementAt(i); } return new ParseException(token, exptokseq, tokenImage); }
bbc8558a-1577-4797-b5d2-f3749c4c921a
6
public void valueChanged(TreeSelectionEvent e) { JTree tree = (JTree) e.getSource(); TreePath treepath = tree.getSelectionPath(); if (null == treepath) return; NamedDataSectionable parentDataSectionable = null; if (treepath.getPathCount() > 1) parentDataSectionable = (NamedDataSectionable)treepath.getPathComponent(treepath.getPathCount() - 2); NamedDataSectionable namedDataSectionable = (NamedDataSectionable)treepath.getPathComponent(treepath.getPathCount() - 1); Object object = namedDataSectionable.getData(); if (namedDataSectionable instanceof ListItemDataSectionable) { ListItemDataSectionable listItemDataSectionable = (ListItemDataSectionable)namedDataSectionable; displayList(listItemDataSectionable.getParentDataSectionable(), listItemDataSectionable.getListID(), listItemDataSectionable.getList(), listItemDataSectionable.getIndex(), listItemDataSectionable.getIndex()); return; } else if (namedDataSectionable instanceof ListDataSectionable) { ListDataSectionable listDataSectionable = (ListDataSectionable)namedDataSectionable; displayList(listDataSectionable.getParentDataSectionable(), listDataSectionable.getListID(), listDataSectionable.getList(), listDataSectionable.getStartIndex(), listDataSectionable.getEndIndex()); return; } else if (null == parentDataSectionable) { displayPanel.removeAll(); displayPanel.add(new JLabel("Nothing selected.")); displayPanel.getTopLevelAncestor().validate(); return; } else { // if (object instanceof byte[]) // { // ByteDataTableControl bDTC = new ByteDataTableControl((byte[])object, 32, 0); // displayPanel.removeAll(); // displayPanel.add(bDTC); // displayPanel.getTopLevelAncestor().validate(); // return; // } DataSection dataSection; if (parentDataSectionable instanceof ListDataSectionable) { ListDataSectionable listDataSectionable = (ListDataSectionable)parentDataSectionable; dataSection = getDataSectionForParentAndName(parentDataSectionable, listDataSectionable.getListID()); } else { dataSection = getDataSectionForParentAndName(parentDataSectionable, namedDataSectionable.getLabel()); } // IMPLEMENT: probably dump the above display(parentDataSectionable, dataSection.getDataSectionName()); } }
d29c6a18-c8c1-424c-9972-60581fc71517
3
@Override public BufferedImage getImage(){ if(!running){ return images.get(0); }else{ long curTime = (System.currentTimeMillis() - startTime) ; for(int i=0; i<times.size(); i++){ if(curTime - times.get(i) <= 0){ return images.get(i); }else{ curTime -= times.get(i); } } } return images.get(images.size()-1); }
f23286a5-eb2d-4ec6-ba1b-f6773e790b52
5
public void actionPerformed(ActionEvent e) { String nick = GUIMain.userList.getSelectedValue().toString(); if (nick.startsWith("@")) { nick = nick.replace("@", ""); } else if (nick.startsWith("$")) { nick = nick.replace("$", ""); } else if (nick.startsWith("+")) { nick = nick.replace("+", ""); } else if (nick.startsWith("%")) { nick = nick.replace("%", ""); } else if (nick.startsWith("~")) { nick = nick.replace("~", ""); } Command.ban(nick); }
4d7ce855-1b34-420f-81a3-9614a47a4a7d
3
private void songEditMenu() { System.out.println(" Edit Menu "); System.out.println("1. |Create a song|"); System.out.println("2. |Delete a song|"); System.out.println("0. |Return|"); int option; option = new Scanner(System.in).nextInt(); switch (option) { case 1: createSong(); break; case 2: deleteSong(); break; case 0: songMenu(); break; } }
4fc1960e-beb8-4b19-84fc-727ce9de0ad1
1
public Timer() { huidigeTijd = BEGIN_TIJD; timer = new javax.swing.Timer(10, new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Date metingEindTijd = new Date(); long verschil = (metingEindTijd.getTime() - metingBeginTijd.getTime()) / 1000; if (verschil >= 1) { huidigeTijd--; setChanged(); notifyObservers(); metingBeginTijd = new Date(); } } }); }
6a091418-481a-4073-9cea-eeb0a2bc45b8
2
public static String moveBlank(String string) { if (null == string || blankPattern.matcher(string).matches()) { return null; } return string.replaceAll("^[\\s ]*|[\\s ]*$", "").trim(); }
2386213b-4356-4494-987a-85e064eb0898
6
public String execute() throws Exception { User user = userService.getCurrentUser(); if (user == null) return "login"; job = this.userService.userJob(user.getUid(), Integer.parseInt(cid)); System.out.println("job:" + job); Map<String, Object> details = new HashMap<String, Object>(); if (job.equals("free")) { destination = "goClubIndex?club.cid=" + cid; return job; } // return something details inside the club Map<String, Object> clubOriginalData = clubService.clubCommanDetails(Integer.parseInt(cid)); System.out.println("clubDetails:" + clubOriginalData.toString()); details.put("cid", clubOriginalData.get("cid")); details.put("name", clubOriginalData.get("name")); details.put("pic", clubOriginalData.get("pic").toString()); details.put("url", clubOriginalData.get("url").toString()); details.put("member", clubOriginalData.get("member").toString()); details.put("intro", clubOriginalData.get("intro").toString()); details.put("activity", clubOriginalData.get("activity").toString()); details.put("file", clubOriginalData.get("file").toString()); details.put("xp", clubOriginalData.get("xp").toString()); details.put("province", clubOriginalData.get("province").toString()); details.put("city", clubOriginalData.get("city").toString()); details.put("college", clubOriginalData.get("college").toString()); details.put("tag", clubOriginalData.get("tag").toString()); // return staff's uid array // PS: get username by Ajax details.put("leader", clubOriginalData.get("leader").toString()); details.put("publisher", clubOriginalData.get("publisher").toString()); details.put("member", clubOriginalData.get("member").toString()); /*details.put("publisher", this.userService.findUsersInfoByUids(clubOriginalData.get("publisher").toString())); details.put("leader", this.userService.findUsersInfoByUids(clubOriginalData.get("leader").toString())); details.put("member", this.userService.findUsersInfoByUids(clubOriginalData.get("member").toString()));*/ System.out.println("Dtails:" + details.toString()); requestMap.put("clubinfo", details); if (job.equals("leader")) { // TODO // something unique } if (job.equals("publisher")) { // TODO } if (job.equals("member")) { } if (job.equals("killer")) destination = "/myclub_member.jsp"; return job; // go to different type of page depends on user's job in the club }
b4bcbaa9-bac5-4495-b898-4c13fdb1b41a
8
public void buttonClick(ClickEvent event) { final Button source = event.getButton(); String initialText = ""; PersonContainer pc = as.getDataSource(); SearchFilter sf = as.getSf(); if(source==generate){ if (sf != null) { pc.removeAllContainerFilters(); pc.addContainerFilter(sf.getPropertyId(), sf.getTerm(), true, false); for (int i = 0; i < pc.size(); i++) { initialText += pc.getIdByIndex(i).getEmail() + ";"; } editor.setValue(initialText); } else { for (int i = 0; i < pc.size(); i++) { initialText += pc.getIdByIndex(i).getEmail() + ";"; } editor.setValue(initialText); } }else if(source==toExcel){ exportToExcel(pc,sf); }else if(source==close){ editor.setValue(""); }else if(source==cb){ editor.setValue(source.booleanValue()? "enabled" : "disabled"); } }
6b3b3602-5aa9-4d2d-9bad-5ee00a9f0a79
5
public static String expectedLocalPath(Case CASE) { String result = null; switch (CASE) { case CASE_1: result = "0000"; break; case CASE_2_3: result = "000"; break; case CASE_4: result = "000"; break; case BOOTSTRAP_1: case BOOTSTRAP_2: result = "0"; break; } return result; }
6ef6ba3f-1951-4a1e-bf9e-4e9bd0b437da
6
private void assertBoardsSize(int size8, Chessboard chessboard, int expectedBoardsSize) { assertThat("all elements are not present on each board", chessboard.placeFiguresOnEmptyBoard() .parallel() .filter(board -> !board.contains(KING.getFigureAsString()) && board.contains(QUEEN.getFigureAsString()) && !board.contains(BISHOP.getFigureAsString()) && !board.contains(ROOK.getFigureAsString()) && !board.contains(KNIGHT.getFigureAsString()) && board.contains(FIELD_UNDER_ATTACK_STRING) && leftOnlyFigures(board).length() == size8) .map(e -> 1) .reduce(0, (x, y) -> x + y), is(expectedBoardsSize)); }
4b502b9e-c367-429f-bdaa-59f19647a4e2
1
public static void main(String args[]) { String filePath = "./b/c.txt"; File file = new File(filePath); try { boolean created = createFile(file); } catch (IOException e) { e.printStackTrace(); } }
55f07f88-2b1e-4dfc-b7a8-3b9df58ca210
9
public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int length = to.length(); char[] circle = new char[length]; /* * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ for (i = 0; i < length; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* * We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* * Compare the circle buffer with the to string. */ for (i = 0; i < length; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= length) { j -= length; } } /* * If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* * Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= length) { offset -= length; } } }
7ae10268-f78f-420e-9612-7c8ecc4efdc4
0
public boolean isMovingDown() { return isMovingDown; }
f55d7f6b-12b6-429f-b03e-5fe62295b2f3
3
@Override public void run() { try { //Keep a socket open to listen to all the UDP trafic that is destined for this port socket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0")); socket.setBroadcast(true); while (true) { System.out.println(getClass().getName() + ">>>Ready to receive broadcast packets!"); //Receive a packet byte[] recvBuf = new byte[15000]; DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length); socket.receive(packet); //Packet received System.out.println(getClass().getName() + ">>>Discovery packet received from: " + packet.getAddress().getHostAddress()); System.out.println(getClass().getName() + ">>>Packet received; data: " + new String(packet.getData())); //See if the packet holds the right command (message) String message = new String(packet.getData()).trim(); if (message.equals("DISCOVER_FUIFSERVER_REQUEST")) { byte[] sendData = "DISCOVER_FUIFSERVER_RESPONSE".getBytes(); //Send a response DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, packet.getAddress(), packet.getPort()); socket.send(sendPacket); System.out.println(getClass().getName() + ">>>Sent packet to: " + sendPacket.getAddress().getHostAddress()); } } } catch (IOException ex) { System.err.println("Error de socket: " + ex.getMessage()); } }
13993df5-2d55-4a9f-b220-8c828363d0d4
3
private int getIntFromElement(Element ele, SPSelector sel) { Elements els = subSelect(ele, sel.getSelector()); if(els.size() == 0) { return -1; } String text = els.get(0).outerHtml(); Modifier mod = sel.getModifier(); if(mod != null) { text = mod.getResult(text); } int res = -1; try { res = Integer.parseInt(text); } catch(NumberFormatException e) { return -1; } return res; }
349b5b9f-703c-4c58-a3f1-cc926625ff66
2
public void testPropertySetSecond() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); TimeOfDay copy = test.secondOfMinute().setCopy(12); check(test, 10, 20, 30, 40); check(copy, 10, 20, 12, 40); try { test.secondOfMinute().setCopy(60); fail(); } catch (IllegalArgumentException ex) {} try { test.secondOfMinute().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} }
34e5cabc-7e77-4253-ab94-a2d33356d844
2
public void setTime(int hhmmss) { if (!hiding && clockmode != MODE_TSET) { clocktime = hhmmss; } clkcanvas.repaint(); }
686ea202-9330-477d-b165-d7464b3fc5f7
1
public ArrayList<Integer> ShuffleDeck(ArrayList<Integer> shuffledDeck){ for (int i=0;i<numOfCards;i++) { shuffledDeck.add(i);//populates arraylist with 0-51 //System.out.println(shuffledDeck.size()); Testing statement } shuffledDeck = Shuffle(shuffledDeck); //calls another shuffling method return shuffledDeck; }
e190c5ea-a4d2-4c8e-8f82-020d91be525d
1
private boolean isMediumPriorityOperator(String o) { return o.equals(OPERATION_MULTIPLY) || o.equals(OPERATION_DIVISION); }
f8d15c7c-8006-4d3a-841c-93a8220d757d
8
String sendSSAPMsg(String msg) { String ret=""; int err=0; deb_print("KpCore:message to send:_"+msg.replace("\n", "")+"_"); deb_print("KpCore:SSAP:Open connection..."); if((err = openConnect()) <0) {err_print("KpCore:SSAP:ERROR:"+ERR_MSG[(err*-1)] ); KP_ERROR_ID=err; return null;} else {deb_print("KpCore:SSAP:"+ERR_MSG[(err)] );} deb_print("KpCore:SSAP:Send the message..."); if((err =send( msg )) <0) {err_print("KpCore:SSAP:ERROR:"+ERR_MSG[(err*-1)] ); KP_ERROR_ID=err; return null;} else {deb_print("KpCore:SSAP:"+ERR_MSG[(err)] );} deb_print("KpCore:SSAP:Read the answer..."); if(msg.indexOf("<transaction_type>UNSUBSCRIBE</transaction_type>")<0) try{ ret = receive(); deb_print("KpCore:SSAP:answer:"+"ok _"+ret.replace("\n", "")+"_\n");} catch(Exception e){err=this.KP_ERROR_ID; if(err<0) err_print("KpCore:SSAP:ERROR:"+ERR_MSG[(err*-1)] ); else{ err=ERR_RECEIVE_FAIL; if(err<0) err_print("KpCore:SSAP:ERROR:"+ERR_MSG[(err*-1)] ); } err_print("EXCEPTION: "+e.toString()); e.printStackTrace(); KP_ERROR_ID=err; return null;} //if(msg.indexOf("")>=0) else deb_print("KpCore:SSAP:UnSubscription Request:no answer expected:"+"ok"+"\n"); deb_print("KpCore:SSAP:Close connection..."); if((err= closeConnection()) <0) {err_print("KpCore:SSAP:ERROR:"+ERR_MSG[(err*-1)] ); KP_ERROR_ID=err; return null;} if(this.KP_ERROR_ID>=0)this.KP_ERROR_ID=err; return ret; }//String SSAP(String msg)
c818471f-cbf2-4132-a59c-fed4bfad59ee
9
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY); if(target==null) return false; final List<DeadBody> DBs=CMLib.utensils().getDeadBodies(target); for(int v=0;v<DBs.size();v++) { final DeadBody DB=DBs.get(v); if(DB.isPlayerCorpse() &&(!DB.getMobName().equals(mob.Name()))) { mob.tell(L("You are not allowed to destroy a player corpse.")); return false; } } if(!CMLib.utensils().canBePlayerDestroyed(mob,target,true)) { mob.tell(L("You are not powerful enough to destroy @x1.",target.name(mob))); return false; } if(!super.invoke(mob,commands, givenTarget, auto,asLevel)) return false; boolean success=proficiencyCheck(mob,(((mob.phyStats().level()+(2*getXLEVELLevel(mob)))-target.phyStats().level())*25),auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto), (auto?"<T-NAME> begins to glow!" :"^S<S-NAME> incant(s) at <T-NAMESELF>!^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); mob.location().show(mob,target,CMMsg.MSG_OK_VISUAL,L("<T-NAME> vanish(es) into thin air!")); target.destroy(); mob.location().recoverRoomStats(); } } else beneficialWordsFizzle(mob,target,L("<S-NAME> incant(s) at <T-NAMESELF>, but nothing happens.")); // return whether it worked return success; }
0829570e-5092-4c1d-b034-dc0e540418e8
2
@RequestMapping(value = {"/MovimientoBancario/{idMovimientoBancario}"}, method = RequestMethod.PUT) public void update(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse, @PathVariable("idMovimientoBancario") int idMovimientoBancario, @RequestBody String json) { try { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); MovimientoBancario movimientoBancarioUpdate = movimientoBancarioDAO.read(idMovimientoBancario); MovimientoBancario movimientoBancario = (MovimientoBancario) objectMapper.readValue(json, MovimientoBancario.class); movimientoBancarioUpdate.setIdMovimientoBancario(movimientoBancario.getIdMovimientoBancario()); movimientoBancarioUpdate.setConcepto(movimientoBancario.getConcepto()); movimientoBancarioUpdate.setCuentaBancaria(movimientoBancario.getCuentaBancaria()); movimientoBancarioUpdate.setFecha(movimientoBancario.getFecha()); movimientoBancarioUpdate.setImporte(movimientoBancario.getImporte()); movimientoBancarioUpdate.setTipoMovimientoBancario(movimientoBancario.getTipoMovimientoBancario()); movimientoBancarioDAO.update(movimientoBancarioUpdate); noCache(httpServletResponse); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setContentType("application/json; charset=UTF-8"); httpServletResponse.getWriter().println(json); } catch (Exception ex) { noCache(httpServletResponse); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); httpServletResponse.setContentType("text/plain; charset=UTF-8"); try { noCache(httpServletResponse); ex.printStackTrace(httpServletResponse.getWriter()); } catch (Exception ex1) { noCache(httpServletResponse); } } }
53f058a3-7b17-46af-81af-a22f4c1c69ae
3
public boolean replace(int index, T newV) { if (index < 0 || index >= size) return false; T oldV = heap.get(index).element(); heap.get(index).setElement(newV); if (comp.compare(oldV, newV) < 0) trickleUp(index); else trickleDown(index); return true; }
d255ba75-447e-4d16-9679-9341f31c1fd6
9
public boolean spacesAvailable(Vehicle v) { // Test for Cars. if (v instanceof Car) { // Test for small cars. if (((Car) v).isSmall()) { if (smallCarsParked.size() < maxSmallCarSpaces) { return true; } else if (carsParked.size() < maxCarSpaces) { return true; } } // Test for normal cars. else if (((Car) v).isSmall() == false) { if (carsParked.size() < maxCarSpaces) { return true; } } return false; } // Test for MotorCycles. else if (v instanceof MotorCycle) { if (motorCyclesParked.size() < maxMotorCycleSpaces) { return true; } else if (smallCarsParked.size() < maxSmallCarSpaces) { return true; } } // Else return false. I.e. No available parks. return false; }
a931f22a-3836-4725-b685-444f923cf46c
4
public int sqrt(int x) { if (x == 0) return 0; if (x == 1) return 1; double value = x; int intvalue = x; while (intvalue > 46340 || intvalue * intvalue > x) { value = (value * value + x) / (2 * value); intvalue = (int) value; } return intvalue; }
46256e63-03aa-4dac-ae24-305327cbc8cb
6
private void completeAllEffects() { if(pendingEffects.isEmpty()) return; Collection<ForkJoinTask> receipts = new LinkedList<>(); //submit all actions. For each agent they happen in sequence for(Map.Entry<Agent,Collection<Effect>> effects : pendingEffects.asMap().entrySet() ) { List<Effect> todo =(List)effects.getValue(); //the cast is always correct because it's a MultiMapList final ForkJoinTask<?> receipt = threadPool.submit(() -> { Collections.sort(todo); for (Effect e : todo) e.run(); }); receipts.add(receipt); } //now wait for all of them to complete try { for (ForkJoinTask receipt : receipts) receipt.get(); pendingEffects.clear(); } catch (Exception e){ e.printStackTrace(); System.err.println("interrupted"); System.exit(-1); } //done }
14104512-0056-4884-b031-73f4ff1c94b3
2
public void pickup(Item i, Player p){ if(id == 0.0f){ return; } scheduleRespawn(); ClassType ct = PluginData.getPlayerData(p).getPlayerClass(); if(ct == null) return; p.setHealth(ct.getMaxHealth()); i.setFireTicks(999); }
72f4cdf9-036f-45e5-a740-cfe821bfb599
9
@Override public long read(T target) throws IOException { long totalRead = 0; while (target.remainingSpace() > 0) { if (buffer.remainingData() > 0) totalRead += buffer.read(target); else if (parentMightBeEmpty && totalRead > 0) break; else { long read = parent.read(buffer); if (buffer.remainingSpace() > 0) parentMightBeEmpty = true; else parentMightBeEmpty = false; if (read == -1) { closed = true; break; } else if (read == 0) break; } } return totalRead == 0 && closed ? -1 : totalRead; }
d59ae7ed-f814-4985-9c86-23e9d9a112a6
5
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Predicate predicate = (Predicate) obj; if (!getArgs().equals(predicate.getArgs())) return false; if (!getName().equals(predicate.getName())) return false; return true; }
9ef8b7ec-61cf-4179-84a4-4c68d2feed88
0
public void DisPlayPic(String _title, int _x, int _y) { JFrame frame = new JFrame(); frame.setTitle(_title); frame.setLocation(_x, _y); JLabel label = new JLabel(new ImageIcon(img)); frame.getContentPane().add(label, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }
47d0dfc5-3a52-4e46-92c2-e85e8ee85a12
6
@Override public void send(String msg, User user) { for (User u : users) { if (!u.equals(user) && user instanceof PrivilegedUser && u instanceof PrivilegedUser) { // security workaround ((PrivilegedUser) u).handleSecret(msg); } else if (!u.equals(user) && !(user instanceof PrivilegedUser)){ // we don't need to handle a message from ourselves u.handle(msg); } } }
fbac4a85-59bb-4323-aae3-5cbb37fef698
3
public Screen() { super(); paused = false; screen = new Square[22][10]; for (int row = 0; row < 20; ++row) { for (int col = 0; col < 10; ++col) { screen[row][col] = new Square(true, Color.BLUE); } } for(int i = 0; i < 10; ++i){ screen[20][i] = new Square(false, Color.BLACK); screen[21][i] = new Square(false, Color.BLACK); } setBackground(Color.BLACK); setBorder(BorderFactory.createLineBorder(Color.RED)); Dimension d = new Dimension(350, 694); setPreferredSize(d); }
e78123bc-d8e2-4bfb-920d-0c86c065e523
3
private String createEventMessage(long time, String eventName, List<MMTFieldValueHeader> fieldValueElements) { String retval = ""; if(this.payloadFormat.equals(this.RFC2822)){ retval = createRequestLine(time, eventName); for (MMTFieldValueHeader fvh : fieldValueElements) { retval = retval + createHeaderLine(fvh); } retval = retval + CRLF; //We end the Message with an extra CRLF } if(this.payloadFormat.equals(this.JSON)){ MMTEvent mmtevent = new MMTEvent(); mmtevent.setProtoName(this.getProtoConfig().getProtocolName()); mmtevent.setProtoId(this.getProtoConfig().getProtocolID()); Event event = new Event(); event.setEventName(eventName); event.setServiceId(serviceID); event.setTimestamp(time); event.setAttributes(fieldValueElements); mmtevent.setEvent(event); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(GenericFieldValueHeader.class, new FieldValueAdapter()); Gson gson = gsonBuilder.create(); retval = gson.toJson(mmtevent); } return retval; }
9bebf586-d320-48d9-a189-1ffdbba8b499
6
public static Keyword invertUpdateMode(Keyword updatemode) { if (updatemode == Logic.KWD_ASSERT_TRUE) { return (Logic.KWD_ASSERT_FALSE); } else if (updatemode == Logic.KWD_PRESUME_TRUE) { return (Logic.KWD_PRESUME_FALSE); } else if (updatemode == Logic.KWD_RETRACT_TRUE) { return (Logic.KWD_RETRACT_FALSE); } else if (updatemode == Logic.KWD_ASSERT_FALSE) { return (Logic.KWD_ASSERT_TRUE); } else if (updatemode == Logic.KWD_PRESUME_FALSE) { return (Logic.KWD_PRESUME_TRUE); } else if (updatemode == Logic.KWD_RETRACT_FALSE) { return (Logic.KWD_RETRACT_TRUE); } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + updatemode + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } }
d6f69bf5-349e-4c18-bc21-0a4401b00664
2
@Override public int compareTo(AstronomicalObject o) { return (this.mass < o.mass) ? -1 : (this.mass > o.mass) ? 1 : 0; }
06fd0f13-a1af-4149-b858-ece3e71dbc95
4
@Override public void mouseClicked(MouseEvent e) { p = e.getPoint(); if(hideButton.contains(p) && hide == false){ hide = true; }else if(hideButton.contains(p) && hide == true){ hide = false; } }
f51da46c-fc7b-4696-96f9-1ea356455a76
5
public void run() { while (true) { if (server.quit) return; try { //System.out.println("Reading..."); PlayerCommand pc = (PlayerCommand) ois.readObject(); if (pc.command == PlayerCommand.MESSAGE) { String message = pc.message; if (playerNumber == 1) message = server.gameState.player1.screenName + ": " + message; else message = server.gameState.player2.screenName + ": " + message; server.sendMessageInBackground(message); } else server.ssc.executePlayerCommand(pc, playerNumber); } catch(Exception e) { server.quitApplication(e); } } }
09d685ce-3b6e-4587-8013-3e44b86b555d
4
* @return the percent as a float */ public float getUniquePercentage( short version ) { int totalLen = 0; int uniqueLen = 0; if ( numVersions()==1 ) return 0.0f; else { for ( int i=0;i<pairs.size();i++ ) { Pair p = pairs.get( i ); if ( p.versions.nextSetBit(version)==version ) { if ( p.versions.size()==1 ) uniqueLen+= p.length(); totalLen += p.length(); } } return (float)uniqueLen/(float)totalLen; } }
2b98e1ad-5eae-4b84-9e9a-f42b499f05a6
7
protected static Ptg calcLarge( Ptg[] operands ) throws CalculationException { if( operands.length != 2 ) { return new PtgErr( PtgErr.ERROR_VALUE ); } Ptg rng = operands[0]; Ptg[] array = PtgCalculator.getAllComponents( rng ); if( array.length == 0 ) { return new PtgErr( PtgErr.ERROR_NUM ); } int k = new Double( PtgCalculator.getDoubleValueArray( operands[1] )[0] ).intValue(); if( (k <= 0) || (k > array.length) ) { return new PtgErr( PtgErr.ERROR_NUM ); } CompatibleVector sortedValues = new CompatibleVector(); for( Ptg p : array ) { try { Double d = new Double( String.valueOf( p.getValue() ) ); sortedValues.addOrderedDouble( d ); } catch( NumberFormatException e ) { } ; } // reverse array Double[] dubRefs = new Double[sortedValues.size()]; for( int i = 0; i < dubRefs.length; i++ ) { dubRefs[i] = (Double) sortedValues.last(); sortedValues.remove( sortedValues.size() - 1 ); } return new PtgNumber( dubRefs[k - 1] ); /* try { Ptg[] parray= PtgCalculator.getAllComponents(operands[0]); Object[] array= new Object[parray.length]; for (int i= 0; i < array.length; i++) { array[i]= parray[i].getValue(); if (array[i] instanceof Integer) { // convert all to double if possible for sort below (cannot have mixed array for Arrays.sort) try { array[i]= new Double(((Integer)array[i]).intValue()); } catch (Exception e) { } } } // now sort java.util.Arrays.sort(array); int position= (int) PtgCalculator.getLongValue(operands[1]); // now return the nth item in the sorted (asc) array if (position >=0 && position <=array.length) { Object ret= array[array.length-position]; if (ret instanceof Double) return new PtgNumber(((Double)ret).doubleValue()); else if (ret instanceof Boolean) return new PtgBool(((Boolean)ret).booleanValue()); else if (ret instanceof String) return new PtgStr((String)ret); } } catch (Exception e) { } return new PtgErr(PtgErr.ERROR_NUM); */ }
fbc17dd9-0403-4551-a1fe-4bc3f2c1fb7b
0
public boolean isAlive() { return this.health <=0 ; }
56339486-f9e9-428e-bd9b-fb12dfc04ec0
3
private String CharToPN(char c) { // binary format of ascii of char c String binaryStringShort = Integer.toBinaryString((int)c); // fill the 0s to get 8 bits StringBuffer paddingBuffer = new StringBuffer(); while(paddingBuffer.length() < 8 - binaryStringShort.length()) { paddingBuffer.append("0"); } String binaryString = paddingBuffer.toString() + binaryStringShort; // split into 2 parts and encode each one String[] binaryStrings = new String[] { binaryString.substring(0, 4), binaryString.substring(4, 8) }; StringBuffer codewordBuffer = new StringBuffer(); for (String bits : binaryStrings) { // if count #one is odd, check is the same as info, or complement String check; if(CountOne(bits) % 2 == 1) { check = bits; } else { check = Complement(bits); } // combine info with check codewordBuffer.append(bits + check); } return codewordBuffer.toString(); }
e97659d5-2760-4313-8620-c4bea40be0eb
7
public ModularityDetection(LinkedList<KeyWord> partKeywords, double[][] correlations, float startDay, float endDay, int window_, String nwtFolder_) throws Exception{ this.startDay = startDay; this.endDay = endDay; window = window_; nwtFolder = nwtFolder_; // instantiate structure NodeFactory<Node> nodeFactory = new NodeFactory<>(new Node()); EdgeFactory<Edge<Node>> edgeFactory = new EdgeFactory<>(new Edge<Node>()); structure = new Structure<>(nodeFactory, edgeFactory); System.out.println(" partKeywords.size()" + partKeywords.size()); for(int i = 0; i < partKeywords.size()-1; i++){ for(int j = i+1; j < partKeywords.size(); j++){ if(correlations[i][j] > 0.0){ //Adding keywords structure.addNode(partKeywords.get(i).getKeyWord()); structure.addNode(partKeywords.get(j).getKeyWord()); //Adding edges structure.addEdge(new Edge<Node>(structure.getNode(partKeywords.get(i).getKeyWord()),structure.getNode(partKeywords.get(j).getKeyWord()),correlations[i][j])); } } } nodeList = structure.getNodesOrderedByNames(); System.out.println("[window "+window+"] ["+startDay+","+endDay+"] : Number of nodes: " + structure.getSize()); System.out.println("[window "+window+"] ["+startDay+","+endDay+"] : Number of edges: " + structure.getNumEdges()); if(structure.getNumEdges()>0){//IF THERE IS NO EDGE, NO NEED TO PARTITION // instantiate JmodNetwork JmodNetwork network = new JmodNetwork(structure); JmodSettings settings = JmodSettings.getInstance(); settings.setUseMovingVertex(false); settings.setUseGlobalMovingVertex(false); if(Boolean.valueOf(Main.mapParam.get("debugMode"))){ // select the datasets to export // modularity Q and number of indivisible communities settings.setExportBasicDataset(true); // export the modules detected to files settings.setExportCommunityNetworks(true); // specify the file format of the modules detected settings.setCommunityNetworkFormat(Structure.TSV); // export the original network in GML format with node // colors depending on which module a given node belongs to settings.setExportColoredCommunities(true); // export the community tree (dendrogram) settings.setExportCommunityTree(true); } // run modularity detection Jmod jmod = new Jmod(); try { jmod.runModularityDetection(network); events = new LinkedList<>(); RootCommunity rc = jmod.getRootCommunity(); System.out.println("[window "+window+"] ["+startDay+","+endDay+"] : There are "+rc.getNumIndivisibleCommunities()+" indivisible communities."); arrayCommunities = rc.getIndivisibleCommunities(); //put events in events explore(rc,nodeList); // for(Community c:arrayCommunities){ // exploreCommunity(c,nodeList); // } } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); } if(Boolean.valueOf(Main.mapParam.get("debugMode"))){ // set output directory //create the folder "results" String pathRes = nwtFolder+"/results/Jmod/window"+window; File fb = new File(pathRes); fb.mkdirs(); URI outputDirURI = new URI(pathRes); // run modularity detection jmod.setOutputDirectory(outputDirURI); jmod.printResult(); jmod.exportDataset(); } } }
f2339511-76f3-429c-827b-4ac61e8e7bb7
5
private static ArrayList<Branch> loadBranch(ArrayList<String> texts) { ArrayList<String> strings = new ArrayList<String>(); ArrayList<Branch> branches = new ArrayList<Branch>(); int startLine = 0; for(int lineNumber = 0;lineNumber < texts.size();lineNumber++){ String aString = texts.get(lineNumber); if(aString.equals("branches:")){ startLine = lineNumber+1; break; } } for(int lineNumber = startLine;lineNumber < texts.size();lineNumber++){ String aString = texts.get(lineNumber); if(aString == null){ break; }else{ strings.add(aString); } } for(String aString : strings) { String[] branchStrings = aString.split(",."); Branch aBranch = new Branch(Integer.parseInt(branchStrings[0]),Integer.parseInt(branchStrings[1])); branches.add(aBranch); } return branches; }
8c49b627-836a-4bef-a71f-515902752146
2
private void commenceTrade() { try { if(host) { Pokemon temp=new Pokemon(Pokemon.Species.BULBASAUR); //Strings temp.species=Pokemon.Species.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].species); outTacular.flush(); temp.nickname=inTacular.readUTF(); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].nickname); outTacular.flush(); temp.originalTrainer=inTacular.readUTF(); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].originalTrainer); outTacular.flush(); temp.status=Pokemon.Status.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].status); outTacular.flush(); temp.substatus=Pokemon.Substatus.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].substatus); outTacular.flush(); temp.move[0]=Pokemon.Move.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].move[0]); outTacular.flush(); temp.move[1]=Pokemon.Move.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].move[1]); outTacular.flush(); temp.move[2]=Pokemon.Move.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].move[2]); outTacular.flush(); temp.move[3]=Pokemon.Move.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].move[3]); outTacular.flush(); //Integers temp.level=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].level)); outTacular.flush(); temp.exp=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].exp)); outTacular.flush(); temp.health=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].health)); outTacular.flush(); temp.healthMax=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].healthMax)); outTacular.flush(); temp.HP_EV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].HP_EV)); outTacular.flush(); temp.ATK_EV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].ATK_EV)); outTacular.flush(); temp.DEF_EV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].DEF_EV)); outTacular.flush(); temp.SPCL_EV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].SPCL_EV)); outTacular.flush(); temp.SPEED_EV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].SPEED_EV)); outTacular.flush(); temp.HP_IV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].HP_IV)); outTacular.flush(); temp.ATK_IV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].ATK_IV)); outTacular.flush(); temp.DEF_IV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].DEF_IV)); outTacular.flush(); temp.SPCL_IV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].SPCL_IV)); outTacular.flush(); temp.SPEED_IV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].SPEED_IV)); outTacular.flush(); temp.TRUE_PP[0]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[0])); outTacular.flush(); temp.TRUE_PP[1]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[1])); outTacular.flush(); temp.TRUE_PP[2]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[2])); outTacular.flush(); temp.TRUE_PP[3]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[3])); outTacular.flush(); temp.TRUE_PPMAX[0]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[0])); outTacular.flush(); temp.TRUE_PPMAX[1]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[1])); outTacular.flush(); temp.TRUE_PPMAX[2]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[2])); outTacular.flush(); temp.TRUE_PPMAX[3]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[3])); outTacular.flush(); //Booleans outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].IS_TRADED); outTacular.flush(); temp.IS_TRADED=Boolean.parseBoolean(inTacular.readUTF()); JokemonDriver.partyPokemon[JokemonDriver.offerIndex]=new Pokemon(temp.species, temp.move[0], temp.move[1], temp.move[2], temp.move[3], temp.level, temp.HP_IV, temp.ATK_IV, temp.DEF_IV, temp.SPCL_IV, temp.SPEED_IV, temp.nickname, temp.status, temp.idNumber, temp.originalTrainer); JokemonDriver.partyPokemon[JokemonDriver.offerIndex].setEV("HP",temp.HP_EV); JokemonDriver.partyPokemon[JokemonDriver.offerIndex].setEV("ATK",temp.ATK_EV); JokemonDriver.partyPokemon[JokemonDriver.offerIndex].setEV("DEF",temp.DEF_EV); JokemonDriver.partyPokemon[JokemonDriver.offerIndex].setEV("SPCL",temp.SPCL_EV); JokemonDriver.partyPokemon[JokemonDriver.offerIndex].setEV("SPEED",temp.SPEED_EV); JokemonDriver.partyPokemon[JokemonDriver.offerIndex].health=temp.health; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].healthMax=temp.healthMax; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].exp=temp.exp; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[0]=temp.TRUE_PP[0]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[1]=temp.TRUE_PP[1]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[2]=temp.TRUE_PP[2]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[3]=temp.TRUE_PP[3]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[0]=temp.TRUE_PPMAX[0]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[1]=temp.TRUE_PPMAX[1]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[2]=temp.TRUE_PPMAX[2]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[3]=temp.TRUE_PPMAX[3]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].IS_TRADED=true; } else { Pokemon temp=new Pokemon(Pokemon.Species.BULBASAUR); //Strings outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].species); outTacular.flush(); temp.species=Pokemon.Species.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].nickname); outTacular.flush(); temp.nickname=inTacular.readUTF(); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].originalTrainer); outTacular.flush(); temp.originalTrainer=inTacular.readUTF(); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].status); outTacular.flush(); temp.status=Pokemon.Status.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].substatus); outTacular.flush(); temp.substatus=Pokemon.Substatus.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].move[0]); outTacular.flush(); temp.move[0]=Pokemon.Move.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].move[1]); outTacular.flush(); temp.move[1]=Pokemon.Move.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].move[2]); outTacular.flush(); temp.move[2]=Pokemon.Move.valueOf(inTacular.readUTF()); outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].move[3]); outTacular.flush(); temp.move[3]=Pokemon.Move.valueOf(inTacular.readUTF()); //Integers outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].level)); outTacular.flush(); temp.level=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].exp)); outTacular.flush(); temp.exp=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].health)); outTacular.flush(); temp.health=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].healthMax)); outTacular.flush(); temp.healthMax=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].HP_EV)); outTacular.flush(); temp.HP_EV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].ATK_EV)); outTacular.flush(); temp.ATK_EV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].DEF_EV)); outTacular.flush(); temp.DEF_EV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].SPCL_EV)); outTacular.flush(); temp.SPCL_EV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].SPEED_EV)); outTacular.flush(); temp.SPEED_EV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].HP_IV)); outTacular.flush(); temp.HP_IV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].ATK_IV)); outTacular.flush(); temp.ATK_IV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].DEF_IV)); outTacular.flush(); temp.DEF_IV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].SPCL_IV)); outTacular.flush(); temp.SPCL_IV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].SPEED_IV)); outTacular.flush(); temp.SPEED_IV=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[0])); outTacular.flush(); temp.TRUE_PP[0]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[1])); outTacular.flush(); temp.TRUE_PP[1]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[2])); outTacular.flush(); temp.TRUE_PP[2]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[3])); outTacular.flush(); temp.TRUE_PP[3]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[0])); outTacular.flush(); temp.TRUE_PPMAX[0]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[1])); outTacular.flush(); temp.TRUE_PPMAX[1]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[2])); outTacular.flush(); temp.TRUE_PPMAX[2]=Integer.parseInt(inTacular.readUTF(),2); outTacular.writeUTF(Integer.toBinaryString(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[3])); outTacular.flush(); temp.TRUE_PPMAX[3]=Integer.parseInt(inTacular.readUTF(),2); //Booleans outTacular.writeUTF(""+JokemonDriver.partyPokemon[JokemonDriver.offerIndex].IS_TRADED); outTacular.flush(); temp.IS_TRADED=Boolean.parseBoolean(inTacular.readUTF()); JokemonDriver.partyPokemon[JokemonDriver.offerIndex]=new Pokemon(temp.species, temp.move[0], temp.move[1], temp.move[2], temp.move[3], temp.level, temp.HP_IV, temp.ATK_IV, temp.DEF_IV, temp.SPCL_IV, temp.SPEED_IV, temp.nickname, temp.status, temp.idNumber, temp.originalTrainer); JokemonDriver.partyPokemon[JokemonDriver.offerIndex].setEV("HP",temp.HP_EV); JokemonDriver.partyPokemon[JokemonDriver.offerIndex].setEV("ATK",temp.ATK_EV); JokemonDriver.partyPokemon[JokemonDriver.offerIndex].setEV("DEF",temp.DEF_EV); JokemonDriver.partyPokemon[JokemonDriver.offerIndex].setEV("SPCL",temp.SPCL_EV); JokemonDriver.partyPokemon[JokemonDriver.offerIndex].setEV("SPEED",temp.SPEED_EV); JokemonDriver.partyPokemon[JokemonDriver.offerIndex].health=temp.health; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].healthMax=temp.healthMax; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].exp=temp.exp; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[0]=temp.TRUE_PP[0]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[1]=temp.TRUE_PP[1]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[2]=temp.TRUE_PP[2]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PP[3]=temp.TRUE_PP[3]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[0]=temp.TRUE_PPMAX[0]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[1]=temp.TRUE_PPMAX[1]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[2]=temp.TRUE_PPMAX[2]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].TRUE_PPMAX[3]=temp.TRUE_PPMAX[3]; JokemonDriver.partyPokemon[JokemonDriver.offerIndex].IS_TRADED=true; } } catch(Exception e) { e.printStackTrace(); JokemonDriver.save(); System.exit(0); } JokemonDriver.tradeConfirm=false; JokemonDriver.friendTradeConfirm=false; Pokedex.seen(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].pokedexNumber-1); Pokedex.caught(JokemonDriver.partyPokemon[JokemonDriver.offerIndex].pokedexNumber-1); JokemonDriver.save(); }
2a36bbad-e718-453a-a498-2f283a73cc86
9
public void moveEntity(Entity e, int dx, int dy) { //move entity //attempt to animate the movement //if cursor... if (e==input.entity) { //if within the map boundaries (0,0) to (map[0].length, map.length)... if (! (e.x+dx < 0 || e.y+dy < 0 || e.x+dx >= map[0].length || e.y+dy >= map.length)) { e.x += dx; e.y += dy; //e._x = - dx * DEFAULT_TILE_SIZE; //e._y = - dy * DEFAULT_TILE_SIZE; //this.moveCamera(-dx * DEFAULT_TILE_SIZE, -dy * DEFAULT_TILE_SIZE); this.moveCamera(dx, dy); } else { System.err.println("Attempted to take cursor outside of map! " + (e.x+dx) + " " + (e.y+dy) + ""); messages.add("Attempted to take entity outside of map! " + (e.x+dx) + " " + (e.y+dy) + ""); } } else { if (! (e.x+dx < 0 || e.y+dy < 0 || e.x+dx >= map[0].length || e.y+dy >= map.length)) { e.x += dx; e.y += dy; //e._x = - dx * DEFAULT_TILE_SIZE; //e._y = - dy * DEFAULT_TILE_SIZE; //this.moveCamera(-dx * DEFAULT_TILE_SIZE, -dy * DEFAULT_TILE_SIZE); //this.moveCamera(dx, dy); } else { //System.err.println("Attempted to take cursor outside of map! " + (e.x+dx) + " " + (e.y+dy) + ""); messages.add("Attempted to take entity outside of map! " + (e.x+dx) + " " + (e.y+dy) + ""); } } }
f1e27a79-e100-4e56-9151-f0b5630d2e00
2
@Override public void run() { while (true) { try { // take next action and handle it DoItLater action = actionQueue.take(); action.doIt(); } catch (InterruptedException e) { } } }
f109a37a-e56c-42a8-abbd-93103845016c
3
public int available() throws IOException { if( this.isClosed ) return 0; if( this.currentReplacementBuffer != null ) return this.currentReplacementBuffer.available(); if( this.multiIn.eoiReached() ) return 0; else return 1; }
553bccef-e228-405b-a42a-22ca16b9a61d
2
public int GetDeviceID(String deviceName, int userID) throws Exception { String s = "-8"; int id = -2; try { // This will load the MySQL driver, each DB has its own driver Class.forName("com.mysql.jdbc.Driver"); // Setup the connection with the DB _connect = DriverManager.getConnection(_url, _user, _password); // PreparedStatements can use variables and are more efficient String sql = "SELECT * FROM devices WHERE name = ? AND users_id = ?"; _preparedStatement = _connect.prepareStatement(sql); _preparedStatement.setString(1, deviceName); _preparedStatement.setInt(2, userID); _resultSet = _preparedStatement.executeQuery(); if (_resultSet.next()) { s = _resultSet.getString("id"); id = Integer.parseInt(s); } } catch (Exception e) { throw e; } finally { close(); } return id; } // End getUserID
f572d33e-8d3b-410a-9abd-cf7bebaa63e7
2
private void doViewAllXinWen(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pageNum = StringUtil.toString(request.getParameter("pageNum")); if("".equals(pageNum)) { pageNum = "1"; } try { Pager<XinWen> pager = manager.getCurrentPageXinWens(pageNum); request.setAttribute("pager",pager); request.getRequestDispatcher("/admin/xinwen/xinwenList.jsp").forward(request,response); return; } catch (SQLException e) { logger.error("查找所有新闻失败",e); request.setAttribute("errorMsg","查找所有新闻失败"); request.getRequestDispatcher("/admin/error.jsp").forward(request, response); return; } }
edd60d70-21ba-49b0-b80c-7ca67d1494ed
3
public void setMatrix(int rows, int columns){ if ((rows<1)||(columns<1)) { System.out.println("number of rows and columns must be positive integer"); } this.rows=rows; this.columns=columns; elements=new double[rows][columns]; if (columns==rows){ determinant=1; } }
0acbb860-4c69-4a70-9b7e-b2544b90918d
6
public void criarEncarregado(Usuario Encarregado, Usuario userLogado) throws SQLException, excecaoEncarregadoExistente, excecaoControleAcesso { UsuarioDAO userDAO = new UsuarioDAO(); DepartamentoDAO DepDAO = new DepartamentoDAO(); Usuario EncarregadoExistente = userDAO.selectEncarregado(Encarregado.getNome(), Encarregado.getTipo()); //VERIFICA SE HA ALGUM ENCARREGADO CADASTRADO COM O MESMO NOME if (EncarregadoExistente == null) { //VERIFICA SE O GERENTE ESTAR CADASTRANDO ENCARREGADOS SOMENTE EM SE DEPARTAMENTO if (userLogado.getTipo().equals("Gerente") || userLogado.getTipo().equals("Diretor")) { if (userLogado.getTipo().equals("Gerente")) { if (Encarregado.getDepartamento().getCodigo().equals(userLogado.getDepartamento().getCodigo())) { userDAO.criaUSER(Encarregado); } } if (userLogado.getTipo().equals("Diretor")) { userDAO.criaUSER(Encarregado); } } else { throw new excecaoControleAcesso(); } } else { throw new excecaoEncarregadoExistente(); } }
ed87e08c-4e1a-407f-ad46-98583f3fd526
8
public ControlsFrame(String title, final CropScreen attatched) { super(title); this.attatched = attatched; ActionListener langChanged = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { ControlsFrame.this.attatched.setLanguage(((JRadioButton)arg0.getSource()).getText()); } }; ActionListener blockChanged = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { blockType = ((JRadioButton)arg0.getSource()).getText(); if (blockType.equals("Image")) attatched.renderingColor = Color.RED; else if (blockType.equals("Paragraph")) attatched.renderingColor = Color.GREEN; else attatched.renderingColor = Color.ORANGE; } }; ActionListener reset = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { attatched.reset(); } }; ActionListener motion = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { System.out.println("Dechid ecrane"); ((JButton)arg0.getSource()).setEnabled(false); EventQueue.invokeLater(new Runnable() { @Override public void run() { MotionScreen.startMotionSCreen(attatched.getRoot()); } }); } }; ActionListener edit = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { System.out.println("Dechid ecrane"); ((JButton)arg0.getSource()).setEnabled(false); EventQueue.invokeLater(new Runnable() { @Override public void run() { UserInterface layoutGUI = new UserInterface(attatched.getRoot()); } }); } }; ActionListener export = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { XMLWriter writer = new XMLWriter(); try { writer.writeFile(attatched.getRoot(), "exported.xml"); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; JPanel top = new JPanel(); top.setLayout(new BorderLayout()); getContentPane().add(top); /** * Adding the lang buttons */ for (String lang : LANGS) { JRadioButton btn = new JRadioButton(lang); langGroup.add(btn); langPanel.add(btn); if (lang.equals("eng")) btn.setSelected(true); btn.addActionListener(langChanged); } /** * Add the block type buttons */ for (String lang : BLOCK_TYPES) { JRadioButton btn = new JRadioButton(lang); blockTypeGroup.add(btn); blockPanel.add(btn); if (lang.equals("Paragraph")) btn.setSelected(true); btn.addActionListener(blockChanged); } langPanel.setBorder(BorderFactory.createTitledBorder("Choose text language")); panel.addTab("Language Settings", langPanel); blockPanel.setBorder(BorderFactory.createTitledBorder("Choose block type")); panel.addTab("Block Type", blockPanel); JButton btn = new JButton("Edit"); buttonsPanel.add(btn); btn.addActionListener(edit); btn = new JButton("Rearrange"); buttonsPanel.add(btn); btn.addActionListener(motion); btn = new JButton("Reset"); buttonsPanel.add(btn); btn.addActionListener(reset); btn = new JButton("Export to XML"); buttonsPanel.add(btn); btn.addActionListener(export); buttonsPanel.setBorder(BorderFactory.createTitledBorder("Actions")); panel.addTab("Actions", buttonsPanel); top.add(panel, BorderLayout.CENTER); add(panel); }
8a598cdb-ff32-4f66-941e-543ff2899edb
5
public void sortingPricesForRefrigirators() { getDriver().findElement(By.xpath(SortingLine.SORT_PRICE)).click(); List<Item> data = new ArrayList<Item>(); int pageCount = 0; while (true && pageCount++ < 3) { data.addAll(grabItems()); if (hasNext()) { next(); } else { break; } } System.out.println(data); int prevPrice = 0; for (Item refrigirator : data) { if (prevPrice > refrigirator.getPrice()) { Assert.fail(); } prevPrice = refrigirator.getPrice(); } }
dd437b15-b5a3-40ea-bad0-7bfa07e6b1c4
6
public void RestoreOriginalPHPFile(DatabaseAccess JavaDBAccess, int TARGET_PHP_FILES_ID) { PreparedStatement ps = null; String PHPFileText; //The text of the PHP file where we want to inject the vulnerabilities String PATH = ""; Connection conn = null; try { if ((conn = JavaDBAccess.setConn()) != null) { System.out.println("Connected to database " + JavaDBAccess.getDatabaseName()); } else { throw new Exception("Not connected to database " + JavaDBAccess.getDatabaseName()); } conn.setAutoCommit(false); // Start a transaction by inserting a record in the TARGET_PHP_FILES table ps = conn.prepareStatement("SELECT TEXT,PATH FROM TARGET_PHP_FILES WHERE ID = ?"); ps.setInt(1, TARGET_PHP_FILES_ID); ResultSet rs = ps.executeQuery(); rs.next(); PHPFileText = rs.getString("TEXT"); PATH = rs.getString("PATH"); rs.close(); conn.commit(); conn.close(); PrintWriter WebPageFileWriter = null; // Open matches log file. try { WebPageFileWriter = new PrintWriter(new FileWriter(PATH)); } catch (Exception e) { System.out.println("Unable to open matches Web Page log file."); } // Add URL to matches log file. try { WebPageFileWriter.print(PHPFileText); } catch (Exception e) { System.out.println("Unable to Web page log match."); } WebPageFileWriter.flush(); // Close matches log file. try { WebPageFileWriter.close(); } catch (Exception e) { System.out.println("Unable to close matches web page log file."); } } catch (Throwable e) { System.out.println("Errors in RestorePHPFile!"); System.out.println("exception thrown:"); if (e instanceof SQLException) { JavaDBAccess.printSQLError((SQLException) e); } else { e.printStackTrace(); } } }
6f803a1d-5e97-426a-a540-be5f1e4fbcc6
3
private Player getPlayer(String name){ if(name == null) return null; for(Player p : allPlayers){ if(p.getName().equals(name)){ return p; } } return null; }
cef706c6-c2d4-4481-baf0-c68edb86802a
3
private Boolean checkForValidFile(File dataFile){ final JPanel frame = new JPanel(); if(!checkForCommas(dataFile)){ JOptionPane.showMessageDialog(frame, "File not compatible (contains no commas)", "File error", JOptionPane.ERROR_MESSAGE); return false; } if(!checkForAttributes(dataFile)){ JOptionPane.showMessageDialog(frame, "File not compatible (attribute error)", "File error", JOptionPane.ERROR_MESSAGE); return false; } if(!checkForConsistentData(dataFile)){ JOptionPane.showMessageDialog(frame, "File not compatible (Data not consistent)", "File error", JOptionPane.ERROR_MESSAGE); return false; } return true; }
243a40c4-6fdf-441e-a642-963b9040959f
0
public CommandParams addParam(Object value) { params.add(value); return this; }
899ed385-f200-4058-9cea-8c9cf29cb323
3
public void startFadeOut() { if(transitionTime > 0.0f && getCurrentSong() != getNextSong(false) && !stopping) { EIError.debugMsg("startFadeOut"); hitFadeOutNext = true; startNextSong(); } }
e3f7a4fb-b2ca-47d1-b9d0-f6a128d5f9df
1
public void processSaveAndExit() { // write to the RefereesOut.txt file writeRefereesOutFile(); // write to the MatchAllocs.txt file if (matchList != null) writeMatchAllocationsFile(matchList); System.exit(0); }
18d11db7-5285-4a0e-9e3d-5fa19fdcfa25
6
public CobolLine getCobolLine(final String sourceLine, final int lineNumber) { final Matcher m = sourceFormat.matcher(sourceLine); final boolean fixedLine = (m.matches() && sourceLine.startsWith("$")) ? false : fixedFormat; final int[] tabs = (fixedLine) ? CobolLineFixed.getTabs() : CobolLineFree.getTabs(); final String line = expandTabs(sourceLine, tabs); CobolLine cobolLine; if (m.matches()) { // $set formatsource must be accepted in both format. cobolLine = (line.startsWith("$")) ? new CobolLineFree(lineNumber, line) : new CobolLineFixed(lineNumber, line); String type = m.group(1); fixedFormat = type.equalsIgnoreCase("FIXED"); } else { // Any other card except $set formatsource cobolLine = (fixedFormat) ? new CobolLineFixed(lineNumber, line) : new CobolLineFree(lineNumber, line); } return cobolLine; }
d13f5af4-4565-48fd-ae29-2dd556ac343a
0
public double getStrength() { return strength; }
c524b3ff-81b7-41b4-a42c-589bb2de6406
6
public ResultSet BuscarFuncionarios(String Departamento) throws SQLException { Connection conexao = null; PreparedStatement comando = null; ResultSet resultado = null; try { conexao = BancoDadosUtil.getConnection(); comando = conexao.prepareStatement(SQL_SELECT_TODOS_BUSCAR_funcionarios); comando.setString(1, Departamento); resultado = comando.executeQuery(); conexao.commit(); } catch (Exception e) { if (conexao != null) { conexao.rollback(); } throw new RuntimeException(e); } finally { if (comando != null && !comando.isClosed()) { comando.close(); } if (conexao != null && !conexao.isClosed()) { conexao.close(); } } return resultado; }
beda2273-86ac-4977-a851-73f8c978039a
4
public void handleError(Client source, Throwable t) { if (networkClient != null && !networkClient.isConnected()) { System.err.println("CLIENT: network error. Connection is closed"); } else { System.err.println("NETWORK ERROR: " + t.getMessage()); if (t instanceof ConnectException) { if (connected) { close(); System.out.println("Server shut down."); } } else { t.printStackTrace(); } } }
d188830f-849b-4c04-af24-998013314a31
1
public java.security.cert.X509Certificate[] getAcceptedIssuers() { java.security.cert.X509Certificate[] chain = null; try { TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); KeyStore tks = KeyStore.getInstance("JKS"); tks.load(this.getClass().getClassLoader().getResourceAsStream("SSL/serverstore.jks"), SERVER_KEY_STORE_PASSWORD.toCharArray()); tmf.init(tks); chain = ((X509TrustManager) tmf.getTrustManagers()[0]).getAcceptedIssuers(); } catch (Exception e) { throw new RuntimeException(e); } return chain; }
0a899001-e697-4f53-9a54-3612061a54ea
4
private char[][] build_sub_block(String setting, char[] key_alphabet, int[] key_block) { int set_len=setting.length(); char[][] result=new char[set_len+1][26]; char[] pt=read_pt(key_alphabet,key_block); for(int i=0;i<26;i++) { result[0][i]=pt[i]; } //create ct: set_len*26 String setting_u=setting.toUpperCase(); for(int i=0;i<set_len;i++) { int pos=Generic_Func.find_char(pt,setting_u.charAt(i)); int filled=0; int pt_col=0; while(filled<26) { result[i+1][pt_col]=pt[pos]; if(pos==25) { pos=0; } else { pos++; } pt_col++; filled++; } } return result; }
5339c936-52ea-4463-894d-01e2b671ef50
6
* @return returns true if Thing is clicked, false otherwise. */ public boolean checkIfClicked(Point mousePos){ //Transparent color seems to give two different results depending on which program exported them int transparentColorID1 = 16777215; int transparentColorID2 = 0; System.out.println(img.getRGB(mousePos.x, mousePos.y)); if( mousePos.x>0 && mousePos.x<img.getWidth(jPanel) && mousePos.y>0 && mousePos.y<img.getHeight(jPanel) && img.getRGB(mousePos.x, mousePos.y)!=transparentColorID1 && //Only check on non-transparent parts of the object img.getRGB(mousePos.x, mousePos.y)!=transparentColorID2 ){ System.out.println("Object clicked with color: " + img.getRGB(mousePos.x, mousePos.y)); this.clicked = true; this.mousePos = mousePos; return true; } return false; }
f96f88b1-73d2-4b3b-8989-1b925b4618f8
5
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj instanceof Point) { Point other = (Point)obj; if (other.x == x && other.y == y) { return true; } } return false; }
6f6969e3-0164-42d3-8184-d86482cdbcc6
8
private boolean r_Step_1c() { int v_1; // (, line 51 // [, line 52 ket = cursor; // or, line 52 lab0: do { v_1 = limit - cursor; lab1: do { // literal, line 52 if (!(eq_s_b(1, "y"))) { break lab1; } break lab0; } while (false); cursor = limit - v_1; // literal, line 52 if (!(eq_s_b(1, "Y"))) { return false; } } while (false); // ], line 52 bra = cursor; // gopast, line 53 golab2: while(true) { lab3: do { if (!(in_grouping_b(g_v, 97, 121))) { break lab3; } break golab2; } while (false); if (cursor <= limit_backward) { return false; } cursor--; } // <-, line 54 slice_from("i"); return true; }
d54ab640-b761-4928-9ba9-155835d741bf
7
public static void main(String[] args) throws InvalidPositionException, NoEmptyTreeException, InvalidKeyException, BoundaryViolationException, EmptyTreeException { // test binary tree AdvancedBinaryTree<Integer> tbt = new AdvancedBinaryTree<>( new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { if (a < b) return -1; else if (a > b) return 1; else return 0; } }); BTPosition<Integer> root, left, right; root = tbt.addRoot(5); left = tbt.insertLeft(root, 3); right = tbt.insertRight(root, 8); tbt.insertLeft(left, 1); tbt.insertRight(left, 4); tbt.insertLeft(right, 7); tbt.insertRight(right, 9); BTPosition<Integer> btRoot = tbt.checkPosition(tbt.root()); tbt.preOrderTraveral(); tbt.inOrderTraveral(); tbt.postOrderTraveral(); tbt.postOrderTraveralIterative(); System.out.println("B or D FS:"); for (Position<Integer> tmp : tbt) {// self iterator,overrided super // class System.out.print(tmp + " "); } System.out.println(); System.out.print("--BFS: "); ArrayList<BTPosition<Integer>> albfs = tbt.BFS(); for (BTPosition<Integer> bt : albfs) { System.out.print(bt.element() + " "); } System.out.println(); System.out.print("--DFS: "); ArrayList<BTPosition<Integer>> aldfs = tbt.DFS(); for (BTPosition<Integer> bt : aldfs) { System.out.print(bt.element() + " "); } System.out.println(); System.out.println("isBST: " + tbt.isBST(btRoot, Integer.MIN_VALUE, Integer.MAX_VALUE)); System.out.println("isBalanced: " + tbt.isBalanced(btRoot)); System.out.println("isBalanced2: " + tbt.isBalanced2(btRoot)); AdvancedBinarySearchTree<Integer> bst = new AdvancedBinarySearchTree<>( new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { if (a < b) return -1; else if (a > b) return 1; else return 0; } }); bst.insertNodeConcised(5); bst.insertNodeConcised(3); bst.insertNodeConcised(7); bst.insertNodeConcised(2); bst.insertNodeConcised(4); bst.insertNodeConcised(6); bst.insertNodeConcised(9); bst.insertNodeConcised(8); // System.out.println(bst.SearchNode(bst.root(), 3)); bst.inOrderTraveral(); bst.preOrderTraveral(); bst.postOrderTraveral(); // bst.print("Binary Search Tree"); // work only for full BT, need // overriding BTPosition<Integer> bstRoot = bst.checkPosition(bst.root()); System.out.println("max element: " + bst.getMax(bstRoot).element()); System.out.println("2nd max element: " + bst.getSecondMax(bstRoot).element()); System.out.println("root tree height: " + bst.treeHeight(bstRoot)); System.out.println("root tree depth: " + bst.treeDepth(bstRoot)); System.out.println("BST next largest: " + bst.NextLargest(5)); System.out.println("BST next largest2: " + bst.NextLargest2(5)); System.out.println("bst isBST: " + bst.isBST(bstRoot, Integer.MIN_VALUE, Integer.MAX_VALUE)); System.out.println("bst isBST2: " + bst.isBST2(bstRoot, Integer.MIN_VALUE)); System.out.println("bt isBST: " + tbt.isBST(btRoot, Integer.MIN_VALUE, Integer.MAX_VALUE)); System.out.println("bt isBST2: " + tbt.isBST2(btRoot, Integer.MIN_VALUE)); System.out .println("LCA: " + bst.lowestCommonAncestor(bst.root(), 9, 3)); bst.KDistanceFromRoot(2); //Hao BST BST haoBST = new BST(); haoBST.insert(5); haoBST.insert(3); haoBST.insert(7); haoBST.insert(4); haoBST.insert(2); haoBST.insert(6); haoBST.insert(9); haoBST.insert(15); haoBST.insert(11); haoBST.insert(13); System.out.println(haoBST.getMaxNode()); System.out.println(haoBST.getSecondMax()); // ArrayHeap<Integer> ah = new ArrayHeap<>(new Comparator<Integer>() { // // @Override // public int compare(Integer a, Integer b) { // if (a < b) // return -1; // else if (a > b) // return 1; // else // return 0; // } // }); // // ah.insert(5); // ah.insert(4); // ah.insert(11); // ah.insert(9); // ah.insert(8); // ah.insert(2); // ah.insert(55); // ah.insert(24); // ah.insert(1); // // ah.print("ArrayHeap"); // // ah.heapSort(); // // ArrayList<BTPosition<Integer>> albt = new ArrayList<>(); // albt.add(new HeapNode<Integer>(6, 0, albt)); // albt.add(new HeapNode<Integer>(5, 1, albt)); // albt.add(new HeapNode<Integer>(4, 2, albt)); // albt.add(new HeapNode<Integer>(3, 3, albt)); // albt.add(new HeapNode<Integer>(2, 4, albt)); // albt.add(new HeapNode<Integer>(1, 5, albt)); // // ArrayHeap<Integer> ahb = new ArrayHeap<>(new Comparator<Integer>() { // // @Override // public int compare(Integer a, Integer b) { // if (a < b) // return -1; // else if (a > b) // return 1; // else // return 0; // } // }, albt); // ahb.print("BuildUp Heap"); // ahb.heapSort(); }
baaf62cb-68c7-4fff-8b04-42abcf61b01a
2
private ArrayList rewriteJListToArrayList(JList list) { ArrayList newList = new ArrayList(); for (int i = 0; i < list.getModel().getSize(); i++) { if (list.getModel().getElementAt(i) != null) newList.add(list.getModel().getElementAt(i)); } return newList; }
f29cab4d-b46c-4510-99e4-b07074928757
4
public String getMessage() { switch (reason) { case BAD_ARGS: return "Bad Arguments"; case BAD_TARGET: return "Bad Target Entity"; case BAD_COMMAND: return "Bad Command"; case BAD_STRING: return "Bad String"; default: return null; } }
1fefc726-f08e-4f81-bb95-bbdad317fcec
7
public BufferedImage getBitmap(int id) { BufferedImage value; if(!low_memory && bmp_loaded != null && (value = bmp_loaded[id]) != null) { return value; } else { long offset = getBitmapOffset(id); if(offset == -1) throw new NXException("NX file does not this canvas."); lock(); try { SeekableLittleEndianAccessor slea = getStreamAtOffset(offset); int width = slea.getUShort(); int height = slea.getUShort(); long length = slea.getUInt(); ByteBuffer output = ByteBuffer.allocateDirect(width * height * 4); NXCompression.decompress(slea.getBuffer(), offset + 4, length + 4, output, 0); output.rewind(); output.order(ByteOrder.LITTLE_ENDIAN); //TODO: optimize this without bitshifts. value = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); for (int h = 0; h < height; h++) { for (int w = 0; w < width; w++) { int b = output.get() & 0xFF; int g = output.get() & 0xFF; int r = output.get() & 0xFF; int a = output.get() & 0xFF; value.setRGB(w, h, (a << 24) | (r << 16) | (g << 8) | b); } } } finally { unlock(); } if(!low_memory) bmp_loaded[id] = value; return value; } }
c72cca49-8206-4cc1-8ec5-80a70393ab66
7
private void saveDependencies() throws ConfigurationChangeException { // Abhängigkeiten nur speichern, wenn mindestens Version 9 des Metamodells vorliegt if(!_storeDependencies) return; synchronized(_areasDependencies) { // Alle Aufrufe in diesem Block können zu Festplattenzugriffen führen. Das kann diese Methode sehr lange blockieren lassen. // In der Zeit ist es auch nicht möglich weitere Abhängigkeiten hinzuzufügen. Das ist aber auch nicht nötig, da diese // Methode am Ende der Konsistenzprüfung aufgerufen wird. final Set<ConfigurationArea> areas = _areasDependencies.keySet(); for(ConfigurationArea area : areas) { final Short desiredVersionObject = _areaVersionMap.get(area); if(desiredVersionObject == null) { // System.out.println("*****************************************************************************"); // System.out.println("*****************************************************************************"); // System.out.println("area = " + area.getPidOrNameOrId()); // System.out.println("*****************************************************************************"); // System.out.println("*****************************************************************************"); continue; } final int desiredVersion = desiredVersionObject.intValue(); int maxFreezedVersion = area.getActiveVersion(); if(maxFreezedVersion < area.getTransferableVersion()) maxFreezedVersion = area.getTransferableVersion(); if(maxFreezedVersion < area.getActivatableVersion()) maxFreezedVersion = area.getActivatableVersion(); // Nur Speichern, wenn der Bereich verändert wurde if( maxFreezedVersion >= desiredVersion) { // System.out.println("*****************************************************************************"); // System.out.println("*****************************************************************************"); // System.out.println("area = " + area.getPidOrNameOrId()); // System.out.println("maxFreezedVersion = " + maxFreezedVersion); // System.out.println("desiredVersion = " + desiredVersion); // System.out.println("*****************************************************************************"); // System.out.println("*****************************************************************************"); continue; } ConfigConfigurationArea configConfigurationArea = ((ConfigConfigurationArea)area); final Set<ConfigurationAreaDependency> dependencies = _areasDependencies.get(area); try { configConfigurationArea.addAreaDependency(dependencies); } catch(ConfigurationChangeException e) { // Der Datensatz, der die Abhängigkeiten speichert, konnte nicht geschrieben werden. final StringBuffer errorText = new StringBuffer(); errorText.append( "Fehler in der Konsistenzprüfung: Der Datensatz, der alle Abhängigkeiten eines Bereich enthält, konnte nicht geschrieben werden. Betroffener Bereich: " + area.getConfigurationArea().getPid() + " KV des Bereichs: " + area.getConfigurationArea().getConfigurationAuthority().getPid() + " KV der Konfiguration: " + _dataModel.getConfigurationAuthorityPid() + " .Abhängigkeiten, die geschrieben werden sollten: " + dependencies ); throw new ConfigurationChangeException(errorText.toString(), e); } } }// synch }