method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
d556d58c-d1da-4965-af16-9f9bc73151a9
5
public void setZhishus(Iterator<Element>tempit,WeatherInfo tempweather){ Element tempElement,tempElement2; Iterator<Element>tempit2; Zhishu zhishu=new Zhishu(); int i=0,j; while(tempit.hasNext()){ tempElement=tempit.next(); tempit2=tempElement.elementIterator(); j=0; while(tempit2.hasNext()){ tempElement2=tempit2.next(); switch (j) { case 0: zhishu.setName(tempElement2.getText()); break; case 1:zhishu.setValue(tempElement2.getText());break; case 2:zhishu.setDetail(tempElement2.getText());break; default:break; } j++; } tempweather.setZhishus(i, zhishu); i++; } }
0b2b76ec-e95b-4e81-9fa0-cb918139a72a
0
public static void main(String[] args) { // 利用抽象工厂,new一个具体工厂,获取具体的产品 Driver driver = new BenzDriver(); Car car = driver.driverCar(); // 利用抽象的产品,根据具体产品进行生产 car.driver(); }
c15ba11c-8d9b-4150-b89e-a994b73ef004
5
@Override public boolean doSmall() { if (!options.useOtherHouse.get() && script.houseTask.getHouseLocation() != HouseTask.HouseLocation.YANILLE) { script.log.info("House not in yanille"); return false; } else { options.status = "Walking to yanille bank"; final Tile smallRandom = locationAttribute.getSmallRandom(ctx); if (smallRandom.distanceTo(ctx.players.local()) < 18) { if (ctx.movement.findPath(smallRandom).traverse()) { return true; } } else { if (OBELISK_AREA.contains(ctx.players.local())) { options.status = ("Walking back from obelisk"); return new TilePath(ctx, PATH_FROM_OBELISK).randomize(2, 2).traverse(); } } return new TilePath(ctx, PATH_TO_BANK).randomize(1, 1).traverse(); } }
bef8e6ec-41b2-4cf0-b17e-e8ee8e4465bd
0
public Level getLogLevel() { return this.level; }
3ea672f0-4fea-4056-b239-a96d21347cf0
0
public String getName() { return name; }
da18abea-641a-4677-83fc-336c9bcf5971
9
public void commit() throws IOException { //write all uncommited free records Iterator<Long> rowidIter = freeBlocksInTransactionRowid.iterator(); Iterator<Integer> sizeIter = freeBlocksInTransactionSize.iterator(); PageCursor curs = new PageCursor(_pageman, Magic.FREEPHYSIDS_PAGE); //iterate over filled pages while (curs.next() != 0) { long freePage = curs.getCurrent(); BlockIo curBlock = _file.get(freePage); FreePhysicalRowIdPage fp = FreePhysicalRowIdPage.getFreePhysicalRowIdPageView(curBlock, blockSize); int slot = fp.getFirstFree(); //iterate over free slots in page and fill them while(slot!=-1 && rowidIter.hasNext()){ long rowid = rowidIter.next(); int size = sizeIter.next(); short freePhysRowId = fp.alloc(slot); fp.setLocationBlock(freePhysRowId, Location.getBlock(rowid)); fp.setLocationOffset(freePhysRowId, Location.getOffset(rowid)); fp.FreePhysicalRowId_setSize(freePhysRowId, size); slot = fp.getFirstFree(); } _file.release(freePage, true); if(!rowidIter.hasNext()) break; } //now we propably filled all already allocated pages, //time to start allocationg new pages while(rowidIter.hasNext()){ //allocate new page long freePage = _pageman.allocate(Magic.FREEPHYSIDS_PAGE); BlockIo curBlock = _file.get(freePage); FreePhysicalRowIdPage fp = FreePhysicalRowIdPage.getFreePhysicalRowIdPageView(curBlock, blockSize); int slot = fp.getFirstFree(); //iterate over free slots in page and fill them while(slot!=-1 && rowidIter.hasNext()){ long rowid = rowidIter.next(); int size = sizeIter.next(); short freePhysRowId = fp.alloc(slot); fp.setLocationBlock(freePhysRowId, Location.getBlock(rowid)); fp.setLocationOffset(freePhysRowId, Location.getOffset(rowid)); fp.FreePhysicalRowId_setSize(freePhysRowId, size); slot = fp.getFirstFree(); } _file.release(freePage, true); if(!rowidIter.hasNext()) break; } if(rowidIter.hasNext()) throw new InternalError(); freeBlocksInTransactionRowid.clear(); freeBlocksInTransactionSize.clear(); }
bc62d65b-7057-4fa6-b45b-453d6804dd82
2
public static InformationUsageEnum fromValue(String v) { for (InformationUsageEnum c : InformationUsageEnum.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); }
e44ae61c-5d40-442e-91cb-cbe7917d4f6f
6
public String compress(String toBeCompressed){ int length = toBeCompressed.length(); ArrayList<Tag> ret = new ArrayList<>(); Tag tempTag , charTag; for(int i = 0 ; i < length; i++){//main loop -> charTag = new Tag(0,0,toBeCompressed.charAt(i)); for(int j = i -1 ; j >= 0 ; j--){//get best match <- if(toBeCompressed.charAt(i) == toBeCompressed.charAt(j)){ int jj = j+1 , ii = i+1; for(; ii < length; ii++,jj++){//match jj-> ii-> char a = toBeCompressed.charAt(ii) ; char b = toBeCompressed.charAt(jj) ; if(b != a) break; } int back = i - j , forward = jj - j; char n = NULL; if(ii < length-1)n = toBeCompressed.charAt(ii); charTag = maxTag(charTag , new Tag(back,forward,n)); } } i = i + charTag.getStepForward(); ret.add(charTag); } return arrayListToString(ret); }
ee650186-9cca-49e9-b79a-65e4559d8f5c
3
private static int findminimumgreedyscorefortailvertex(int tailvertex) { // TODO Auto-generated method stub int temp = 0; for(int j = 0 ; j<graph.get(tailvertex).size();j++){ if(!(exploredarray.contains(graph.get(tailvertex).get(j)))){ temp = pathlength[tailvertex] + edgewieght[tailvertex][graph.get(tailvertex).get(j)]; if(temp<score){ score = temp; vertextotransverse = graph.get(tailvertex).get(j); vertextotraversefrom = tailvertex; } } } return score; }
4cebd9f7-2a89-4d89-85f0-ecf9b0381d51
8
private static int findMedian(int[] a, int lo, int hi) { int mid_ind = (hi + lo) / 2; /*System.err.println("------------------"); for (int i = 0; i < a.length; i++) { System.err.print(a[i] + " "); } System.err.println(); System.err.println(" {" + lo + " " + mid_ind + " " + hi + "}");*/ int result = -1; if ((a[lo] <= a[mid_ind] && a[mid_ind] <= a[hi]) || (a[hi] <= a[mid_ind] && a[mid_ind] <= a[lo])) { result = mid_ind; } else if ((a[lo] <= a[hi] && a[hi] <= a[mid_ind]) || (a[mid_ind] <= a[hi] && a[hi] <= a[lo])) { result = hi; } else { result = lo; } /*System.err.println(" " + a[lo] + " " + a[mid_ind] + " " + a[hi]); System.err.println(" med = " + a[r]);*/ return result; }
ff7d388b-f99e-42d4-8e17-56add6379db3
5
public Fenetre(final ActionsClientMessagerie irc) { this.irc = irc; // Initialisation de la fenêtre this.setTitle("Messagerie instantanée"); this.setSize(400, 700); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setBackground(Color.gray); this.setContentPane(panel); this.setLayout(new GridBagLayout()); GridBagConstraints constraint = new GridBagConstraints(); // Ajouter la zone des messages this.messages = new JTextArea(); constraint.fill = GridBagConstraints.BOTH; constraint.gridx = 0; constraint.gridy = 0; constraint.gridwidth = 2; constraint.weightx = 1; constraint.weighty = 0.8; this.messages.setEnabled(false); this.add(this.messages, constraint); // Ajouter la zone de saisie final JTextField saisie = new JTextField(); constraint.fill = GridBagConstraints.BOTH; constraint.gridx = 0; constraint.gridy = 1; constraint.gridwidth = 1; constraint.weightx = 0.75; constraint.weighty = 0.1; this.add(saisie, constraint); // Ajouter le bouton d'envoi d'un message final JButton envoyer = new JButton("Envoyer"); constraint.fill = GridBagConstraints.BOTH; constraint.gridx = 1; constraint.gridy = 1; constraint.gridwidth = 1; constraint.weightx = 0.25; constraint.weighty = 0.1; envoyer.setEnabled(false); this.add(envoyer, constraint); envoyer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { irc.send(saisie.getText()); saisie.setText(""); } catch (RemoteException e1) { System.out.println("Erreur de réseau"); } } }); // Menu JMenu menuFichier = new JMenu("Fichier"); JMenuItem quitter = new JMenuItem("Quitter"); JMenuItem connecter = new JMenuItem("Connecter"); JMenuItem listing = new JMenuItem("Liste des clients"); JMenuItem deconnecter = new JMenuItem("Déconnecter"); menuFichier.add(connecter); menuFichier.add(listing); menuFichier.add(deconnecter); menuFichier.add(quitter); JMenuBar menu = new JMenuBar(); menu.add(menuFichier); this.setJMenuBar(menu); quitter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { irc.bye(); } catch (RemoteException e1) { e1.printStackTrace(); } System.exit(0); } }); connecter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { irc.connect(); envoyer.setEnabled(true); } catch (RemoteException e1) { System.out.println("Erreur de réseau"); } } }); deconnecter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { irc.bye(); envoyer.setEnabled(false); } catch (RemoteException e1) { System.out.println("Erreur de réseau"); } } }); listing.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { messages.append("Listing des clients connectés au serveur :\n" + irc.who() + "\n"); } catch (RemoteException e1) { System.out.println("Erreur de réseau : " + e1.getMessage()); e1.printStackTrace(); } } }); // Affiche la fenetre this.setVisible(true); }
9eb63abe-cb56-4dbd-80e3-9f2e493d99f1
7
private static void generateTestCases(){ firstNumbers = new ArrayList<int[]>(); secondNumbers = new ArrayList<int[]>(); bases = new ArrayList<Integer>(); // you can change the bases here int [] basesArray = {2,10,17}; int [] firstNum; int [] secondNum; int [] zero = {0}; Random rand = new Random(); for (int i =0 ; i< basesArray.length ; i++){ // number of digits of first and second // Make them really big (bigger than can be represented with type "long") int firstLength = 50; int secondLength = 40; firstNum = new int[firstLength]; secondNum = new int[secondLength]; // TEST // use the biggest possible numbers for the given lengths i.e. 999999999...999 in base 10 for(int j = 0 ; j<firstLength ; j++){ firstNum[j]=basesArray[i]-1; } for(int j = 0 ; j<secondLength ; j++){ secondNum[j]=basesArray[i]-1; } firstNumbers.add(firstNum); secondNumbers.add(secondNum); bases.add(basesArray[i]); // TEST // use firstNum (9999999...99999 in base 10) for both first number and second number firstNumbers.add(firstNum); secondNumbers.add(firstNum); bases.add(basesArray[i]); // TEST // use the smallest possible numbers for the given lengths i.e. 1000000...00000 for(int j = 1 ; j<50 ; j++){ firstNum[j]=0; } for(int j = 1 ; j<40 ; j++){ secondNum[j]=0; } firstNum[0]= 1; secondNum[0]=1; firstNumbers.add(firstNum); secondNumbers.add(secondNum); bases.add(basesArray[i]); // TEST // make two random numbers for(int j = 1 ; j<50 ; j++){ firstNum[j]=Math.abs(rand.nextInt()%basesArray[i]); } for(int j = 1 ; j<40 ; j++){ secondNum[j]=Math.abs(rand.nextInt()%basesArray[i]); } firstNumbers.add(firstNum); secondNumbers.add(secondNum); bases.add(basesArray[i]); // Use the (random) firstNum for both numbers. firstNumbers.add(firstNum); secondNumbers.add(firstNum); bases.add(basesArray[i]); // One random number and zero firstNumbers.add(firstNum); secondNumbers.add(zero); bases.add(basesArray[i]); // both numbers are zero firstNumbers.add(zero); secondNumbers.add(zero); bases.add(basesArray[i]); } }
33851e8e-d3db-4bd1-96a7-d522cacef583
1
@Override public void start() { if (this.mcApplet != null) { this.mcApplet.start(); return; } }
ba694739-7083-498d-b26e-4514c6a43923
8
public boolean sign_in(String username, String password) { BasicDBObject query = new BasicDBObject("username", username); DBCursor the_row = getTable("User").find(query); // System.out.println(the_row.toArray()); ArrayList row_list = (ArrayList) the_row.toArray(); if (row_list.isEmpty()) return false; String temp = row_list.toString(); String[] row = temp.split(","); String username1 = null; String password1 = null; char c = '"'; for (int i = 0; i < row.length; i++) { // System.out.println(row[i]); if (row[i].contains("username")) { String[] username11 = row[i].split(":"); // username1=username11[1].substring(2,username11[1].length()-2); if (username11[1].startsWith(" " + c)) { username1 = username11[1].substring(2, username11[1].length() - 2); // System.out.println(username1); } else username1 = username11[1].substring(2, username11[1].length() - 1); } else if (row[i].contains("password")) { String[] password11 = row[i].split(":"); // username1=username11[1].substring(2,username11[1].length()-2); if (password11[1].startsWith(" " + c)) { password1 = password11[1].substring(2, password11[1].length() - 2); //System.out.println(password1); } else password1 = password11[1].substring(1, password11[1].length() - 1); } } if (username1.equals(username) && password1.equals(password)) return true; else return false; }
cdd514f5-5b77-4122-953f-7c3682bb5d09
9
void handleWrite() { if (queue.isEmpty() && outgoing == null) { key.interestOps(SelectionKey.OP_READ); return; } try { if (outgoing == null) { Queued b = (Queued) queue.pop(); ByteBuffer[] msg = b.getMsg(); if (msg == null) { return; } short port = b.getPort(); int size = 0; for (int i = 0; i < msg.length; i++) { size += msg[i].remaining(); } ByteBuffer header = ByteBuffer.allocate(6); header.putInt(size); header.putShort(port); header.flip(); outgoing = new ByteBuffer[msg.length + 1]; outgoing[0] = header; System.arraycopy(msg, 0, outgoing, 1, msg.length); outremaining = size + 6; } if (outgoing != null) { long n = sock.write(outgoing, 0, outgoing.length); dirty=true; transport.bytesOut+=n; outremaining -= n; if (outremaining == 0) { transport.pktOut++; outgoing = null; } key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ); } } catch (IOException e) { handleClose(); } catch (CancelledKeyException cke) { // Make sure connection is closed transport.notifyClose(this); } }
362677a2-e546-4b69-9311-899aafeb5b05
8
@SuppressWarnings("deprecation") private void placeMushroomTree(World world, int x, int y, int z, Random rand) { boolean brownTree = rand.nextBoolean(); if(brownTree) { int height = rand.nextInt(3)+5; for(int y2 = 0; y2 < height; y2++) { setBlockWithData(world, x, y+y2, z, Material.HUGE_MUSHROOM_1.getId(), 10); } for(int x2 = -2; x2 <= 2; x2++) { for(int z2 = -2; z2 <= 2; z2++) { setBlockWithData(world, x+x2, y+height, z+z2, Material.HUGE_MUSHROOM_1.getId(), 5); } } for(int x2 = -1; x2 <= 1; x2++) { setBlockWithData(world, x+x2, y+height, z-3, Material.HUGE_MUSHROOM_1.getId(), 2); setBlockWithData(world, x+x2, y+height, z+3, Material.HUGE_MUSHROOM_1.getId(), 8); } for(int z2 = -1; z2 <= 1; z2++) { setBlockWithData(world, x-3, y+height, z+z2, Material.HUGE_MUSHROOM_1.getId(), 4); setBlockWithData(world, x+3, y+height, z+z2, Material.HUGE_MUSHROOM_1.getId(), 6); } setBlockWithData(world, x-3, y+height, z-2, Material.HUGE_MUSHROOM_1.getId(), 1); setBlockWithData(world, x-2, y+height, z-3, Material.HUGE_MUSHROOM_1.getId(), 1); setBlockWithData(world, x+3, y+height, z-2, Material.HUGE_MUSHROOM_1.getId(), 3); setBlockWithData(world, x+2, y+height, z-3, Material.HUGE_MUSHROOM_1.getId(), 3); setBlockWithData(world, x-3, y+height, z+2, Material.HUGE_MUSHROOM_1.getId(), 7); setBlockWithData(world, x-2, y+height, z+3, Material.HUGE_MUSHROOM_1.getId(), 7); setBlockWithData(world, x+3, y+height, z+2, Material.HUGE_MUSHROOM_1.getId(), 9); setBlockWithData(world, x+2, y+height, z+3, Material.HUGE_MUSHROOM_1.getId(), 9); } else { int height = rand.nextInt(3)+4; for(int y2 = 0; y2 < height; y2++) { setBlockWithData(world, x, y+y2, z, Material.HUGE_MUSHROOM_2.getId(), 10); } setBlockWithData(world, x, y+height, z, Material.HUGE_MUSHROOM_2.getId(), 5); setBlockWithData(world, x, y+height, z-1, Material.HUGE_MUSHROOM_2.getId(), 2); setBlockWithData(world, x-1, y+height, z, Material.HUGE_MUSHROOM_2.getId(), 4); setBlockWithData(world, x+1, y+height, z, Material.HUGE_MUSHROOM_2.getId(), 6); setBlockWithData(world, x, y+height, z+1, Material.HUGE_MUSHROOM_2.getId(), 8); for(int y2 = height-3; y2 <= height-1; y2++) { setBlockWithData(world, x, y+y2, z-2, Material.HUGE_MUSHROOM_2.getId(), 2); setBlockWithData(world, x-2, y+y2, z, Material.HUGE_MUSHROOM_2.getId(), 4); setBlockWithData(world, x+2, y+y2, z, Material.HUGE_MUSHROOM_2.getId(), 6); setBlockWithData(world, x, y+y2, z+2, Material.HUGE_MUSHROOM_2.getId(), 8); setBlockWithData(world, x-2, y+y2, z-1, Material.HUGE_MUSHROOM_2.getId(), 1); setBlockWithData(world, x-1, y+y2, z-2, Material.HUGE_MUSHROOM_2.getId(), 1); setBlockWithData(world, x+2, y+y2, z-1, Material.HUGE_MUSHROOM_2.getId(), 3); setBlockWithData(world, x+1, y+y2, z-2, Material.HUGE_MUSHROOM_2.getId(), 3); setBlockWithData(world, x-2, y+y2, z+1, Material.HUGE_MUSHROOM_2.getId(), 7); setBlockWithData(world, x-1, y+y2, z+2, Material.HUGE_MUSHROOM_2.getId(), 7); setBlockWithData(world, x+2, y+y2, z+1, Material.HUGE_MUSHROOM_2.getId(), 9); setBlockWithData(world, x+1, y+y2, z+2, Material.HUGE_MUSHROOM_2.getId(), 9); } setBlockWithData(world, x-1, y+height, z-1, Material.HUGE_MUSHROOM_2.getId(), 1); setBlockWithData(world, x+1, y+height, z+1, Material.HUGE_MUSHROOM_2.getId(), 9); setBlockWithData(world, x+1, y+height, z-1, Material.HUGE_MUSHROOM_2.getId(), 3); setBlockWithData(world, x-1, y+height, z+1, Material.HUGE_MUSHROOM_2.getId(), 7); } }
47e34d48-a11b-438e-91df-c4436934e904
0
public EncryptionMethodType createEncryptionMethodType() { return new EncryptionMethodType(); }
78a4fd56-8fc8-40b7-99b8-0fbc3db8f3ac
1
void fireStart(ComponentAccess w) { if (shouldFire) { fire(Type.EXECUTING, new ComponentEvent(c, w.getComponent())); } }
6412b786-7de4-4229-b8b4-3d3265f66c59
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VtnOpcionesCompu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VtnOpcionesCompu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VtnOpcionesCompu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VtnOpcionesCompu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VtnOpcionesCompu().setVisible(true); } }); }
2fe64f31-842f-43eb-af64-4113ee9ef0b1
3
/* */ @EventHandler /* */ public void onInventoryClose(InventoryCloseEvent event) /* */ { /* 319 */ if (!(event.getPlayer() instanceof Player)) /* */ { /* 321 */ return; /* */ } /* */ /* 325 */ Player p = (Player)event.getPlayer(); /* */ /* 327 */ if (Main.getAPI().isBeingSpectated(p)) /* */ { /* 329 */ for (Player spectators : Main.getAPI().getSpectators(p)) /* */ { /* 331 */ spectators.closeInventory(); /* */ } /* */ } /* */ }
a3f6803a-18ee-4a7b-833c-35867d3d2adf
2
public void positionAnywhereIn(GameObject go) { if(this.getSize().width > go.getSize().width || this.getSize().height > go.getSize().height){ throw new IllegalArgumentException("GameObject is bigger than the passed GameObject"); }else{ Random generator = new Random(); int xOffset = generator.nextInt(go.getSize().width - this.getSize().width + 1); int yOffset = generator.nextInt(go.getSize().height - this.getSize().height + 1); this.setLocation(go.getX() + xOffset, go.getY() + yOffset); } }
0af8f752-8e82-4655-8733-8fb13f3c1c42
3
@Test public void test2() { System.out.println("Test avec l'init avec 1 argument et tous les états possibles"); System.out.println("Tests de couverture des post-conditions d'init"); for(BlocType b : BlocType.values()) { bloc2.init(b); assertTrue("type initial Fail",bloc2.getType()==b); assertTrue("power-up initial Fail",bloc2.getPowerUpType() == PowerUpType.RIEN); } System.out.println("Tests de couverture des postconditions des operators"); for(BlocType b : BlocType.values()) { bloc2.setType(b); assertTrue("changement de type Fail",bloc2.getType() == b); for(PowerUpType p : PowerUpType.values()) { bloc2.setPowerUpType(p); assertTrue("changement de power-up Fail",bloc2.getPowerUpType() == p); } } }
75109267-8b21-437a-96da-7f0103ded74c
0
public BinaryTime() { setLayout(new BorderLayout(0, 0)); timer.start(); JButton btnBack = new JButton("BACK"); btnBack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MainFrame.cardLayout.show(getParent(), "startScreen"); } }); add(btnBack, BorderLayout.SOUTH); }
4c1c4d60-539f-46f4-ace3-d03dfa8a574d
9
public boolean isValidFor(SeedNode node) { if (node.x < Consts.SEED_RADIUS - Consts.EPSILON || node.x > width - (Consts.SEED_RADIUS - Consts.EPSILON) || node.y < Consts.SEED_RADIUS - Consts.EPSILON || node.y > height - (Consts.SEED_RADIUS - Consts.EPSILON)) return false; for (Location tree : trees) { if (Location.distance(node, tree) < Consts.SEED_RADIUS + Consts.TREE_RADIUS - Consts.EPSILON) return false; } for (SeedNode otherNode : seedNodes) { if (otherNode != node && Location.distance(node, otherNode) < 2*Consts.SEED_RADIUS - Consts.EPSILON) return false; } return true; }
6ce82f6b-35c9-46e6-8a59-8c5ca0bcf5b9
7
public void testKeySetRemoveAllTCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); assertTrue( set.removeAll( set ) ); assertTrue( set.isEmpty() ); // repopulate the set. map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } set = map.keySet(); // With empty set TIntSet tintset = new TIntHashSet(); assertFalse( "set: " + set + ", collection: " + tintset, set.removeAll( tintset ) ); // With partial set tintset = new TIntHashSet( keys ); tintset.remove( 42 ); assertTrue( "set: " + set + ", collection: " + tintset, set.removeAll( tintset ) ); assertEquals( "set: " + set, 1, set.size() ); assertEquals( "set: " + set, 1, map.size() ); for ( int i = 0; i < keys.length; i++ ) { if ( keys[i] == 42 ) { assertTrue( set.contains( keys[i] ) ); assertTrue( map.containsKey( keys[i] ) ); } else { assertFalse( set.contains( keys[i] ) ); assertFalse( map.containsKey( keys[i] ) ); } } // repopulate the set. map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } set = map.keySet(); // Empty list TIntCollection collection = new TIntArrayList(); assertFalse( "set: " + set + ", collection: " + collection, set.removeAll( collection ) ); // partial list collection = new TIntArrayList( keys ); collection.remove( 42 ); assertTrue( "set: " + set + ", collection: " + collection, set.removeAll( collection ) ); assertEquals( "set: " + set, 1, set.size() ); assertEquals( "set: " + set, 1, map.size() ); for ( int i = 0; i < keys.length; i++ ) { if ( keys[i] == 42 ) { assertTrue( set.contains( keys[i] ) ); assertTrue( map.containsKey( keys[i] ) ); } else { assertFalse( set.contains( keys[i] ) ); assertFalse( map.containsKey( keys[i] ) ); } } }
f60eec87-74c1-47a9-aeea-a020fabb119a
2
public void requestPlayCard(Card card) { if (playRequest == null && this.canPlay(card)) { playRequest = card; } }
8fcb6e9d-ab84-4dd0-b217-e1bea2c05bc2
0
public void setSuccess(String success) { this.success = success; }
d16d2510-b745-4e22-8339-15c31ed0105a
4
public XMLMenu() { JMenu menu; JMenuItem item; menu = new JMenu("Arquivo"); item = new JMenuItem("Criar");//arquivo item.addMouseListener(new MouseAdapter() { String nome_da_pasta = "Novo Arquivo"; @Override public void mousePressed(MouseEvent e) { new NovoArquivo(InterfaceUsuario.main, true); } }); menu.add(item); item = new JMenuItem("Copiar");//arquivo item.addMouseListener(new MouseAdapter() { String nome_da_pasta; @Override public void mousePressed(MouseEvent e) { new CopiarArquivo(InterfaceUsuario.main, false); } }); menu.add(item); item = new JMenuItem("Mover"); item.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { new MoverArquivo(InterfaceUsuario.main, false); } }); menu.add(item); item = new JMenuItem("Renomear"); item.addMouseListener(new MouseAdapter() { String nome_da_pasta = "Novo Arquivo"; @Override public void mousePressed(MouseEvent e) { new Renomear(InterfaceUsuario.main, true); } }); menu.add(item); item = new JMenuItem("Excluir");//arquivo item.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { XMLTreeNode arquivo = XMLTreePanel.node_selecionado; String caminho = XMLTreePanel.getCaminhoSelecionado(false); caminho = caminho.substring(0, caminho.length() - 1); int resposta = JOptionPane.showConfirmDialog( InterfaceUsuario.main, "Deseja realmente apagar este arquivo " + arquivo.toString() + " (" + caminho + ") ?", "Confirmação", JOptionPane.YES_NO_OPTION ); if (resposta == JOptionPane.YES_OPTION) { try { PainelDeControle.middleware.deletarArquivo(caminho); } catch (RemoteException ex) { Logger.getLogger(XMLMenu.class.getName()).log(Level.SEVERE, null, ex); } } XMLTreePanel.atualizaArvore(); } }); menu.add(item); add(menu);//FIM OPÇÕES ARQUIVO menu = new JMenu("Pasta"); item = new JMenuItem("Criar"); item.addMouseListener(new MouseAdapter() { String nome_da_pasta = "Nova Pasta"; @Override public void mousePressed(MouseEvent e) { new NovaPasta(InterfaceUsuario.main, true); } }); menu.add(item); item = new JMenuItem("Copiar");//arquivo item.addMouseListener(new MouseAdapter() { String nome_da_pasta; @Override public void mousePressed(MouseEvent e) { new CopiarPasta(InterfaceUsuario.main, false); } }); menu.add(item); item = new JMenuItem("Mover");//arquivo item.addMouseListener(new MouseAdapter() { String nome_da_pasta; @Override public void mousePressed(MouseEvent e) { new MoverPasta(InterfaceUsuario.main, false); } }); menu.add(item); item = new JMenuItem("Excluir");//arquivo item.addMouseListener(new MouseAdapter() { String nome_da_pasta; @Override public void mousePressed(MouseEvent e) { XMLTreeNode pasta = XMLTreePanel.node_selecionado; String caminho = XMLTreePanel.getCaminhoSelecionado(false); caminho = caminho.substring(0, caminho.length() - 1); int resposta = JOptionPane.showConfirmDialog( InterfaceUsuario.main, "Deseja realmente apagar esta pasta " + pasta.toString() + " (" + caminho + ") ?", "Confirmação", JOptionPane.YES_NO_OPTION ); if (resposta == JOptionPane.YES_OPTION) { try { PainelDeControle.middleware.deletarPasta(caminho); } catch (RemoteException ex) { Logger.getLogger(XMLMenu.class.getName()).log(Level.SEVERE, null, ex); } } XMLTreePanel.atualizaArvore(); } }); menu.add(item); add(menu); menu = new JMenu("Atualizar Árvore"); menu.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { XMLTreePanel.atualizaArvore(); } }); add(menu); menu = new JMenu("Sair"); menu.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { System.exit(0); } }); add(menu); }
9e4457c8-2e7d-4432-85d4-a0356669d4ec
2
@Override public Class<?> getColumnClass(int index) { return index == 0 ? Icon.class : String.class; }
3f7e5ef9-3ab6-423a-8b38-af396cbc7b1c
4
private boolean checkValid20() { if ((inChar8[0]==false)&&(inChar8[6]==true)&&(inChar8[7]==true)&&(bcount>=8)) return true; else return false; }
8ecd2f08-2426-46e9-82c6-41eb0eb6d370
8
protected String checkMap(int paramInt1, int paramInt2) { if (this.ImageMap != null) { Enumeration localEnumeration = this.ImageMap.keys(); Object localObject = null; int i = 0; while ((localEnumeration.hasMoreElements()) && (i == 0)) { localObject = localEnumeration.nextElement(); if ((localObject instanceof Rectangle)) { if (((Rectangle)localObject).contains(paramInt1, paramInt2)) i = 1; } else if ((localObject instanceof Polygon)) { if (!((Polygon)localObject).contains(paramInt1, paramInt2)) continue; i = 1; } else { System.out.println("ImageButton: Somebody put some weird object in my ImageMap."); } } if (i != 0) { return (String)this.ImageMap.get(localObject); } return null; } return null; }
6129a641-3dfe-4fe6-87c9-94d0af8b083a
3
@Override public List<Consulta> listPorDate(Date data) { Connection con = null; PreparedStatement pstm = null; ResultSet rs = null; List<Consulta> consultas = new ArrayList<>(); try { con = ConnectionFactory.getConnection(); pstm = con.prepareStatement(LISTBYDATE); pstm.setString(1, "%" + new java.sql.Date(data.getTime()) + "%"); rs = pstm.executeQuery(); while (rs.next()) { //codigo, data_consulta,descricao, codigo_paciente,tipo_consulta,horario Consulta c = new Consulta(); c.setCodigo(rs.getInt("consulta.codigo")); c.setDataDaConsulta(rs.getDate("consulta.data_consulta")); c.setDescricao(rs.getString("consulta.descricao")); c.setTipoConsulta(rs.getString("consulta.tipo_consulta")); c.setHorario(rs.getTime("consulta.horario")); Paciente p = new Paciente(); p.setCodigo(rs.getInt("paciente.codigo")); p.setNome(rs.getString("paciente.nome")); c.setPaciente(p); consultas.add(c); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao listar(All): " + ex.getMessage()); } finally { try { ConnectionFactory.closeConnection(con, pstm, rs); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro ao fechar a conexão" + e.getMessage()); } } return consultas; }
40fbe0e8-b981-4935-a9c6-3795105858a3
1
private static void buildFromScratch() { for (int i = 2; i <= 365994; i++) { lookup(i); } save(); }
a88534e2-e7c0-40d0-a170-97a8cfe0c63c
2
public static String[][] parse(String s) throws IOException { if (s == null) { throw new IllegalArgumentException("Null argument not allowed."); } String[][] result = (new CSVParser(new StringReader(s), CSVStrategy.DEFAULT_STRATEGY)).getAllValues(); if (result == null) { // since CSVStrategy ignores empty lines an empty array is returned // (i.e. not "result = new String[][] {{""}};") result = EMPTY_DOUBLE_STRING_ARRAY; } return result; }
89be9bf7-9dc8-4d0d-85a7-53a2e3b92601
8
public String downloadUrl(String filename, String urlString) { BufferedInputStream in = null; FileOutputStream fout = null; HttpURLConnection connection = null; String md5 = ""; try { URL url_ = new URL(urlString); byte data[] = new byte[1024]; connection = (HttpURLConnection) url_.openConnection(); connection.setAllowUserInteraction(true); connection.setConnectTimeout(14000); connection.setReadTimeout(20000); connection.connect(); md5 = connection.getHeaderField("Content-MD5"); in = new BufferedInputStream(connection.getInputStream()); fout = new FileOutputStream(filename); int count, amount = 0, modPackSize = connection.getContentLength(), steps = 0; SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setMaximum(10000); } }); while((count = in.read(data, 0, 1024)) != -1) { fout.write(data, 0, count); downloadedPerc += (count * 1.0 / modPackSize) * 100; amount += count; steps++; if(steps > 100) { steps = 0; final String txt = (amount / 1024) + "Kb / " + (modPackSize / 1024) + "Kb"; final int perc = (int)downloadedPerc * 100; SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(perc); label.setText(txt); } }); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(in != null) { in.close(); } if(fout != null) { fout.flush(); fout.close(); } if(connection != null) { connection.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } return md5; }
00e1aacd-13cd-43ee-b4a4-cb43085fc835
0
public void setName(String name) { this.name = name; }
81101613-dfdd-47e2-b555-cbd77b83ad5f
2
@Test public void test() { Vote fetchedVote = (Vote) MongoHelper.fetch(vote, "votes"); if(fetchedVote == null) TestHelper.failed("vote not found"); fetchedVote.setOptionID(new Integer(5)); if(!MongoHelper.save(fetchedVote, "votes")){ TestHelper.failed("Option ID update failed"); } Vote updatedVote = (Vote) MongoHelper.fetch(fetchedVote, "votes"); TestHelper.asserting(fetchedVote.getOptionID().equals(updatedVote.getOptionID())); System.out.println("updated Vote id: " + updatedVote.getId()); TestHelper.passed(); }
cfecc04c-425f-40fb-b6ca-4d800c9c636c
0
public SHSMemberEntity() { setId(System.nanoTime()); }
f4c79eff-5790-4b8a-a76b-5c5f626fd839
6
public static double getSilhouette(Dataset trainingSet, ArrayList<ArrayList<Integer>> clusters, double[][] distance, int VERBOSE) { int logFlag = Constants.LOG_SILHOUETTE; /** initial phase **/ // build an inverted index of cluster assg, i.e., clusterAssignment[objectNo] = clusterId; int[] clusterAssignment = new int[trainingSet.size()]; for (int i=0; i<clusters.size(); i++) { for (int j=0; j<clusters.get(i).size(); j++){ clusterAssignment[clusters.get(i).get(j)] = i; } } /** compute silhouette(i) **/ //ArrayList<Double> silh = new ArrayList<Double> (); double sumSilh = 0.0; for (int i=0; i<trainingSet.size(); i++) { // compute a(i) double ai = (sumRowAgainstColumn(distance, i, clusters.get(clusterAssignment[i])) + 0.0)/ (clusters.get(clusterAssignment[i]).size() + 0.0); Util.logPrintln(VERBOSE, logFlag, "item "+i+", ai:"+ai+", clusterId: "+clusterAssignment[i]+", fellow-cluster: "+ clusters.get(clusterAssignment[i])); // compute b(i) // average dissimilarity with other clusters double minBi = Double.MAX_VALUE; for (int j=0; j<clusters.size(); j++) { if (j!=clusterAssignment[i]) { double bis = (sumRowAgainstColumn(distance, i, clusters.get(j)) + 0.0 ) / clusters.get(j).size(); if ( bis < minBi ) minBi = bis; } } Double maxAiBi = Math.max(ai, minBi); double silh = ( (minBi - ai) / maxAiBi); sumSilh += silh; Util.logPrintln(VERBOSE, logFlag, ai+","+minBi + ", " + (minBi - ai) +"," + silh); } double silhouette = sumSilh / trainingSet.size(); Util.logPrintln(VERBOSE, logFlag, "silhouette: "+silhouette); return silhouette; }
55d24385-f093-44b5-a43c-449c13cfcf04
5
public Shader(String name) { this.shader = ARBShaderObjects.glCreateProgramObjectARB(); if (this.shader != 0) { this.vertShader = createVertShader("/shader/" + name + ".vert.txt"); this.fragShader = createFragShader("/shader/" + name + ".frag.txt"); } else { this.useShader = false; } if ((this.vertShader != 0) && (this.fragShader != 0)) { ARBShaderObjects.glAttachObjectARB(this.shader, this.vertShader); ARBShaderObjects.glAttachObjectARB(this.shader, this.fragShader); ARBShaderObjects.glLinkProgramARB(this.shader); if (ARBShaderObjects.glGetObjectParameteriARB(this.shader, 35714) == 0) { printLogInfo(this.shader); this.useShader = false; } ARBShaderObjects.glValidateProgramARB(this.shader); if (ARBShaderObjects.glGetObjectParameteriARB(this.shader, 35715) == 0) { printLogInfo(this.shader); this.useShader = false; } } else { this.useShader = false; } }
e2db0dad-8223-4fcb-b88b-1652ddb402db
4
public static Class<? extends CTFSession> getSession(String name) { for (Class<? extends CTFSession> cls : sessionTypes) { if (cls.getSimpleName().equalsIgnoreCase(name)) { return cls; } } return null; }
490ad87a-0875-42ec-bc81-3ca93baa0c93
0
@Override public String getIpdbserver() { return ipdbserver; }
9584773b-abe0-4126-b233-3d7a20716cd8
3
public static String filter(String str) { String output = ""; StringBuffer sb = new StringBuffer(); for (int i = 0; i < str.length(); i++) { int asc = str.charAt(i); if (asc != 10 && asc != 13) { sb.append(str.subSequence(i, i + 1)); } } output = new String(sb); return output; }
f203d84b-d04b-4684-85b2-8e88f9850ad5
2
public void animateEntity(Entity entity, int x, int y) { // this.game.stroke(0, 0, 255); // this.game.rect(x * this.game.c_tilesize, y * this.game.c_tilesize, this.game.c_tilesize, // this.game.c_tilesize); // moving if (entity.busy > 0 && entity.center < 2) { entity.xold = x - entity.dx; entity.yold = y - entity.dy; float progress = ((float) entity.speed - entity.busy) / entity.speed; entity.xprogress = (int) (entity.dx * progress * this.game.c_tilesize); entity.yprogress = (int) (entity.dy * progress * this.game.c_tilesize); this.game.image(this.get(entity.resourceId), entity.xold * this.game.c_tilesize + entity.xprogress, entity.yold * this.game.c_tilesize + entity.yprogress, this.game.c_tilesize, this.game.c_tilesize); } // standing around else { entity.xprogress = 0; entity.yprogress = 0; this.game.image(ResourceLoader.getImg(entity.resourceId), x * this.game.c_tilesize, y * this.game.c_tilesize, this.game.c_tilesize, this.game.c_tilesize); } }
05245e03-8d0f-41c1-bc25-142bf084874d
7
public static void avlToFile(AVL avl, Path file, Path origin) throws IOException { FileOutputStream fos = new FileOutputStream(file.toFile()); avl.getGeometry().writeAVLData(fos); fos.close(); String fileMassPath = file.toString().replace(".avl", ".mass"); File fileMass = new File(fileMassPath); fos = new FileOutputStream(fileMass); avl.writeAVLMassData(fos); fos.close(); Path dest = file.getParent(); for(Body body : avl.getGeometry().getBodies()){ if (!body.getBFILE().isEmpty() && !Files.exists(dest.resolve(body.getBFILE()))) Files.copy(origin.resolve(body.getBFILE()), dest.resolve(body.getBFILE())); } for(Surface surface : avl.getGeometry().getSurfaces()){ for(Section section : surface.getSections()){ if (!section.getAFILE().isEmpty() && !Files.exists(dest.resolve(section.getAFILE()))) Files.copy(origin.resolve(section.getAFILE()), dest.resolve(section.getAFILE())); } } }
61661457-f0f5-424c-a256-b48c0066690e
8
public AngleDR Ampqk(AngleDR ap, AMParams amprms) { double gr2e; /* (grav rad Sun)*2/(Sun-Earth distance) */ double ab1; /* sqrt(1-v*v) where v=modulus of Earth vel */ double ehn[] = new double[3]; /* Earth position wrt Sun (unit vector, FK5) */ double abv[] = new double[3]; /* Earth velocity wrt SSB (c, FK5) */ double p[] = new double[3], p1[] = new double[3]; double p2[] = new double[3], p3[] = new double[3]; /* work vectors */ double ab1p1, p1dv = 0.0, p1dvp1, w, pde = 0.0, pdep1; int i, j; TRACE("Ampqk"); /* Unpack some of the parameters */ gr2e = amprms.getGrad(); ab1 = amprms.getRoot(); ehn = amprms.getHelio(); abv = amprms.getEarthv(); /* Apparent RA,Dec to Cartesian */ p3 = Dcs2c(ap); /* Precession and nutation */ p2 = Dimxv(amprms.getPrecess(), p3); /* Aberration */ ab1p1 = ab1 + 1.0; for (i = 0; i < 3; i++) { p1[i] = p2[i]; } for (j = 0; j < 2; j++) { p1dv = Dvdv(p1, abv); p1dvp1 = 1.0 + p1dv; w = 1.0 + p1dv / ab1p1; for (i = 0; i < 3; i++) { p1[i] = (p1dvp1 * p2[i] - w * abv[i]) / ab1; } w = Dvn(p1, p3); for (i = 0; i < 3; i++) { p1[i] = p3[i]; } } /* Light deflection */ for (i = 0; i < 3; i++) { p[i] = p1[i]; } for (j = 0; j < 5; j++) { pde = Dvdv(p, ehn); pdep1 = 1.0 + pde; w = pdep1 - gr2e * pde; for (i = 0; i < 3; i++) { p[i] = (pdep1 * p1[i] - gr2e * ehn[i]) / w; } w = Dvn(p, p2); for (i = 0; i < 3; i++) { p[i] = p2[i]; } } /* Mean RA,Dec */ ap = Dcc2s(p); ap.setAlpha(Dranrm(ap.getAlpha())); ENDTRACE("Ampqk"); return ap; }
778a52ad-60bd-438c-94d7-33d9894eea5a
0
public void setPowered(boolean a){ powered = a; }
202155ee-3df6-4f1b-9ea2-331360af1fc5
1
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; }
973639c8-8144-4de8-873f-9261ce8db714
9
public void checkCollision(){ if(player1.getArrX()[0]==player2.getArrX()[0] && player1.getArrY()[0]==player2.getArrY()[0]) { snake1Alive=false; snake2Alive=false; } else{ for(int i = 0; i<player2.getSize(); i++) { if(player1.getArrX()[0]==player2.getArrX()[i] && player1.getArrY()[0]==player2.getArrY()[i]) { player2.setSize(i); } } if(alive) { for(int i = 0; i<player1.getSize(); i++) { if(player2.getArrX()[0]==player1.getArrX()[i] && player2.getArrY()[0]==player1.getArrY()[i]) { player1.setSize(i); } } } } }
ec0f2751-b1e5-4678-8611-0652e0d43d83
8
protected boolean orderConnections(NeuralNetwork neuralNetwork, Layer currentLayer, Set<Layer> calculatedLayers, Set<Layer> inProgressLayers, List<ConnectionCandidate> calculateCandidates) { boolean result = false; if (calculatedLayers.contains(currentLayer) || Util.isBias(currentLayer)) { result = true; } else if (!inProgressLayers.contains(currentLayer)) { inProgressLayers.add(currentLayer); List<ConnectionCandidate> currentCandidates = new ArrayList<ConnectionCandidate>(); boolean hasNoBiasConnections = false; for (Connections c : currentLayer.getConnections(neuralNetwork)) { Layer opposite = Util.getOppositeLayer(c, currentLayer); if (orderConnections(neuralNetwork, opposite, calculatedLayers, inProgressLayers, calculateCandidates)) { currentCandidates.add(new ConnectionCandidate(c, currentLayer)); if (!Util.isBias(opposite)) { hasNoBiasConnections = true; } } } if (currentCandidates.size() > 0 && hasNoBiasConnections) { calculateCandidates.addAll(currentCandidates); result = true; } inProgressLayers.remove(currentLayer); calculatedLayers.add(currentLayer); } return result; }
64759a6e-2388-4b40-809b-d5a6bdbd0938
0
@Test public void testRemoveAnt() throws IOException { System.out.println("removeAnt"); Cell instance = new Cell(0,0); AntBrain ab = new AntBrain("cleverbrain1.brain"); Ant ant = new Ant(ab, true, 0); instance.setAnt(ant); instance.removeAnt(); Ant expResult = null; Ant result = instance.getAnt(); assertEquals(expResult, result); }
05108f90-6061-46dc-b1c1-255c2a15b951
6
public String getNextComponent(Identifier ident) { String prefix = ident.getFullName(); if (prefix.length() > 0) prefix += "."; int lastDot = prefix.length(); if (!wildcard.startsWith(prefix)) return null; int nextDot = wildcard.indexOf('.', lastDot); if (nextDot > 0 && (nextDot <= firstStar || firstStar == -1)) return wildcard.substring(lastDot, nextDot); else if (firstStar == -1) return wildcard.substring(lastDot); else return null; }
8481c8f3-c39a-45dc-942b-e22c57699bdd
0
@Override public void handlePeerReady(SharingPeer peer) { /* Do nothing */ }
eadbb0fe-a3f3-458d-8fed-0625c9076b87
2
IntIterator getReverse(int key) { int bucket = key % buckets; if(bucket < 0) { bucket = -bucket; } int[] data = content[bucket]; if(data == null) { return IntIterator.EMTPY_ITERATOR; } else { //return new IntIterator(data, key); iterator.data = data; iterator.offset = data[0] * 2 + 1; iterator.key = key; return iterator; } }
a893a867-fe53-4c89-9297-407e9fa6e855
6
private static boolean method518(char c) { return c < 'a' || c > 'z' || c == 'v' || c == 'x' || c == 'j' || c == 'q' || c == 'z'; }
119d4007-f437-41c2-9931-d22bd3f01356
3
private void writeObjectDictionary(Dictionary obj) throws IOException { logger.log(Level.FINER, "writeObjectDictionary() obj: {0}", obj); if (obj == null) throw new IllegalArgumentException("Object must be non-null"); Reference ref = obj.getPObjectReference(); logger.log(Level.FINER, "writeObjectDictionary() ref: {0}", ref); if (ref == null) throw new IllegalArgumentException("Reference must be non-null for object: " + obj); if (obj.isDeleted()) { //if (!obj.isNew()) { // addEntry( new Entry(ref) ); //} // Make deleted entries for unused object numbers resulting from // deleting newly created objects addEntry( new Entry(ref) ); return; } addEntry( new Entry(ref, startingPosition + output.getCount()) ); writeInteger(ref.getObjectNumber()); output.write(SPACE); writeInteger(ref.getGenerationNumber()); output.write(SPACE); output.write(BEGIN_OBJECT); writeDictionary(obj); output.write(END_OBJECT); }
684eec16-90ef-487a-b61d-f7814882239d
2
private static List<Appointment> findMonthlyByDaySpan(long uid, long startDay, long endDay) throws SQLException { List<Appointment> aAppt = new ArrayList<Appointment>(); PreparedStatement statement = null; // select * from Appointment where frequency = $MONTHLY // and startTime <= $(endDay + DateUtil.DAY_LENGTH) // and $startDay <= lastDay String str = "select * from (" + makeSqlSelectorForUser(uid) + ") as Temp where frequency = ? " + "and startTime <= ? " + "and ? <= lastDay "; Date startD = new Date(startDay); Date endD = new Date(endDay); if (startD.getMonth() == endD.getMonth()) { // if within a month str += "and ? <= freqHelper and freqHelper <= ? "; statement = connect.prepareStatement(str); statement.setInt(4, Appointment.computeFreqHelper( Frequency.MONTHLY, startDay)); statement.setInt(5, Appointment.computeFreqHelper( Frequency.MONTHLY, endDay)); } else { // if span 2 months Date startOfMonth2D = new Date(endD.getYear(), endD.getMonth(), 0); long endOfMonth1 = new Date(startOfMonth2D.getTime() - DateUtil.DAY_LENGTH) .getTime(); str += "and (? <= freqHelper and freqHelper <= ? or freqHelper <= ?) "; statement = connect.prepareStatement(str); statement.setInt(4, Appointment.computeFreqHelper( Frequency.MONTHLY, startDay)); statement.setInt(5, Appointment.computeFreqHelper( Frequency.MONTHLY, endOfMonth1)); statement.setInt(6, Appointment.computeFreqHelper( Frequency.MONTHLY, endDay)); } statement.setInt(1, Frequency.MONTHLY); statement.setLong(2, endDay + DateUtil.DAY_LENGTH); statement.setLong(3, startDay); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { aAppt.add(Appointment.createOneFromResultSet(resultSet)); } return aAppt; }
d6e40568-d050-4e57-bb00-009620d11303
5
public void getSuggestions(ArrayList<ISuggestionWrapper> suggestions) { ArrayList<SuggestionCacheWrapper<IDocument>> cachedSuggestions = queryPosition.getCachedSuggestions(); for (SuggestionCacheWrapper<IDocument> suggestion : cachedSuggestions){ double suggestionRank = suggestion.getRank() * EditOperation.getRankDiscount(previousEdits); boolean hasSuggestion = false; for(int i = 0; i < suggestions.size(); i++){ ISuggestionWrapper suggestionWrapper = suggestions.get(i); if(suggestionWrapper.getSuggestion().equals(suggestion.getSuggestion().getLabel())){ if(suggestionWrapper.getRank() < suggestionRank){ suggestions.set(i, new SuggestionWrapper(suggestion.getSuggestion().getLabel(), suggestionRank)); } hasSuggestion = true; break; } } if(!hasSuggestion){ suggestions.add(new SuggestionWrapper(suggestion.getSuggestion().getLabel(), suggestionRank)); } } }
fcb2b7f4-8245-4a92-914b-a928a037a207
1
public Value pop() throws IndexOutOfBoundsException { if (top == 0) { throw new IndexOutOfBoundsException( "Cannot pop operand off an empty stack."); } return values[--top + locals]; }
6002146a-3b30-42ba-8db3-ef189012e998
7
private boolean needEvents(int count) { int level = 0; Iterator<Event> iter = events.iterator(); iter.next(); while (iter.hasNext()) { Event event = iter.next(); if (event instanceof DocumentStartEvent || event instanceof CollectionStartEvent) { level++; } else if (event instanceof DocumentEndEvent || event instanceof CollectionEndEvent) { level--; } else if (event instanceof StreamEndEvent) { level = -1; } if (level < 0) { return false; } } return events.size() < count + 1; }
d2fe84ef-22e1-4958-aaa4-d208aa6910eb
7
private final boolean prepareWriteBuffer(final MMOConnection<T> con) { boolean hasPending = false; DIRECT_WRITE_BUFFER.clear(); // if there is pending content add it if (con.hasPendingWriteBuffer()) { con.movePendingWriteBufferTo(DIRECT_WRITE_BUFFER); hasPending = true; } if ((DIRECT_WRITE_BUFFER.remaining() > 1) && !con.hasPendingWriteBuffer()) { final NioNetStackList<SendablePacket<T>> sendQueue = con.getSendQueue(); final T client = con.getClient(); SendablePacket<T> sp; for (int i = 0; i < MAX_SEND_PER_PASS; i++) { synchronized (con.getSendQueue()) { if (sendQueue.isEmpty()) { sp = null; } else { sp = sendQueue.removeFirst(); } } if (sp == null) { break; } hasPending = true; // put into WriteBuffer putPacketIntoWriteBuffer(client, sp); WRITE_BUFFER.flip(); if (DIRECT_WRITE_BUFFER.remaining() >= WRITE_BUFFER.limit()) { DIRECT_WRITE_BUFFER.put(WRITE_BUFFER); } else { con.createWriteBuffer(WRITE_BUFFER); break; } } } return hasPending; }
1612a1e9-5cc0-416d-ae1b-71bdd1fec3fb
8
public void insert(Symbol sy) throws ParseException { if(containsLocal(sy)) { throw new SemanticException(sy, "Symbol is already defined in scope " + identName); } switch(sy.kind) { case constKind: // is constant nrOfConstants++; break; case funcKind: // is function nrOfFunctions++; break; case parKind: // is parameter nrOfParams++; break; case varKind: // is local variable nrOfLocals++; break; case undefKind: // is undefined throw new SemanticException(sy, "Undefined symbol kind @ " + sy); //break; case fieldKind: // is class variable nrOfFields++; break; default: break; } if(locals == null) { locals = sy; // first local element in scope } else { locals.insert(sy, level); // add symbol to locals "chain" } }
ff8d64c2-c3ea-4b61-af45-0f61fcdf2e2c
2
public String getStateDescription(State state) { /* * If the output has not been set i.e. this is a brand new state * before the user has entered a state output, then an * empty string shows up instead of lamba. It is purely cosmetic. */ if(myMap.get(state) == null) return ""; else if(getOutput(state).length() == 0) // if output is empty string return Universe.curProfile.getEmptyString(); else return getOutput(state); }
f3b262a3-3515-4127-a900-5c20cd95cbec
9
static boolean matchStr(String str, String pat, String matches[]) { int i = 0; // move through str int j = 0; // move through matches int pos = 0; // move through pat // System.out.println("Inside matchStr :\n"); // System.out.print("Strlen of str,pat,match="+str.length()+pat.length()+matches.length+"\n"); while (pos < pat.length() && j < matches.length) { char p = pat.charAt(pos); // System.out.println("p="+p+"\n"); if (p == '*') { // System.out.println("p==*"); int n; if (pos+1 == pat.length()) { // * is the last thing in pat // n is remaining string length n = str.length() - i; // System.out.println("n="+n+"\n"); } else { // * is not last in pat // find using remaining pat // System.out.println("* is NOT the last thing in pat"); // System.out.println("Str.substring="+str.substring(i)+" "+pat.substring(pos+1)); // System.out.println("Before executing pat\n"); n = findPat(str.substring(i), pat.substring(pos+1)); // Number of characters common in str and pattern // // System.out.println("After executing findPat function n=:"+n+"\n"); } if (n < 0) return false; //if -1 is returned String temp=str.substring(i, i+n); matches[j++] = temp; //eg reasmb:is stored in matches i += n; pos++; // } else if (p == '#') { int n = findNum(str.substring(i)); matches[j++] = str.substring(i, i+n); i += n; pos++; } else { int n = amatch(str.substring(i), pat.substring(pos)); if (n <= 0) return false; i += n; pos += n; } } if (i >= str.length() && pos >= pat.length()) return true; return false; }
704f9cf7-1626-44ac-a203-da657a324a51
7
public Command getCommand(char currentOperator){ Command command; switch (currentOperator){ case BrainFuckConstants.SHIFT_RIGHT: command = new ShiftRight(); break; case BrainFuckConstants.SHIFT_LEFT: command = new ShiftLeft(); break; case BrainFuckConstants.INCREMENT_VALUE: command = new IncrementValue(); break; case BrainFuckConstants.DECREMENT_VALUE: command = new DecrementValue(); break; case BrainFuckConstants.PRINT_TO_CONSOLE: command = new PrintToConsole(); break; case BrainFuckConstants.WHILE: command = new While(); break; case BrainFuckConstants.END: command = new End(); break; default: command = new Comment(); break; } return command; }
03bfb54d-150b-4e03-8ac3-c315e23bf5e3
4
public static byte[] decrypt(byte[] data, byte[] key) { byte[] tmp = new byte[data.length]; byte[] bloc = new byte[16]; key = paddingKey(key); S = generateSubkeys(key); int i; for(i=0;i<data.length;i++){ if(i>0 && i%16 == 0){ bloc = decryptBloc(bloc); System.arraycopy(bloc, 0, tmp, i-16, bloc.length); } if (i < data.length) bloc[i % 16] = data[i]; } bloc = decryptBloc(bloc); System.arraycopy(bloc, 0, tmp, i - 16, bloc.length); tmp = deletePadding(tmp); return tmp; }
52349bbd-7fa7-4657-b0bd-4175b17a22d5
7
public void create(Roles roles) throws PreexistingEntityException, RollbackFailureException, Exception { if (roles.getEmpleadoCollection() == null) { roles.setEmpleadoCollection(new ArrayList<Empleado>()); } EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Collection<Empleado> attachedEmpleadoCollection = new ArrayList<Empleado>(); for (Empleado empleadoCollectionEmpleadoToAttach : roles.getEmpleadoCollection()) { empleadoCollectionEmpleadoToAttach = em.getReference(empleadoCollectionEmpleadoToAttach.getClass(), empleadoCollectionEmpleadoToAttach.getEmpNoEmpleado()); attachedEmpleadoCollection.add(empleadoCollectionEmpleadoToAttach); } roles.setEmpleadoCollection(attachedEmpleadoCollection); em.persist(roles); for (Empleado empleadoCollectionEmpleado : roles.getEmpleadoCollection()) { empleadoCollectionEmpleado.getRolesCollection().add(roles); empleadoCollectionEmpleado = em.merge(empleadoCollectionEmpleado); } em.getTransaction().commit(); } catch (Exception ex) { try { em.getTransaction().rollback(); } catch (Exception re) { throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); } if (findRoles(roles.getRolidRol()) != null) { throw new PreexistingEntityException("Roles " + roles + " already exists.", ex); } throw ex; } finally { if (em != null) { em.close(); } } }
811f7de6-157b-481d-b6a6-a9c73162377b
8
private static String escapeJSON(String text) { StringBuilder builder = new StringBuilder(); builder.append('"'); for (int index = 0; index < text.length(); index++) { char chr = text.charAt(index); switch (chr) { case '"': case '\\': builder.append('\\'); builder.append(chr); break; case '\b': builder.append("\\b"); break; case '\t': builder.append("\\t"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; default: if (chr < ' ') { String t = "000" + Integer.toHexString(chr); builder.append("\\u" + t.substring(t.length() - 4)); } else { builder.append(chr); } break; } } builder.append('"'); return builder.toString(); }
1e44282f-11b1-4e5e-9499-dd909f094f7c
2
private String requestInput(String Prompt) { String r = ""; while (r.isEmpty()) { r = console.readLine("%s: ", Prompt); if (r.isEmpty()) { console.printf("%s", "Please provide an answer!\n"); } } return r; }
d3916b7c-d982-4504-a424-d2c4e74209c8
3
public void read(Reader reader, ParserHandler handler) throws IOException, ParseException { StringBuffer buffer = new StringBuffer(); int c = reader.read(); while (c != -1) { buffer.append((char) c); if (c == separator) { boolean shallContinue = handler.handleContent(buffer.toString()); if (!shallContinue) { return; } buffer = new StringBuffer(); } // Read the next character c = reader.read(); } }
63811bbb-31f0-4698-872c-49c82bf7de17
2
@Override protected boolean onCache(ByteBuffer buffer) { // If the buffer doesn't have the same buffer size or the buffer // is not a DirectByteBuffer then return. if (buffer.capacity() != maxSize || !buffer.isDirect()) { return false; } stack.push(buffer); return true; }
c11b7949-43a0-4d65-80e7-c2351b8aace9
1
private void handlePointMovement(Point draggedPoint) { if (selectedPoint != -1) { selectedCurve.setPoint(selectedPoint, draggedPoint); selectedCurve.updateBezierPoints(); Main.state = State.Drawing; } }
59c21882-2a26-4117-8aff-12e0a4bfa410
1
private void writeTile(Tile tile, XMLWriter w) throws IOException { w.startElement("tile"); w.writeAttribute("id", tile.getId()); writeProperties(tile.getProperties(), w); if (tile instanceof AnimatedTile) writeAnimation(((AnimatedTile)tile).getSprite(), w); w.endElement(); }
58ad6fe0-e4e0-49e4-a398-51b87ce2f644
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Participant that = (Participant) o; if (email != null ? !email.equals(that.email) : that.email != null) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; return true; }
a7088e3a-a715-4966-ab21-8105bd91f59b
1
public void decoder(int[] octets_data){ if (taille == 7){ //System.out.println("DEplacement1 cr��"); positionXhigh = octets_data[0]; positionXlow = octets_data[1]; positionX = ((positionXhigh<<8) + positionXlow); positionYhigh = octets_data[2]; positionYlow = octets_data[4]; positionY = ((positionYhigh<<8) + positionYlow); // anglehigh = octets_data[5]; // anglelow = octets_data[6]; // pos_speciale = (octets_data[7] & 0xF0) >>> 4; // pos_speciale_att = (octets_data[7] & 0x8) >>> 3; // SOS_int = (octets_data[7] & 0x4) >>> 2; } else { System.out.println("taille != 7"); } }
fc01d0de-8b2a-4841-ab56-8a58ce94e91f
1
private void startGame(){ //starts the mechanics iterator gameServer = new Server(); gameServer.run(); ObjectInputStream objInStream = null; try{ //wait for the server to settle Thread.sleep(1000); //initialize tcp connection sock = new Socket("localhost", 1337); //set receive buffer size sock.setReceiveBufferSize(512); objInStream = new ObjectInputStream(sock.getInputStream()); clientReader = new ClientStreamReader(objInStream); //renders game data gameRender = new GameRender(); gameRender.gameRender(sm, clientReader);//This is the render game loop! //END GAME CODE STARTS NOW// //end the reader clientReader.running = false; //game close down code sock.close(); } catch (Exception e){ e.printStackTrace(); } //end server gameServer.stop(); }
f89a2c2e-94fa-4d3e-bc59-8deeec6b0b63
0
public int getId() { return id; }
8e3d01e8-954d-487c-9418-10365c51acb4
5
public boolean addCoefDecalage(String name, BigDecimal coefficient, BigDecimal gap) { if (name != null && !name.equals("") && !this.existInList(name) && coefficient != BigDecimal.ZERO && this.coefficientList != null) { Unit unit = new Unit(name, coefficient, gap, false); this.coefficientList.add(unit); unit.setType(this); return true; } return false; }
84ea4fb0-ef30-4b48-8b73-4e228e1b6015
3
@Override public void cadastarIntNota(ItensNota intensNot) throws ClassNotFoundException, SQLException,Exception { dados.cadastarIntNota(intensNot); if(intensNot.getQtdComprada()<=0){ throw new ItensNotaException("Quantidade Comprada nao pode ser menor ou igual zero"); } if(intensNot.getValorUnit()<0){ throw new ItensNotaException(" Valor unitario Não poder ser Zero"); } if(intensNot.getProduto().getCodProduto()<0){ throw new ItensNotaException(" o Codigo do Produto não Pode ser menor que zero"); } }
e1cd78fa-e15e-4435-8a25-f9dd0b0a1a7e
2
private void setButtonMode (Integer bm) { if (bm == 0) { okButton.setEnabled(false); cancelButton.setEnabled(false); copyButton.setEnabled(true); deleteButton.setEnabled (true); editButton.setEnabled(true); newButton.setEnabled(true); } if (bm == 1) { okButton.setEnabled(true); cancelButton.setEnabled(true); copyButton.setEnabled(false); deleteButton.setEnabled (false); editButton.setEnabled(false); newButton.setEnabled(false); } }
95c9cbbd-2b4d-4046-9bf2-e0ecf3c02cd4
9
public static boolean analysisNSMJ(AnalysisOutput o, List<AnalysisOutput> candidates) throws MorphException { int idxVbSfix = VerbUtil.endsWithVerbSuffix(o.getStem()); if(idxVbSfix==-1) return false; o.setVsfx(o.getStem().substring(idxVbSfix)); o.setStem(o.getStem().substring(0,idxVbSfix)); o.setPatn(PatternConstants.PTN_NSMJ); o.setPos(PatternConstants.POS_NOUN); WordEntry entry = DictionaryUtil.getWordExceptVerb(o.getStem()); if(entry!=null) { if(entry.getFeature(WordEntry.IDX_NOUN)=='0') return false; else if(o.getVsfx().equals("하")&&entry.getFeature(WordEntry.IDX_DOV)!='1') return false; else if(o.getVsfx().equals("되")&&entry.getFeature(WordEntry.IDX_BEV)!='1') return false; else if(o.getVsfx().equals("내")&&entry.getFeature(WordEntry.IDX_NE)!='1') return false; o.setScore(AnalysisOutput.SCORE_CORRECT); // '입니다'인 경우 인명 등 미등록어가 많이 발생되므로 분석성공으로 가정한다. }else { o.setScore(AnalysisOutput.SCORE_ANALYSIS); // '입니다'인 경우 인명 등 미등록어가 많이 발생되므로 분석성공으로 가정한다. } candidates.add(o); return true; }
55e7a57a-cf32-4a50-8c9d-e142678ecafd
7
private final boolean cons(int i){ switch (b[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': return false; case 'y': return (i==0) ? true : !cons(i-1); default: return true; } }
3f655257-8940-4b61-838f-eb5984ad851a
3
public static ByteToMessageDecoder createProtocolHandler(int protocolVersion) { if (protocolVersion == 4 || protocolVersion == 5) return new MC1_7Handler(); if (protocolVersion == 47) return new MC1_8Handler(); return null; }
e8566405-9226-4f6d-b26d-3f5cc1cd22eb
6
private boolean _jspx_meth_c_choose_0(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:choose org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_choose_0 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _jspx_tagPool_c_choose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class); _jspx_th_c_choose_0.setPageContext(_jspx_page_context); _jspx_th_c_choose_0.setParent(null); int _jspx_eval_c_choose_0 = _jspx_th_c_choose_0.doStartTag(); if (_jspx_eval_c_choose_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\n"); out.write(" "); if (_jspx_meth_c_when_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context)) return true; out.write("\n"); out.write(" "); if (_jspx_meth_c_otherwise_0((javax.servlet.jsp.tagext.JspTag) _jspx_th_c_choose_0, _jspx_page_context)) return true; out.write("\n"); out.write(" "); int evalDoAfterBody = _jspx_th_c_choose_0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_choose_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_0); return true; } _jspx_tagPool_c_choose.reuse(_jspx_th_c_choose_0); return false; }
1f42cc59-9c38-4ecb-b4bf-7f2b50ba563f
0
Speed(long delay) { this.delay = delay; }
481851a0-88ed-4b50-88ab-48c568fb324b
2
@Override public int compare(GenericEdge o1, GenericEdge o2) { if(o1.getAttribute().getValue() < o2.getAttribute().getValue()){ return -1; } if(o1.getAttribute().getValue() > o2.getAttribute().getValue()){ return 1; } return 0; }
4d93cb7f-2ff6-4455-ab61-09bb53abcfd3
9
public static Method findMethod(Class target_class, String method_name, Object[] args) throws Exception { int len=args != null? args.length : 0; Method retval=null; Method[] methods=getAllMethods(target_class); for(int i=0; i < methods.length; i++) { Method m=methods[i]; if(m.getName().equals(method_name)) { Class<?>[] parameter_types=m.getParameterTypes(); if(parameter_types.length == len) { retval=m; // now check if all parameter types are primitive types: boolean all_primitive=true; for(Class<?> parameter_type: parameter_types) { if(!isPrimitiveType(parameter_type)) { all_primitive=false; break; } } if(all_primitive) return m; } } } return retval; }
7738d1fe-4193-48f5-90a8-2b1afe6608d7
7
public int escribir(String nombre, String rutaArchivo) { InputStream entrada = null; PreparedStatement pst = null; int ingresados = 0; try { File archivo; String insert; z.con.setAutoCommit(false); insert = "Insert into documentos (nombre, documentos, fecha) values(?,?, NOW())"; pst = (PreparedStatement) z.con.prepareStatement(insert); archivo = new File(rutaArchivo); entrada = new FileInputStream(archivo); pst.setString(1, nombre.toUpperCase()); pst.setBinaryStream(2, entrada, (int) archivo.length()); ingresados = pst.executeUpdate(); z.con.commit(); flag = 1; } catch (FileNotFoundException ex) { Logger.getLogger(Archivos.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Archivos.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(Archivos.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (entrada != null) { entrada.close(); } } catch (IOException ex) { Logger.getLogger(Archivos.class.getName()).log(Level.SEVERE, null, ex); } try { if (pst != null) { pst.close(); } } catch (SQLException ex) { Logger.getLogger(Archivos.class.getName()).log(Level.SEVERE, null, ex); } } return ingresados; }
478a1a0d-4ead-4edb-aa0d-6b9a50a8473d
3
protected void setDirection(String newDirection, int tape) { if (!(newDirection.equals("L") || newDirection.equals("R") || newDirection .equals("S"))) throw new IllegalArgumentException("Direction must be L, R, or S!"); direction.set(tape, newDirection); }
a10aac0f-b114-4559-a9cf-f85c4a120685
2
@Override public void doLoopAction() { if (hit) { //super.ai(); } if (changeAni) { setAnimation(); changeAni = false; } }
4e62105e-3f59-47d3-8286-acb550a27e57
9
public final void run() { anInt4553++; for (;;) { int i; synchronized (this) { for (;;) { if (ioexception != null) return; if ((anInt4556 ^ 0xffffffff) != -1) { if (anInt4556 < anInt4558) i = -anInt4558 + bufferSize; else i = -1 + anInt4556 - anInt4558; } else i = -1 + (bufferSize + -anInt4558); if ((i ^ 0xffffffff) < -1) break; try { this.wait(); } catch (InterruptedException interruptedexception) { /* empty */ } } } int i_1_; try { i_1_ = inputstream.read(buffer, anInt4558, i); if (i_1_ == -1) throw new EOFException(); } catch (IOException ioexception) { synchronized (this) { ioexception = ioexception; break; } } synchronized (this) { anInt4558 = (i_1_ + anInt4558) % bufferSize; } } }
01a638a9-823a-4b02-abf1-2bff28194525
4
public void confirmApplication(Application a) { employs.base().incCredits(0 - a.hiringFee()) ; final Actor works = a.applies ; // // TODO: Once you have incentives worked out, restore this- //works.gear.incCredits(app.salary / 2) ; //works.gear.taxDone() ; works.setVocation(a.position) ; works.mind.setWork(employs) ; // // If there are no remaining openings for this background, cull any // existing applications. Otherwise, refresh signing costs. for (Application oA : applications) if (oA.position == a.position) { if (employs.numOpenings(oA.position) == 0) { a.applies.mind.switchApplication(null) ; applications.remove(oA) ; } } // // If the actor needs transport, arrange it- if (! works.inWorld()) { final Commerce commerce = employs.base().commerce ; commerce.addImmigrant(works) ; } }
4c4a0785-a842-45c1-901b-17bbe29267ee
3
public void drawWave2Text(int x, String text, int effectSpeed, int y, int color) { // method387 if (text == null) { return; } x -= getANTextWidth(text) / 2; y -= trimHeight; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c != ' ') { drawChar(pixels[c], x + horizontalKerning[c] + (int) (Math.sin(i / 5D + effectSpeed / 5D) * 5D), y + verticalKerning[c] + (int) (Math.sin(i / 3D + effectSpeed / 5D) * 5D), width[c], height[c], color); } x += charWidths[c]; } }
c32cc122-7d22-4186-b80b-5dbe5b200474
8
@Override public void run() { for (int i = this.nTimes + (this.nTimes == 0 ? 0 : 1); i != 1; i--) { long t = (long) (Math.random() * thinkMillis); System.out.println("Philosopher " + id + " thinks for " + t + " time units."); try { Thread.sleep(t); } catch (InterruptedException e) { } IFork myFork = (rHanded ? right : left); String forkName = (rHanded ? "right" : "left"); System.out.println("Philosopher " + id + " goes for " + forkName + " fork."); myFork.acquire(); System.out.println("Philosopher " + id + " has " + forkName + " fork."); Thread.yield(); IFork myFork2 = (rHanded ? left : right); String fork2Name = (rHanded ? "left" : "right"); System.out.println("Philosopher " + id + " goes for " + fork2Name + " fork."); myFork2.acquire(); System.out.println("Philosopher " + id + "has " + fork2Name + " fork."); Thread.yield(); t = (long) (Math.random() * eatMillis); System.out.println("Philosopher " + id + " eats for " + t + " time units"); try { Thread.sleep(t); } catch (InterruptedException e) { } right.release(); System.out.println("Philosopher " + id + " releases right fork."); left.release(); System.out.println("Philosopher " + id + " releases left fork."); } }
a93a0cb1-5eeb-4dfd-becb-50d96b530feb
0
public String getName() { return nameLabel.getText(); }
7c65cc11-8ffe-4265-b176-2801eda59f74
9
@Override public void endElement( final String namespace_uri, final String local_name, final String qualified_name ) throws SAXException { if ( ForesterUtil.isEmpty( namespace_uri ) || namespace_uri.startsWith( ForesterConstants.PHYLO_XML_LOCATION ) ) { if ( local_name.equals( TolXmlMapping.CLADE ) ) { try { TolXmlHandler.mapElementToPhylogenyNode( getCurrentXmlElement(), getCurrentNode() ); if ( !getCurrentNode().isRoot() ) { setCurrentNode( getCurrentNode().getParent() ); } setCurrentXmlElement( getCurrentXmlElement().getParent() ); } catch ( final PhylogenyParserException ex ) { throw new SAXException( ex.getMessage() ); } } else if ( local_name.equals( TolXmlMapping.PHYLOGENY ) ) { try { TolXmlHandler.mapElementToPhylogeny( getCurrentXmlElement(), getCurrentPhylogeny() ); } catch ( final PhylogenyParserException ex ) { throw new SAXException( ex.getMessage() ); } finishPhylogeny(); reset(); } else if ( ( getCurrentPhylogeny() != null ) && ( getCurrentXmlElement().getParent() != null ) ) { setCurrentXmlElement( getCurrentXmlElement().getParent() ); } setCurrentElementName( null ); } }
e8af81cf-e2a5-4d1f-8ddc-4a55d48fb6e2
9
public double lloydPlusPlus(int k, int n, int d, Point points[]) { //System.out.println("starting kMeans++"); //choose random centres this.tmpCentresStreamingCoreset = chooseRandomCentres(k, n, d, points); double cost = targetFunctionValue(k, n, this.tmpCentresStreamingCoreset, points); double newCost = cost; Point[] massCentres = new Point[k]; double[] numberOfPoints = new double[k]; do { cost = newCost; //reset centres of mass int i = 0; for (i = 0; i < k; i++) { massCentres[i] = new Point(d); numberOfPoints[i] = 0.0; } //compute centres of mass for (i = 0; i < n; i++) { int centre = points[i].determineClusterCentreKMeans(k, this.tmpCentresStreamingCoreset); for (int l = 0; l < massCentres[centre].dimension; l++) { if (points[i].weight != 0.0) massCentres[centre].coordinates[l] += points[i].coordinates[l]; } numberOfPoints[centre] += points[i].weight; } //move centres for (i = 0; i < k; i++) { for (int l = 0; l < this.tmpCentresStreamingCoreset[i].dimension; l++) { this.tmpCentresStreamingCoreset[i].coordinates[l] = massCentres[i].coordinates[l]; this.tmpCentresStreamingCoreset[i].weight = numberOfPoints[i]; } } //calculate costs newCost = targetFunctionValue(k, n, this.tmpCentresStreamingCoreset, points); //System.out.println("old cost: "+cost+", new cost: "+newCost); } while (newCost < THRESHOLD * cost); //System.out.println("Centres: \n"); int i = 0; for (i = 0; i < k; i++) { //System.out.print("("); int l = 0; for (l = 0; l < this.tmpCentresStreamingCoreset[i].dimension; l++) { // System.out.print(this.tmpCentresStreamingCoreset[i].coordinates[l] / this.tmpCentresStreamingCoreset[i].weight); this.tmpCentresStreamingCoreset[i].coordinates[l] /= this.tmpCentresStreamingCoreset[i].weight; // System.out.print(","); } //System.out.println(")"); } //System.out.println("kMeans++ finished"); //System.out.println(i+" "+newCost+" "+this.tmpCentresStreamingCoreset.length);*/ return newCost; }
5b94bd9f-4145-4960-9d74-0b5f354e12be
6
public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(newJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(newJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(newJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(newJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new newJFrame().setVisible(true); } }); }
cc83c019-b301-4748-9445-645524a3262f
0
public void setImage(File image) { this.image = image; }
36264b00-9c11-4ca1-8e06-a6f502738697
4
public void initTable() { tableModel.addTableModelListener(deckTable); deckTable.setRowSelectionAllowed(true); deckTable.getTableHeader().setReorderingAllowed(false); //deckTable.setRowSorter(sorter = new TableRowSorter<DeckTableModel>(tableModel)); //sorter.setSortsOnUpdates(true); deckTable.setRowHeight(25); deckTable.setDeck(deck); deckTable.setDragEnabled(true); deckTable.setDropMode(DropMode.INSERT_ROWS); deckTable.setTransferHandler(new DeckTableTransferHandler(this)); deckTable.setFillsViewportHeight(true); deckTable.setDefaultRenderer(Object.class, new DeckTableRowCellRenderer(true)); initTableMouseListener(); initTableHeaderListener(); initImageListMouseListener(); imageList.getList().setDragEnabled(true); imageList.getList().setDropMode(DropMode.INSERT); imageList.getList().setTransferHandler(new ImageListTransferHandler(imageList, this)); ListSelectionModel cellSelectionModel = deckTable.getSelectionModel(); cellSelectionModel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); cellSelectionModel.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) { return; } cardBuffer.clear(); for (int row: deckTable.getSelectedRows()) { if (row != -1) { cardBuffer.add(row); } } if (deckTable.getSelectedRow() != -1) { //this was code from when the refComplex was visible on page (maybe bring back as alternate view) //imageSelection.setCurrentImage(deck.get(deckTable.getSelectedRow()).getImage()); //cardStats.setText(deck.get(deckTable.getSelectedRow()).getDescription()); //new CardInfoPanel(deck.get(deckTable.getSelectedRow())); //new CardInfoPanel(); } else { //imageSelection.resetCurrentImage(); //cardStats.setText(""); } } }); }