method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
ee4d1a49-eb7c-42a2-a590-f1f7ed95e9d1
4
public static void renew(final LogGildedAltar script) { script.options.status = "Renewing familiar"; if (script.ctx.summoning.summoned()) { script.ctx.summoning.renew(); } else { script.ctx.summoning.summon(script.options.beastOfBurden); Condition.wait(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return script.familiarFailed.get() || !(script.ctx.summoning.canSummon(script.options.beastOfBurden) && (script.ctx.summoning.timeLeft() <= 150 || !script.ctx.summoning.summoned())); } }); } }
cbb36cca-9ee1-41b0-a9d8-ec597aa8e9ad
6
@EventHandler public void MagmaCubeNightVision(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getMagmaCubeConfig().getDouble("MagmaCube.NightVision.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if ( plugin.getMagmaCubeConfig().getBoolean("MagmaCube.NightVision.Enabled", true) && damager instanceof MagmaCube && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, plugin.getMagmaCubeConfig().getInt("MagmaCube.NightVision.Time"), plugin.getMagmaCubeConfig().getInt("MagmaCube.NightVision.Power"))); } }
6b004765-ea45-4925-bbc1-bf960fcefcff
0
@Override public Set<String> getUsers() throws DataLoadFailedException { return getList("users", "name"); }
b19d783b-f50e-4913-ba39-f6c3eeb0c273
3
public void play() { stop(); try { bitStream.reset(); } catch (IOException e) { // ignore if no mark } player = new Thread() { public void run() { try { playStream(Thread.currentThread()); } catch (InternalException e) { e.printStackTrace(); } try { bitStream.reset(); } catch (IOException e) { e.printStackTrace(); } }; }; player.setDaemon(true); player.start(); }
615056a4-e3e6-4b07-b9d8-ecad2774694c
5
public void convertGedcom(File file) { try { Gedcom gedcom = parser.parseGedcom(file); OutputStream out = (gedcomOut != null ? new FileOutputStream(new File(gedcomOut, file.getName())) : new ByteArrayOutputStream()); writer.write(gedcom, out); if (gedcomOut != null) { out.close(); } else { System.out.println(out.toString()); } } catch (SAXParseException e) { logger.error("SaxParseException for file: "+file.getName()+" "+e.getMessage()+" @ "+e.getLineNumber()); } catch (IOException e) { logger.error("IOException for file: " + file.getName() + " " + e.getMessage()); } catch (RuntimeException e) { e.printStackTrace(); logger.error("Exception for file: "+file.getName()+" "+e.getMessage()); } }
1e906931-7490-4980-a1dc-e8785b720852
4
public boolean generate(World var1, Random var2, int var3, int var4, int var5) { for(int var6 = 0; var6 < 10; ++var6) { int var7 = var3 + var2.nextInt(8) - var2.nextInt(8); int var8 = var4 + var2.nextInt(4) - var2.nextInt(4); int var9 = var5 + var2.nextInt(8) - var2.nextInt(8); if(var1.isAirBlock(var7, var8, var9)) { int var10 = 1 + var2.nextInt(var2.nextInt(3) + 1); for(int var11 = 0; var11 < var10; ++var11) { if(Block.cactus.canBlockStay(var1, var7, var8 + var11, var9)) { var1.setBlock(var7, var8 + var11, var9, Block.cactus.blockID); } } } } return true; }
d1b1882b-66a3-4d55-a403-fedc10248428
8
public void paintComponent(Graphics g){ if(histData == null || histData.length == 0) { return; } Graphics2D g2 = (Graphics2D)g; RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHints(rh); g2.setFont(textFont); int h = this.getHeight(); int w = this.getWidth(); g2.clearRect(0, 0, w, h); int b = 4; int yoff = 10; int bottomLine = h - b - g2.getFontMetrics().getHeight(); int tackHeight = 5; int ib = 1; int binWidth = (w - (2*b) - ((histData.length-1)*ib)) / histData.length; int binHeight = bottomLine - yoff; double pixPerUnit = (double)(binHeight)/(double)maxScore; int x = b; g2.setColor(barColour); barBacks = new Rectangle2D[histData.length]; x = b; for(int i=0;i<histData.length;i++) { barBacks[i] = new Rectangle2D.Double(x,yoff,binWidth,binHeight); x += binWidth + ib; } g2.setColor(barBackColour); for(Rectangle2D r : barBacks) { g2.fill(r); } x = b+ib; int bh =0; for(int[] i : histData) { bh = (int)(i[1] * pixPerUnit); g2.setColor(barColour); g2.fillRect(x, yoff + (binHeight - bh), binWidth, bh); g2.setColor(Color.black); g2.drawLine(x-ib, bottomLine-tackHeight, x-ib, bottomLine); x += binWidth + ib; } g2.drawLine(x-ib, bottomLine-tackHeight, x-ib, bottomLine); g2.setColor(Color.BLACK); { g2.drawLine(b, bottomLine, x-ib, bottomLine); } if(barInfo != -1 && barBacks != null && barInfo < barBacks.length) { Rectangle2D bar = barBacks[barInfo]; int xt = (int)bar.getCenterX(); int yt = (int)bar.getCenterY(); String text = "bin: " + histData[barInfo][0] + "\ncount: " + histData[barInfo][1]; CTB.draw(g2, xt, yt, this.getWidth(), this.getHeight(), text); } }
d985cad6-d6c1-438c-bced-92050df22ebe
9
static final void method3309(Animable animable, Node_Sub29[] node_sub29s) { if (Class239.aBoolean2932) { int i = animable.method819(node_sub29s, 1); CacheNode_Sub18.aGraphicsToolkit9607.a(i, node_sub29s); } if (Class368.aPlaneArray4548 == Class320_Sub10.aPlaneArray8300) { int i; int i_1_; if (animable instanceof Mobile) { i = ((Mobile) animable).aShort9119; i_1_ = ((Mobile) animable).aShort9120; } else { i = animable.anInt5934 >> Class36.anInt549; i_1_ = animable.anInt5940 >> Class36.anInt549; } CacheNode_Sub18.aGraphicsToolkit9607.EA(Node_Sub38_Sub37.aPlaneArray10466[0].method3260(animable.anInt5940, -123, animable.anInt5934), Class320_Sub2.method3684(i, i_1_), Class184.method1844(i, i_1_), Class117_Sub2.method1172(i, i_1_)); } EntityNode_Sub6 entitynode_sub6 = animable.method807(-99, CacheNode_Sub18.aGraphicsToolkit9607); if (entitynode_sub6 != null) { if (animable.aBoolean5945) { EntityNode_Sub5[] entitynode_sub5s = entitynode_sub6.anEntityNode_Sub5Array5995; for (int i = 0; i < entitynode_sub5s.length; i++) { EntityNode_Sub5 entitynode_sub5 = entitynode_sub5s[i]; if (entitynode_sub5.aBoolean5987) { Class362.method4053(entitynode_sub5.anInt5986 - entitynode_sub5.anInt5983, entitynode_sub5.anInt5984 + entitynode_sub5.anInt5983, entitynode_sub5.anInt5985 - entitynode_sub5.anInt5983, (byte) -54, entitynode_sub5.anInt5982 + entitynode_sub5.anInt5983); } } } if (entitynode_sub6.aBoolean5994) { entitynode_sub6.anAnimable5990 = animable; if (Class188_Sub2.aBoolean6868) { synchronized (Node_Sub36_Sub3.aClass179_10058) { Node_Sub36_Sub3.aClass179_10058.method1813(0, entitynode_sub6); } } else { Node_Sub36_Sub3.aClass179_10058.method1813(0, entitynode_sub6); } } else { Class148.method1650(0, entitynode_sub6); } } }
bcc321de-4ff1-4398-a3cb-a013faa6e8ac
5
public void load() throws TemplateException { // set label try { label = "t" + Integer.toString(Integer.valueOf(id)); } catch (Exception e) { label = "t" + id; } String baseURL = "http://www.radreport.org/xml/xml.php?id=" + id; URL url; try { // download template url = new URL(baseURL); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); xml = db.parse(url.openStream()); // parse template TemplateParser.parse(this); // convert template TemplateBuilder.build(this); } catch (MalformedURLException e) { throw new TemplateException("MalformedURLException", e); } catch (ParserConfigurationException e) { throw new TemplateException("ParserConfigurationException", e); } catch (SAXException e) { throw new TemplateException("SAXException", e); } catch (IOException e) { throw new TemplateException("IOException", e); } }
06b9badf-d5ee-4962-b3c1-82f649c75ada
9
public static void writeXmlBean(XMLBean xmlBean) throws IOException { if (null != xmlBean) { File file = new File(xmlBean.getPath()); if (!file.exists()) { // file.mkdirs(); file.getParentFile().mkdirs(); file.createNewFile(); } if (file.canWrite()) { StringBuilder sbd = new StringBuilder(); // final String END_LINE = "\r\n"; sbd.append("<?xml version=\"1.0\" encoding=\""); sbd.append(xmlBean.getCharset()); sbd.append("\"?>").append(END_LINE); sbd.append("<?xml-stylesheet type=\"text/xsl\" href=\"style.xsl\"?>"); sbd.append(END_LINE); sbd.append("<"); sbd.append(xmlBean.getRootName()); Class<?> beanClass = xmlBean.getBeanClass(); String bcs = null == beanClass ? "" : beanClass.getName(); sbd.append(" class=\"").append(bcs); sbd.append("\" >").append(END_LINE); // TODO classforname // iXmlProcess = XMLProcessFactory.getXmlProcess(xmlBean.getRootName()); List<?> itemList = xmlBean.getItemList(); Set<Object> objSet = new HashSet<Object>(); if (null != itemList && !itemList.isEmpty()) { objectToXmlString(itemList, sbd, objSet, null); } else { objectToXmlString(xmlBean.getBean(), sbd, objSet, null); } sbd.append("</").append(xmlBean.getRootName()).append(">"); OutputStreamWriter fw = null; try { fw = new OutputStreamWriter(new FileOutputStream(file), Charset.forName(xmlBean.getCharset())); fw.write(sbd.toString()); // fw.append(new // String(sbd.toString().getBytes("ISO-8859-1"),"GBK")); fw.flush(); } finally { if (null != fw) fw.close(); } } } }
68295e93-0abd-47d8-a44e-57262dcd309b
0
public int getProcessMode() {return processMode;}
494b9d59-1917-4cb2-961f-c37145ef2656
2
private void insertServers() throws SQLException { for (String data : proxy.getServers().keySet()) { if (!utils.serverExists(data)) { utils.createServer(data); cl.cLog("&2 Server " + data + " added to database!"); } } cl.cLog("&6 -" + proxy.getServers().values().size() + " Servers loaded"); }
9dcc0c76-ab71-4c44-9cad-c057996e8062
1
public String getMainClassName() throws IOException { URL u = new URL("jar", "", url + "!/"); JarURLConnection uc = (JarURLConnection)u.openConnection(); Attributes attr = uc.getMainAttributes(); return attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null; }
1e337e44-e0a3-4d52-ac8d-acb985cc79e6
8
public static JulianDate jauUt1utc(double ut11, double ut12, double dut1) throws JSOFAIllegalParameter, JSOFAInternalError { double utc1, utc2; boolean big1; int i; double duts, u1, u2, d1, dats1, d2, fd, dats2, ddats, us1, us2, du; /* UT1-UTC in seconds. */ duts = dut1; /* Put the two parts of the UT1 into big-first order. */ big1 = ( ut11 >= ut12 ); if ( big1 ) { u1 = ut11; u2 = ut12; } else { u1 = ut12; u2 = ut11; } /* See if the UT1 can possibly be in a leap-second day. */ d1 = u1; dats1 = 0; for ( i = -1; i <= 3; i++ ) { d2 = u2 + (double) i; Calendar dt = jauJd2cal(d1, d2 ); dats2 = jauDat(dt.iy, dt.im, dt.id, 0.0); if ( i == - 1 ) dats1 = dats2; ddats = dats2 - dats1; if ( abs(ddats) >= 0.5 ) { /* Yes, leap second nearby: ensure UT1-UTC is "before" value. */ if ( ddats * duts >= 0 ) duts -= ddats; /* UT1 for the start of the UTC day that ends in a leap. */ JulianDate jd = jauCal2jd(dt.iy, dt.im, dt.id ); d1 = jd.djm0; d2 = jd.djm1; us1 = d1; us2 = d2 - 1.0 + duts/DAYSEC; /* Is the UT1 after this point? */ du = u1 - us1; du += u2 - us2; if ( du > 0 ) { /* Yes: fraction of the current UTC day that has elapsed. */ fd = du * DAYSEC / ( DAYSEC + ddats ); /* Ramp UT1-UTC to bring about SOFA's JD(UTC) convention. */ duts += ddats * ( fd <= 1.0 ? fd : 1.0 ); } /* Done. */ break; } dats1 = dats2; } /* Subtract the (possibly adjusted) UT1-UTC from UT1 to give UTC. */ u2 -= duts / DAYSEC; /* Result, safeguarding precision. */ if ( big1 ) { utc1 = u1; utc2 = u2; } else { utc1 = u2; utc2 = u1; } /* FIXME Status. */ return new JulianDate(utc1, utc2); };
3c5d046e-8149-447b-861d-360627411841
3
public static String camelCaseToUnderscore(String camelCase) { StringBuilder builder = new StringBuilder(); char[] chars = camelCase.toCharArray(); for (int j = 0; j < chars.length; j++) { if (Character.isUpperCase(chars[j])) { if (j != 0) { builder.append('_'); } builder.append(Character.toLowerCase(chars[j])); } else { builder.append(chars[j]); } } return builder.toString(); }
55922462-afd6-4c7b-8d79-229a0a3764b3
8
private static void liftBreakLabels(Statement stat) { for (Statement st : stat.getStats()) { liftBreakLabels(st); } while (true) { boolean found = false; for (StatEdge edge : stat.getLabelEdges()) { if (edge.explicit && edge.labeled && edge.getType() == StatEdge.TYPE_BREAK) { Statement newclosure = getMaxBreakLift(stat, edge); if (newclosure != null) { newclosure.addLabeledEdge(edge); edge.labeled = isBreakEdgeLabeled(edge.getSource(), newclosure); found = true; break; } } } if (!found) { break; } } }
4101eded-c02a-4532-af9f-0f8bf252bafe
8
void onReceiveFromRemote(final MuxClientRemote remote, final MuxPacket msg) { // Remote is MUX if (msg.syn()) { // New SubChannel Log.info(this.getClass().getSimpleName() + "::onReceiveFromRemote " + msg); openLocal(msg.getIdChannel(), msg.getIdEndPoint(), msg.getSourceAddress()); } else if (msg.fin()) { // End SubChannel Log.info(this.getClass().getSimpleName() + "::onReceiveFromRemote " + msg); final MuxClientLocal local = getLocal(msg.getIdChannel()); if (local != null) local.setShutdown(); } else if (msg.ack()) { // Flow-Control ACK Log.debug(this.getClass().getSimpleName() + "::onReceiveFromRemote " + msg); final MuxClientLocal local = getLocal(msg.getIdChannel()); if (local != null) local.unlock(msg.ackSize()); } else if (msg.nop()) { // NOP Log.info(this.getClass().getSimpleName() + "::onReceiveFromRemote " + msg); } else { // Data Log.debug(this.getClass().getSimpleName() + "::onReceiveFromRemote " + msg); try { final MuxClientLocal local = getLocal(msg.getIdChannel()); if (local == null) return; final RawPacket raw = context.allocateRawPacket(); raw.put(msg.getIdChannel(), msg.getBufferLen(), msg.getBuffer()); local.sendQueueLocal(raw); } catch (Exception e) { Log.error(this.getClass().getSimpleName() + "::onReceiveFromRemote " + e.toString(), e); } } }
8c11e41f-d8e3-4bdf-93f5-e93188ce6d29
2
public static void createRandomPlanets(ResourceManager rm, TileMap t, int numPlanets){ int mapWidth = t.getWidth(); int mapHeight = t.getWidth(); Random r = new Random(); int tileFromEdge = 5; for(int n = 0; n < numPlanets; n++){ int newX = r.nextInt((mapWidth-tileFromEdge)-tileFromEdge)+tileFromEdge; int newY = r.nextInt((mapHeight-tileFromEdge)-tileFromEdge)+tileFromEdge; // center the sprite Planet newP = (Planet)rm.planetSprites.get(r.nextInt(rm.planetImages.size()-1)+1).clone(); newP.setX( TileMapRenderer.tilesToPixels(newX) + (TileMapRenderer.tilesToPixels(1) - newP.getWidth()) / 2); newP.setY( TileMapRenderer.tilesToPixels(newY) + (TileMapRenderer.tilesToPixels(1) - newP.getHeight()) / 2); newP.setRandomTotalPower(); newP.circle.setFrame(newP.circle.getX(), newP.circle.getY(), newP.totalPower()/Planet.POWER_TO_SIZE, newP.totalPower()/Planet.POWER_TO_SIZE); if(canPlacePlanet(newP, t.getSprites())){ t.addSprite(newP); }else{ createRandomPlanets(rm, t, 1); //can't add this sprite at this location, so try again with only one sprite. } } //System.out.println("here"); }
9a0279f7-7e97-4a60-8488-bfdc6b7e9c6a
1
private void initialize() { for (int i = 0; i < id.length; i++) { id[i] = i; siz[i] = 1; } }
313fdfb5-08ae-44f9-a977-70bbcb6c5488
2
public static void main(String[] args) { int i = 1, j = 1; switch(i) { // case 0,1 : j = 1; case 1 :j = -1; break; case 2 : j = 2; default : j = 0; } System.out.println("j=" + j); System.out.println("------------------------"); System.out.println("value = " + switchlt(2)); }
addddc1e-475d-4e7f-b4eb-454bad9dcfd9
4
public Shell() { env = new EnvironmentImpl(); defaultId = "User"; inReader = new InputStreamReader(System.in); bufReader = new BufferedReader(inReader); fileManager = new FileManager(); contentArchiveDir = new File(contentDirectoryPath); if (!(contentArchiveDir.exists() && contentArchiveDir.isDirectory())) { contentArchiveDir.mkdir(); } try { nodeCounter = new File(nodeCounterPath); if (!nodeCounter.exists()) { nodeCounter.createNewFile(); } } catch (IOException ioe) { System.out.println("Error while loading shell settings "); System.exit(-1); } }
7403eb85-5c4d-4efd-b466-92654ad574bb
4
public static String getPrettyString(String cmdLineArg) { String result = null; if (cmdLineArg == null || cmdLineArg.isEmpty()) { return result; } String rawCmdLine = cmdLineArg.trim(); if (rawCmdLine.startsWith("\"") && rawCmdLine.endsWith("\"")) { result = rawCmdLine.replace("\"", ""); } return result; }
20487846-300e-4e33-af6c-d20417c4c56b
8
public void actionPerformed( ActionEvent e ) { String username = textFieldId.getText(); String password = String.valueOf(textFieldPassword.getPassword()); //transfer char[] type to String if(e.getSource() == btnShowReservationCard) { cardManager = (CardLayout) pnlCardDeck.getLayout(); cardManager.show(pnlCardDeck, (String)"Reservation"); }else if (e.getSource()== btnShowCustomerCard) { cardManager = (CardLayout) pnlCardDeck.getLayout(); cardManager.show(pnlCardDeck, (String)"Customer"); }else if (e.getSource()== btnShowServiceCard) { cardManager = (CardLayout) pnlCardDeck.getLayout(); cardManager.show(pnlCardDeck, (String)"Service"); }else if (e.getSource()== btnShowMgtCard) { cardManager = (CardLayout) pnlCardDeck.getLayout(); cardManager.show(pnlCardDeck, (String)"Management"); } if ( e.getSource() == btnLogin ) if( !username.isEmpty() && !password.isEmpty() && loginValidation(username,password) == true) { JOptionPane.showMessageDialog(this, "Login Success!"); cardManager = (CardLayout) mainPane.getLayout(); cardManager.show(mainPane, (String)"Menu"); } else { JOptionPane.showMessageDialog(this, "Invalid ID or Password. Please Try again.", "Login Failed", JOptionPane.ERROR_MESSAGE); } textFieldId.setText(""); textFieldPassword.setText(""); }
266595c0-7e59-49ee-921f-27c6d00800ee
3
public synchronized void update(long elapsedTime) { if (frames.size() > 1) { animTime += elapsedTime; if (animTime >= totalDuration) { animTime = animTime % totalDuration; currentFrame = 0; } while (animTime > getFrame(currentFrame).endTime) { currentFrame++; } } }
c25803e8-8621-4892-92e3-ea04b6b147f5
1
public JPanel getShutdownFrameMenu() { if (!isInitialized()) { IllegalStateException e = new IllegalStateException("Call init first!"); throw e; } return this.shutdFrame; }
72f1ab62-87b7-4d25-a2ed-5fe68dabc478
0
protected void writePIDOut(double output) { Robot.driveTrain.tankDrive(output, -output); }
d6ca01d4-74e8-47ba-91f0-870b558f2e38
2
public Teaches(ClassGroup c, Teacher t) { if (c == null || t == null) throw new IllegalArgumentException(); this.teacher = t; this.classTaught = c; }
bf106696-f3f6-4878-a42e-8798c3601985
3
public Word get(Word word){ Node current = root; while (current != null){ int d = current.data.compareTo(word); if (d == 0) return (Word) current.data; else if (d > 0) current = current.left; else current = current.right; } return null; }
be45b8e1-b8fa-4a2b-b2d1-9d9ef7d2d20d
5
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { boolean isValueNumeric = false; try { if (value.equals("0") || !value.endsWith("0")) { Double.parseDouble(value); isValueNumeric = true; } } catch (NumberFormatException e) { isValueNumeric = false; } if (json.charAt(json.length() - 1) != '{') { json.append(','); } json.append(escapeJSON(key)); json.append(':'); if (isValueNumeric) { json.append(value); } else { json.append(escapeJSON(value)); } }
5639e2cb-f8bb-48ce-b0e2-3b173fd481e8
8
private static byte reverse(byte v) { byte r = 0; if ((v & 0x01) != 0) r |= 0x80; if ((v & 0x02) != 0) r |= 0x40; if ((v & 0x04) != 0) r |= 0x20; if ((v & 0x08) != 0) r |= 0x10; if ((v & 0x10) != 0) r |= 0x08; if ((v & 0x20) != 0) r |= 0x04; if ((v & 0x40) != 0) r |= 0x02; if ((v & 0x80) != 0) r |= 0x01; return r; }
a675134a-16f9-4cdf-9aa6-391004f70253
2
private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed String text = txtBuscar.getText().toString(); PrestamosCRUD pdao = new PrestamosCRUD(MyConnection.getConnection()); ArrayList<Prestamos> rows = new ArrayList<>(); Prestamos p; if(text.isEmpty()){ rows = pdao.getPendientes(); }else{ String option = jComboBox1.getSelectedItem().toString(); switch(option){ case "Fecha": JOptionPane.showMessageDialog(this, "Opcion no disponible en este momento"); break; /*case "Codigo de Libro": String texto = JOptionPane.showInputDialog(this, "Ingrese el codigo de libro para general la consulta"); p = new Prestamos(); listado = udao.getByNombre(u); break; case "DNI": u = new Usuarios(null, null, text); listado = udao.getByDNI(u); break;*/ } } /*if(listado.isEmpty()){ JOptionPane.showMessageDialog(this, "No se encontraron coincidencias"); }else{ //volcarDatos(listado); }*/ }//GEN-LAST:event_btnBuscarActionPerformed
8cddb40f-72d3-4471-8a93-d8ea909bd79d
1
final public CycVariable metaVariable(boolean requireEOF) throws ParseException { CycVariable val = null; Token t = null; t = jj_consume_token(META_VARIABLE); val = new CycVariable(t.image); eof(requireEOF); {if (true) return val;} throw new Error("Missing return statement in function"); }
9dd49a8c-1b96-4ee6-bada-441206868fef
5
public static void WeekEight() throws IOException { System.out.println("So what did Damon learn this week?"); boolean next = false; BufferedReader r = new BufferedReader (new InputStreamReader(System.in)); while (!next) { System.out.println("Knowledge: " + DamonStats.Knowledge); System.out.println("Damon learned:"); System.out.println("1. RSA"); System.out.println("2. Proceed to next week"); int choice = DamonTools.validInput(Integer.parseInt(r.readLine()), 2, 1); if (choice == 1 && !DamonMath135.RSA && DamonStats.Knowledge >= DamonMath135.RSAPt) { DamonStats.Knowledge -= DamonMath135.RSAPt; DamonMath135.RSA = true; } else if (choice == 2) { next = true; } else { System.out.println("Damon has either already learned that, or he does not have enough knowledge."); System.out.println("Please choose again. "); } } }
9352ba40-130a-469c-9610-1f21ab4bb8f8
6
public KeyNodeStringPair dealWithPromote(String newKey, Node rightChild, InternalNodeString node) { // if new key is greater than the key in the last element of list // insert child into the node if (newKey.compareTo(node.getKeys().get(node.size() - 1)) > 0) { node.getKeys().add(newKey); node.getChildren().add(rightChild); } else { int size = node.size(); for (int i = 0; i < size; i++) { if (newKey.compareTo(node.getKeys().get(i)) < 0) { node.getKeys().add(i, newKey); node.getChildren().add(i + 1, rightChild); break; } } } // determine the return value if (node.size() <= MAX_NODE_KEYS) { return null; } InternalNodeString sibling = new InternalNodeString(); int mid = (node.size() + 1) / 2 - 1; // move node.keys from mid - node.size to sibling.node starting from 0 int size = node.size(); for (int i = mid + 1; i < size; i++) { sibling.getKeys().add(node.getKeys().get(mid + 1)); node.getKeys().remove(mid + 1); } // move node.child from mid - node.size to sibling.child starting from // 0 for (int i = mid + 1; i < size + 1; i++) { sibling.getChildren().add(node.getChildren().get(mid + 1)); node.getChildren().remove(mid + 1); } String promoteKey = node.getKeys().get(mid); // remove key which is promoted from node node.getKeys().remove(mid); return new KeyNodeStringPair(promoteKey, sibling); }
1153c207-9d9e-4ae4-9c2b-389f3b403896
1
public GameScreen(JFrame parent) { this.parent = parent; this.width = parent.getContentPane().getWidth(); this.height = parent.getContentPane().getHeight(); super.setSize(width, height); this.width -= 10; super.setBackground(Color.BLACK); keys = new boolean[256]; for (int i = 0; i < keys.length; i++) keys[i] = false; parent.addKeyListener(new MyKeyListener()); parent.addMouseWheelListener(new MyMouseWheelListener()); parent.addMouseListener(new MyMouseListener()); parent.addMouseMotionListener(new MyMouseMotionListener()); setFocusable(true); points = 0; _points = 0; movement = 10; scoreY = height/5; ball = getBall(); ball.setSpeed(6); player = getPaddle(); player.setSpeed(7); ai = getAiPaddle(); url = Pong.class.getResource("pongLimit.wav"); _url = Pong.class.getResource("pongScore.wav"); clipContact = Applet.newAudioClip(url); clipScore = Applet.newAudioClip(_url); timer = new Timer(10, this); timer.start(); ballMovement = true; }
aafa2195-c8cb-4e7b-8009-a6de6439aefa
8
public static void main(String args[]) { try { t = PdfUtilities.chooseFolder(); // TODO: create a method which tests if the file is an // ok-to-the-end-PDF to work with if (t != null) { ArrayList<File> files = PdfUtilities.getPaths(new File(t), new ArrayList<File>()); if (files != null) { for (int i = 0; i < files.size(); i++) { if (!files.get(i).isDirectory() && files.get(i) != null) { try { System.out.println(files.get(i) .getCanonicalPath()); if (PdfUtilities.testPdfOk(files.get(i))) { PDDocument testfile = PDDocument .load(files.get(i)); // to create new file eliminate the // ".pdf"-extension int lenOld = files.get(i) .toString().length(); int lenNew = lenOld - 4; newFileName = (files.get(i) .toString().substring(0, lenNew)); convertToJpegPages(testfile); } } catch (IOException e) { System.out.println(e); } } } } } } catch (IOException e) { System.out.println(e); } }
d80b1464-72dd-4475-af58-b482f905caeb
3
public void setAlive(boolean alive) { aliveDirty = true; lifeDirty = true; if (this.alive == false && alive) { this.setLife(1); for (WeaponInfo wi : getWeaponsData()) { wi.resetAmoAmount(); } } this.alive = alive; }
b6dd7b69-74cf-4639-93a4-f2acd8d9c338
3
private boolean clickedOnHand(MouseEvent e) { return e.getX() >= handXStart() && e.getX() <= handXEnd() && e.getY() >= handYStart() && e.getY() <= handYEnd(); }
c462431c-4866-4535-ab58-5d46f25e670f
1
public static void main(String[] args) throws Exception { InputStreamReader is = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(is); String str; while(null !=(str = br.readLine())) { System.out.println(str); } }
75899bd5-6a84-4b88-bd9b-90e57a2f3e96
3
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Library library = new Library(); if (request.getParameter("cardNumber") != null) { request.getSession().setAttribute("patron", library.getPatron(Integer.parseInt( request.getParameter("cardNumber")))); } if (request.getSession().getAttribute("patron") != null) { request.setAttribute("bookResults", library.getPatronRecord( ((Patron) request.getSession().getAttribute( "patron")).getCardNumber(), "", "Title", "Title", 0)); } } catch (SQLException e) { e.printStackTrace(); } request.getRequestDispatcher("WEB-INF/patron-record.jsp").forward( request, response); }
1194c5a7-5960-441a-b358-bc62523262c6
2
public ArrayList regresaCatalogo(String catalogo) { String res = ""; ArrayList lista = new ArrayList(); try { Class.forName(driver); Connection con = DriverManager.getConnection(connectString, user, password); PreparedStatement query = con.prepareStatement("select descripcion from " + catalogo + " order by descripcion"); ResultSet rset = query.executeQuery(); while (rset.next()) { res = (rset.getString(1)); lista.add(res); } } catch (SQLException | java.lang.ClassNotFoundException e) { System.out.println(e.getMessage()); } return lista; }
deeec336-4324-44ec-a8a9-3d1d3b65731a
6
protected void createSubbands() { int i; if (mode == Frame.SINGLE_CHANNEL) for (i = 0; i < num_subbands; ++i) subbands[i] = new SubbandLayer1(i); else if (mode == Frame.JOINT_STEREO) { for (i = 0; i < header.intensity_stereo_bound(); ++i) subbands[i] = new SubbandLayer1Stereo(i); for (; i < num_subbands; ++i) subbands[i] = new SubbandLayer1IntensityStereo(i); } else { for (i = 0; i < num_subbands; ++i) subbands[i] = new SubbandLayer1Stereo(i); } }
e4dd0716-a80c-4f5a-9ce3-5c908cc60245
7
public static boolean setConsulta(Consulta consulta) { Connection connect = connect(); if(connect != null){ try { connect.setAutoCommit(false); PreparedStatement statement = connect.prepareStatement("insert into consultas (paciente, detalhes, data_inicio, data_fim) values (?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); statement.setInt(1, consulta.getPaciente().getId()); statement.setString(2, consulta.getDescricao()); statement.setTimestamp(3, DateUtil.toSql(consulta.getData_inicio())); statement.setTimestamp(4, DateUtil.toSql(consulta.getData_fim())); statement.executeUpdate(); int consultaId = -1; ResultSet keys = statement.getGeneratedKeys(); if(keys != null && keys.next()){ consultaId = keys.getInt(1); } else throw new Exception("getGeneratedKeys is empty!"); if(consulta.getMedicamentos() != null && consulta.getMedicamentos().size() > 0){ for(Medicamento medicamento : consulta.getMedicamentos()){ String query = String.format("insert into consultas_medicamentos (consulta, medicamento) values (%d, %d)",consultaId,medicamento.getId()); statement.executeUpdate(query); } } connect.commit(); return true; } catch(Exception e){ e.printStackTrace(); } finally { close(connect); } } return false; }
152d5c6b-f7eb-450a-9a3a-b99b285f7c50
1
public void insertBack(Node node) { if (node.previous != null) { node.unlink(); } node.previous = head.previous; node.next = head; node.previous.next = node; node.next.previous = node; }
d18641bd-e6bb-42ac-8355-09fa6b825268
2
private void collectClosedParents(TreeRow row, Set<TreeContainerRow> parents) { TreeContainerRow parent = row.getParent(); if (parent != null) { if (!isOpen(parent)) { parents.add(parent); } collectClosedParents(parent, parents); } }
61358929-0702-43b7-811a-efc955f4dec4
4
public void run() { while (NATBox.RUNNING) { /* Wait time */ try { Thread.sleep(NATBox.REFRESH_TIME); } catch (InterruptedException e) { e.printStackTrace(); } /* Reset counter for removed entries */ int removed_entries = 0; /* Find and remove old entries */ for (String key : NATBox.NAT_Table.keySet()) { if (NATBox.NAT_Table.get(key).time + NATBox.REFRESH_TIME < System.currentTimeMillis()) { NATBox.NAT_Table.remove(key); removed_entries++; } } System.out.println("[NATBoxTableHandler] " + removed_entries + " idle entries removed from NAT Table."); } }
43216992-65b7-498f-9a33-1278490de78d
2
public GroupRequestBuilder setCount(Integer count) { // TODO make via logger if (count != null && count > 1000) { System.out.println("WARN: Cannot be greater then 1000"); } request.count = count; return this; }
e9024ea3-22c9-4c8e-a909-ec63880b7eff
3
public int maxStreak(){ int max_streak = 1, cur_streak = 1; for (int i=1; i<cards.length; i++){ if (cards[i] == cards[i-1]+1) cur_streak++; else{ if (cur_streak > max_streak) max_streak = cur_streak; cur_streak = 1; } } return max_streak; }
be7936e3-7fad-4072-ad1d-349025f501a2
6
public static int changePassword(String userid, String oldpassword, String newPassword){ PreparedStatement pst = null; Connection conn=null; boolean result = false; try { conn=ConnectionPool.getConnectionFromPool(); PreparedStatement pst2 =conn.prepareStatement("SELECT COUNT(*) FROM PERSON WHERE USERID=? AND PASSWORD=?"); pst2.setString(1, userid); pst2.setString(2, oldpassword); ResultSet rs = pst2.executeQuery(); int count =0; if(rs.next()){ count = rs.getInt(1); } if(count==1){ pst = conn .prepareStatement("UPDATE PERSON SET PASSWORD=SHA1(?) WHERE USERID=? AND PASSWORD=SHA1(?)"); pst.setString(1, newPassword); pst.setString(2, userid); pst.setString(3, oldpassword); pst.executeUpdate(); return 1; }else{ return 0; } }catch (Exception e) { System.out.println(e); } finally { if(conn!=null){ ConnectionPool.addConnectionBackToPool(conn); } if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } } return 0; }
f9166a7d-b957-4ce6-958a-512cd22c6879
3
public double dameGananciaMedia(Nodo n) { int ganancia = 0; int num = 0; for (Nodo ady : memoria.getAdjacents(n)) { if (!ady.isEstimacion()) { ganancia += ady.ganancia; num++; } } if (num != 0) { return ganancia / num; } return 0; }
0aca4a87-fe0e-4903-ab4a-f2b3cca7f6b1
1
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * Servlet ottaa vastaan asiakkaan henkilö- sekä toimitustiedot. * Tietoja voi muokata seuraavan sivun Muokkaa-linkin kautta, * mikäli niihin lipsahti jokin virhe. */ // Onko sessiossa valmiiksi asiakkaan tietoja? Tarkistetaan sessiosta. Tilaus tilaus = (Tilaus) request.getSession().getAttribute("asiakas"); // Jos tietoja ei ole syötetty, alustetaan olio. if (tilaus == null) { tilaus = new Tilaus(); } // Jsp-sivu muotoilee. request.getRequestDispatcher("toimitus.jsp").forward(request, response); }
efbaa59e-b261-4b69-87a0-add9d3edceaf
9
public Node simplify(Node n) { leafNodes.clear(); matches.clear(); n.clearMarks(); if(!q_simplify(n)) //if it can not be simplified with this DynamicFormula, return as it is return n; Node target = match_node; //get Node where the match is found if( target.equals(n) ) //if match was found at root { Node ret = new Node(state2); //take other state substituteValues(ret); //put the values of this variables in it ArrayList<Node> temp = unused_simplify(target); //make a list of unused children if(state2.data.equals(n.data) || temp.size() == 0) //if new root operator is same as old, merge em { for (Node aTemp : temp) { ret.child.add(aTemp); //make all unused children, the children of ret } Parser.condense(ret); ArithmeticSolver.simplifySolve(ret); //apply simplifySolve() before returning return ret; } else //otherwise, make new root a children of the old { Node ret2 = new Node(); ret2.data = n.data; ret2.child.add(ret); for (Node aTemp : temp) { ret2.child.add(aTemp); //make all unused children, the children of ret } ArithmeticSolver.simplifySolve(ret2); //apply simplifySolve() before returning Parser.condense(ret2); return ret2; } } else { Node p_targ = findParent(n, target); for(int j = 0; j<p_targ.child.size(); j++) //loop through parent's kids { if(p_targ.child.get(j).equals(target)) //find target { ArrayList<Node> temp = unused_simplify(target); p_targ.child.set(j, new Node(state2)); substituteValues(p_targ.child.get(j)); for (Node aTemp : temp) { p_targ.child.get(j).child.add(aTemp); } ArithmeticSolver.simplifySolve(n); Parser.condense(n); return n; } } } ArithmeticSolver.simplifySolve(n); Parser.condense(n); return n; }
7c6ab351-4d66-42a8-bd46-31eaee1092c2
7
public static Runnable launchAppropriateHandler(String[] args) { if (args == null || args.length == '0') { System.err.println("Invalid Input"); return null; } try { if(args[0].toString().equalsIgnoreCase("PM") && args.length == 3) //Commands to start a Process Manager { return new ProcessManager(args[1].toString().trim(), Integer.parseInt(args[2])); //This Process Manager will fire up and it will act as the Controller for USER INPUT } else if(args[0].toString().equalsIgnoreCase("W") && args.length == 5) //Commands to start a Worker { return new WorkerManager(args[1].toString().trim(),Integer.parseInt(args[2]), args[3].toString().trim(), Integer.parseInt(args[4])); //Workers returned here who will do some Work //Logically Workers Represent Some Entities Doing Work } else { System.err.println("Invalid use of Command"); return null; } } catch (NumberFormatException e) { System.err.println("Invalid port number."); return null; } }
3a96b891-c34e-470e-8587-1de9c75ceb19
4
public static List<Peer> findRutgersPeers(List<Peer> peers) { List<Peer> rutgersPeers = Collections.synchronizedList(new ArrayList<Peer>()); for(Peer p : peers) { String pIP = p.getIP(); if(pIP.equals("128.6.171.131") && p.getPeerId().contains("-AZ5400-")) { rutgersPeers.add(p); } else if (pIP.equals("128.6.171.130")) { rutgersPeers.add(p); } } return rutgersPeers; }
a5272a24-669f-4f8f-9209-daf63137d031
7
@Override public void attackFinished() { if (this.currentFlashFrame == this.numOfFlashTextures - 1) { this.frameNum = 0; this.currentFlashFrame = -1; this.isAttacking = false; if (this.isCrouching) { if (xProectionSign) { changeAnimationType(3); } else { changeAnimationType(2); } } else { if (xProectionSign) { changeAnimationType(1); } else { changeAnimationType(0); } } Shell bullet; if (xProectionSign) { if (isCrouching) { bullet = new Bullet(this.getCurrentCoordinates().getX() + this.currentWidth, this.getCurrentCoordinates().getY() + (int) Math.round(this.currentHeight * this.crouchBulletCoordCoeff), null); bullet.setHeroOwnHorizontalSpeed(10000 / AppFrame.getUpdatesPerSecond()); } else { bullet = new Bullet(this.getCurrentCoordinates().getX(), this.getCurrentCoordinates().getY() + (int) Math.round(this.currentHeight * this.bulletCoordCoeff), null); bullet.setHeroOwnHorizontalSpeed(10000 / AppFrame.getUpdatesPerSecond()); } AppFrame.getFrameDesign().addMovingObject(bullet); } else { if (isCrouching) { bullet = new Bullet(this.getCurrentCoordinates().getX(), this.getCurrentCoordinates().getY() + (int) Math.round(this.currentHeight * this.crouchBulletCoordCoeff), null); bullet.setHeroOwnHorizontalSpeed(-10000 / AppFrame.getUpdatesPerSecond()); } else { bullet = new Bullet(this.getCurrentCoordinates().getX(), this.getCurrentCoordinates().getY() + (int) Math.round(this.currentHeight * this.bulletCoordCoeff), null); bullet.setHeroOwnHorizontalSpeed(-10000 / AppFrame.getUpdatesPerSecond()); } AppFrame.getFrameDesign().addMovingObject(bullet); } } else { currentFlashFrame++; } }
dd4010b4-724a-46ed-bf02-9530521047eb
0
public int[] getSubstitutions() { return subs; }
2fc4fa96-00fa-47bc-85f4-489b2c977e3d
2
@Override public void execute(CommandSender sender, String[] arg1) { if (!CommandUtil.hasPermission(sender, PERMISSION_NODES)) { sender.sendMessage(plugin.NO_PERMISSION); return; } HashSet<String> list = plugin.getChatPlayer(sender.getName()).getIgnores(); String message = ChatColor.DARK_AQUA + "Ignoring players: " + ChatColor.RESET; for (String data : list) { message += data + ", "; } sender.sendMessage(message); }
27a13235-f24b-4762-b0bc-a43dd0eb8a7d
2
public static void main(String[] args) { //Instantiate Scanner Scanner scanner = new Scanner (System.in); //Ask user how many students they want to enter. Use that response to instantiate an object array. System.out.println("How many students would you like to enter?"); int num = scanner.nextInt(); //Instantiate an object Array Student [] studentInputArray = new Student [num]; //use a for loop to: //1.Print the questions and store the answer in local variables. //2.Instantiate a new object of Student. //3.Assign the local variables in the object. //4.Store the object in an array. for(int i = 0; i < studentInputArray.length; i++){ System.out.println("What is your first name?"); String firstName = scanner.nextLine(); System.out.println("What is your last name?"); String lastName = scanner.nextLine(); System.out.println("Where do you go to school?"); String school = scanner.nextLine(); System.out.println("What is your address?"); String address = scanner.nextLine(); System.out.println("How old are you?"); int age = scanner.nextInt(); System.out.println("What grade are you in?"); int grade = scanner.nextInt(); System.out.println("What is your phone number?"); String phoneNumber = scanner.nextLine(); System.out.println("What is your birthday?"); String birthday = scanner.nextLine(); //Instantiate an object of Student class. Student studentObject = new Student(); //populate the object with the values from scanner. studentObject.setFirstName(firstName); studentObject.setLastName(lastName); studentObject.setSchool(school); studentObject.setAddress(address); studentObject.setAge(age); studentObject.setGrade(grade); studentObject.setPhoneNumber(phoneNumber); studentObject.setBirthday(birthday); //store the object in the array. studentInputArray[i] = studentObject; } //I use a for loop to print the values of all the arrays. for (int i=0; i<studentInputArray.length; i++) { System.out.println(studentInputArray[i].getFirstName()); System.out.println(studentInputArray[i].getLastName()); System.out.println(studentInputArray[i].getSchool()); System.out.println(studentInputArray[i].getAddress()); System.out.println(studentInputArray[i].getPhoneNumber()); System.out.println(studentInputArray[i].getBirthday()); System.out.println(studentInputArray[i].getAge()); System.out.println(studentInputArray[i].getGrade()); } }
984069d7-a261-44b7-ac4d-3f81f55fab57
7
private static void setupVirtualServerAndToolkit() { final int MAX = 30; int i; File target; final String DISPLAY; final Runtime runtime; try { /* * This seems quite the kludge, but apparently this is the * algorithm used by X itself to find an available display number. * It's also used by Gentoo's virtualx eclass. */ for (i = 0; i < MAX; i++) { target = new File("/tmp/.X" + i + "-lock"); if (!(target.exists())) { break; } } if (i == MAX) { fail("\n" + "Can't find an available X server display number to use"); } DISPLAY = ":" + i; /* * Xvfb arguments: * * -ac disable access control (necessary so that other program can * draw there) * * -wr white background * * -fp built-ins workaround "fixed" font not being present. * * Also, don't try to force Xvfb to 32 bits per pixed in -screen; * for some reason this makes it unable to start. */ runtime = Runtime.getRuntime(); virtual = runtime.exec("/usr/bin/Xvfb " + DISPLAY + " -ac -dpi 96 -screen 0 800x600x24 -wr -fp built-ins"); sleep(100); checkVirtualServerRunning(); /* * Attempt to terminate the virtual X server when the tests are * complete. This is far from bullet proof. It would be better if * we knew when all the tests were done running and called * destroy() then. */ runtime.addShutdownHook(new Thread() { public void run() { if (virtual == null) { return; } try { virtual.destroy(); virtual.waitFor(); } catch (InterruptedException e) { // already exiting } } }); /* * Finally, initialize GTK. We close stderr to prevent noise from * Xlib (as used by GTK) about "XRANR not being available". This * of course means we're missing anything else to stderr. That * seems like a bad idea, but what else can we do? */ System.err.close(); Gtk.init(new String[] { "--display=" + DISPLAY }); initialized = true; } catch (IOException ioe) { fail("Unexpected I/O problem: " + ioe.getMessage()); } catch (InterruptedException ie) { fail("How did this Thread get interrupted?"); } }
f5c0eeb3-ca4f-477c-914d-2f1922031bf4
6
private FileBlock[] getFileAllocation(String DFSFileName, int no_of_blocks){ Logger.log("no of blocks:" + no_of_blocks); Collections.sort(dataNodeList); Logger.log("Nodes after sorting: "); for(DataNodeInfo s: dataNodeList) Logger.log(s.getId()+ " | Stores: " + s.getsizeOfStoredFiles() +" | FREE: "+ s.getFreeSpace()); FileBlock[] allocation = new FileBlock[no_of_blocks]; //TODO synchronization failure for(int i=0;i<no_of_blocks;i++){ allocation[i] = new FileBlock( "FILE" + (currentBlockNumber++)); } try{ Iterator<DataNodeInfo> iter = dataNodeList.iterator(); //TODO Use a more sophisticated load balancing strategy later for(int i=0;i<Constants.REPLICATION_FACTOR*no_of_blocks;i++){ if(!iter.hasNext()) iter = dataNodeList.iterator(); allocation[(i/Constants.REPLICATION_FACTOR)%no_of_blocks].addNodeLocation(iter.next().getId()); } //allocation[0] = new FileBlock(DFSFileName+"_"+NameNode.currentBlockNumber++, allocatedBlocks); } catch(Exception e){ e.printStackTrace(); //TODO delete } for(int i=0;i<no_of_blocks;i++){ Logger.log(i+": "+ allocation[i].getNodeLocations()[0] + allocation[i].getNodeLocations()[1] + allocation[i].getNodeLocations()[2]); } return allocation; }
5221b41d-db5b-4770-be59-97a3104e9f79
8
@Override public void set(long i, Object o) { if (o == null) { if (ptr != 0) { objectLengths.setShort(i, (short) -1); } else { if (isConstant()) { throw new IllegalAccessError("Constant arrays cannot be modified."); } data[(int) i] = null; } } else { if (ptr != 0) { byte[] ba = toByteArray(o); if (ba.length > maxObjectLength) { throw new IllegalArgumentException("Object " + o + " is too long."); } int objLen = ba.length; if (objLen > Short.MAX_VALUE) { throw new IllegalArgumentException("Object " + o + " is too long."); } objectLengths.setShort(i, (short) objLen); long offset = sizeof * i * maxObjectLength; for (int j = 0; j < objLen; j++) { Utilities.UNSAFE.putByte(ptr + offset + sizeof * j, ba[j]); } } else { if (isConstant()) { throw new IllegalAccessError("Constant arrays cannot be modified."); } data[(int) i] = o; } } }
18035ef8-ac25-4ea3-b59d-180e9774cc55
9
private void initDimensions() throws InvalidInput { String[][] rows = CSVHelper.getTrimmedTable(dimensionsToTestCSV); if (CSVHelper.isInputsEmpty(rows)) return; if (!CSVHelper.isTableConsistent(rows) || rows[0].length != 3) throw new WrongFileStructure("Rows are not consistent", INPUT_AREA); for (int i=0; i<rows.length; i++) { int steps; try { steps = Integer.parseInt(rows[i][2]); } catch(NumberFormatException e) { throw new NotInteger(rows[i][2], INPUT_AREA, i+1, 3); } if (steps < 0) throw new Negative(steps, INPUT_AREA, i+1, 3); dimensionsIDs.add(rows[i][0]); if (rows[i][1].equals("integer")) dimensionTypes.add(DimensionType.INTEGER); else if (rows[i][1].equals("float")) dimensionTypes.add(DimensionType.FLOAT); else if (rows[i][1].equals("enumeration")) dimensionTypes.add(DimensionType.ENUMERATION); else throw new WrongDimensionType(rows[i][1], INPUT_AREA, i+1, 2); totalSteps.add(steps); } }
ef2682cf-ce8a-4da8-94e9-e01f7911f8ae
4
@Override public boolean update(Hotelier x) { Statement stm = null; try { String req = "UPDATE hotelier SET \n" + "email=\""+x.getEmail()+"\",\n" + "motdepasse=\""+x.getMotDePasse()+"\",\n" + "siteweb=\""+x.getSiteweb()+"\",\n" + "nomentreprise=\""+x.getNomEntreprise()+"\"\n" + "WHERE hotelierid="+x.getHotelierId()+"\n" + //Les conditions suivantes empechent la requète de donner un email qui serait déjà utilisé par un autre membre (hotelier ou particulier) //Notez que MySQL ne permet pas de selectionner directement la table que l'on modifie pendant un update //c'est pourquoi les selections ont un niveau de profondeur additionnel. "and not exists ( select * from (select * from hotelier \n" + " where email = \""+x.getEmail()+"\"\n" + " and hotelierid<>"+x.getHotelierId()+"\n" + " )temphotelier)\n" + "and not exists ( select * from (select * from particulier \n" + " where email = \""+x.getEmail()+"\"\n" + " )tempparticulier)"; if (cnx.createStatement().executeUpdate(req)>0) { return true; } } catch (SQLException exp) { } finally { if (stm!=null) try { stm.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return false; }
0c579fae-9c5c-4687-a03b-1cc18d74fc4e
3
@Override public void run() { cpu.start(); dispositivo.start(); if (cpu != null){ while(simulacion){ numTicks++; /* Paso del tiempo */ /* Notificacion del paso del tiempo */ cpu.notifica(); dispositivo.notifica(); try { Reloj.sleep(tick); } catch (InterruptedException ex) { System.out.println("ERROR durmiendo Reloj"); return; } } } }
d1782c43-3158-4dad-b1ea-a6cd9831d450
2
@Override public String toString() { String entryString = "";//Arrays.toString(entries.toArray()); for (byte entry: entries){ entryString += ","+(char)entry; } return "" + (char) id + "(" + (entries.length==0?"":entryString.substring(1, entryString.length())) + ")"; }
17d0ef54-8145-4797-be3f-d58ae806584d
9
public void transform(JavaClass javaClass) { if (javaClass.className.equals("Heaper")) { return; } boolean foundEmptyConstructor = false; boolean foundRcvrConstructor = false; for (Iterator iter = javaClass.methods.iterator(); iter.hasNext();) { JavaMethod method = (JavaMethod) iter.next(); if (method.name.equals(javaClass.className) && method.parameters.isEmpty()) { foundEmptyConstructor = true; } if (method.name.equals(javaClass.className) && method.parameters.size() == 1 && ((JavaField)method.parameters.get(0)).type.equals("Rcvr")) { foundRcvrConstructor = true; } } if (!foundEmptyConstructor) { javaClass.methods.add(createEmptyConstructor(javaClass)); } if (!foundRcvrConstructor) { javaClass.methods.add(createReceiverConstructor(javaClass)); } }
40468ca6-6b6b-4ee4-9e09-1cf579a8187e
4
public void add(String sana) { Node uusi = getChild(sana.charAt(0)); String loput = sana.substring(1); if (uusi == null) { uusi = new Node(); uusi.setName(sana.charAt(0)); if (juuri.isEmpty()) { juuri.add(uusi); } else { int paikka = compareTo(uusi); juuri.add(paikka, uusi); } if (loput.length() > 0) { uusi.add(loput); } } else { if (loput.length() > 0) { uusi.add(loput); uusi.increaseSize(); } // Jos päästiin sanan loppuun, lisätään vain solmun kokoa else { uusi.increaseSize(); } } }
4435ddf5-915f-4075-9cbc-115431c8adba
5
public static void scheduleRecurringEvent( String method, Object target, long delay, Object... parameters ) { Event event = new Event(); try { if ( parameters != null ) { Class< ? >[] paramClasses = new Class< ? >[ parameters.length ]; for ( int i = 0; i < paramClasses.length; i++ ) { paramClasses[ i ] = parameters[ i ].getClass(); } event.action = target.getClass().getMethod( method, paramClasses ); } else { event.action = target.getClass().getMethod( method ); } } catch ( SecurityException | NoSuchMethodException e ) { Lumberjack.throwable( "Scheduler", e ); } event.target = target; event.delay = delay; event.executionTime = TimeHelper.toTicks( Sys.getTime() ) + delay; event.parameters = parameters; recurringEvents.add( event ); }
9627adcd-a104-4d5a-b4f3-018fe3260a59
9
private boolean jj_scan_token(int kind) { if (jj_scanpos == jj_lastpos) { jj_la--; if (jj_scanpos.next == null) { jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); } else { jj_lastpos = jj_scanpos = jj_scanpos.next; } } else { jj_scanpos = jj_scanpos.next; } if (jj_rescan) { int i = 0; Token tok = token; while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } if (tok != null) jj_add_error_token(kind, i); } if (jj_scanpos.kind != kind) return true; if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; return false; }
34f9765f-2450-4de5-9f6d-e224ed1eed15
9
private boolean runTestCase(File dir) throws IOException { File xmlDir = new File(dir, toDir); File compactDir = new File(dir, COMPACT_DIR); File outputDir = new File(dir, OUT_DIR); File correct = new File(compactDir, CORRECT_SCHEMA_NAME + COMPACT_EXTENSION); File incorrect = new File(compactDir, INCORRECT_SCHEMA_NAME + COMPACT_EXTENSION); boolean passed = true; if (correct.exists()) { File output = new File(outputDir, CORRECT_SCHEMA_NAME + toExt); if (!run(correct, output, outputFormat, toExt) || !compareDir(xmlDir, outputDir)) { passed = false; failed(correct); } else if (toExt.equals(XML_EXTENSION)) { cleanDir(outputDir); File output2 = new File(outputDir, CORRECT_SCHEMA_NAME + COMPACT_EXTENSION); if (!run(correct, output2, compactOutputFormat, COMPACT_EXTENSION) || !run(output2, output, outputFormat, toExt) || !compareDir(xmlDir, outputDir)) { passed = false; failed(correct); } } } if (incorrect.exists()) { File output = new File(outputDir, INCORRECT_SCHEMA_NAME + toExt); if (run(incorrect, output, outputFormat, toExt)) { passed = false; failed(incorrect); } } return passed; }
2dfc1fa4-2daa-4fdb-b6b7-e6083c0409fe
0
@Override public void mouseClicked(MouseEvent e) {}
1d6baa70-55b0-40f6-800f-f882787f67fd
8
public static void main(String[] args) throws IOException { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a regexp: "); String regexp = keyboard.readLine(); ConvertRegexpToNFA nfaBuilder = new ConvertRegexpToNFA(regexp); FiniteAutomaton a = nfaBuilder.convertToNFA(); if (DEBUG) { System.out.println("NFA:"); PrintAutomaton pa = new PrintAutomaton(); pa.print(a); } System.out.println("Initial automaton is " + (FiniteAutomatonUtil.isDeterministic(a) ? "deterministic" : "nondeterministic")); System.out.print("Convert the automaton to a DFA (yes/no)? "); boolean convert = keyboard.readLine().toLowerCase(Locale.US).equals("yes"); if (convert) { ConvertNFAToDFA dfaBuilder = new ConvertNFAToDFA(); dfaBuilder.add(a); a = dfaBuilder.execute(FiniteAutomatonTransformerMode.NONDESTRUCTIVE); if (DEBUG) { System.out.println("DFA:"); PrintAutomaton pa = new PrintAutomaton(); pa.print(a); } System.out.println("Converted automaton is " + (FiniteAutomatonUtil.isDeterministic(a) ? "deterministic" : "nondeterministic")); } ExecuteFiniteAutomaton executor = convert ? new ExecuteDFA() : new ExecuteNFA(); executor.setAutomaton(a); System.out.println("Enter strings:"); for (;;) { String line = keyboard.readLine(); if (line == null) { break; } System.out.println(executor.execute(line)); } }
6e7e6fc0-ff8b-44e1-81f4-c40f04c3a004
5
public Object nextEntity(char ampersand) throws JSONException { StringBuffer sb = new StringBuffer(); for (;;) { char c = next(); if (Character.isLetterOrDigit(c) || c == '#') { sb.append(Character.toLowerCase(c)); } else if (c == ';') { break; } else { throw syntaxError("Missing ';' in XML entity: &" + sb); } } String string = sb.toString(); Object object = entity.get(string); return object != null ? object : ampersand + string + ";"; }
8a5a270f-7645-4748-be45-fa64be044545
0
public int getActionType() { return actionType; }
056ee2a5-468b-4afa-8f7c-7f844fad335a
1
public static Configuration loadConfiguration() { if (instance == null) instance = new Configuration(); return instance; }
11c86fd4-0c9e-486b-81a5-5b5493567dbe
2
private void placeLightGrenades() { while(grid.getLightGrenadeCoverage() < 5){ int randomX = (int) Math.round(Math.random() * grid.getHorLength()); int randomY = (int) Math.round(Math.random() * grid.getVerLength()); LightGrenade lg = new LightGrenade(new Position(randomX, randomY)); if (grid.canHaveAsLightGrenade(lg)) { grid.addElement(lg); } } }
591c8804-240c-4fca-a1e7-3b61593feb3b
2
public void testWithers() { TimeOfDay test = new TimeOfDay(10, 20, 30, 40); check(test.withHourOfDay(6), 6, 20, 30, 40); check(test.withMinuteOfHour(6), 10, 6, 30, 40); check(test.withSecondOfMinute(6), 10, 20, 6, 40); check(test.withMillisOfSecond(6), 10, 20, 30, 6); try { test.withHourOfDay(-1); fail(); } catch (IllegalArgumentException ex) {} try { test.withHourOfDay(24); fail(); } catch (IllegalArgumentException ex) {} }
862dc41f-e9ec-470c-a031-d3182f6ea9aa
4
public void setRotation(Rotation rotation) { switch(rotation) { case BOTTOM: this.rotation = 0; break; case LEFT: this.rotation = 90; break; case TOP: this.rotation = 180; break; case RIGHT: this.rotation = 270; break; } }
1ccaa48f-13d9-4dc0-833a-5ff3e85ffc2a
5
private long removeRefOfferDataNym(long lIndex) { // // loop through the elements in the actual container, in order to find the one // at lIndex. Once it is found, then loop through the reference list and remove // the corresponding reference for that element. // OfferDataNym refActualElement = GetOfferDataNym(lIndex); if (refActualElement == null) return lIndex; // oh well. // Loop through the reference list and remove the corresponding reference // for the specified element. // for(int intIndex = 0; intIndex < elementList.size(); intIndex++) { Object theObject = elementList.get(intIndex); if ((theObject == null) || !(theObject instanceof OfferDataNym)) continue; OfferDataNym tempRef = (OfferDataNym)(theObject); if ((OfferDataNym.getCPtr(tempRef) == OfferDataNym.getCPtr(refActualElement))) { elementList.remove(tempRef); break; } } return lIndex; }
7f4654d1-1df7-41a6-b53b-eda1edaf74f0
3
public static void main(String[] args) { // TODO Auto-generated method stub //�����v�f��*���‚��āA�t�B�{�i�b�`����̍ŏ��̕�̗v�f��\������ System.out.println("��ǃt�B�{�i�b�`����"); String[] stringImprovedFibonacci = new String[MAX_INDEX]; int lo = 1; int hi = 1; String mark; stringImprovedFibonacci[0] = "1:" + lo; for(int i = MAX_INDEX-1; i >= 1; i--){ if(hi%2 == 0) mark = "*"; else mark = ""; stringImprovedFibonacci[MAX_INDEX - i] = MAX_INDEX - i + ":" + hi + mark; hi = lo + hi; lo = hi- lo; } for(int i=0; i<MAX_INDEX-1; i++){ System.out.println(stringImprovedFibonacci[i]); } }
b77e80e2-083a-4689-8d02-becf36560ecd
3
private boolean rightEdge(int particle, int cubeRoot) { for(int i = 0; i < cubeRoot; i++){ for(int k = 1; k < cubeRoot; k++){ if(particle == i * cubeRoot * cubeRoot + cubeRoot - 1 + k * cubeRoot){ return true; } } } return false; }
ca12af39-9bf6-4ff4-bc47-f07e5095720c
8
public static void main(String[] args) throws Exception { HashSet<String> set = getMatchingSequences(); System.out.println(set); System.out.println(set.size()); BufferedReader reader = new BufferedReader(new InputStreamReader( new GZIPInputStream( new FileInputStream( ConfigReader.getVanderbiltDir() + File.separator + "MSHRM1" + File.separator + "lane1_Undetermined_L001_R1_001.fastq.gz")))); int numChecked=0; int numMatched=0; for(FastQ fq = FastQ.readOneOrNull(reader); fq != null; fq = FastQ.readOneOrNull(reader)) { numChecked++; String aSeq = fq.getSequence().trim(); String backSeq = Translate.safeReverseTranscribe(fq.getSequence().trim()); boolean match = false; for(String s : set) { if( aSeq.startsWith(s) || aSeq.endsWith(s) || backSeq.startsWith(s) || backSeq.endsWith(s)) match = true; } if( match) numMatched++; if(numChecked % 100000 ==0) System.out.println(numChecked + " " + numMatched); } }
284113c1-c329-4fb9-a82d-3cb228272e27
9
public void searchAvailableCells(){ int numB1 = 1 ; int numB2 = 1 ; int numB3 = 1 ; int numB4 = 1 ; for (int i = 0; i < 28; i++) { if (i < 7) { if (this.testAvailabe(numB1 , 0, i)){ numB1++; }else{ this.FilterAvailable(i, 7); i = 7 ; continue; } } else if (i < 14) { if(this.testAvailabe(numB2 * -1, 0, i)){ numB2++; }else{ this.FilterAvailable(i, 14); i= 14 ; continue; } } else if (i < 21) { if(this.testAvailabe(0, numB3 , i)){ numB3++; }else{ this.FilterAvailable(i, 21); i= 21; continue; } } else if (i < 28) { if(this.testAvailabe(0, numB4*-1, i)){ numB4++; }else{ this.FilterAvailable(i, 28); i= 28 ; continue; } } } }
7ea76414-6cd6-49ff-acfe-f580fac47b7f
2
public void run() { try { while (alreadyRunning) { Socket socket = incoming.accept(); log.debug(name + ": Accepting connection..."); new EventHandler(this, socket); Thread.sleep(1500); } } catch (Exception e) { log.error("Error in communication protocol! ", e); } }
905f390b-3293-4139-a510-31a78625215e
9
private void handleNumericAttribute(Instances trainInstances) throws Exception { m_c45S = new C45Split(m_attIndex, 2, m_sumOfWeights, true); m_c45S.buildClassifier(trainInstances); if (m_c45S.numSubsets() == 0) { return; } m_errors = 0; Instances [] trainingSets = new Instances [m_complexityIndex]; trainingSets[0] = new Instances(trainInstances, 0); trainingSets[1] = new Instances(trainInstances, 0); int subset = -1; // populate the subsets for (int i = 0; i < trainInstances.numInstances(); i++) { Instance instance = trainInstances.instance(i); subset = m_c45S.whichSubset(instance); if (subset != -1) { trainingSets[subset].add((Instance)instance.copy()); } else { double [] weights = m_c45S.weights(instance); for (int j = 0; j < m_complexityIndex; j++) { Instance temp = (Instance)instance.copy(); if (weights.length == m_complexityIndex) { temp.setWeight(temp.weight() * weights[j]); } else { temp.setWeight(temp.weight() / m_complexityIndex); } trainingSets[j].add(temp); } } } /* // compute weights (weights of instances per subset m_weights = new double [m_complexityIndex]; for (int i = 0; i < m_complexityIndex; i++) { m_weights[i] = trainingSets[i].sumOfWeights(); } Utils.normalize(m_weights); */ Random r = new Random(1); int minNumCount = 0; for (int i = 0; i < m_complexityIndex; i++) { if (trainingSets[i].numInstances() > 5) { minNumCount++; // Discretize the sets Discretize disc = new Discretize(); disc.setInputFormat(trainingSets[i]); trainingSets[i] = Filter.useFilter(trainingSets[i], disc); trainingSets[i].randomize(r); trainingSets[i].stratify(5); NaiveBayesUpdateable fullModel = new NaiveBayesUpdateable(); fullModel.buildClassifier(trainingSets[i]); // add the errors for this branch of the split m_errors += NBTreeNoSplit.crossValidate(fullModel, trainingSets[i], r); } else { for (int j = 0; j < trainingSets[i].numInstances(); j++) { m_errors += trainingSets[i].instance(j).weight(); } } } // Check if minimum number of Instances in at least two // subsets. if (minNumCount > 1) { m_numSubsets = m_complexityIndex; } }
23208353-63e4-4218-9b5b-64f38ef8220f
8
@Override public ExecuteResult start() { String currentActionName = startActionName; Map<String, Action> actions = getActionMap(); while (true) { // 如果没有提前预置标志结束的ActionName,则使用end。如果当前actionName等于标志结束的ActionName,则退出并认为引擎成功结束 if (StringUtils.equals(currentActionName, endActionName)) { log.info("Meet action [" + currentActionName + "], end the SequenceActionEngine."); return ExecuteResult.SUCCESS; } // 如果当前actionName等于标志运行失败的ActionName,退出引擎并抛出异常 if (StringUtils.equals(currentActionName, EOF.fail.name())) { log.error("Meet action [fail], stop the SequenceActionEngine"); return ExecuteResult.FAILED; } // 如果要运行的actionName在工作计划中不存在,则抛出异常 if (!actions.containsKey(currentActionName)) { log.error("Doesn't found any action named [" + currentActionName + "] in this Workflow."); return ExecuteResult.FAILED; } log.info("Current action is [" + currentActionName + "]"); Action action = actions.get(currentActionName); OperateCode oc = action.execute(); log.info("Action [" + currentActionName + "] is " + oc.name()); String nextAction = null; Jump j = jumpMap.get(currentActionName); switch (oc) { case SUCCESS: nextAction = j.getSucJumpTo(); break; case FAILED: nextAction = j.getErrJumpTo(); break; case KILL: default: log.info("Kill the engine."); return ExecuteResult.KILL; } currentActionName = nextAction; try { Thread.sleep(getHalfTime()); } catch (InterruptedException e) { return ExecuteResult.KILL; } } }
be5dbd24-3a3f-4e6e-a2ef-9acbc56a3e75
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(mainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(mainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(mainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(mainForm.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 mainForm().setVisible(true); } }); }
3bb46b77-d304-47b8-a24f-7729b9c7a3d4
6
private void setupBlock() throws IOException { if (this.data == null) { return; } final int[] cftab = this.data.cftab; final int[] tt = this.data.initTT(this.last + 1); final byte[] ll8 = this.data.ll8; cftab[0] = 0; System.arraycopy(this.data.unzftab, 0, cftab, 1, 256); for (int i = 1, c = cftab[0]; i <= 256; i++) { c += cftab[i]; cftab[i] = c; } for (int i = 0, lastShadow = this.last; i <= lastShadow; i++) { tt[cftab[ll8[i] & 0xff]++] = i; } if ((this.origPtr < 0) || (this.origPtr >= tt.length)) { throw new IOException("stream corrupted"); } this.su_tPos = tt[this.origPtr]; this.su_count = 0; this.su_i2 = 0; this.su_ch2 = 256; /* not a char and not EOF */ if (this.blockRandomised) { this.su_rNToGo = 0; this.su_rTPos = 0; setupRandPartA(); } else { setupNoRandPartA(); } }
27773102-7aed-49ab-8119-b8bb0a8513c9
7
public FeatureMap(File file,int idxOfName,int idxOfIndex,String sep,int offset){ BufferedReader br = null; int idxError = 0; int intFormatError =0; try { // 构造BufferedReader对象 br = new BufferedReader(new FileReader(file)); String line = null; while ((line = br.readLine()) != null) { String[] cols = line.split(sep); if(cols.length< Math.max(idxOfName, idxOfIndex)){ idxError++; continue; } try{ int idx = Integer.parseInt(cols[idxOfIndex]); idx +=offset; String name = cols[idxOfName]; idx2name.put(idx,name); name2idx.put(name, idx); }catch(Exception ee){ intFormatError++; continue; } } } catch (IOException e) { e.printStackTrace(); } finally { // 关闭BufferedReader if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } if((idxError+intFormatError)>0){ System.out.println("found "+idxError+" index overflow errors and "+intFormatError+" Integer format errors."); } }
a1838ac9-205e-4111-8b5b-90243c859f90
3
public String login(String userId, String password, int department) { User user = validateUser(userId); if (user == null) { m_logger.debug("userId " + userId + " is not valid"); return ResponseMessages.USER_DOES_NOT_EXIST; } if (!password.equals(user.getPassword())) { m_logger.debug("password for " + userId + " not matched"); return ResponseMessages.PASSWORD_NOT_MATCHED; } if (department != user.getDepartment()) { m_logger.debug("department for " + userId + " not successful"); return ResponseMessages.DEPARTMENT_NOT_MATCHED; } setUser(user); return ResponseMessages.LOGIN_SUCCESSFUL; }
8fa95fdf-5b18-441e-b4c2-15c796a00699
9
void CardTypes_Show (javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, javax.servlet.http.HttpSession session, javax.servlet.jsp.JspWriter out, String sCardTypesErr, String sForm, String sAction, java.sql.Connection conn, java.sql.Statement stat) throws java.io.IOException { String sWhere = ""; int iCounter=0; int iPage = 0; boolean bIsScroll = true; boolean hasParam = false; String sOrder = ""; String sSQL=""; String transitParams = ""; String sQueryString = ""; String sPage = ""; int RecordsPerPage = 20; String sSortParams = ""; String formParams = ""; // Build WHERE statement // Build ORDER statement sOrder = " order by c.name Asc"; String sSort = getParam( request, "FormCardTypes_Sorting"); String sSorted = getParam( request, "FormCardTypes_Sorted"); String sDirection = ""; String sForm_Sorting = ""; int iSort = 0; try { iSort = Integer.parseInt(sSort); } catch (NumberFormatException e ) { sSort = ""; } if ( iSort == 0 ) { sForm_Sorting = ""; } else { if ( sSort.equals(sSorted)) { sSorted="0"; sForm_Sorting = ""; sDirection = " DESC"; sSortParams = "FormCardTypes_Sorting=" + sSort + "&FormCardTypes_Sorted=" + sSort + "&"; } else { sSorted=sSort; sForm_Sorting = sSort; sDirection = " ASC"; sSortParams = "FormCardTypes_Sorting=" + sSort + "&FormCardTypes_Sorted=" + "&"; } if ( iSort == 1) { sOrder = " order by c.name" + sDirection; } } // Build full SQL statement sSQL = "select c.card_type_id as c_card_type_id, " + "c.name as c_name " + " from card_types c "; sSQL = sSQL + sWhere + sOrder; String sNoRecords = " <tr>\n <td colspan=\"1\" style=\"background-color: #FFFFFF; border-width: 1\"><font style=\"font-size: 10pt; color: #000000\">No records</font></td>\n </tr>"; String tableHeader = ""; tableHeader = " <tr>\n <td style=\"background-color: #FFFFFF; border-style: inset; border-width: 0\"><a href=\""+sFileName+"?"+formParams+"FormCardTypes_Sorting=1&FormCardTypes_Sorted="+sSorted+"&\"><font style=\"font-size: 10pt; color: #CE7E00; font-weight: bold\">Name</font></a></td>\n </tr>"; try { out.println(" <table style=\"\">"); out.println(" <tr>\n <td style=\"background-color: #336699; text-align: Center; border-style: outset; border-width: 1\" colspan=\"1\"><a name=\"CardTypes\"><font style=\"font-size: 12pt; color: #FFFFFF; font-weight: bold\">Card Types</font></a></td>\n </tr>"); out.println(tableHeader); } catch (Exception e) {} try { java.sql.ResultSet rs = null; // Open recordset rs = openrs( stat, sSQL); iCounter = 0; java.util.Hashtable rsHash = new java.util.Hashtable(); String[] aFields = getFieldsName( rs ); // Show main table based on recordset while ( rs.next() ) { getRecordToHash( rs, rsHash, aFields ); String fldname = (String) rsHash.get("c_name"); out.println(" <tr>"); out.print(" <td style=\"background-color: #FFFFFF; border-width: 1\">"); out.print("<a href=\"CardTypesRecord.jsp?"+transitParams+"card_type_id="+toURL((String) rsHash.get("c_card_type_id"))+"&\"><font style=\"font-size: 10pt; color: #000000\">"+toHTML(fldname)+"</font></a>"); out.println("</td>"); out.println(" </tr>"); iCounter++; } if (iCounter == 0) { // Recordset is empty out.println(sNoRecords); out.print(" <tr>\n <td colspan=\"1\" style=\"background-color: #FFFFFF; border-style: inset; border-width: 0\"><font style=\"font-size: 10pt; color: #CE7E00; font-weight: bold\">"); out.print("<a href=\"CardTypesRecord.jsp?"+formParams+"\"><font style=\"font-size: 10pt; color: #CE7E00; font-weight: bold\">Insert</font></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); out.println("</td>\n </tr>"); iCounter = RecordsPerPage+1; bIsScroll = false; } else { out.print(" <tr>\n <td colspan=\"1\" style=\"background-color: #FFFFFF; border-style: inset; border-width: 0\"><font style=\"font-size: 10pt; color: #CE7E00; font-weight: bold\">"); out.print("<a href=\"CardTypesRecord.jsp?"+formParams+"\"><font style=\"font-size: 10pt; color: #CE7E00; font-weight: bold\">Insert</font></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); out.println("</td>\n </tr>"); } if ( rs != null ) rs.close(); out.println(" </table>"); } catch (Exception e) { out.println(e.toString()); } }
7b8f53a6-7883-4088-8f13-b11ca832df1c
4
public void createNewKey(String username, boolean client,ObjectInputStream in, ObjectOutputStream out) { try { System.out.println("Initiating the key agreement protocol ..."); System.out.println("Generating a Diffie-Hellman KeyPair..."); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH"); kpg.initialize(PARAMETER_SPEC); KeyPair keyPair = kpg.genKeyPair(); Message syn; KeyAgreement ka = null; initializationVector = null; if (client) { System.out.println("Receiving the server's public key ..."); syn = (Message) in.readObject(); byte[] keyBytes = syn.getEncondedPublicKey(); KeyFactory kf = KeyFactory.getInstance("DH"); X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(keyBytes); PublicKey serverPublicKey = kf.generatePublic(x509Spec); System.out.println("Sending my public key ..."); keyBytes = keyPair.getPublic().getEncoded(); syn.setEncondedPublicKey(keyBytes); out.writeObject(syn); out.reset(); out.flush(); System.out.println("Performing the KeyAgreement..."); ka = KeyAgreement.getInstance("DH"); ka.init(keyPair.getPrivate()); ka.doPhase(serverPublicKey, true); System.out.println("Receiving the initialization vector ..."); initializationVector = new byte[8]; syn = (Message) in.readObject(); initializationVector = syn.getInitializationVector(); } else { syn=new Message(username, "NEW"); System.out.println("Sending the server public key to client: "+ username); byte[] keyBytes = keyPair.getPublic().getEncoded(); syn.setEncondedPublicKey(keyBytes); out.writeObject(syn); out.reset(); out.flush(); System.out.println("Receiving client's public key: " + username); syn = (Message) in.readObject(); keyBytes = syn.getEncondedPublicKey(); KeyFactory kf = KeyFactory.getInstance("DH"); X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(keyBytes); PublicKey clientPublicKey = kf.generatePublic(x509Spec); System.out.println("Performing the KeyAgreement..."); ka = KeyAgreement.getInstance("DH"); ka.init(keyPair.getPrivate()); ka.doPhase(clientPublicKey, true); System.out.println("Create and send the IVParameterSpec to the client: "+ username); initializationVector = new byte[8]; SecureRandom random = new SecureRandom(); random.nextBytes(initializationVector); syn.setInitializationVector(initializationVector); out.writeObject(syn); out.reset(); out.flush(); } System.out.println("Creating a session key ..."); byte[] sessionKeyBytes = ka.generateSecret(); SecretKeyFactory skf = SecretKeyFactory.getInstance("TripleDES"); DESedeKeySpec tripleDesSpec = new DESedeKeySpec(sessionKeyBytes); sessionKey = skf.generateSecret(tripleDesSpec); System.out.println("Creating the CipherStreams to be used with server..."); Cipher decrypter = Cipher.getInstance("TripleDES/CFB8/NoPadding"); Cipher encrypter = Cipher.getInstance("TripleDES/CFB8/NoPadding"); IvParameterSpec spec = new IvParameterSpec(initializationVector); encrypter.init(Cipher.ENCRYPT_MODE, sessionKey, spec); decrypter.init(Cipher.DECRYPT_MODE, sessionKey, spec); cipherOut = new ObjectOutputStream(new CipherOutputStream(out,encrypter)); cipherOut.flush(); cipherIn = new ObjectInputStream(new CipherInputStream(in, decrypter)); if (!client){ // add a new table entry for future connections SessionKey key = new SessionKey(initializationVector,sessionKey); record = new Record(username, key, System.currentTimeMillis()); } } catch (Exception e) { if (DEBUG) e.printStackTrace(); } }
3f8c0904-2ba3-4852-b4e4-a00da46f2c14
2
public static void style(Component comp) { comp.setForeground(theme.getForeground()); comp.setBackground(theme.getBackground()); if (!(comp instanceof Container)) { return; } Component[] comps = ((Container) comp).getComponents(); for (int i = 0; i < comps.length; i++) { style(comps[i]); } }
7ee427f5-4c7e-455c-be49-510def7e2f4b
6
* @param terminal Cell state that represents the terminal. * @param source Boolean indicating if the terminal is the source or target. */ public mxConnectionConstraint getConnectionConstraint(mxCellState edge, mxCellState terminal, boolean source) { mxPoint point = null; Object x = edge.getStyle() .get((source) ? mxConstants.STYLE_EXIT_X : mxConstants.STYLE_ENTRY_X); if (x != null) { Object y = edge.getStyle().get( (source) ? mxConstants.STYLE_EXIT_Y : mxConstants.STYLE_ENTRY_Y); if (y != null) { point = new mxPoint(Double.parseDouble(x.toString()), Double.parseDouble(y.toString())); } } boolean perimeter = false; if (point != null) { perimeter = mxUtils.isTrue(edge.style, (source) ? mxConstants.STYLE_EXIT_PERIMETER : mxConstants.STYLE_ENTRY_PERIMETER, true); } return new mxConnectionConstraint(point, perimeter); }
732d93be-0d03-4a90-8674-41556f9e9ad4
4
@Override public boolean testPermission(CommandSender target) { if (testPermissionSilent(target)) { return true; } if (getPermissionMessage() == null) { target.sendMessage(ChatColor.RED + "I'm sorry, but you do not have permission to perform this command. Please contact the server administrators if you believe that this is in error."); } else if (getPermissionMessage().length() != 0) { for (String line : getPermissionMessage().replace("<permission>", getPermission()).split("\n")) { target.sendMessage(line); } } return false; }
46b5b2ab-cd85-41b7-9afc-53f5e82595c6
3
private int[][] initCellValues(int rows, int columns) { int[][] values = new int[rows][columns]; int totalPoints = 0; for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { int value = map.getCellValue(r, c); values[r][c] = value; totalPoints += value > 0 ? 1 : 0; } } values[0][0] = totalPoints; return values; }
2a709906-e3dc-4232-99a5-58b28801493d
9
private void buildMenu() { boolean exit = false; int type = findType(id); if (type == TYPE_PATIENT) { System.out.println("Welcome patient " + id + " here is the list of your record(s):"); patientMenu(id, id); } else if (type == TYPE_DOCTOR) { System.out.println("Welcome doctor, what would you like to do?"); do { System.out.println("1. Read a record"); System.out.println("2. Write to a record"); System.out .println("3. Add a new record to an existing patient"); int choice = sc.nextInt(); docMenu(choice, id); System.out.println("Would you like to exit? Y/N"); String s = sc.next(); exit = s.equals("Y") || s.equals("y"); } while (!exit); } else if (type == TYPE_NURSE) { System.out.println("Welcome nurse, what would you like to do?"); do { System.out.println("1. Read a record"); System.out.println("2. Write to a record"); int choice = sc.nextInt(); nurseMenu(choice, id); System.out.println("Would you like to exit? Y/N"); String s = sc.next(); exit = s.equals("Y") || s.equals("y"); } while (!exit); } else { System.out .println("Welcome goverment agency, what would you like to do?"); do { System.out.println("1. Read a record"); System.out.println("2. Delete a record"); int choice = sc.nextInt(); govMenu(choice, id); System.out.println("Would you like to exit? Y/N"); String s = sc.next(); exit = s.equals("Y") || s.equals("y"); } while (!exit); } }
61f3954c-45ea-4fd5-a7d2-422562dd2ed6
4
public static int getSailplaneVelocityUnit() throws ClassNotFoundException { int velocityUnit = 0; try{ //Class derbyClass = RMIClassLoader.loadClass("lib/", "derby.jar"); Class.forName(driverName); Class.forName(clientDriverName); }catch(java.lang.ClassNotFoundException e) { throw e; } try (Connection connect = DriverManager.getConnection(databaseConnectionName)) { Statement stmt = connect.createStatement(); ResultSet thePilots = stmt.executeQuery("SELECT velocity_unit " + "FROM SailplaneUnits " + "WHERE unit_set = 0"); while(thePilots.next()) { try { velocityUnit = Integer.parseInt(thePilots.getString(1)); }catch(NumberFormatException e) { //TODO What happens when the Database sends back invalid data JOptionPane.showMessageDialog(null, "Number Format Exception in reading from DB"); } } thePilots.close(); stmt.close(); }catch(SQLException e) { JOptionPane.showMessageDialog(null, e.getMessage()); return -1; } return velocityUnit; }
4638469c-66f0-4606-8074-3e38b7dc71c4
3
private void disconnect(int id, boolean status) { ServerClient c = null; for (int i = 0; i < clients.size(); i++) if (clients.get(i).getID() == id) { c = clients.get(i); clients.remove(i); break; } String message = ""; if (status) { message = "Client " + c.name.trim() + " (" + c.getID() + ") @ " + c.address.toString() + ":" + c.port + " disconnected."; } else { message = "Client " + c.name.trim() + " (" + c.getID() + ") @ " + c.address.toString() + ":" + c.port + " timed out."; } System.out.println(message); }
2c828111-4732-440f-aa91-8b408b839b2c
3
public void financeManager(){ if (turretBuilder.size() != 0){ if (turretBuilder.get(turretsPlaced).buy()+turretsPlaced*5 > player.getGold()){ turretBuilder.remove(turretsPlaced); } else{ player.moneyLoss(turretBuilder.get(turretsPlaced).buy()+turretsPlaced*5); int loop; for(loop = 0; loop < 5; loop++){ glassDisplay[loop].adjustCost(true); } holdingTurret = true; playSound("TurretPurchase.wav"); turretHolder.start(); } repaint(); } }