method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
0bc38360-d4d8-40f3-ae43-1b193d15cb65
9
public void run() { // Used to assign each error an id so an error tree structure can be // constructed. int errorIdCounter = 0; while (true) { try { // Read from dump file to point array String dumpData = dReader.readDumpFile(); if (dumpData != null) { JSExecutionTracer.addPoint(dumpData); // Check if ERROR occurs if (dumpData.contains(":::ERROR")) { stateCounter++; // Output the trace JSExecutionTracer.generateTrace(new Integer( stateCounter).toString(), FileManager .getProxyTraceFolder()); } // Check if trace folder is empty // If not, we need analyse the error from traces if (!FileManager.isDirectoryEmpty(FileManager .getProxyTraceFolder())) { // rca analysis RCAPlugin rca = new RCAPlugin( FileManager.getProxyTraceExecutiontraceFolder(), FileManager.getProxyJsSourceFolder()); rca.rcaStart(errorIdCounter); errorIdCounter++; // Clean the point array by removing the last finished error JSONArray temJSONArray = new JSONArray(); for(int j = 0; j < JSExecutionTracer.points.length(); j++){ if(!JSExecutionTracer.points.get(j).toString().contains(":::ERROR")){ temJSONArray.put(JSExecutionTracer.points.get(j)); } } JSExecutionTracer.points = temJSONArray; } } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } }
ec9ff06e-3fbc-4e17-983a-9e0ea5901c2a
9
private void parseSimpleFace(String[] tokens, MeshData md, ScanData sd) { short[] indices = new short[tokens.length-1]; for(int i = 1; i < tokens.length; i++) indices[i-1] = (short) (Short.parseShort(tokens[i])-1); if(computeNormals) { // First we compute the normal float[] normal = {0,0,0}; float[] v1 = {0,0,0}; float[] v2 = {0,0,0}; // Compute v1 from vertex1 to vertex2 float[] vec1 = sd.vertexList.get(indices[0]); float[] vec2 = sd.vertexList.get(indices[1]); float[] vec3 = sd.vertexList.get(indices[2]); MyMath.subtract(vec2, vec1, v1); MyMath.subtract(vec3, vec2, v2); MyMath.crossProduct(v1, v2, normal); MyMath.normalize(normal); short normalIndex = -1; // Search for an existing normal in the list for(float[] n: sd.normalList) if(n[0] == normal[0] && n[1] == normal[1] && n[2] == normal[2]) { normalIndex = (short) sd.normalList.indexOf(n); } if(normalIndex < 0) { normalIndex = (short) sd.normalList.size(); sd.normalList.add(normal); } for(int i = 2; i < indices.length; i++) { md.addIndex(indices[0], normalIndex, sd); md.addIndex(indices[i-1], normalIndex, sd); md.addIndex(indices[i], normalIndex, sd); } } else for(int i = 2; i < indices.length; i++) { md.addIndex(indices[0], sd); md.addIndex(indices[i-1], sd); md.addIndex(indices[i], sd); } }
907bbbb1-ac7c-49b0-99c2-bef7c7c06caf
5
public void setEditedBlock(JBlock b) { if(b==editing) return ; if(editing!=null) finnishEdit(); editing=(startBlock)b; fields.clear(); fieldsPane.removeAll(); name.setText(editing.name); silent.setSelected(editing.silent); displayName.setSelected(editing.displayName); String l[][]=editing.getFields(); for(String f[]:l){ Field field=new Field(this); field.name.setText(f[0]); for(ComboText c: types){ if(c.getValue().equals(f[1])){ field.type.setSelectedItem(c); break; } } fields.add(field); } makeList(); }
e8f7b254-f130-45c8-983c-55f4a540614e
2
public void testProviderSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); DateTimeZone.setProvider(new MockOKProvider()); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } }
3442187f-fcbb-4924-a96c-389aad5a8bf2
2
public static String itostrx(int hex) { final int BASE = 16; final int ASCII_DIGITS = 48; final int ASCII_LETTERS = 55; final int CUTOFF = 10; String result = ""; do{ int remainder = (hex % BASE); if(remainder >= CUTOFF){// If it is a letter result = (char) (remainder + ASCII_LETTERS) + result; } else{ //if it is a normal digit. result = (char) ((hex % BASE) + ASCII_DIGITS) + result; } hex /= BASE; } while(hex > 0); return result; }
2b2aa540-2212-4a12-a92e-1c07ce089eba
8
public static void shootProjectile(String projectileName, Screen screen, int ref, TimeManager currentTime, int dist, Point shooterPosition) { if (projectileName.equals(ProjectileNames.CANNISTER_SHOT)) { Projectile canisterShot = new CanisterShot(screen, ref, currentTime); canisterShot.shoot(dist, shooterPosition); } else if (projectileName.equals(ProjectileNames.CARCASS)) { Projectile carcass = new Carcass(screen, ref, currentTime); carcass.shoot(dist, shooterPosition); } else if (projectileName.equals(ProjectileNames.CHAIN_SHOT)) { Projectile chainShot = new ChainShot(screen, ref, currentTime); chainShot.shoot(dist, shooterPosition); } else if (projectileName.equals(ProjectileNames.HEATED_SHOT)) { Projectile heatedShot = new HeatedShot(screen, ref, currentTime); heatedShot.shoot(dist, shooterPosition); } else if (projectileName.equals(ProjectileNames.SHRAPNEL)) { Projectile shrapnel = new Shrapnel(screen, ref, currentTime); shrapnel.shoot(dist, shooterPosition); } else if (projectileName.equals(ProjectileNames.SIMPLE_SHELL)) { Projectile simpleShell = new SimpleShell(screen, ref, currentTime); simpleShell.shoot(dist, shooterPosition); } else if (projectileName.equals(ProjectileNames.SPIDER_SHOT)) { Projectile spiderShot = new SpiderShot(screen, ref, currentTime); spiderShot.shoot(dist, shooterPosition); } else if (projectileName.equals(ProjectileNames.TRI_GRAPE_SHOT)) { Projectile triGrapeShot = new TriGrapeShot(screen, ref, currentTime); triGrapeShot.shoot(dist, shooterPosition); } else { System.out.println("Undefined projectile type"); } }
981c658e-9027-4f62-87ba-e1eede229a62
1
public static void install() { if (installed == null) { installed = new RepeatingReleasedEventsFixer(); Toolkit.getDefaultToolkit().addAWTEventListener(installed, AWTEvent.KEY_EVENT_MASK); } }
db4b508f-2a9a-40d7-8606-887a23e3fb2f
7
public static Rule_COMMA parse(ParserContext context) { context.push("COMMA"); boolean parsed = true; int s0 = context.index; ArrayList<Rule> e0 = new ArrayList<Rule>(); Rule rule; parsed = false; if (!parsed) { { ArrayList<Rule> e1 = new ArrayList<Rule>(); int s1 = context.index; parsed = true; if (parsed) { boolean f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { rule = Terminal_NumericValue.parse(context, "%x2c", "[\\x2c]", 1); if ((f1 = rule != null)) { e1.add(rule); c1++; } } parsed = c1 == 1; } if (parsed) e0.addAll(e1); else context.index = s1; } } rule = null; if (parsed) rule = new Rule_COMMA(context.text.substring(s0, context.index), e0); else context.index = s0; context.pop("COMMA", parsed); return (Rule_COMMA)rule; }
d6860bc3-457a-4f63-8180-fd79e8bca631
5
@Override public void run() { while (true) { if (shutdown) { if (this.id % 10 == 0) // every 10th thread logger.info("Thread #" + this.id + " increased the counter " + this.sum + "-times"); else logger.info("Thread #" + this.id + " summed up to " + this.sum); return; } if (start) { if (this.id % 10 == 0) { // every 10th thread increaseCounter(); this.sum++; } else { this.sum += getCounter(); } } } }
06f2e070-8f83-4532-853a-cbd592536198
7
@Override public Object execute(Scope scope, Statement tokens) { Method method = null; Object[] args = new Object[tokens.size()]; for (int i = 0 ; i < args.length;++i){ try { args[i] = scope.getValue(tokens.get(i)); } catch (PoslException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(args[i] instanceof Java){ Java j = (Java)args[i]; args[i] = j.getObject(); } } method = appropriateMethod(args); try { Object reply = method.invoke(reference, args); if(reply == null) { return null; } else if(reply instanceof Number || reply instanceof String){ return reply; } else { return new Java(reply); } }catch(Exception e){ throw new RuntimeException(e); } }
be4f9e31-5ee6-4b0b-ad57-d3fa2cf70ae9
2
private Float averageMarketChange(float[] changes) { float sum = 0; float valid = 0; for (float f : changes) { if (f == f) { sum += f; valid++; } } // System.out.println("SUMMING GIVES : " + sum); return sum / valid; }
03234d63-98a1-463f-b152-d88fc4a32151
4
public List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException { try { if (isRollback) { return Collections.emptyList(); } else { return executeStatements(); } } finally { for (StatementData stmt : statementsData.values()) { closeStatement(stmt.getStatement()); } if (!reuseBetweenFlushes) { for (StatementData stmt : unusedStatementData.values()) { closeStatement(stmt.getStatement()); } } lastKey = null; statementsData.clear(); unusedStatementData.clear(); } }
1621edcf-4d93-4663-a5ef-0e5266b94521
6
@Override public boolean onCommand(final CommandSender sender,final Command command,final String label,final String[] args) { if (args.length <= 1) { return false; } final OfflinePlayer player = this.plugin.getServer().getOfflinePlayer(args[0]); if (player == null) { sender.sendMessage(ChatColor.RED + "Unknown player."); return true; } if (!this.plugin.isBanned(player.getName())) { sender.sendMessage(ChatColor.RED + player.getName() + " is not banned. Cannot unban."); return true; } // Unban, no reason. if (args.length == 2) { Event event = this.plugin.tempUnbanPlayer( player.getName(), sender.getName(), args[1] ); if (event != null) { this.plugin.broadcast(event); } return true; } // Unban. Event event = this.plugin.tempUnbanPlayer( player.getName(), sender.getName(), StringUtils.join(args," ",2,args.length), args[1] ); if (event != null) { this.plugin.broadcast(event); } return true; }
b808b77d-384d-4099-8579-8ca9e7fa1850
7
private void createFiles(File path, File rel) throws DBException { if (path.isDirectory()) { for (String name : path.list()) createFiles(new File(path, name), new File(rel, name)); } if (null != rel && !path.isDirectory()) { NodeNameDTO node = nameDAO.find(rel, false); if (null == node) throw new IllegalStateException("Missing node for file " + rel); if ((1 + fileCount) % 5 == 0) { FileDTO file = new FileDTO(); file.setNameId(node.getId()); fileDAO.insert(file); VersionDTO mark = VersionDTO.newDeletionMark(file, new java.sql.Timestamp(System.currentTimeMillis())); versionDAO.insert(mark); file.setCurrentVersionId(mark.getId()); fileDAO.update(file); } if ((1 + fileCount) % 10 != 0) { FileDTO file = new FileDTO(); file.setNameId(node.getId()); fileDAO.insert(file); VersionDTO version = new VersionDTO(file); version.setModifiedTime(new java.sql.Timestamp(System.currentTimeMillis())); version.setSize(0); versionDAO.insert(version); file.setCurrentVersionId(version.getId()); fileDAO.update(file); } files.put(rel, node); fileCount++; } }
1e7a8e59-6c49-45fb-9448-85e390f6529a
9
public static String modUtente(HttpServletRequest req) { HttpSession s = req.getSession(); UserBean user = (UserBean) s.getAttribute("user"); String username = user.getUsername(); try { Utente u = Model.getUtente(username); switch (u.getPermission()) { case "admin": int idUtente = -1; try { idUtente = Integer.parseInt(req.getParameter("id")); } catch (NumberFormatException e) { errorMessage(s, req.getParameter("id") + " non int"); } Utente modu = Model.getUtente(idUtente); ///modifica utente String moduser_name = modu.getUsername(); String name = req.getParameter("name") + ""; if (name != null && !name.equals("")) { modu.setUsername(name); } ///modifica password String password = req.getParameter("password") + ""; if (password != null && !password.equals("")) { modu.setPwd(password); } ///modifica permission String permission = req.getParameter("rule"); if (permission != null && !permission.equals("")) { modu.setPermission(permission); } Model.modUtente(moduser_name, modu); goodMessage(s, "utente aggiornato"); return View.getUtenteElement(modu); default: errorMessage(s, "non hai i permessi per modificare gli utenti"); break; } } catch (SQLException e) { errorMessage(s, e.getMessage()); } return ""; }
84e7275a-44f1-4c13-91b7-ef81e10fb046
1
private void addTable() { tableModel = new DefaultTableModel(new String[] { "nazwa", "punkty", "czas zakończenia" }, 0); table = new JTable(tableModel); table.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1) { JTable target = (JTable) e.getSource(); rowNum = target.getSelectedRow(); colNum = target.getSelectedColumn(); EventQueue.invokeLater(new Runnable() { @Override public void run() { //UserDetailsView.getUserDetailsViewInstance((String) tableModel // .getValueAt(rowNum, 0), null); } }); } } }); table.setBounds(74, 12, 312, 154); contentPane.setLayout(new BorderLayout()); contentPane.add(table.getTableHeader(), BorderLayout.NORTH); contentPane.add(table, BorderLayout.CENTER); }
71cb3169-1b85-4e84-8057-7e025417342f
0
public String getEventName() { return eventName; }
581e44f5-6385-4ce6-b6f1-c04904a88f08
9
static GateType getTypeFromString(String type) { if (type.toUpperCase().trim().equals("AND")) return AND; else if (type.toUpperCase().trim().equals("OR")) return OR; else if (type.toUpperCase().trim().equals("NOT")) return NOT; else if (type.toUpperCase().trim().equals("NAND")) return NAND; else if (type.toUpperCase().trim().equals("NOR")) return NOR; else if (type.toUpperCase().trim().equals("INPUT")) return INPUT; else if (type.toUpperCase().trim().equals("OUTPUT")) return OUTPUT; else if(type.toUpperCase().trim().equals("XOR")) return XOR; else if(type.toUpperCase().trim().equals("CELL")) return CELL; //somebody didn't type in the input correctly else{ System.err.println("You dun messed up son! " + type.toUpperCase().trim() + " isn't a valid gate type!"); System.exit(1); return null; //stupid compiler making me put this in even though it'll never be reached } }
fa081218-7474-4059-928b-f5541b4c00eb
0
public void setProtocol(FileProtocol protocol) { this.protocol = protocol; setText(protocol.getName()); }
a0dc3fd4-7787-4c21-9d09-9779178e8a3a
5
@Override public Class<?> getColumnClass(int columnIndex) { switch(columnIndex){ case 0: return String.class; case 1: return String.class; case 2: return Double.class; case 3: return Component.class; default: return Object.class; } }
47b08615-65fa-4a19-abb2-4714e9aeb726
7
void createTabList(Composite parent) { tabList = new Tree(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); Arrays.sort(tabs, new Comparator() { public int compare(Object tab0, Object tab1) { return ((GraphicsTab)tab0).getText().compareTo(((GraphicsTab)tab1).getText()); } }); HashSet set = new HashSet(); for (int i = 0; i < tabs.length; i++) { GraphicsTab tab = tabs[i]; set.add(tab.getCategory()); } String[] categories = new String[set.size()]; set.toArray(categories); Arrays.sort(categories); for (int i = 0; i < categories.length; i++) { String text = categories[i]; TreeItem item = new TreeItem(tabList, SWT.NONE); item.setText(text); } tabs_in_order = new ArrayList(); TreeItem[] items = tabList.getItems(); for (int i = 0; i < items.length; i++) { TreeItem item = items[i]; for (int j = 0; j < tabs.length; j++) { GraphicsTab tab = tabs[j]; if (item.getText().equals(tab.getCategory())) { TreeItem item1 = new TreeItem(item, SWT.NONE); item1.setText(tab.getText()); item1.setData(tab); tabs_in_order.add(tab); } } } tabList.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { TreeItem item = (TreeItem)event.item; if (item != null) { GraphicsTab gt = (GraphicsTab)item.getData(); if (gt == tab) return; setTab((GraphicsTab)item.getData()); } } }); }
d333b2bf-ad6c-4cc4-9ba1-5f0b3020ffc0
8
public void resetStatus() { if (map.isEmpty()) return; synchronized (map) { for (ModelCanvas mc : map.values()) { if (!mc.isUsed()) continue; final MDContainer c = mc.getMdContainer(); c.getModel().stop(); c.getModel().clearMouseScripts(); c.getModel().clearKeyScripts(); mc.setUsed(false); mc.showBorder(true); mc.getMdContainer().setStatusBarShown(true); List list = c.getModel().getModelListeners(); if (list != null) list.clear(); list = c.getModel().getMovie().getMovieListeners(); if (list != null) { for (Iterator j = list.iterator(); j.hasNext();) { if (j.next() != ((SlideMovie) (c.getModel().getMovie())).getMovieSlider()) j.remove(); } } // CAUTION: Free-up memory causes problem of inserting a new model in a new page. // c.getModel().freeUpMemory(); c.getModel().clear(); /* * leave this job to when it is time to repopulate the tool bar EventQueue.invokeLater(new Runnable(){ * public void run(){ if(c.getToolBar()!=null) c.getToolBar().removeAll(); if(c.getExpandMenu()!=null) * c.getExpandMenu().removeAll(); c.removeToolbar(); } }); */ if (c instanceof AtomContainer) { ((AtomContainer) c).disableGridMode(); } } } }
d6352d05-bfce-4075-bf86-31eba7e3d189
5
public void step(SimulationComponent mComp) { String tLine = lineList.get(ticks); tick(); Pattern tPat1 = Pattern.compile("\\s*print\\s*\"(.*)\".*"); Matcher tM1 = tPat1.matcher(tLine); if(tM1.matches()) { mComp.addStatusMessage(name + " output : " + tM1.group(1)); } else { mComp.addStatusMessage(name + " : " + tLine.trim()); } Pattern tPat2 = Pattern.compile("\\s*(\\S*)\\s*\\(.*?\\).*"); Matcher tM2 = tPat2.matcher(tLine); if(tM2.matches()) { Method m = gParent.getMethod(tM2.group(1)); if(m != null && callStack != null) { callStack.push(m); } } if(ticks > lineList.size()) { System.err.println(name + " should have exited by now..."); } }
7824156f-ed14-41aa-96f7-6c0bae56ebd3
4
private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed // TODO add your handling code here: try { //Para establecer el modelo al JTable DefaultTableModel modelo = new DefaultTableModel(); this.Jtable.setModel(modelo); //Para conectarnos a nuestra base de datos Class.forName("org.sqlite.JDBC"); //DriverManager.registerDriver(new JDBC("org.sqlite.JDBC"); //DriverManager.registerDriver(new com.mysql.jdbc.Driver()); Connection conexion = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\V1C70R MU3N735\\Desktop\\pruebaIndumaster", "root", " "); //Para ejecutar la consulta Statement s = conexion.createStatement(); //Ejecutamos la consulta que escribimos en la caja de texto //y los datos lo almacenamos en un ResultSet ResultSet rs = s.executeQuery(txtConsulta.getText()); //Obteniendo la informacion de las columnas que estan siendo consultadas ResultSetMetaData rsMd = rs.getMetaData(); //La cantidad de columnas que tiene la consulta int cantidadColumnas = rsMd.getColumnCount(); //Establecer como cabezeras el nombre de las colimnas for (int i = 1; i <= cantidadColumnas; i++) { modelo.addColumn(rsMd.getColumnLabel(i)); } //Creando las filas para el JTable while (rs.next()) { Object[] fila = new Object[cantidadColumnas]; for (int i = 0; i < cantidadColumnas; i++) { fila[i]=rs.getObject(i+1); } modelo.addRow(fila); } rs.close(); conexion.close(); } catch (Exception ex) { ex.printStackTrace(); } }//GEN-LAST:event_btnConsultarActionPerformed
357881a0-6c9f-41cc-908a-dcdb906b0af0
5
public double Caldj(int iy, int im, int id) throws palError { int ny; double d = 0.0; TRACE("Caldj"); /* Default century if appropriate */ if ((iy >= 0) && (iy <= 49)) { ny = iy + 2000; } else if ((iy >= 50) && (iy <= 99)) { ny = iy + 1900; } else { ny = iy; } ENDTRACE("Caldj"); /* Modified Julian Date */ try { return Cldj(ny, im, id); } catch (palError e) { throw e; } }
47bd1b79-ef6a-4ccc-916e-d85c7d10e87a
8
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!super.okMessage(myHost,msg)) return false; if(!(affected instanceof MOB)) return true; if((msg.source()==affected) &&(msg.targetMinor()==CMMsg.TYP_DAMAGE) &&(msg.target() instanceof MOB) &&(msg.source().getWorshipCharID().length()>0) &&(!((MOB)msg.target()).getWorshipCharID().equals(msg.source().getWorshipCharID()))) { if(((MOB)msg.target()).getWorshipCharID().length()>0) msg.setValue(msg.value()*2); else msg.setValue(msg.value()+(msg.value()/2)); } return true; }
d2db69b5-66db-460a-8eac-dad6bd7ba116
5
public double operar(){ double a,b, resultado = 0; String operacion; while(miPila.size()>2){ a = Double.parseDouble(miPila.pop()+""); b = Double.parseDouble(miPila.pop()+""); operacion = miPila.pop()+""; if(operacion.equals("+")){ resultado = a + b; miPila.push(resultado+""); } if(operacion.equals("-")){ resultado = a - b; miPila.push(resultado+""); } if(operacion.equals("*")){ resultado = a * b; miPila.push(resultado+""); } if(operacion.equals("/")){ resultado = a / b; miPila.push(resultado+""); } } return resultado; }
2d90eba1-c7c8-431c-80a3-386e35b8e056
4
@Test(expected = UnsupportedOperationException.class) public void test() throws IOException { pq = new PacketQueue(); cl = new ConnectionListener(Settings.getPortNumber(), "", pq); Thread simserver = new Thread(new Runnable() { @Override public void run() { GameNetworkInterface net; while (true) { pq.waitForPacket(); IPacket p = pq.getPacket(); if (p instanceof JoinGamePacket) { JoinGamePacket j = (JoinGamePacket) p; net = j.getGameNetwork(); try { if (secondjoin) { net.send(new PlayerJoined(j.getName())); } else { secondjoin = true; net.stop(); } } catch (IOException e) { fail(e.getMessage()); } } } } }, "FakeServer"); simserver.start(); this.ps = ReaderFactory.initTestReader(); this.pf = TestDataProvider.getPacketFactory(); this.cr = ReaderFactory.getReader(pf); new ReaderFactory(); assertEquals(pf, cr.getPacketFactory()); ps.println("blub"); ps.println("/ "); ps.println("/join"); ps.println("/joinip"); ps.println("/bet"); ps.println("/joasfinip"); ps.println("/join Knorke jhgfjh"); ps.println("/join Knorke1"); ps.println("/join Knorke2"); ps.println("/join Knorke2"); ps.println("/start"); ps.println("/bet"); ps.println("/bet a"); ps.println("/bet 1 1"); ps.println("/bet 1"); ps.println("/bet 1 1"); ps.println("/play"); ps.println("/play Human 1"); ps.println("/play 1 1"); ps.println("/play Human blub"); ps.println("/exit"); cr.waitforexit(); cr.reset(); ps.println("/joinip 255.255.255.255 fail"); ps.println("/joinip 127.0.0.1 knorke3 asdfsf"); ps.println("/joinip localhost knorke3"); ps.println("/joinip localhost knorke3"); ps.println("/exit"); cr.waitforexit(); cl.interrupt(); throw new UnsupportedOperationException(); }
29148d38-7975-4cf9-a125-a31100c4c2a2
1
public static void main(String[] args) throws SQLException { //RequetesPays pp= new RequetesPays(); pays ok // RequetesPays.ecrirePays("ALLEMAGNE"); // VuePays vtest= new VuePays(); // vtest.setVisible(true); //Pays ll= RequetesPays.paysId(2); // VueCouleur vTest = new VueCouleur(); // vTest.setVisible(true); // VueInterlocuteur vInter= new VueInterlocuteur(); // vInter.setVisible(true); // RequetesInterlocuteur zz=new RequetesInterlocuteur(); // RequetesInterlocuteur.ecrireInterlocuteur(1,"dupont","marcel","toto@free.fr"); // RequetesVille vv= new RequetesVille(); // RequetesVille.ecrireVille(1, "OISSEL","76350"); // RequetesVille.villecp("76000"); // RequetesVille vv= new RequetesVille(); // RequetesVille vv1= RequetesVille.villecp("76000"); // List vv1 =RequetesVille.villecp("76350") ; // System.out.println(vv1.toString()); /* VueVille v2 = new VueVille(); v2.setVisible(true); List<Pays> pp1 = RequetesPays.listerPays(); System.out.println(pp1.size()); for (int i = 0; i < pp1.size(); i++) { System.out.println("Élément à l'index " + i + " = " + pp1.get(i).getIdPays() + " = " + pp1.get(i).getPays()); } for (Pays pays : pp1) { pays.getIdPays(); } */ // Interlocuteur pp1 = RequetesInterlocuteur.selectId(2); // System.out.println(pp1.toString()); // List <Interlocuteur> pp1= RequetesInterlocuteur.listerInterlocuteur(); // RequetesUtilisateur.ecrireUtilisateur(1,1,"DUPONT","Marcel", "10 rue du pont",""); // RequetesInterlocuteur.ecrireInterlocuteur(1, 1, 1, "dupuis", "louis", "dupouisl@free.fr"); /*List<Pays> pp1 = RequetesPays.listerPays(); System.out.println(pp1.size()); for (Pays pays : pp1) { pays.getIdPays(); } JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComboBox jComboBox1 = new JComboBox(); for(int i = 0; i < pp1.size(); i++) jComboBox1.addItem(pp1.get(i).getPays()); Object cmboitem = jComboBox1.getSelectedItem(); System.out.println(cmboitem); frame.add(jComboBox1); frame.setSize(300, 200); frame.setVisible(true);*/ /* manipulliationde de date*/ /* Date madate=new Date(); DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); Date date = null; try { date = df.parse("25-12-2010"); System.out.println(date); RequetesActionCom.insertActionCom(1, 1, date, "test"); } catch (ParseException e) { System.out.println(e); } */ List< Stock> pp1 = RequetesStock.selectStock(); System.out.println(pp1.size()); for (int i = 0; i < pp1.size(); i++) { System.out.println("Élément à l'index " + i + " = " + pp1.get(i).getIdstock() + " = " +"-"+pp1.get(i).getDatemaj()); } }
95027882-b0a8-4841-b5f0-5598f9c18d0c
8
@Override public void undoableEditHappened(UndoableEditEvent undoableEditEvent) { UndoableEdit edit = undoableEditEvent.getEdit(); // Make sure this event is a document event if (edit instanceof DefaultDocumentEvent) { // Get the event type DefaultDocumentEvent event = (DefaultDocumentEvent) edit; EventType eventType = event.getType(); // Check if the event type is not a change on character attributes, but instead an insertion or removal of // text. if (eventType != EventType.CHANGE) { boolean isEndCompoundEdit = false; // Check if current compound edit must be ended as it contains at least one new line if (eventType == EventType.INSERT) { try { // Check if the inserted text contains a new line character String insertedText = event.getDocument().getText(event.getOffset(), event.getLength()); isEndCompoundEdit = insertedText.contains("\n"); } catch (BadLocationException e) { e.printStackTrace(); } } // Make sure we are not in an explicit marked compound edit if (!isCompoundMarkStart) { // Check if current compound edit must be ended due to change between insertion or removal change isEndCompoundEdit |= (eventType != lastEventType); // Check if the current compound edit should be ended and a new one started if (isEndCompoundEdit) { endCurrentCompoundEdit(); } // Save the last event type lastEventType = eventType; } // Create new compound edit if the current one has been ended or does not exist if (currentCompoundEdit == null) { newCurrentCompoundEdit(); } } // Added event edit to the current compound edit if (currentCompoundEdit != null) { currentCompoundEdit.addEdit(edit); } } // Update the state of the actions updateUndoRedoState(); }
7e035e1d-44a3-4415-a6b9-e56e6e44a0ee
6
protected Term extractTerm(String fis) { String line = ""; for (char c : fis.toCharArray()) { if (!(c == '[' || c == ']')) { line += c; } } List<String> nameTerm = Op.split(line, ":"); if (nameTerm.size() != 2) { throw new RuntimeException(String.format( "[syntax error] expected term in format 'name':'class',[params], " + "but found <%s>", line)); } List<String> termParams = Op.split(nameTerm.get(1), ","); if (termParams.size() != 2) { throw new RuntimeException(String.format( "[syntax error] expected term in format 'name':'class',[params], " + "but found <%s>", line)); } List<String> parameters = Op.split(termParams.get(1), " "); for (int i = 0; i < parameters.size(); ++i) { parameters.set(i, parameters.get(i).trim()); } return createInstance( termParams.get(0).trim(), nameTerm.get(0).trim(), parameters); }
2bae812b-dc31-407f-a26d-3dc480aeedd0
8
public IEvaluableToken parse() { try { // 1. Extract all parentheses into TokenLists extractParentheses(); // 2. Convert operator tokens to operators, including their arguments // in the correct order ^ * / + - extractOperator(TokenOperatorFactorial.class); extractOperator(TokenOperatorPower.class); extractOperator(TokenOperatorMultiply.class); extractOperator(TokenOperatorDivide.class); extractOperator(TokenOperatorModulo.class); extractOperator(TokenOperatorAdd.class); extractOperator(TokenOperatorSubtract.class); // 3. Check for leftovers, throw error if any if (this.size() > 1) { throw new ParseError("TokenList didn't parse entirely, probably a syntax error: " + this); } // 4. If last token is a TokenList, use its content instead if (this.get(0) instanceof TokenList) { TokenList theList = (TokenList) this.get(0); if (theList.size() == 1 && (theList.get(0) instanceof IEvaluableToken)) { IEvaluableToken eval = (IEvaluableToken) theList.get(0); this.clear(); this.add(eval); } } // 5. Throw error if last token remaining is not evaluable if (!(this.get(0) instanceof IEvaluableToken)) { throw new ParseError("Last token in a TokenList is not evaluable: " + this.get(0)); } } catch (ParseError e) { throw e; } catch (IndexOutOfBoundsException e) { throw new ParseError("Missing operand(s)."); } catch (Exception e) { throw new ParseError(e); } return (IEvaluableToken) this.get(0); // checked earlier }
aff69455-ee86-4e56-ae8c-b4694f58a374
7
public void merge(int A[], int m, int B[], int n) { if (m<=0&&n<=0){ return; } int index = m+n-1; while(m!=0&&n!=0){ if(A[m-1]>B[n-1]){ A[index]=A[m-1]; m--; } else { A[index]=B[n-1]; n--; } index--; } if (n!=0){ for(int i=n-1;i>=0;i--){ A[i]=B[i]; } } }
3e4e58d2-7971-4e41-bb5f-a7eb01944de1
9
public ArrayList<Auction> searchWinnerByBoth(String keyword, String username, String winner) { try { ArrayList<Auction> auctions = new ArrayList<Auction>(); String[] keywords = keyword.split(" "); String[] usernames = username.split(" "); String[] winners = winner.split(" "); String sql = "select * from (select * from (select * from " + tableName + " where "; for (int i = 0; i < usernames.length; i++) { if (i != 0) sql = sql + "OR "; sql = sql + "WINNER = " + "'" + winners[i] + "' "; } sql = sql + ") as t WHERE "; for (int i = 0; i < usernames.length; i++) { if (i != 0) sql = sql + "OR "; sql = sql + "USERNAME LIKE " + "'% " + usernames[i] + " %' OR "; sql = sql + "USERNAME LIKE " + "'" + usernames[i] + " %' OR "; sql = sql + "USERNAME LIKE " + "'% " + usernames[i] + "' OR "; sql = sql + "USERNAME LIKE " + "'% " + usernames[i] + " %' OR "; sql = sql + "USERNAME LIKE " + "'" + usernames[i] + "' "; } sql = sql + ") as q WHERE "; for (int i = 0; i < keywords.length; i++) { if (i != 0) sql = sql + "OR "; sql = sql + "NAME LIKE " + "'% " + keywords[i] + " %' OR "; sql = sql + "NAME LIKE " + "'" + keywords[i] + " %' OR "; sql = sql + "NAME LIKE " + "'% " + keywords[i] + "' OR "; sql = sql + "NAME LIKE " + "'% " + keywords[i] + " %' OR "; sql = sql + "NAME LIKE " + "'" + keywords[i] + "' OR "; sql = sql + "DESCRIPTION LIKE " + "'% " + keywords[i] + " %' OR "; sql = sql + "DESCRIPTION LIKE " + "'" + keywords[i] + " %' OR "; sql = sql + "DESCRIPTION LIKE " + "'% " + keywords[i] + "' OR "; sql = sql + "DESCRIPTION LIKE " + "'% " + keywords[i] + "_ %' OR "; sql = sql + "DESCRIPTION LIKE " + "'" + keywords[i] + "' "; } s = conn.createStatement(); rs = s.executeQuery(sql); if (!rs.next()) return null; do { Auction auction = new Auction(); auction.setID(rs.getInt("ID")); auction.setName(rs.getString("NAME")); auction.setDescription(rs.getString("DESCRIPTION")); auction.setReserver(rs.getInt("RESERVER")); auction.setBuyOut(rs.getInt("BUYOUT")); auction.setStartPrice(rs.getInt("STARTINGPRICE")); auction.setCurrentPrice(rs.getInt("CURRENTPRICE")); auction.setStartTime(rs.getTimestamp("STARTTIME")); auction.setAuctionTime(rs.getTimestamp("AUCTIONTIME")); auction.setUserName(rs.getString("USERNAME")); auction.setWinner(rs.getString("WINNER")); auction.setSold(rs.getInt("SOLD")); auctions.add(auction); } while (rs.next()); return auctions; } catch (Exception e) { System.out.print("error SQL"); return null; } }
bd1a1526-01ba-428d-9644-cba1617cc9b9
5
private Operator findO(I I, ArrayList<O> Oids){ for(O O:Oids){ if(O.id.equals(I.id)){ return O; } } Operator curr = I.next; while(curr != null){ if(curr.type == Operator.Type.O && I.id.equals(curr.id)){ return curr; } curr = curr.next; } return null; }
50bee4d5-5a57-4585-90c9-b30895ee5ed4
2
/** @param column The source column being dragged. */ protected void setSourceDragColumn(Column column) { if (mSourceDragColumn != null) { repaintColumn(mSourceDragColumn); } mSourceDragColumn = column; if (mSourceDragColumn != null) { repaintColumn(mSourceDragColumn); } }
74acd2af-ce89-4acf-8ec7-3cf5a35409bd
7
public void updateRightClick(int cellPosX, int cellPosY) { if (!(cells[cellPosX][cellPosY].getIsRevealed())) { cells[cellPosX][cellPosY].setCellState(); if (cells[cellPosX][cellPosY].getCellState() == 1) { for (GameEventHandler gameEvent : gameEventList) { gameEvent.buttonUpdate(cellPosX, cellPosY, ButtonImage.FLAG); } nbFlags++; } else if (cells[cellPosX][cellPosY].getCellState() == 2) { for (GameEventHandler gameEvent : gameEventList) { gameEvent.buttonUpdate(cellPosX, cellPosY, ButtonImage.QUESTION_MARK); } nbFlags--; } else { for (GameEventHandler gameEvent : gameEventList) { gameEvent.buttonUpdate(cellPosX, cellPosY, ButtonImage.EMPTY); } } for (GameEventHandler gameEvent : gameEventList) { gameEvent.updateFlag(nbMines - nbFlags); } } }
76daa047-3796-4103-866e-85d8581a9f2c
7
private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
d8c7b509-24c5-413b-a312-3ba24b810fd5
6
* The plant that the creature is interested in * @param amount * The amount of energy that the creature is interested in * @return true, if the creature is happy to make a partnership, else false */ protected synchronized boolean requestCompanionship(IntelCreature creature, int combo, Plant currentDesiredPlant, int amount) { if (!hasPartner() && !isAPartner() && !creature.isAPartner() && combo == getDesiredCombo() && amount >= (getComboAmount(combo) / 2) && currentDesiredPlant == getCurrentDesiredPlant()) { WorldFrame.log.append("Intel Leader Creature " + getCreautreNumber() + " Companionship with creature " + creature.getCreautreNumber() + " has been accepted\n"); return true; } return false; }
cd4d4c6a-89af-4cb7-84e9-d3b6886c563f
9
@Override public Room modifyRoom(MOB mob, Room R, int showFlag) throws IOException { if((showFlag == -1) && (CMProps.getIntVar(CMProps.Int.EDITORTYPE)>0)) showFlag=-999; boolean ok=false; while(!ok) { int showNumber=0; R=genRoomType(mob,R,++showNumber,showFlag); genDisplayText(mob,R,++showNumber,showFlag); genDescription(mob,R,++showNumber,showFlag); if(R instanceof GridZones) { genGridLocaleX(mob,(GridZones)R,++showNumber,showFlag); genGridLocaleY(mob,(GridZones)R,++showNumber,showFlag); //((GridLocale)mob.location()).buildGrid(); } if(R instanceof LocationRoom) { genLocationCoords(mob,(LocationRoom)R, ++showNumber, showFlag); } //genClimateType(mob,R,++showNumber,showFlag); //R.setAtmosphere(genAnyMaterialCode(mob,"Atmosphere",R.getAtmosphereCode(),true,++showNumber,showFlag)); genBehaviors(mob,R,++showNumber,showFlag); genAffects(mob,R,++showNumber,showFlag); for(int x=R.getSaveStatIndex();x<R.getStatCodes().length;x++) R.setStat(R.getStatCodes()[x],prompt(mob,R.getStat(R.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(R.getStatCodes()[x]))); if (showFlag < -900) { ok = true; break; } if (showFlag > 0) { showFlag = -1; continue; } showFlag=CMath.s_int(mob.session().prompt(L("Edit which? "),"")); if(showFlag<=0) { showFlag=-1; ok=true; } } return R; }
ebd55d0c-75e3-4e9e-be21-7b7b627bf083
0
public void setAcceptByFinalState(boolean t) { turingAcceptByFinalState = t; turingAcceptByFinalStateCheckBox.setSelected(t); }
9b0b50d6-6388-4e3b-82e2-c1230a6471eb
4
public InputStream getInputStream() throws IOException { if( !this.isOpen() ) throw new IOException( "Cannot retrieve resource's input stream. Resouce was not yet opened." ); if( this.readLimitInputStream == null ) { if( this.contentRange.getLastBytePosition() >= this.getCoreResource().getLength() ) throw new IOException( "Failed to initialize the RangedResource's input stream; the passed Content-Range " + this.contentRange.toString() + " is out of bounds!" ); // Init the stream(s)! InputStream tmpIn = this.getCoreResource().getInputStream(); if( this.contentRange.getFirstBytePosition() > 0 ) { // Skip n bytes at the beginning tmpIn.skip( this.contentRange.getFirstBytePosition() ); } this.readLimitInputStream = new ReadLimitInputStream( tmpIn, this.contentRange.calculateLength() ); } return this.readLimitInputStream; }
3b9614d3-f4a5-4370-aab3-e9b9c005b8d5
3
private void initGenome(StateObservation stateObs) { genome = new int[N_ACTIONS][POPULATION_SIZE][SIMULATION_DEPTH]; // Randomize initial genome for (int i = 0; i < genome.length; i++) { for (int j = 0; j < genome[i].length; j++) { for (int k = 0; k < genome[i][j].length; k++) { genome[i][j][k] = randomGenerator.nextInt(N_ACTIONS); } } } }
d3bf1d99-82c0-4317-b8c6-446ee7f8633c
3
public IllegalOrphanException(List<String> messages) { super((messages != null && messages.size() > 0 ? messages.get(0) : null)); if (messages == null) { this.messages = new ArrayList<String>(); } else { this.messages = messages; } }
c92d2daa-7fc0-43ce-9287-28d77801df57
7
protected Size2D arrangeNN(BlockContainer container, Graphics2D g2) { double x = 0.0; double width = 0.0; double maxHeight = 0.0; List blocks = container.getBlocks(); int blockCount = blocks.size(); if (blockCount > 0) { Size2D[] sizes = new Size2D[blocks.size()]; for (int i = 0; i < blocks.size(); i++) { Block block = (Block) blocks.get(i); sizes[i] = block.arrange(g2, RectangleConstraint.NONE); width = width + sizes[i].getWidth(); maxHeight = Math.max(sizes[i].height, maxHeight); block.setBounds( new Rectangle2D.Double( x, 0.0, sizes[i].width, sizes[i].height ) ); x = x + sizes[i].width + this.horizontalGap; } if (blockCount > 1) { width = width + this.horizontalGap * (blockCount - 1); } if (this.verticalAlignment != VerticalAlignment.TOP) { for (int i = 0; i < blocks.size(); i++) { //Block b = (Block) blocks.get(i); if (this.verticalAlignment == VerticalAlignment.CENTER) { //TODO: shift block down by half } else if (this.verticalAlignment == VerticalAlignment.BOTTOM) { //TODO: shift block down to bottom } } } } return new Size2D(width, maxHeight); }
dccad8ee-05f5-4780-a80e-28a56460aa93
1
public BEValue toBEValue() throws UnsupportedEncodingException { Map<String, BEValue> peer = new HashMap<String, BEValue>(); if (this.hasPeerId()) { peer.put("peer id", new BEValue(this.getPeerId().array())); } peer.put("ip", new BEValue(this.getIp(), Torrent.BYTE_ENCODING)); peer.put("port", new BEValue(this.getPort())); return new BEValue(peer); }
98035ccf-53ad-4e90-9d8e-9715687c731c
8
private boolean arePiecesBetweenSourceAndTarget(int sourceRow, int sourceColumn, int targetRow, int targetColumn, int rowIncrementPerStep, int columnIncrementPerStep) { int currentRow = sourceRow + rowIncrementPerStep; int currentColumn = sourceColumn + columnIncrementPerStep; while (true) { if (currentRow == targetRow && currentColumn == targetColumn) { break; } if (currentRow < Figure.ROW_1 || currentRow > Figure.ROW_8 || currentColumn < Figure.COLUMN_A || currentColumn > Figure.COLUMN_H) { break; } if (this.game.isNonCapturedFigureAt(currentRow, currentColumn)) { System.out.println("Warning #13: Figures in between source and target."); return true; } currentRow += rowIncrementPerStep; currentColumn += columnIncrementPerStep; } return false; }
7be061b3-c242-4f90-9f85-b31dbf50f48b
6
public void find(Course[][] courses) { System.out.print("Enter Department: "); String dept = scan.next(); dept = dept.toUpperCase(); System.out.print("Enter Course Number: "); int courseNum = scan.nextInt(); boolean found = false; for(int x = 0; x < courses.length; x++) { for(int y = 0; y < courses[x].length; y++) { if (courses[x][y] != null) { if (courses[x][y].getDepartment().equals(dept) && courses[x][y].getCourseNumber() == courseNum) { System.out.println(); System.out.println(courses[x][y]); found = true; } } } } if (!(found)) { System.out.println(); System.out.println("Course was not found"); } }
841ba9a9-88a1-4579-875f-dd592df88c3b
2
public static void nouvellePartie() { if (fenetreNouvellePartie != null) { fenetreNouvellePartie.dispose(); } fenetreNouvellePartie = new WindowNouvellePartie(); if (fenetrePrincipale != null) { fenetrePrincipale.dispose(); } }
950ab7c6-792a-4dc7-8b65-08d255631343
3
private void btnAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAbrirActionPerformed //Se le asigna lo que hay en la caja de texto a nombre String nombre = String.valueOf(txtNombreArchivo.getText()); //Se crea un objeto General g = new General(); String codigo; String nota; //Se revisa que en nombre halla algun valor if( !nombre.equals("") ) { File f = new File(nombre); Scanner informacionArchivo; try { informacionArchivo = new Scanner(f); while( informacionArchivo.hasNext()== true ) { //Se busca lo que hay en el archivo y se trae g.nombre = informacionArchivo.nextLine(); codigo = informacionArchivo.nextLine(); g.materia = informacionArchivo.nextLine(); nota = informacionArchivo.nextLine(); //Muestra lo que hay en el archivo txtMostrarInformacionArchivo.setText(g.nombre + "\n" + codigo +"\n"+ g.materia +"\n"+ nota); } informacionArchivo.close(); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "No se ha encontrado el archivo"); } } }//GEN-LAST:event_btnAbrirActionPerformed
4dccdd43-d38b-417b-a2b1-654db872d277
2
protected void checkCommand(String command) { if (command == null) throw new IllegalArgumentException("ERR00403012b"); if (!drinkPattern.matcher(command).matches()) { Out.infoLn("Processing command: '%1$s' ...", command); Processing.process("Sending mail", 1000); Out.infoLn("Command seems to be invalid, asking the knowledge base for further instruction..."); Processing.process("Sending mail", 2000); Out.infoLn("No alternative found"); throw new IllegalArgumentException("ERR000156987a"); } }
91e1ebf8-e366-4db4-a71e-817e171a7099
7
public void setSpawnEye(World world, Location location){ if (customConfigurationFile == null) { customConfigurationFile = new File(plugin.getDataFolder(), "spawn.yml"); } customConfig = YamlConfiguration.loadConfiguration(customConfigurationFile); String worldName = world.getName(); for (String worldN : plugin.mainWorlds){ if (worldName.startsWith(worldN + "_")){ //World is a copy world worldName = worldN; } } String worldGet = customConfig.getString(worldName); if (worldGet != null){ customConfig.set(worldName + ".yaw", location.getYaw()); customConfig.set(worldName + ".pitch", location.getPitch()); }else{ customConfig.createSection(worldName); customConfig.createSection(worldName + ".yaw"); customConfig.createSection(worldName + ".pitch"); customConfig.set(worldName + ".yaw", location.getYaw()); customConfig.set(worldName + ".pitch", location.getPitch()); } if (customConfig == null || customConfigurationFile == null) { return; } try { customConfig.save(customConfigurationFile); plugin.setSpawnEye.put(worldName, location); Bukkit.getWorld(worldName).setSpawnLocation(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } catch (IOException ex) { plugin.logMessage("Could not save config to " + customConfigurationFile); } }
55d668c6-3228-44eb-b65b-66f501e05667
2
@Override public boolean activate() { return (Players.getLocal().isMoving() && !Constants.BEAR_AREA.contains(Players.getLocal()) && !Constants.ESCAPE_AREA.contains(Players.getLocal())); }
8aa64bd4-9e42-484d-b82e-5ca12b31736f
6
public SetTranslationInfoResult genLoad() { checkPermission(viewerId); HashoutListToJson hashoutListToJson = new HashoutListToJson(); List<EntityJson> jsons = hashoutListToJson.loadEntities(HashoutList.INTL_MESSAGES_CURRENT.getId().getKey()); Map<String, List<EntityJson>> nameToJson = new HashMap<String, List<EntityJson>>(); for (EntityJson json : jsons) { String name = json.getName(); if (!nameToJson.containsKey(name)) { nameToJson.put(name, new ArrayList<EntityJson>()); } nameToJson.get(name).add(json); } if (intlMessagesSource != null) { saveNewJson(hashoutListToJson, IntlMessagesType.INTL_MESSAGES_SOURCE, nameToJson, intlMessagesSource); } if (intlMessagesUk != null) { saveNewJson(hashoutListToJson, IntlMessagesType.INTL_MESSAGES_UK, nameToJson, intlMessagesUk); } if (intlMessagesRu != null) { saveNewJson(hashoutListToJson, IntlMessagesType.INTL_MESSAGES_RU, nameToJson, intlMessagesRu); } if (intlMessagesEn != null) { saveNewJson(hashoutListToJson, IntlMessagesType.INTL_MESSAGES_EN, nameToJson, intlMessagesEn); } return new SetTranslationInfoResult(); }
01311ee8-4379-48e0-a121-7ae8230a1bb9
8
private void loadConfig( String filename ) { try{ File file = new File(filename); BufferedReader br = new BufferedReader(new FileReader(file)); String str; while((str = br.readLine()) != null) { if( str != null ) { String item[] = str.split(":"); if( item[0].equals( "port" ) ) { try { mPortNum = Integer.parseInt(item[1]); } catch( NumberFormatException e ) { mPortNum = -1; } } else if(item[0].equals( "debug" ) ) { if( item[1].equals( "true" ) ) { mIsDebug = true; } } } } br.close(); } catch(FileNotFoundException e) { System.out.println(e); } catch(IOException e) { System.out.println(e); } }
fd65f5d7-f3c0-40c6-a314-704abad37f9a
0
public Vision() { _setDistance(0); }
e3517e28-ce36-4da3-a67b-e1caf11dacbb
0
public DWT() { }
7b8a2475-5625-44dd-ac99-4571176e3667
6
public void executeSequence(MoveSequence sequence) { for (MovementAction action : sequence) { switch (action) { case Forward: forward(); break; case TurnLeft90: turnLeft90(); break; case TurnLeft45: turnLeft45(); break; case TurnRight90: turnRight90(); break; case TurnRight45: turnRight45(); break; } } }
4cd0513c-e062-4cb7-bcfc-96fa05f7c0ad
9
private void sendMsg(TsapiRequest req, CSTAPrivate priv) throws IOException { synchronized (this.out) { IntelByteArrayOutputStream acBlock = new IntelByteArrayOutputStream( 18); IntelByteArrayOutputStream encodeStream = new IntelByteArrayOutputStream(); IntelByteArrayOutputStream privateData = new IntelByteArrayOutputStream( priv != null ? 34 + priv.data.length : 0); try { log.info("Sent InvokeID " + req.getInvokeID() + " for " + this.debugID); if (log.isDebugEnabled()) { Collection<String> lines = req.print(); for (String line : lines) log.debug(line); } try { req.encode(encodeStream); } catch (Exception e) { log.error("encode: " + e); } if (priv != null) { if (log.isDebugEnabled()) { for (String str : priv.print()) { log.debug(str); } } int length = priv.vendor.length(); byte[] vendor = priv.vendor.getBytes(); for (int i = 0; i < 32; i++) { privateData.write(i < length ? vendor[i] : 0); } privateData.writeShort(priv.data.length); privateData.write(priv.data, 0, priv.data.length); } acBlock.writeShort(1); acBlock.writeInt(req.getInvokeID()); acBlock.writeInt(0); acBlock.writeShort(req.getPDUClass()); acBlock.writeShort(req.getPDU()); acBlock.writeShort(encodeStream.size()); acBlock.writeShort(privateData.size()); this.out.writeInt(acBlock.size() + encodeStream.size() + privateData.size()); acBlock.writeTo(this.out); encodeStream.writeTo(this.out); privateData.writeTo(this.out); this.channel.write(this.out); this.out.reset(); } finally { privateData.close(); encodeStream.close(); acBlock.close(); } } }
fdda6963-276f-4c68-8c0d-6ab2d9977b64
9
@Override public void spremi(Resource r) { Evictor e = new Izbaci(); File file = new File(m.getNazivSpremista() + "\\" + r.getNaziv()); try { if (m.isKb()) { trenutnaVelicina = m.izracunajVelicinu(); if ((trenutnaVelicina + r.getSadrzaj().toString().getBytes().length / 1000) > m.getOgranicenje()) { if (m.isStrategija()) { toBig = e.izbaci(lista, m.getNazivSpremista()); } else { toBig = e.izbaciKB(lista, m.getNazivSpremista()); } } } else { if (Ztintor_zadaca_4.postoji) { //Ztintor_zadaca_4.ser=true; m.setOgranicenje(m.getOgranicenje() + 1); Ztintor_zadaca_4.postoji = false; } System.out.println("-----------------------------------------------------"+m.getOgranicenje()); if (new File(m.getNazivSpremista()).listFiles().length == m.getOgranicenje() + 1) { if (m.isStrategija()) { toBig = e.izbaci(lista, m.getNazivSpremista()); } else { toBig = e.izbaciKB(lista, m.getNazivSpremista()); } } } if (toBig) { System.exit(1); } if (!m.provjeriListu(r.getNaziv())) { r.setVrijemeSpremanja(new Date()); r.setId(getLista().size()); r.setSpremljen(true); r.setBrojKoristenja(0); lista.add(r); setLista(lista); m.upisiUDnevnik(r); } file.createNewFile(); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(r.getSadrzaj().toString()); bw.close(); } catch (IOException ex) { Logger.getLogger(CacheImpl.class.getName()).log(Level.SEVERE, null, ex); } }
38d4161b-b100-4dc0-b462-29017889652a
1
public String[] toArray() { return new String [] {String.valueOf(points), endTime==null?" ":endTime.toString()} ; }
fe82b653-50e3-4b0b-8778-9cbe4efb2e44
4
public static void createImages() { String pokemonType; char a; URL url; for (int i = 0; i < pokedexImg.length; i++) { pokemonType = getSpecies(i+1).toString(); if(pokemonType.equalsIgnoreCase("Mr_Mime")) pokemonType="Mr_Mime"; else if(pokemonType.equalsIgnoreCase("Nidoran_M")) pokemonType="Nidoran_M"; else if(pokemonType.equalsIgnoreCase("Nidoran_F")) pokemonType="Nidoran_F"; else { pokemonType = pokemonType.toLowerCase(); pokemonType = pokemonType.replace("_"," "); a = pokemonType.charAt(0); a = Character.toUpperCase(a); pokemonType = a + pokemonType.substring(1,pokemonType.length()); } url = Pokemon.class.getResource("Sprites/pokemon/Right/" + pokemonType + ".png"); pokedexImg[i] = Toolkit.getDefaultToolkit().createImage(url); } }
59f9146a-e185-4c04-81c2-ea4d20daf445
3
public void moveCannonBalls(){ // Move the cannonballs for(int i=0; i<cannons.size(); i++){ CannonBall cannon = cannons.get(i); if(cannon.getDone()){ try { // Makes the "splashed" cannonball appear longer Thread.sleep(10); } catch (InterruptedException ex) { System.out.println(ex); ex.printStackTrace(); } cannons.remove(cannon); } else{ cannon.move(); } }// end for }
d07552ae-8a65-43d5-a737-021ed35eb349
4
@RequestMapping(value = {"search", "s"}) @ResponseBody public Map search( @RequestParam int page, @RequestParam(value = "limit") int pageSize, @RequestParam(required = false, defaultValue = "0") int gradeId, @RequestParam(required = false, defaultValue = "0") int specialtyId, @RequestParam(required = false, defaultValue = "0") int collegeId, @RequestParam(required = false) String clazzName ) { Map<String, Object> map = new HashMap<>(); Map<String, Object> conditions = new HashMap<>(); if (!Strings.isNullOrEmpty(clazzName)) { conditions.put("clazz_name", clazzName); } if (gradeId != 0) { conditions.put("grade_id", gradeId); } if (gradeId != 0) { conditions.put("specialty_id", specialtyId); } if (collegeId != 0) { conditions.put("college_id", collegeId); } List<Class> list = classService.search(page, pageSize, conditions); int total = classService.count(conditions); map.put("success", true); map.put("total", total); map.put("list", list); return map; }
b1831263-6e35-4d90-a016-58c56795c19c
9
protected void evalDefinitions(String[] command) { Matcher matcher; boolean isStatic = false; for (String ci : command) { ci = ci.trim(); if (ci.equals("")) continue; if (ci.toLowerCase().startsWith("static")) { ci = ci.substring(6).trim(); isStatic = true; } else { isStatic = false; } matcher = DEFINE_VAR.matcher(ci); if (matcher.find()) { int end = matcher.end(); String variable = ci.substring(ci.indexOf("%"), end).toLowerCase(); String value = ci.substring(end).trim().toLowerCase(); if (value.startsWith("<t>")) { String s; if (value.endsWith("</t>")) { s = value.substring(3, value.length() - 4); } else { s = value.substring(3); } if (isStatic) { storeSharedDefinition(variable, s); } else { definition.put(variable, s); } } else if (value.startsWith("array")) { String size = value.substring(5).trim(); size = size.substring(1, size.length() - 1); double x = parseMathExpression(size); if (Double.isNaN(x)) return; createArray(variable, (int) Math.round(x)); } else { evaluateDefineMathexClause(isStatic, variable, value); } } } }
3eb22750-8897-42ec-96dd-a3cb791f3d3b
4
@Override public boolean equals(Object o) { if(o == null) { return false; } if(o == this) { return true; } if(!(o instanceof Pixel)) { return false; } Pixel other = (Pixel) o; return (this.x == other.x) && (this.y == other.y); }
772cbad4-7679-4898-ab28-1b6f04f882b3
9
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); InterfaceDepartamento aO = new DepartamentoDAO(); Departamento dep = new Departamento(); HttpSession session = request.getSession(true); RequestDispatcher dispatcher; String pagina; String op = request.getParameter("op"); int id; switch(Integer.parseInt(op)){ case 1: pagina = "/vista/dpto/listardpto.jsp"; session.setAttribute("list1", aO.list()); dispatcher = getServletContext().getRequestDispatcher(pagina); dispatcher.forward(request, response); case 2: pagina = "/vista/dpto/ingresardpto.jsp"; //session.setAttribute("list", aO.list()); dispatcher = getServletContext().getRequestDispatcher(pagina); dispatcher.forward(request, response); case 3: pagina = "/vista/dpto/modificardpto.jsp"; id = Integer.parseInt(request.getParameter("id")); session.setAttribute("list2", aO.list(id)); dispatcher = getServletContext().getRequestDispatcher(pagina); dispatcher.forward(request, response); case 4: pagina = "/dpto?op=1"; dep.setIddpto(Integer.parseInt(request.getParameter("id"))); dep.setDpto(request.getParameter("depar")); dep.setCostos(Integer.parseInt(request.getParameter("costos"))); dep.setStatus(Integer.parseInt(request.getParameter("status"))); if(aO.edit(dep)){ dispatcher = getServletContext().getRequestDispatcher(pagina); dispatcher.forward(request, response); }else{ out.println("<h3>Error al modificar registro..!!</h3>"); } case 5: pagina = "/dpto?op=1"; dep.setDpto(request.getParameter("depar")); dep.setCostos(Integer.parseInt(request.getParameter("costos"))); dep.setStatus(Integer.parseInt(request.getParameter("status"))); if(aO.save(dep)){ dispatcher = getServletContext().getRequestDispatcher(pagina); dispatcher.forward(request, response); }else{ out.println("<h3>Error AL guardar registro..!!</h3>"); } case 6: pagina = "/dpto?op=1"; id = Integer.parseInt(request.getParameter("id")); if(aO.delete(id)){ dispatcher = getServletContext().getRequestDispatcher(pagina); dispatcher.forward(request, response); }else{ out.println("<h3>Error al eliminar registro..!!</h3>"); } } }
82e9cdfb-7088-48c1-b0f0-071a67be1371
1
public TestInstanceInfo getTestInstance(long testInstanceId) throws Exception { TestInstanceInfo testInstance = null; QcRequest qcRequest = new QcRequest(QcConstants.QC_ENDPOINT_URL + "/test-instance/" + testInstanceId); try { XMLConfiguration testInstanceData = restClient.get(qcRequest); testInstance = QcXmlConfigUtil.getTestInstanceInfo(testInstanceData); } catch (NotFound notFound) { throw new TestInstanceNotFound("No test instance is found for Id #" + testInstanceId); } return testInstance; }
496c8872-3962-4d1f-b47c-09b84e6e5795
0
@Override public PermissionType getType() { return PermissionType.RCON; }
ae78365e-2204-4467-b7a5-b858536fc91f
2
public void healPokemonNoPrompt() { for (Pokemon aPartyPokemon : partyPokemon) { if (aPartyPokemon != null) { aPartyPokemon.health = aPartyPokemon.healthMax; aPartyPokemon.status = Pokemon.Status.OK; aPartyPokemon.substatus = Pokemon.Substatus.OK; System.arraycopy(aPartyPokemon.TRUE_PPMAX, 0, aPartyPokemon.TRUE_PP, 0, 4); } } System.out.println("Pokemon Party Healed."); }
538ed9b5-efa7-447e-bbbd-944a268f7dd2
4
public void run() { try { sourceDataLine.open(audioFormat); sourceDataLine.start(); int cnt; // Keep looping until the input read method // returns -1 for empty stream or the // user clicks the Stop button causing // stopPlayback to switch from false to // true. while ((cnt = audioInputStream.read(tempBuffer, 0, tempBuffer.length)) != -1 && stopPlayback == false) { if (cnt > 0) { // Write data to the internal buffer of // the data line where it will be // delivered to the speaker. sourceDataLine.write(tempBuffer, 0, cnt); }// end if }// end while // Block and wait for internal buffer of the // data line to empty. sourceDataLine.drain(); sourceDataLine.close(); // Prepare to playback another file stopBtn.setEnabled(false); playBtn.setEnabled(true); stopPlayback = false; } catch (Exception e) { e.printStackTrace(); System.exit(0); }// end catch }// end run
99a28af6-0ada-4471-a8af-bf024c0007d7
9
private byte[] decrypt(final byte[] encryptedResponse) throws IOException { // if (DISPLAY_APDU) { // System.out.println("CIPHERTEXT RESPONSE APDU:"); // System.out.println("yo: " + Integer.toHexString(encryptedResponse[0] & 0xFF)); // for (int i = 0; i < encryptedResponse.length; i++) // System.out.print(" " + Integer.toHexString // (encryptedResponse[i] & 0xFF)); // System.out.println("length " + encryptedResponse.length); // } // // decrypt the data field in response APDU // // note that JCRMI puts SW1 and SW2 first in the response // // and not as a trailer (unlike a standard response APDU) // if ((encryptedResponse.length - 2) % BLOCK_SIZE != 0) { // throw new IOException("Illegal block size in response"); // } // if (publicKey == null) { // only for symmetric encryption // System.out.println("SYMMETRIC"); // initCipher(Cipher.DECRYPT_MODE); // } // byte[] deciphertext = null; // try { // deciphertext = cipher.doFinal(encryptedResponse, OFFSET_RDATA, encryptedResponse.length - 2); // System.out.println("length is " + deciphertext.length); // for (int i = 0; i < deciphertext.length; i++){ // System.out.print(".. " + Integer.toHexString // (deciphertext[i] & 0xFF)); // } // System.out.println(); // } catch (IllegalBlockSizeException e) { // System.err.println("Illegal padding in decryption: " + e); // } catch (BadPaddingException e) { // System.err.println("Bad padding in decryption: " + e); // } // if (deciphertext.length == 0) // throw new IllegalStateException("deciphertext length is 0"); // byte numPadding = deciphertext[deciphertext.length - 1]; // int unpaddedLength = deciphertext.length - numPadding; // int onelessunpaddedLength = unpaddedLength-1; // byte[] decryptedResponse // = new byte[OFFSET_RDATA + onelessunpaddedLength]; // decryptedResponse[OFFSET_SW1] = encryptedResponse[OFFSET_SW1]; // decryptedResponse[OFFSET_SW2] = encryptedResponse[OFFSET_SW2]; // System.arraycopy(deciphertext, 0, decryptedResponse, // OFFSET_RDATA, onelessunpaddedLength); // for (int i = 0; i < unpaddedLength; i++){ // System.out.print(":) " + Integer.toHexString // (deciphertext[i] & 0xFF)); // } // System.out.println(); // if (DISPLAY_APDU) { // System.out.println("DECIPHERTEXT RESPONSE APDU:"); // for (int i = 0; i < decryptedResponse.length; i++) // System.out.print(" " + Integer.toHexString // (decryptedResponse[i] & 0xFF)); // System.out.println(); // } // byte le = decryptedResponse[3]; // byte onelessle = (byte)((short)(le-1)); // decryptedResponse[3] = onelessle; // return decryptedResponse; if (DISPLAY_APDU) { System.out.println("CIPHERTEXT RESPONSE APDU:"); for (int i = 0; i < encryptedResponse.length; i++) System.out.print(" " + Integer.toHexString (encryptedResponse[i] & 0xFF)); System.out.println(); } // decrypt the data field in response APDU // note that JCRMI puts SW1 and SW2 first in the response // and not as a trailer (unlike a standard response APDU) if ((encryptedResponse.length - 2) % BLOCK_SIZE != 0) { throw new IOException("Illegal block size in response"); } if (publicKey == null) { // only for symmetric encryption initCipher(Cipher.DECRYPT_MODE); } byte[] deciphertext = null; try { deciphertext = cipher.doFinal(encryptedResponse, OFFSET_RDATA, encryptedResponse.length - 2); } catch (IllegalBlockSizeException e) { System.err.println("Illegal padding in decryption: " + e); } catch (BadPaddingException e) { System.err.println("Bad padding in decryption: " + e); } if (deciphertext.length == 0) throw new IllegalStateException("deciphertext length is 0"); byte numPadding = deciphertext[deciphertext.length - 1]; int unpaddedLength = deciphertext.length - numPadding; byte[] decryptedResponse = new byte[OFFSET_RDATA + unpaddedLength]; decryptedResponse[OFFSET_SW1] = encryptedResponse[OFFSET_SW1]; decryptedResponse[OFFSET_SW2] = encryptedResponse[OFFSET_SW2]; System.arraycopy(deciphertext, 0, decryptedResponse, OFFSET_RDATA, unpaddedLength); if (DISPLAY_APDU) { System.out.println("DECIPHERTEXT RESPONSE APDU:"); for (int i = 0; i < decryptedResponse.length; i++) System.out.print(" " + Integer.toHexString (decryptedResponse[i] & 0xFF)); System.out.println(); } return decryptedResponse; }
2c1a2ca3-0ed3-44e3-96f7-be46866ee894
6
public Position getNodeAhead(Position position, int angle){ Position _pos = null; if(angle >= 360){ angle -= 360; } if(angle < 0){ angle += 360; } switch(angle){ case 0: _pos = new Position(position.getX(), position.getY() - 1); break; case 90: _pos = new Position(position.getX() + 1, position.getY()); break; case 180: _pos = new Position(position.getX(), position.getY() + 1); break; case 270: _pos = new Position(position.getX() - 1, position.getY()); break; } return _pos; }
570abd9d-2678-452b-971c-a107a911b296
3
private void createControlPanel(){ controlPanel = new JPanel(); final JButton startButton = new JButton("start"); final JButton stopButton = new JButton("stop"); stopButton.setEnabled(false); final JButton pauseButton = new JButton("pause"); pauseButton.setEnabled(false); final JButton settingsButton = new JButton("settings"); startButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(config.getMainTag().equals("")){ showError("Main tag not defined"); return; } if(config.getAccessToken().equals("")){ showError("Access token ton defined"); return; } File f = new File(config.getIrfanViewPath()); if(!f.exists()){ showError("IrfanView not found"); return; } startButton.setEnabled(false); settingsButton.setEnabled(false); //Config config = new Config(); long time = (new Date().getTime())/ 1000 - 20*60; System.out.println("start time:" + time); controller = new Controller(config, new IrfanViewPrinter(config.getIrfanViewPath()), TIMEOUT, time, ic); controller.start(); stopButton.setEnabled(true); } }); stopButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopButton.setEnabled(false); controller.stop(); controller = null; startButton.setEnabled(true); settingsButton.setEnabled(true); } }); settingsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ConfigDialog dialog = new ConfigDialog(frame, config); dialog.create(); } }); controlPanel.add(settingsButton); controlPanel.add(startButton); controlPanel.add(pauseButton); controlPanel.add(stopButton); }
74b3f71a-91d4-418a-bd4b-6328f543b212
3
public String getParsedFormat() { String formatted = ""; for(String str : format.split(" ")) if(!str.isEmpty() && !str.equalsIgnoreCase("...")) formatted = formatted + " " + str.substring(1, str.length()); else formatted = formatted + " " + str; return formatted; }
dc4f849a-c5b9-4532-9671-22e5f2a27b91
8
public static void main(String[] args) { Scanner scan = new Scanner(System.in); Integer rowNumber = Integer.parseInt(scan.nextLine()); Integer startNumber = scan.nextInt(); scan.nextLine(); boolean hasElement = false; ArrayList<Integer> outputs = new ArrayList<Integer>(); outputs.add(startNumber); for (Integer i = 1; i < rowNumber; i++) { String[] elements = scan.nextLine().split("\\s+"); Integer[] numbers = new Integer[elements.length]; // parse array for (Integer p = 0; p < elements.length; p++) { if (!elements[p].equals("")) { numbers[p] = Integer.parseInt(elements[p]); } else { numbers[p] = Integer.MIN_VALUE; } } //sort array Arrays.sort(numbers); for (Integer number : numbers) { if (number > startNumber) { startNumber = number; outputs.add(startNumber); hasElement = true; break; } } if (!hasElement) { startNumber++; } hasElement = false; } for (Integer i = 0; i < outputs.size(); i++) { if (i < outputs.size() - 1) { System.out.printf("%s, ", outputs.get(i)); } else { System.out.printf("%s", outputs.get(i)); } } }
30fcb8b7-b18c-44b2-bbb5-c5d9f633df6e
2
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.WHITE); for (MoveableObject asteroid : field.getAsteroids()) { asteroid.draw(g); } g.setColor(Color.RED); for (MoveableObject bullet : field.getBullets()) { bullet.draw(g); } g.setColor(Color.GREEN); field.getShip().draw(g); }
31b87571-4d4a-461f-9404-eda613bb7f0f
7
@Override public String healthText(MOB viewer, MOB mob) { final double pct=(CMath.div(mob.curState().getHitPoints(),mob.maxState().getHitPoints())); if(pct<.10) return L("^r@x1^r is almost squashed!^N",mob.name(viewer)); else if(pct<.25) return L("^y@x1^y is severely gashed and bruised.^N",mob.name(viewer)); else if(pct<.40) return L("^p@x1^p has lots of gashes and bruises.^N",mob.name(viewer)); else if(pct<.55) return L("^p@x1^p has some serious bruises.^N",mob.name(viewer)); else if(pct<.70) return L("^g@x1^g has some bruises.^N",mob.name(viewer)); else if(pct<.85) return L("^g@x1^g has a few small bruises.^N",mob.name(viewer)); else if(pct<.95) return L("^g@x1^g is barely bruised.^N",mob.name(viewer)); else return L("^c@x1^c is in perfect condition^N",mob.name(viewer)); }
2be810b6-7ae1-4010-ad30-cb5fbe17ee54
2
public static AccessibilityFeatureEnumeration fromValue(String v) { for (AccessibilityFeatureEnumeration c: AccessibilityFeatureEnumeration.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); }
99792c6b-ba63-4ee1-9279-932ccdf7dcaf
2
@Override public void execute() { System.out.println("Production Dialog is off..... Turning on"); Constants.PRODUCTION_WIDGET.interact("Toggle Production Dialog"); final Timer timeout = new Timer(2000); while(timeout.isRunning() && Settings.get(1173)==1879048192) { Task.sleep(50); } }
3de736eb-6776-44b0-8c54-3195f2e4c558
0
public static void main(String[] args) { Flyweight flyweight1, flyweight2, flyweight3; FlyweightFactory ff = new FlyweightFactory(); flyweight1 = ff.factory("aaa"); flyweight2 = ff.factory("bbb"); // 如果存在,则不创建新的对象 flyweight3 = ff.factory("aaa"); flyweight1.func(); flyweight2.func(); flyweight3.func(); ff.checkFlyweight(); }
1b901f80-cfc8-40fb-8ab3-77faa50f0cc5
7
public static PlayerConfig getPlayerConfig(String name) throws Exception { PlayerConfig config = new PlayerConfig(name); HashMap<String, String> classifiers = new HashMap<String, String>(); HashMap<String, HashMap<String, Boolean>> attributes = new HashMap<String, HashMap<String, Boolean>>(); SAXBuilder builder = new SAXBuilder(); File file = new File(FILE_PATH, FILE_NAME); Document doc = null; if (!file.exists()) { doc = new Document(); Element root = new Element("AgentConfigs"); doc.setRootElement(root); String xmlFileData = new XMLOutputter().outputString(doc); write2File(xmlFileData); } try { doc = builder.build(file); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Element root = doc.getRootElement(); @SuppressWarnings("unchecked") List<Element> eleList = root.getChildren("Config"); for (Iterator<Element> iter = eleList.iterator(); iter.hasNext();) { Element configEle = iter.next(); String configName = configEle.getChildText("Name"); if (configName.equals(name)) { // Set classifiers Element clsEle = configEle.getChild("Classifiers"); classifiers.put("ActionTypeClassifier", clsEle.getChildText("ActionTypeClassifier")); classifiers.put("ActionPowerClassifier", clsEle.getChildText("ActionPowerClassifier")); classifiers.put("ActionAngleClassifier", clsEle.getChildText("ActionAngleClassifier")); // Set dataset attributes Element attEle = configEle.getChild("DatasetAttributes"); attributes.put("ActionType", getAttributeSetting(attEle, "ActionType")); attributes.put("KickPower", getAttributeSetting(attEle, "KickPower")); attributes.put("KickAngle", getAttributeSetting(attEle, "KickAngle")); attributes.put("DashPower", getAttributeSetting(attEle, "DashPower")); attributes.put("TurnAngle", getAttributeSetting(attEle, "TurnAngle")); attributes.put("CatchAngle", getAttributeSetting(attEle, "CatchAngle")); } } if (classifiers.isEmpty() || attributes.isEmpty()) { return null; } config.setClassifiers(classifiers); config.setAttSetting(attributes); return config; }
c3bb81c8-ef4f-4119-a707-a5d44c978162
2
private void isLessThanEqualsToInteger(Integer param, Object value) { if (value instanceof Integer) { if (!(param <= (Integer) value)) { throw new IllegalStateException("Integer is not greater than supplied value."); } } else { throw new IllegalArgumentException(); } }
447e5eb6-60c7-404a-a6d6-e4284f589bb0
3
private void createItems() { ih = new ItemHandler(); MenuItem info = new MenuItem("(c) UploadR v"+Constants.VERSION +" | shortcuts "+(Constants.KEYS_ENABLED ? "enabled" : "disabled")); info.setEnabled(false); this.add(info); for(byte i=0;i<ItemHandler.items.length;++i) { if(ItemHandler.items[i][0].equals("s")) { this.addSeparator(); continue; } MenuItem item = new MenuItem(ItemHandler.items[i][0]); item.setActionCommand(ItemHandler.items[i][1]); item.addActionListener(ih); this.add(item); } }
3e3475c1-77a3-47df-96fd-bc441b67dda7
7
public static void generateCsvFromList(String fileName, List<Object> elems, Integer rowElems) throws IOException { StringBuffer buffer = new StringBuffer(); if (elems.isEmpty()) { createCsvFile(fileName, buffer.toString()); } else { rowElems = rowElems == null ? 1 : rowElems < 1 ? 1 : rowElems; int elemIndex = 1; ListIterator<Object> it = elems.listIterator(); while (it.hasNext()) { buffer.append(generateSingleElement(it.next())); if (elemIndex < rowElems && it.hasNext()) { buffer.append(singleElementSeparator); elemIndex++; } else if(it.hasNext()){ buffer.append(newLineSeparator); elemIndex = 1; } } } createCsvFile(fileName, buffer.toString()); }
35235fa1-7da6-4003-86f5-d309f03c680e
7
public static void experimentEcoli3(String[] args) { // insertion of sequence with partly similarity final String ID = args[0]; ExecutorService exec = Executors.newFixedThreadPool(Runtime .getRuntime().availableProcessors()); System.out.println("Start with " + Runtime.getRuntime().availableProcessors() + " threads"); try { // test with following mutation frequencies: double[] mutationFrequencies = { 0 }; int[] fragmentLengths = { 1000 }; double[] percentageReadLengths = { 0.05 }; int[] readLengths = { 50 }; for (final double mutFreq : mutationFrequencies) { for (final double p : percentageReadLengths) { for (final int readLength : readLengths) { for (final int i : fragmentLengths) { exec.submit(new Runnable() { @Override public void run() { try { testDetectabilityEcoli3(readLength, (int) (readLength * p), i, mutFreq, ID + "_" + i + "_" + p + "_" + readLength + "_" + mutFreq); } catch (Exception e1) { e1.printStackTrace(); } try { PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter( "output/" + ID + "_" + i + "_" + p + "_" + readLength + "_" + mutFreq + "/log.txt", true))); out.println("Ran argos with:\tREAD_LENGTH\t" + readLength + "\tSTEP_SIZE\t" + (int) (readLength * p) + "\tFRAGMENT_SIZE\t" + i + "\tPercReadLen\t" + p + "\n"); out.close(); } catch (IOException e) { e.printStackTrace(); } } }); } } } } } catch (Exception e) { e.printStackTrace(); } finally { exec.shutdown(); } }
9a2a25f5-7f1a-4da3-81bc-de393c6c7a8d
2
private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) { //Set options of all panels for (Component p : getParent().getComponents()) { if(p instanceof AbleToGetOptions) { ((AbleToGetOptions) p).getOptions(); } } CardLayout cl = (CardLayout) (getParent().getLayout()); cl.show(getParent(), MENU_PANEL); }
4ef96d7b-f91e-4531-9b3a-a5b5518d8d79
2
public static void checkGlobalConfigYAML() { File config = new File(path + "config.yml"); if(!config.exists()) { try { config.createNewFile(); FileConfiguration c = YamlConfiguration.loadConfiguration(config); c.set("Features.AutoBroadcast.Enabled", false); c.set("Features.AutoSave.Enabled", true); c.set("Features.JumpPads.Enabled", true); c.save(config); } catch (IOException e) { e.printStackTrace(); } } }
b78b6f6a-3b63-4c00-9cb3-100aaeac2440
5
private static double[] getResistPoints(int curvePoints,int lineNumber, double[] highPrices) { double[] rPoints = new double[lineNumber]; for(int i =0;i<lineNumber-1;i++){ double price = 0; for(int j=-curvePoints;j<=0;j++){ if((i+j>=0) && (i+j<lineNumber-1) && highPrices[i+j]>price){ price =highPrices[i+j]; rPoints[i]=price; } } } return rPoints; }
13231c70-ff0a-43c1-ac4b-2d66c04c1afa
2
private void drawVillagers(int screenX0, int screenY0, Graphics2D gI) { ArrayList<Village> villages = getVillages(); for (Village v : villages) { for (Villager villager : v.getPopulation()) { double vAbsX = villager.getRelativeX()+(v.getX()-screenX0+0.5)*Chunk.lengthOfChunk-0.5, vAbsY = villager.getRelativeY()+(v.getY()-screenY0+0.5)*Chunk.lengthOfChunk-0.5; //gI.drawImage(villager.draw(), (int)(vAbsX*Building.lengthOfBuilding), (int)(vAbsY*Building.lengthOfBuilding), null); } } }
a5127ea0-86fb-4381-8d47-44e2f96e4d82
7
private void checkStatus(boolean force) { if (isMuted()) { if (status != MicStatus.MUTED || force) { status = MicStatus.MUTED; trayIcon.setImage(mutedIcon); if (guiDisplay) { guiPanel.setBackground(mutedColour); } } } else { if (status != MicStatus.UNMUTED || force) { status = MicStatus.UNMUTED; trayIcon.setImage(normalIcon); if (guiDisplay) { guiPanel.setBackground(normalColour); } } } }
962b40af-b0c8-4aa3-ab06-db34fd6a98df
0
@Override public Iterator<TElement> iterator() { return this._source.iterator(); }
8a12cb3b-5159-40ac-90ea-a145ded32dfc
2
@Override public void onEnable() { this.log = getLogger(); saveConfig(); this.world = getConfig().getString("world", "world"); this.ccost = getConfig().getInt("chunk-cost", 0); int id = getConfig().getInt("tool.id", 280); String name = getConfig().getString("tool.name", "Chunk Selector"); List<String> lore = getConfig().getStringList("tool.lore"); this.tool = new ItemStack(id); { ItemMeta meta = this.tool.getItemMeta(); meta.setDisplayName(name); meta.setLore(lore); this.tool.setItemMeta(meta); } this.cmanager = new ChunkManager(this); this.cmanager.load(); PluginManager pm = Bukkit.getPluginManager(); if(Bukkit.getWorld(this.world) == null) { log.log(Level.SEVERE, "World {0} not found. Disabling plugin", this.world); pm.disablePlugin(this); return; } Plugin p = pm.getPlugin("Essentials"); if(p == null) { log.log(Level.SEVERE, "Failed to hook into Essentials Eco. Disabling plugin"); pm.disablePlugin(this); return; } // Initializing commands this.cmdTool = new CommandTool(this); this.cmdList = new CommandList(this); this.cmdSell = new CommandSell(this); this.cmdNoClaim = new CommandNoClaim(this); this.cmdAddMember = new CommandAddMember(this); this.cmdRemoveMember = new CommandRemoveMember(this); // Register pm.registerEvents(new PlayerListener(this, this.cmdTool), this); pm.registerEvents(new BlockListener(this), this); pm.registerEvents(new InventoryListener(this), this); new BukkitRunnable() { @Override public void run() { cmanager.save(); } }.runTaskTimer(this, 300L, getConfig().getLong("save-interval", 300L)*20L); }
c3740bd0-108c-49e9-b313-27a1c1b386c7
4
@Override public void addComponent(Component component, LayoutParameter... layoutParameters) { Set<LayoutParameter> asSet = new HashSet<LayoutParameter>(Arrays.asList(layoutParameters)); if(asSet.contains(MAXIMIZES_HORIZONTALLY) && asSet.contains(GROWS_HORIZONTALLY)) throw new IllegalArgumentException("Component " + component + " cannot be both maximizing and growing horizontally at the same time"); if(asSet.contains(MAXIMIZES_VERTICALLY) && asSet.contains(GROWS_VERTICALLY)) throw new IllegalArgumentException("Component " + component + " cannot be both maximizing and growing vertically at the same time"); componentList.add(new LinearLayoutComponent(component, asSet)); }
ccab1ffb-b49a-4d67-885f-10103ddbda40
4
public Pair<Pair<Livraison, PlageHoraire>, NoeudItineraire> supprimerLivraison(Noeud noeudSel) { if(this.testItineraireCharger()){ //Suppression autoris�e Livraison liv = null; for(PlageHoraire ph : this.plagesHoraire){ liv = ph.rechercheLivraison(noeudSel); if(liv != null){ //Livraison supprimer Pair<Livraison, PlageHoraire> pairLiv = new Pair<Livraison, PlageHoraire>(liv, ph); if(this.testTourneeCalculee()){ //La tourn�e est d�j�� calcul�e NoeudItineraire noeudPrecedent = this.rechercheNoeudLivraisonPrecedent(liv); Trajet nouvTrajet = new Trajet(this.plan.getCheminlePlusCourt(noeudPrecedent.getAdresse(), liv.getTrajet().getDestination())); noeudPrecedent.setTrajet(nouvTrajet); ph.supprimerLivraison(liv); calculerHoraires(); return new Pair<Pair<Livraison, PlageHoraire>, NoeudItineraire>(pairLiv, noeudPrecedent); } else{ //La tourn�e n'est pas encore calcul�e ph.supprimerLivraison(liv); return new Pair<Pair<Livraison, PlageHoraire>, NoeudItineraire>(pairLiv, null); } } } } return null; }
bd5091e1-74b9-4e45-a4f2-f7eb23531fa0
6
public static boolean isGamemode(String gamemode) { if (gamemode.equalsIgnoreCase("survival") || gamemode.equalsIgnoreCase("0") || gamemode.equalsIgnoreCase("creative") || gamemode.equalsIgnoreCase("1") || gamemode.equalsIgnoreCase("adventure") || gamemode.equalsIgnoreCase("2")) { return true; } else { return false; } }
d550e63f-8ffc-4c17-843a-dccf722b51bd
0
public Piste getPelaajanAlkusijainti() { return pelaajanAlkusijainti; }
3f047330-f10f-4372-ae32-73bc0a815e79
3
public void testPlus() { Period base = new Period(1, 2, 3, 4, 5, 6, 7, 8); Period baseDaysOnly = new Period(0, 0, 0, 10, 0, 0, 0, 0, PeriodType.days()); Period test = base.plus((ReadablePeriod) null); assertSame(base, test); test = base.plus(Period.years(10)); assertEquals(11, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); test = base.plus(Years.years(10)); assertEquals(11, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); test = base.plus(Period.days(10)); assertEquals(1, test.getYears()); assertEquals(2, test.getMonths()); assertEquals(3, test.getWeeks()); assertEquals(14, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); test = baseDaysOnly.plus(Period.years(0)); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(10, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); test = baseDaysOnly.plus(baseDaysOnly); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(20, test.getDays()); assertEquals(0, test.getHours()); assertEquals(0, test.getMinutes()); assertEquals(0, test.getSeconds()); assertEquals(0, test.getMillis()); try { baseDaysOnly.plus(Period.years(1)); fail(); } catch (UnsupportedOperationException ex) {} try { Period.days(Integer.MAX_VALUE).plus(Period.days(1)); fail(); } catch (ArithmeticException ex) {} try { Period.days(Integer.MIN_VALUE).plus(Period.days(-1)); fail(); } catch (ArithmeticException ex) {} }
341a8289-7394-4bf0-85f2-a9b73ecd042e
4
private Object parseString() throws StreamCorruptedException { int strLen = readLength(); indexPlus(1); // get rid of " Object output; CharBuffer cb = CharBuffer.allocate(strLen); boolean containsZeroChar = false; for (int r = 0; r < strLen; r++) { char ch; try { ch = input.get(); if (ch == '\u0000') { containsZeroChar = true; } } catch (Throwable e) { throw new StreamCorruptedException("Char failed to parse, got " + cb.toString() + " so far"); } cb.put(ch); } indexPlus(2); cb.rewind(); String test = cb.toString(); if (!containsZeroChar) { // no stringy loss output = test; } else { output = cb; } objHistory.add(output); return output; }
05209008-3a11-4788-9e1e-44a1df640db3
0
private void menuOpenMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuOpenMouseClicked // TODO add your handling code here: }//GEN-LAST:event_menuOpenMouseClicked