method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
c2afdfa0-0995-4d39-957e-e9cd19ba2e20
5
@Override public void preform(int source) { if(source == 0) { openNewGui(References.GUI_LOBBY); }else if(source == 1) { Object ip = JOptionPane.showInputDialog("Set IP address to join."); if(ip != null && ip instanceof String) { Rocket.getRocket().properties.IP = (String) ip; } }else if(source == 2) { closeGui(this); } }
177e53e5-07ec-4152-89d2-f08fd7094778
7
private Region createRegion(Attributes atts) { String abbyyType = null; int i; if ((i = atts.getIndex(ATTR_blockType)) >= 0) { abbyyType = atts.getValue(i); } RegionType primaType = RegionType.UnknownRegion; if ("Text".equals(abbyyType)) primaType = RegionType.TextRegion; else if ("Table".equals(abbyyType)) primaType = RegionType.TableRegion; else if ("Picture".equals(abbyyType)) primaType = RegionType.ImageRegion; else if ("Barcode".equals(abbyyType)) primaType = RegionType.GraphicRegion; else if ("Separator".equals(abbyyType)) primaType = RegionType.SeparatorRegion; else if ("SeparatorsBox".equals(abbyyType)) primaType = RegionType.SeparatorRegion; return layout.createRegion(primaType); }
de1efc02-30bc-4ad7-bad3-5fca6bc13acb
7
public int readB(int bits) { int ret; int m = 32 - bits; bits += endbit; if (endbyte + 4 >= storage) { /* not the main path */ ret = -1; if (endbyte * 8 + bits > storage * 8) { ptr += bits / 8; endbyte += bits / 8; endbit = bits & 7; return (ret); } } ret = (buffer[ptr] & 0xff) << (24 + endbit); if (bits > 8) { ret |= (buffer[ptr + 1] & 0xff) << (16 + endbit); if (bits > 16) { ret |= (buffer[ptr + 2] & 0xff) << (8 + endbit); if (bits > 24) { ret |= (buffer[ptr + 3] & 0xff) << (endbit); if (bits > 32 && (endbit != 0)) { ret |= (buffer[ptr + 4] & 0xff) >> (8 - endbit); } } } } ret = (ret >>> (m >> 1)) >>> ((m + 1) >> 1); ptr += bits / 8; endbyte += bits / 8; endbit = bits & 7; return (ret); }
3affe512-ce5a-4948-a231-c67616ef92f4
8
public static void main(String[] args) { Random rand = new Random(47); for(int i = 0; i < 100; i++) { int c = 'a' + rand.nextInt(26); System.out.print((char)c + ", " + c + ": "); switch(c) { case 'a': case 'e': case 'i': case 'o': case 'u': System.out.println("vowel"); break; case 'y': case 'w': System.out.println("Sometimes a vowel"); break; default: System.out.println("consonant"); } } }
9bb7fcb8-a2c6-4756-95d6-8a2cbc632c0f
9
public void printUrkunden() { if (table.getSelectedRowCount() == 0) return; List<EinzelWettkampf> lewk = new Vector<EinzelWettkampf>(); List<MannschaftsWettkampf> lmwk = new Vector<MannschaftsWettkampf>(); for (int i : table.getSelectedRows()) { Wettkampf w = (Wettkampf) table.getValueAt(i, -1); if (w instanceof EinzelWettkampf) lewk.add((EinzelWettkampf) w); if (w instanceof MannschaftsWettkampf) lmwk.add((MannschaftsWettkampf) w); } boolean ok = true; for (EinzelWettkampf w : lewk) { try { AuswertungService.printUrkunden(AuswertungService.getAuswertung(w)); } catch (Exception e) { AxtresLogger.error("Beim erstellen der Urkunden ist ein Fehler aufgetreten.", e); ok = false; } } for (MannschaftsWettkampf w : lmwk) { try { AuswertungService.printUrkunden(AuswertungService.getAuswertung(w)); } catch (Exception e) { AxtresLogger.error("Beim erstellen der Urkunden ist ein Fehler aufgetreten.", e); ok = false; } } if (!ok) JOptionPane.showMessageDialog(this, "Beim erstellen der Urkunden ist ein Fehler aufgetreten.", "Fehler", JOptionPane.ERROR_MESSAGE); }
a341170a-d46b-4f15-9055-f60569ece3bf
3
public static String toString(JSONObject o) throws JSONException { boolean b = false; Iterator keys = o.keys(); String s; StringBuffer sb = new StringBuffer(); while (keys.hasNext()) { s = keys.next().toString(); if (!o.isNull(s)) { if (b) { sb.append(';'); } sb.append(Cookie.escape(s)); sb.append("="); sb.append(Cookie.escape(o.getString(s))); b = true; } } return sb.toString(); }
69245e08-4f11-4aa9-864c-54648ffcb465
1
public void mouseDragged(MouseEvent event) { if (myTrapState == null) return; myTrapState.setPoint(event.getPoint()); getView().repaint(); }
78a9cec9-e207-4fe4-b26a-90140fd11200
5
protected void save() { ImageSettings imageSettings = null; IndexerState indexerState = null; WindowSettings windowSettings = null; for (SaveSubscriber s : subscribers) { if (imageSettings == null) { imageSettings = s.saveImageSettings(); } if (indexerState == null) { indexerState = s.saveIndexerState(); } else { indexerState.combine(s.saveIndexerState()); } if (windowSettings == null) { windowSettings = s.saveWindowSettings(); } else { windowSettings.combine(s.saveWindowSettings()); } } if (imageSettings == null) { indexerState = null; } this.saveImageSettings(imageSettings); this.saveIndexerState(indexerState); this.saveWindowSettings(windowSettings); }
9959b724-c14a-40af-8a15-4d5eb81be510
9
public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int mod = Integer.parseInt(st.nextToken()); int[] a = new int[n]; for(int i=0; i<m; i++){ String s = br.readLine(); for(int j=0; j<n; j++) a[j]+=s.charAt(j)-'0'; } long[][] dp = new long[n+1][n+1]; int[] count = new int[2]; for(int i=0; i<n; i++){ if(a[i]<2) count[a[i]]++; } dp[count[0]][count[1]]=1; for(int i=n; i>=0; i--){ for(int j=n-i; j>=0; j--){ if(i>=2) dp[i-2][j+2] = (dp[i-2][j+2]+dp[i][j]*i*(i-1)/2)%mod; if(i>=1) dp[i-1][j] = (dp[i-1][j]+dp[i][j]*i*j)%mod; if(j>=2) dp[i][j-2] = (dp[i][j-2]+dp[i][j]*j*(j-1)/2)%mod; } } System.out.println(dp[0][0]); }
dbfda627-38a4-4d08-9ca9-8713889527ff
8
public final void startElement(java.lang.String ns, java.lang.String name, java.lang.String qname, Attributes attrs) throws SAXException { dispatch(true); context.push(new Object[]{qname, new org.xml.sax.helpers.AttributesImpl(attrs)}); if ("edge".equals(qname)) { handler.start_edge(attrs); } else if ("locator".equals(qname)) { handler.handle_locator(attrs); } else if ("node".equals(qname)) { handler.start_node(attrs); } else if ("graph".equals(qname)) { handler.start_graph(attrs); } else if ("endpoint".equals(qname)) { handler.start_endpoint(attrs); } else if ("graphml".equals(qname)) { handler.start_graphml(attrs); } else if ("hyperedge".equals(qname)) { handler.start_hyperedge(attrs); } else if ("port".equals(qname)) { handler.start_port(attrs); } }
cd11ae10-e6e2-445d-9cd8-215c8d9192c7
7
@Override public void ParseIn(Connection Main, Server Environment) { Room Room = Environment.RoomManager.GetRoom(Main.Data.CurrentRoom); if (Room == null) { return; } if((Room.Flags & Server.rmAllowPets) != Server.rmAllowPets && !Room.CheckRights(Main.Data, true)) { Environment.InitPacket(608, Main.ClientMessage); Environment.Append(1, Main.ClientMessage); Environment.EndPacket(Main.Socket, Main.ClientMessage); return; } if (Room.PetCounter >= 5) { Environment.InitPacket(608, Main.ClientMessage); Environment.Append(2, Main.ClientMessage); Environment.EndPacket(Main.Socket, Main.ClientMessage); return; } int PetId = Main.DecodeInt(); Pet Pet = Main.GetPet(PetId); if (Pet == null) { return; } int X = Main.DecodeInt(); int Y = Main.DecodeInt(); if (!Room.CanWalk2(X, Y, true)) { Environment.InitPacket(608, Main.ClientMessage); Environment.Append(4, Main.ClientMessage); Environment.EndPacket(Main.Socket, Main.ClientMessage); return; } RoomBot Bot = new RoomBot(Pet.Id, Pet.Name, "", Pet.Type + " " + Pet.Race + " " + Pet.Color); Double Z = Room.SqAbsoluteHeight(X, Y, false, null); RoomUser PetUser = Room.DeployPet(Bot, Pet, X, Y, Z); if (PetUser == null) { return; } Environment.InitPacket(604, Main.ClientMessage); Environment.Append(Pet.Id, Main.ClientMessage); Environment.EndPacket(Main.Socket, Main.ClientMessage); Main.Data.InventoryPets.remove(Pet.Id); }
12b53d37-b19e-4b80-9805-798b254ba1b1
3
*@param nick * @return resultado **/ public beansMiembro buscarDentroDownline(beansMiembro miembro, String nick){ for(beansMiembro busquedaInterior : miembro.getListaInterna() ){ if(busquedaInterior.getNick().equals(nick)){ return busquedaInterior; }else{ resultado = buscarDentroDownline(busquedaInterior, nick); if(resultado != null) return resultado; } } return null; }
894ba0a5-de15-4f02-ac4f-0e5424d305db
6
@Test public void toolsTest2() { userInput.add("hello"); userInput.add("daniel"); userInput.add("can you help me with cooking"); userInput.add("tell me the tools"); userInput.add("hamburger"); userInput.add("tools"); runMainActivityWithTestInput(userInput); assertTrue(nlgResults.get(2).contains("what") || nlgResults.get(2).contains("What") && nlgResults.get(3).contains("what") || nlgResults.get(3).contains("What") || nlgResults.get(3).contains("name") && nlgResults.get(4).contains("hamburger") && nlgResults.get(5).contains("knife")); }
c8250088-9f5e-4dfb-b833-3a9b92cee688
7
public boolean supprimerRessource(String typeRessource, int nombre) { if (nombre > 0) { if(typeRessource.equals(Constantes.RESS_NOURRITURE)) { if (nbNourriture - nombre < 0) { return false; } nbNourriture -= nombre; return true; } if(typeRessource.equals(Constantes.RESS_PIERRE)) { if (nbPierre - nombre < 0) { return false; } nbPierre -= nombre; return true; } if(typeRessource.equals(Constantes.RESS_TERRE)) { if (nbTerre - nombre < 0) { return false; } nbTerre -= nombre; return true; } } return false; }
8931790e-3edd-446e-973d-258c3a1f2532
3
public static PathwayElement createState( double relX, double relY, double width, double height, Color color, int lineStyle, int lnThickness, Color fillColor, IShape shapeType, int zOrder, DataSource database, String ID, List<String> bioPaxRefs, String graphId, String graphRef, String textLabel, String stateType) { // create pathwayElement State PathwayElement pwElt = PathwayElement.createPathwayElement(ObjectType.STATE); // for better definition of identifier and database Xref ref = new Xref(ID, database); pwElt.setRelX(relX); pwElt.setRelY(relY); pwElt.setMWidth(width); pwElt.setMHeight(height); pwElt.setColor(color); pwElt.setLineStyle(lineStyle); pwElt.setLineThickness(lnThickness); pwElt.setFillColor(fillColor); pwElt.setShapeType(shapeType); pwElt.setZOrder(zOrder); pwElt.setDataSource(ref.getDataSource()); pwElt.setElementID(ref.getId()); pwElt.setGraphId(graphId); pwElt.setGraphRef(graphRef); pwElt.setTextLabel(textLabel); if (stateType == "unknown") {} else {} if (bioPaxRefs.size() > 0) { for (int i = 0; i < bioPaxRefs.size(); i++) { pwElt.addBiopaxRef(bioPaxRefs.get(i)); } } return pwElt; }
0553b018-eb11-44c1-a41b-e0b225baa178
5
public byte[] delete(InputStream is, int fStart, int fEnd) throws Exception{ int cont = 0; Manager reader = new Manager(is); if( fStart > fEnd ){ throw new Exception("fStart can't be greater than fEnd!!"); } FrameData fd ; final int opt = Constants.HUFFMAN_DOMAIN; do{ try{ fd = reader.decodeFrame(opt); } catch (Exception e){ LOGGER.info("End of file"); break; } // effects if (cont < fStart || cont > fEnd){ reader.storeData(fd, reader.getMainData()); } cont++; } while(true); mp3_byte_stream = reader.getStream(); return mp3_byte_stream; }
f338a369-047a-4c34-8519-ee92a73ccd8b
4
private String getRemoteRecipe(long ID, String Title, String Brewer, int iteration) { try { String baseURL = Options.getInstance().getProperty("cloudURL"); if (!baseURL.startsWith("http://")) { baseURL = "http://" + baseURL; } URL url = new URL(baseURL+"/recipes/"+ID); InputStream response = url.openStream(); HttpURLConnection huc = ( HttpURLConnection ) url.openConnection (); huc.setRequestMethod ("GET"); huc.connect () ; int code = huc.getResponseCode ( ) ; if(code != 200) { JOptionPane.showMessageDialog(null, "Couldn't find the selected recipe (ID "+ ID +")"); huc.disconnect(); this.close = true; return "" ; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setIgnoringComments(false); dbf.setIgnoringElementContentWhitespace(true); dbf.setNamespaceAware(true); // dbf.setCoalescing(true); // dbf.setExpandEntityReferences(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); //db.setEntityResolver(new NullResolver()); // db.setErrorHandler( new MyErrorHandler()); Document readXML = db.parse(response); // check if we already have this file String file = Title + " - " + Brewer + " ("+ iteration + ").xml"; File recipeFile = new File(currentDir, file); if(recipeFile.exists()) { JOptionPane.showMessageDialog(null, "This file already exists!"); return recipeFile.getAbsolutePath(); } Debug.print("Writing recipe file: " + recipeFile.getAbsolutePath()); // file doesn't exist, lets dump the file Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(readXML); transformer.transform(source, result); OutputStream oStream = new FileOutputStream(recipeFile); String outXML = result.getWriter().toString(); oStream.write(outXML.getBytes(Charset.forName("UTF-8"))); oStream.close(); return recipeFile.getAbsolutePath(); } catch (Exception e) { e.printStackTrace(); return ""; } }
df9fbb8f-0fbf-4c8a-8daa-38812b54e80a
8
@SuppressWarnings("unchecked") private Map<MarketQuotesResponseField, String> getMarketQuotePaths(Document doc) throws UtilityException { Map<MarketQuotesResponseField, String> toReturn = new HashMap<MarketQuotesResponseField, String>(); for (MarketQuotesResponseField f : MarketQuotesResponseField.values()) { String[] paths = f.getPaths(); if (f.equals(MarketQuotesResponseField.ERROR)) { if (paths != null) { for (String path : paths) { List<DefaultElement> list = doc.selectNodes(path); for (Iterator<DefaultElement> iter = list.iterator(); iter.hasNext();) { DefaultElement attribute = iter.next(); String url = attribute.getText(); throw new UtilityException(url); } } } } if (paths != null) { for (String path : paths) { List<DefaultElement> list = doc.selectNodes(path); for (Iterator<DefaultElement> iter = list.iterator(); iter.hasNext();) { DefaultElement attribute = iter.next(); String url = attribute.getText(); toReturn.put(f, url); } } } } return toReturn; }
36d7f2ee-aaa7-481d-aa09-8f4d65eb6992
8
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(Hauptfenster.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Hauptfenster.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Hauptfenster.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Hauptfenster.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() { try { new Hauptfenster().setVisible(true); } catch (FileNotFoundException ex) { Logger.getLogger(Hauptfenster.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Hauptfenster.class.getName()).log(Level.SEVERE, null, ex); } } }); }
5a99649d-9c0c-455f-984b-3d02cda0a807
4
@Override public UserDetails getValue(HttpContext context) { UserDetails userDetails = null; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!(auth instanceof AnonymousAuthenticationToken)) { userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } if (userDetails == null && authenticationRequired){ throw new WebApplicationException( Response .status(Response.Status.UNAUTHORIZED) .entity("Unauthorized") .header("WWW-Authenticate", "Basic realm='innovationgateway.us'") .type(MediaType.TEXT_PLAIN) .build() ); } if (userDetails == null ) { userDetails = new AnonymousUserDetails(); } return userDetails; }
e0191f42-7ae7-466d-8806-9ec7dfceac54
1
public DataOut getData(int index){ if(listDataOut != null) return listDataOut.get(index); else return null; }
c0393cbb-a180-431a-b2d6-1df18eb1631e
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(ModifierPharmacie.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ModifierPharmacie.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ModifierPharmacie.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ModifierPharmacie.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 ModifierPharmacie().setVisible(true); } }); }
23299d75-aca0-45d5-add8-e0f9d2acea29
3
public SpriteSheet(String path, int tileWidth, int tileHeight, int gid) { this.firstGID = gid; Image img = null; try { img = new Image(path); } catch (SlickException e) { e.printStackTrace(); } int imgWidth = img.getWidth(); int imgHeight = img.getHeight(); numTilesX = (int) Math.floor(imgWidth / tileWidth); numTilesY = (int) Math.floor(imgHeight / tileHeight); subImages = new Image[numTilesY][numTilesX]; for (int i = 0; i < numTilesY; i++) { for (int j = 0; j < numTilesX; j++) { subImages[i][j] = img.getSubImage(j * tileWidth, i * tileHeight, tileWidth, tileHeight); } } }
d074b7f1-8025-438e-8b49-461812d133ba
6
public static int position(Byte[] jeu, byte player){ int val=0; byte opponent=0; Byte empty = 0; if (player == 1) opponent = 2; else if (player == 2) opponent = 1; else System.out.println("erreur IA"); /* POSITION IA */ int [] tabIA = {50, 15, 50, 1000, 40, 25, 25, 50, 50, 40, 25, 25, 50, 25, 15, 60, 30, 30, 50, 25, 25, 50, 30, 50, 50, 30, 25, 40, 75, 75, 50, 30, 40, 1000000000, 75, 30, 60 }; /* 0, 1, 2, 3 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 15, 16, 17, 18, 19, 20, 21 22, 23, 24, 25, 26, 27 28, 29, 30, 31, 32, 33, 34, 35, 36 */ for (int i=0; i<37; i++){ if (jeu[i] == player){ val += tabIA[i]; } } // if ((jeu[22] == player) && (jeu[28] != opponent)) val += 120; // if ((jeu[35] == player) && (jeu[34] != opponent)) val += 120; // // if (jeu[29] == player){ // if ((jeu[28] != opponent) || (jeu[34] != opponent)) // val += 50; // } // // if ((jeu[23] == player) && (jeu[22] != opponent)) val += 20; // if ((jeu[30] == player) && (jeu[35] != opponent)) val += 20; // // // if (((jeu[24] == player) && (jeu[18] == player)) || ((jeu[18] == player) && (jeu[12] == player))) // val += 30; // // // if ((jeu[28] == player || jeu[29] == player || jeu[34] == player) && jeu[33] == 0) //sur le point de gagner // val += 1000; ////////////////\\\\\\\\\\\\\\\\ //////// POSITION JOUEUR \\\\\\\\\ //////////////////\\\\\\\\\\\\\\\\\\ int [] tabJoueur = {60,30,100,1000000000, 40,30,50,100,100, 40,25,30,50,50,30, 50,25,25,50,30,30,60, 15,25,50,25,25,40, 50,50,25,25,40, 1000,50,15,50}; for (int i=0; i<37; i++){ if (jeu[i] == opponent){ val -= tabJoueur[i]; } } // if ((jeu[2] == opponent || jeu[7] == opponent || jeu[8] == opponent) && jeu[3] == empty) //sur le point de perdre // val -= 1000; // // if (jeu[12] == opponent) { // if (jeu[7] == 0) val -= 75; // else val -= 50; // // } // if (jeu[6] == opponent) { // if (jeu[1] == player || jeu[2] == player || jeu[7] == player) // val -=50; // else val -= 75; // // } // if (jeu[13] == opponent) { // if (jeu[7] == player || jeu[8] == player || jeu[14] == player) // val -= 50; // else // val -= 75; // } // if (jeu[4] == opponent){ // if (jeu[0] == player) // val -= 50; // else // val -= 75; // } // if (jeu[27] == opponent){ // if (jeu[21] == player) // val -= 50; // else // val -= 75; // } // if (jeu[1] == opponent && (jeu[0] == opponent || jeu[0] == player)) { // if (jeu[2] == player && jeu[3] == 0) // val -= 1000; // else // val -= 25; // } // if (jeu[14] == opponent && (jeu[21] == opponent || jeu[21] == player)) { // if (jeu[8] == player && jeu[3] == 0) // val -= 1000; // else // val -= 25; // } // if (jeu[0] == opponent || jeu[21] == opponent ) val -= 100; //////////////////////////////////////////////////////// return val; }
c60173da-e7b0-41f6-8ae4-461526600635
3
public static ArrayList<bConsultaCompo> getPesquisaCompoAt(String prod, String data_in) throws SQLException, ClassNotFoundException { ArrayList<bConsultaCompo> sts = new ArrayList<bConsultaCompo>(); Connection conPol = conMgr.getConnection("PD"); ResultSet rs; if (conPol == null) { throw new SQLException("Numero Maximo de Conexoes Atingida!"); } try { call = conPol.prepareCall("{call sp_consulta_componemteAt(?,?)}"); call.setString(1, prod); call.setString(2, data_in); rs = call.executeQuery(); while (rs.next()) { bConsultaCompo reg = new bConsultaCompo(); reg.setCont(rs.getInt("f1")); reg.setCod_prod(rs.getString("f2")); reg.setStr_compo(rs.getString("f3")); reg.setDescricao1(rs.getString("f4")); sts.add(reg); } } finally { if (conPol != null) { conMgr.freeConnection("PD", conPol); } } return sts; }
447ee9ed-2188-48bb-9416-79d4088f9fd8
3
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final WorkPlace other = (WorkPlace) obj; if (!Objects.equals(this.workPlaceId, other.workPlaceId)) { return false; } return true; }
0cdc38cc-2b1b-473b-af9d-337fe3a44ff0
0
public CarBuilder setTintedGlass(boolean tintedGlass) { delegate.setTintedGlass(tintedGlass); return this; }
f9a3bbb3-fd8f-4875-9aae-40fbc09dbe1d
1
public void removeRange(int fromIndex, int toIndex) { int numMoved = size - toIndex; System.arraycopy(attributeLists, toIndex, attributeLists, fromIndex, numMoved); int newSize = size - (toIndex - fromIndex); while (size != newSize) { attributeLists[--size] = null; } }
cae4ed70-60ce-4a9f-865e-bba107e2e412
6
public static GRESCAnswer fromText(String text) { GRESCAnswer gAnswer = new GRESCAnswer(); if (text != null && text.length() > GRE_ANSWER_INDICATOR.length()) { int answerIndex = text.indexOf(GRE_ANSWER_INDICATOR); if (answerIndex != -1) { String[] answers = text.substring(answerIndex + GRE_ANSWER_INDICATOR.length(), text.length()).split(" "); for (String answer : answers) { if (GRESCOption.isValidOption(answer)) { gAnswer.answers.add(answer); } } } } if (gAnswer.answers.size() == 0) { SparkUtils.getLogger().severe("ai"); } return gAnswer; }
7eeb7314-6dca-439d-bdf3-a0e06fe51169
6
public void gen_where(final Map<String, Object> context, final QLSelect select, final PrintWriter out) { final Class<?> clazz = (Class<?>) context.get("class"); if (clazz == null) { throw new IllegalArgumentException("context not contains 'class'"); } final QLExpr where = select.getWhere(); if (where == null) { return; } final QLLimit limit = select.getLimit(); QLAstVisitorAdapter setTypeVisitor = new SetTypeVisitor(clazz); where.accept(setTypeVisitor); out.print(" if("); QLAstVisitor visitor = new WhereGenOutputVisitor(out, clazz); where.accept(visitor); out.println(") {"); if (limit != null && select.getOrderBy() == null) { out.println(" if (_dest_.size() >= rowCount) {"); out.println(" break;"); out.println(" }"); } out.println(" " + destCollectionName + ".add(item);"); out.println(" }"); out.println(); }
74022f07-f2cc-445e-912c-1c6cc66b1239
7
public static final void write(final Define define, final File directory) { if (define == null || directory == null) { return; } OutputStream outputStream = null; try { String fileName = define.getProxyClassName().replace('/', File.separatorChar).concat(".class"); File file = new File(directory, fileName); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } if (!file.exists()) { file.createNewFile(); } outputStream = new FileOutputStream(file); outputStream.write(define.getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { } } } }
bac97245-1cb5-484c-91a0-556626650701
2
public boolean replaceSubBlock(StructuredBlock oldBlock, StructuredBlock newBlock) { for (int i = 0; i < 2; i++) { if (subBlocks[i] == oldBlock) { subBlocks[i] = newBlock; return true; } } return false; }
901ee9a1-9909-42ea-b59e-6fd5d0b0e1d6
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ConsultantSales)) { return false; } ConsultantSales other = (ConsultantSales) object; if ((this.salesId == null && other.salesId != null) || (this.salesId != null && !this.salesId.equals(other.salesId))) { return false; } return true; }
c5498eab-d091-44f6-8638-dd6ea715525c
4
private Point getPoint(int x, int y){ if (x < 0|| y < 0 || x >= FIELD_SIZE || y >= FIELD_SIZE){ return null; } return points[x][y]; }
69f9a311-064a-4eff-9cc8-87813e517907
5
public ArrayList<Integer> getNeighbors(int position) { ArrayList<Integer> neighborIndexes = new ArrayList<Integer>(); int x = position % columns; int y = position / columns; ArrayList<Point> neighbors = new ArrayList<Point>(); neighbors.add(new Point(x - 1, y - 1)); neighbors.add(new Point(x, y - 1)); neighbors.add(new Point(x + 1, y - 1)); neighbors.add(new Point(x + 1, y)); neighbors.add(new Point(x + 1, y + 1)); neighbors.add(new Point(x, y + 1)); neighbors.add(new Point(x - 1, y + 1)); neighbors.add(new Point(x - 1, y)); for (Point p : neighbors) { if ((p.x < 0) || (p.x > columns - 1) || (p.y < 0) || (p.y > rows - 1)) { continue; } neighborIndexes.add(p.x + p.y * columns); } return neighborIndexes; }
2cfec8e5-321d-4d03-881f-ba2ea4f5b518
4
@Test public void testCardTypes() { // make new sets (since they wont store repeats) Set<Card> personCards = new HashSet<Card>(); Set<Card> weaponCards = new HashSet<Card>(); Set<Card> roomCards = new HashSet<Card>(); // store all cards in correct set for(Card c : game.getCards()) { if (c.getType() == Card.CardType.PERSON) personCards.add(c); else if (c.getType() == Card.CardType.WEAPON) weaponCards.add(c); else if (c.getType() == Card.CardType.ROOM) roomCards.add(c); } // test the set sizes. This also checks that there were no repeats due to the Set data structure Assert.assertEquals(6, personCards.size()); Assert.assertEquals(6, weaponCards.size()); Assert.assertEquals(9, roomCards.size()); }
6e0e2542-e72d-4774-9b80-401c27b7dca6
2
@Override public void mousePressed(MouseEvent e) { if (e.getButton() != MouseEvent.BUTTON1) { System.out.println(e.getButton()); return; } ptPress = e.getPoint(); final Panel screen = (Panel) e.getSource(); try { win.getModel().add(getNewElement(ptPress, ptPress)); screen.repaint(); } catch (final NoShapeChosenException e1) { ptPress = null; } }
569da99f-8401-4ec7-b5ab-e39509eb7078
3
public static void generate(int[] result, int N, ArrayList<String[]> a) { if (result.length == N) { a.add(print(result)); } else { for (int i=0; i<result.length; i++) { result[N] = i; if (isConsistent(result, N)) generate(result, N+1, a); } } }
f3b6135a-122e-4633-a3cb-18319c3a956e
0
public void setRegEx(String regex) {this.regex = regex;}
c908fd4f-cdab-4f69-85d8-f9e0779314b8
3
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Position other = (Position) obj; if (this.x != other.x) { return false; } return this.y == other.y; }
c8c075cf-4cdd-4bbc-ba4f-f56751637115
1
public int getPosition() { int position = lastPosition; AudioDevice out = audio; if (out!=null) { position = out.getPosition(); } return position; }
676a0e38-b3a7-4ff3-9995-8c6e37a794b2
8
synchronized protected void negotiate() throws IOException { if(this.input != null) try { this.input.close(); } catch(IOException f) { } if(this.output != null) try { this.output.close(); } catch(IOException f) { } if(this.socket != null) try { this.socket.close(); } catch(IOException f) { } this.socket = new Socket(host, port); this.socket.setTcpNoDelay(true); this.socket.setKeepAlive(true); this.input = new DataInputStream(socket.getInputStream()); this.output = new DataOutputStream(socket.getOutputStream()); long thisBlockCount = NBDUtil.readHello(input, writableExpected); if(this.blockCount != null) { if((long)this.blockCount != thisBlockCount) throw new RuntimeException(String.format("device size changed during renegotiation! Was %d, now %d", this.blockCount, thisBlockCount)); } else { this.blockCount = thisBlockCount; } }
f77b5a67-285f-4cf3-8b08-3990ad8fa1bf
1
public static void convert_to_binary(Integer n) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 32; i++) { sb.append(n >> i & 1); } sb.reverse(); System.out.println(sb.substring(sb.indexOf("1"))); }
a3fdac4e-8c1d-4742-87f6-77b10a6c36e1
8
public void triggerSubscribe(final boolean isSource, final TransactionDataDescription dataDescription, final Collection<InnerDataSubscription> subscriptions) throws OneSubscriptionPerSendData { if (_attributeGroup == null || _receiveAspect == null || _sendAspect == null) { throw new IllegalStateException("Das verwendete Datenmodell unterstützt keine Transaktionen."); } final long id = generateRequestId(); try { sendBytes( _connection.getLocalDav(), id, isSource ? SUBSCRIBE_TRANSMITTER_SOURCE : SUBSCRIBE_TRANSMITTER_DRAIN, serializeTransactionSubscriptions(dataDescription, subscriptions), _connection.getLocalApplicationObject() ); } catch(IOException e) { throw new IllegalStateException(e); } synchronized(_answerIdMap){ while(!_answerIdMap.containsKey(id)){ try { _answerIdMap.wait(); } catch(InterruptedException e) { throw new IllegalStateException(e); } } final Result answer = _answerIdMap.get(id); if(answer.getRequestKind() != ANSWER_OK) { throw new OneSubscriptionPerSendData(new String(answer.getBytes())); } } }
526f6c73-c841-438e-baa6-5b7722554ffd
1
public static void setField(Field field, Object target, Object value) { try { field.set(target, value); } catch (IllegalAccessException ex) { handleReflectionException(ex); throw new IllegalStateException( "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage()); } }
32e5044a-44de-436f-a41a-c91edef7f5c3
2
public void changeDelimiter(char newDelim) throws BadDelimiterException { if (newDelim == delimiter) return; // no need to do anything. if (!charIsSafe(newDelim)){ throw new BadDelimiterException(newDelim + " is not a safe delimiter."); } updateCharacterClasses(delimiter, newDelim); // keep a record of the current delimiter. delimiter = newDelim; }
b9f1a3fa-65d0-47fb-ba51-340afeb9134b
7
public static void main (String str[]){ //Ready Set Go! initialize(); //Trololololol int kappaX = -100; final int kappaY = EZ.getWindowHeight()-550; EZImage kappa = EZ.addImage("resources/kappa.png", kappaX , kappaY); //The object for the ball and paddle PongBall ball = new PongBall(Color.WHITE, PongPad.doFill()); PongPad pad = new PongPad(); //The Game Loop while(PongPause.isRunning()){ PongPause.pause(); //This is nothing... Nothing too worrying if(EZInteraction.wasKeyPressed('t') && !troll){ troll = true; kappaX = -100; } if(troll){ kappa.show(); kappa.translateTo(kappaX, kappaY); if(kappaX != 1550) kappaX+=3; if(kappaX >= 1550){ kappa.hide(); troll = false; } } //game logic, will activate when pause is false if(!PongPause.isPaused()){ PongMessage.hideMessage(); PongSound.loopSound("tetris"); PongSound.stopSound(); pad.padMove(); pad.checkPad(); ball.ballBounce(); //Set the players' current score PongMessage.scoreMessage(); } //Do awesome magic stuff that allows morals to see the animations and score changes EZ.refreshScreen(); }//while loop end System.exit(0); // I think there's a better way... }//main() end
50cc5601-b029-4aba-9d88-0ef8618f4e08
1
public void draw(Graphics g) { if (nextGlied != null) { nextGlied.draw(g); } Rectangle masse = getAbsoluteRect(); g.setColor(color); g.fillOval((int)masse.getX(), (int)masse.getY(), (int)masse.getWidth(), (int)masse.getHeight()); }
b24ce261-3fd6-43a2-adf1-47c450d304fd
6
public void generater(int x, int w, byte type) { /* for (int i = 0; i <= 30; i++) { ClearCircle(x+random.nextInt(w),y+random.nextInt(h),random.nextInt(w/2)); } generateSandAndWater();*/ float vs = -random.nextInt(12),grav = random.nextFloat(), time = 12; for (int e = x; e < x+w; e++) { if (random.nextInt(1200)==5) { entityList.add(new HouseEntity(5+e,maGenH,12+random.nextInt(24),12+random.nextInt(24))); } maGenH=(maGenH>700)?700:(maGenH<10)?10:maGenH; for (int i = maGenH; i < h; i++)cellData[e][i] = type; maGenH+=vs; vs+=grav; if (e % time == 0) { time = random.nextInt(30)+1; grav = random.nextFloat(); vs = -random.nextInt(8); } } }
5cd54549-805a-4c3d-8d7a-d3298c42a592
3
@Test public void test() { try { MarketQuote quote = new MarketQuote(new Symbol("SIRI")); for(MarketQuotesResponseField f: MarketQuotesResponseField.values()) { if(quote.hasField(f)) { System.out.println(f.name()+"="+quote.getField(f)); } } assertTrue("Expected Field not in response",quote.hasField(MarketQuotesResponseField.DATE_TIME)); } catch (ModelException e) { fail(); } }
f5427fb2-d140-49d4-b580-0a38c8755f0a
4
protected String compressJavaScript(String source) { //set default javascript compressor if(javaScriptCompressor == null) { YuiJavaScriptCompressor yuiJsCompressor = new YuiJavaScriptCompressor(); yuiJsCompressor.setNoMunge(yuiJsNoMunge); yuiJsCompressor.setPreserveAllSemiColons(yuiJsPreserveAllSemiColons); yuiJsCompressor.setDisableOptimizations(yuiJsDisableOptimizations); yuiJsCompressor.setLineBreak(yuiJsLineBreak); if(yuiErrorReporter != null) { yuiJsCompressor.setErrorReporter(yuiErrorReporter); } javaScriptCompressor = yuiJsCompressor; } //detect CDATA wrapper boolean cdataWrapper = false; Matcher matcher = cdataPattern.matcher(source); if(matcher.matches()) { cdataWrapper = true; source = matcher.group(1); } String result = javaScriptCompressor.compress(source); if(cdataWrapper) { result = "<![CDATA[" + result + "]]>"; } return result; }
8b21efa2-491d-4f77-abca-48b5fd450b71
3
public static boolean isPrimitive(Object obj) { Class[] primitives = new Class[] { boolean.class, byte.class, char.class, short.class, int.class, long.class, float.class, double.class }; for (Class<?> c : primitives) if (c.isAssignableFrom(obj.getClass())) return true; return false; }
dba84d19-8819-4145-945a-d93d93bf7bea
5
@Override public Object getValueAt(int rowIndex, int columnIndex) { LeverandoerDTO leverandoer = leverandoerList.get(rowIndex); Object value = null; switch (columnIndex) { case 0: value = leverandoer.getLeverandoerId(); break; case 1: value = leverandoer.getFirmaNavn(); break; case 2: value = leverandoer.getKontaktNavn(); break; case 3: value = leverandoer.getTelefonNr(); break; case 4: value = leverandoer.getStatus(); break; } return value; }
75d77bfb-acfd-4111-a1e9-3b55f7d3b68b
1
private double f(double b) { double PrB=1, p=probLessThan(b); for (int i = 0; i < futureBowls; i++) { PrB*=p; } double PrA=1-PrB; double ExA=exptGreaterThan(b); double ExB=exptLessThan(b); double Ex2=PrA*ExA+PrB*ExB; return Ex2; }
f474b471-5dd1-4d3b-812c-cb8bd5c3c058
3
public static Data getDataFromJson(String json){ ObjectMapper mapper = new ObjectMapper(); Data data = null ; try { data = mapper.readValue(json, Data.class) ; } catch (JsonGenerationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return data ; // return null si �a �choue }
82c199a8-cade-4f29-8a23-0c56acd18af5
9
static final void method3060(byte b, boolean bool, boolean bool_1_, Node_Sub2 node_sub2) { anInt3073++; int i = node_sub2.interfaceId; int i_2_ = (int) node_sub2.aLong2797; node_sub2.method2160((byte) 55); if (bool_1_) { Node_Sub15_Sub6.method2571(i, false); } Class150_Sub3_Sub1.method1665((byte) -102, i); IComponentDefinitions widget = Class76.method771((byte) 107, i_2_); if (widget != null) { ClientScript.method2321(-1, widget); } Node_Sub8.method2423((byte) -42); if (!bool && (Class320_Sub15.WINDOWS_PANE_ID ^ 0xffffffff) != 0) { Class76.method770(121, 1, Class320_Sub15.WINDOWS_PANE_ID); } Class303 class303 = new Class303(Class289.aHashTable3630); for (Node_Sub2 node_sub2_3_ = (Node_Sub2) class303.method3542(true); node_sub2_3_ != null; node_sub2_3_ = (Node_Sub2) class303.method3539(0)) { if (!node_sub2_3_.method2161(-127)) { node_sub2_3_ = (Node_Sub2) class303.method3542(true); if (node_sub2_3_ == null) { break; } } if ((node_sub2_3_.cliped ^ 0xffffffff) == -4) { int i_4_ = (int) node_sub2_3_.aLong2797; if ((i ^ 0xffffffff) == (i_4_ >>> 16 ^ 0xffffffff)) { method3060((byte) 95, bool, true, node_sub2_3_); } } } @SuppressWarnings("unused") int i_5_ = 30 % ((b - 20) / 32); }
3632c95d-b944-41e8-903f-63ad5b0dc098
7
public View render(View convertView, Context context, FeedView webFeedView) { this.context = context; if (convertView == null) { convertView = getInflater(context).inflate(layout, null); holder = new ViewHolder(); holder.wrapper = (FrameLayout) convertView.findViewById(Rzap.id("wrapper")); holder.linearLayout = (LinearLayout) convertView.findViewById(Rzap.id("linear_layout")); holder.container = (RelativeLayout) convertView.findViewById(Rzap.id("container")); holder.glowTop = (View) convertView.findViewById(Rzap.id("glow_top")); holder.glowBottom = (View) convertView.findViewById(Rzap.id("glow_bottom")); holder.separatorTop = (View) convertView.findViewById(Rzap.id("separator_top")); holder.separatorBottom = (View) convertView.findViewById(Rzap.id("separator_bottom")); holder.userThumb = (ImageView) convertView.findViewById(Rzap.id("user_thumb")); holder.userName = (TextView) convertView.findViewById(Rzap.id("user_name")); holder.editUserName = (EditText) convertView.findViewById(Rzap.id("edit_user_name")); holder.score = (TextView) convertView.findViewById(Rzap.id("score")); holder.rank = (TextView) convertView.findViewById(Rzap.id("rank")); holder.buttonWrapper = (LinearLayout) convertView.findViewById(Rzap.id("button_wrapper")); holder.greenActionButton = (Button) convertView.findViewById(Rzap.id("green_action_button")); holder.lightActionButton = (LinearLayout) convertView.findViewById(Rzap.id("light_action_button")); holder.lightActionButtonWrapper = (FrameLayout) convertView.findViewById(Rzap.id("light_action_wrapper")); holder.lightActionButtonLabel = (TextView) holder.lightActionButton.findViewById(Rzap.id("label")); holder.lightActionButtonIcon = (ImageView) holder.lightActionButton.findViewById(Rzap.id("icon")); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.feedlette = this; holder.userThumb.setBackgroundResource(Rzap.drawable("icon_default_people")); if (picture != null && !picture.equals("") && !picture.equals("null")) { if (!downloadingUserImage) { downloadingUserImage = true; new DownloadImageTask(new DownloadImageListener() { @Override public void onImageDownloaded(Bitmap bitmap) { downloadedUserImage = bitmap; if (holder.feedlette == LeaderboardUserFeedlette.this) { holder.userThumb.setImageBitmap(downloadedUserImage); } } }).execute(picture); } if (downloadedUserImage != null) { holder.userThumb.setImageBitmap(downloadedUserImage); } else { holder.userThumb.setImageDrawable(null); } } else { holder.userThumb.setImageDrawable(null); } holder.userName.setText(displayName); holder.score.setText(displayScore); holder.rank.setText(rank); holder.editUserName.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { holder.greenActionButton.setTag(s.toString()); } }); holder.buttonWrapper.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); setType(this.type); convertView.setOnClickListener(null); return convertView; }
658cac22-8677-423f-ad3a-4eb27c85a60e
7
public void move(int dx,int dy){ if(x+dx>=Level.SIZE || y+dy>=Level.SIZE || x+dx<=0 || y+dy<=0 || (l.world[x+dx][y+dy] != TileType.AIR && l.world[x+dx][y+dy] != TileType.FIRE && l.world[x+dx][y+dy] != TileType.TORCH)){ }else{ x+=dx; y+=dy; } }
2ebacdd3-71b0-4d34-9e15-0d1c0ec119c7
3
private boolean rosterExists (Roster r) { for (Roster mr: getRosters()) { if ((r.getFamilyName().equals(mr.getFamilyName())) && (r.getGivenName().equals(mr.getGivenName()))) return true; } return false; }
545e9233-3cc9-429e-bd0d-743e500d395f
6
public static void maxProductII(int[] input){ int max[] = new int[input.length]; int maxStart[] = new int[input.length]; int minStart[] = new int[input.length]; int min[] = new int[input.length]; max[0] = min[0] = input[0]; maxStart[0] = minStart[0] = 0; int maxProduct = Integer.MIN_VALUE; int leftMax = -1; int rightMax = -1; for(int i = 1; i< input.length; i++) { max[i] = Math.max(Math.max(max[i-1] * input[i], input[i]), min[i-1] * input[i]); maxStart[i] = maxStart[i-1]; if(max[i] == input[i]) { maxStart[i] = i; } else if( max[i] == min[i-1] * input[i]) { maxStart[i] = minStart[i-1]; } min[i] = Math.min(Math.min(max[i - 1] * input[i], input[i]), min[i - 1] * input[i]); minStart[i] = minStart[i-1]; if(min[i] == input[i]){ minStart[i] = i; } else if(min[i] == max[i-1] * input[i]) { minStart[i] = maxStart[i-1]; } if(maxProduct < max[i]){ maxProduct = max[i]; leftMax = maxStart[i]; rightMax = i; } } System.out.println("Max Product : "+ maxProduct+ " from Left:"+ leftMax+ " to "+ rightMax); }
e3d3fd99-0c9f-46e7-8b28-7a0ae6994bad
6
public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; }
e13c8b95-aa3a-497d-9380-2628d7b920b8
6
public void beginUpgrade(Upgrade upgrade, boolean checkExists) { int atIndex = -1 ; for (int i = 0 ; i < upgrades.length ; i++) { ///I.sayAbout(venue, "Upgrade is: "+upgrades[i]) ; if (checkExists && upgrades[i] == upgrade) return ; if (upgrades[i] == null) { atIndex = i ; break ; } } if (atIndex == -1) I.complain("NO ROOM FOR UPGRADE!") ; upgrades[atIndex] = upgrade ; upgradeStates[atIndex] = STATE_INSTALL ; if (upgradeIndex == atIndex) upgradeProgress = 0 ; upgradeIndex = nextUpgradeIndex() ; checkMaintenance() ; }
b9d26579-333f-489e-a8d7-a1c054d65998
7
public void calculateBasicScore(ROB_entry entry) { // the baseline score, based only on instruction type (+mispredicted branch) if (entry.theUop.type == UopType.insn_CBRANCH){ // score for conditional branch entry.score += BRANCH_SCORE; if(heuristic.type != HeuristicType.heuristic_BASE_SCORE){//if we're doing the basic score we don't have the misprediction predictor if (entry.mispredictedBranch_f) {// check if need to add score for mispredicted branch entry.score += MISPREDICTED_BRANCH_SCORE; } } } else if (entry.theUop.type == UopType.insn_UBRANCH) // score for unconditional branch entry.score += BRANCH_SCORE; else if (entry.theUop.type == UopType.insn_LOAD) // score for load entry.score += LOAD_SCORE; else if (entry.theUop.type == UopType.insn_DIVIDE) // score for divide entry.score += DIVIDE_SCORE; else if (entry.theUop.type == UopType.insn_MULTIPLY) // score for multiply entry.score += MULTIPLY_SCORE; }
ba27152b-09b3-431d-86cf-962d37646193
8
public void actionPerformed(ActionEvent evt) { String Action = evt.getActionCommand(); String last_line = null; String tmp = ""; if (Action.equals("answer")) { if(state == -1) { return; //Unexpected notification } last_line = serial.readline(); Logtext = "<-- ["+last_line+"]"; caller.mylog(Logtext); switch (state) { case 0: //Wake up sent to meter (DM@ sent : we should receive @ at 1st position) //Check if answer or not yet if(last_line.equals("") || ! last_line.substring(0, 1).equals("@")) { //No expected answer : redo ! state = 0; connectToDevice(); return; } else { tmp = ex_string(last_line, 2 , "\""); Logtext = "Meter ready, serial <"+tmp+"> received "; caller.meter_id = tmp; Logger(Logtext); notify_main("meter_id"); state = 1; //Wake up success ! InitiateReadRecords(); } break; case 1: // read BG records sent to meter : We should receive records count break; case 2: // Process record sent by meter processed++; caller.processed = processed; //caller.Record = new Record_factory(caller.meter_id, caller.unit, itemdate, itemtime, res, itemflag); notify_main("record"); if(processed >= expected) { notify_main("readfinished"); state = -1; //Nothing else expected } break; } } }
0e98db16-b30e-4710-b8a5-3f299b3e615d
9
public void refresh(){ if(!canrun) return; CGroupNode newDelete = dispCache; CGroupNode newDisp = Renderer.paintDialog(currentSeq, parent.gui.getBounds()); CGroupNode fadeGroup = new CGroupNode(fadeGroupName); for(ACItem item : newDisp.getChildrenCopy()){ if(!(item.getName().endsWith(bgsuffix) || item.getName().endsWith(framesuffix) || item.getName().endsWith(charsuffix))){ fadeGroup.addChild(item); newDisp.removeChild(item); } } fadeGroup.setOpacity(0); newDisp.addChild(fadeGroup); if(newDelete != null && newDisp.getName().equals(newDelete.getName())){ return; } dispCache = newDisp; parent.gui.getMasterNode().addChild(dispCache); parent.gui.refreshControls(); parent.accFading(fadeGroup, 1, fadeLen, fadeAcc); if(newDelete != null){ parent.accFading(newDelete, -1, fadeLen, fadeAcc); if(toDelete != null) actionPerformed(null); toDelete = newDelete; fadeTimer.start(); } }
9aa45fc5-2eb0-4c09-9b7f-bab0b67b73d0
1
public SettingsDlg(Joculus j) { super(); app_instance = j; // read the settings from the preferences, or use defaults. dialog_settings = new Settings(); dialog_settings.load(); // set up the dialog. this.setLayout(new BorderLayout()); default_border = new EmptyBorder(10, 20, 10, 20); JTabbedPane tab_pane = new JTabbedPane(); // get the folder icon to use for the browse buttons. try { folder_icon = new ImageIcon( ImageIO.read(this.getClass().getClassLoader().getResource("abstrys/joculus/res/toolbar/open.png"))); } catch (IOException ex) { Joculus.showError(ex.getMessage()); } tab_pane.addTab(UIStrings.SETTINGS_DIALOG_GENERAL_TITLE, createGeneralSettingsPanel()); tab_pane.addTab(UIStrings.SETTINGS_DIALOG_CSS_TITLE, createCSSSettingsPanel()); tab_pane.addTab(UIStrings.SETTINGS_DIALOG_MARKDOWN_PROCESSOR_TITLE, createProcessorSettingsPanel()); this.add(tab_pane, BorderLayout.CENTER); add(createButtonsPanel(), BorderLayout.SOUTH); this.pack(); this.setVisible(true); this.setResizable(false); this.setTitle(UIStrings.SETTINGS_DIALOG_TITLE); reset(); }
1a174c6f-36bb-4c00-88ba-f7f5527bbf5e
9
private void destroy(int x, int y) { int mouseX = x; int mouseY = y; int rowCount = genX / blockSize; int startY = (Math.round(mapY / blockSize))* rowCount + 1; int endY = (Math.round((mapY + screenHeight) / blockSize) - 1)* rowCount; if(startY < 0) startY = 0; if(endY > map.length) endY = map.length; playerHitBox.setLocation(mouseX, mouseY + mapY); for(int i = startY; i < endY; i++){ if(playerHitBox.intersects(map[i]) && map[i].type != 0 && map[i].type != 14){ if(map[i].type != -1)type = map[i].type; blockBreakTimer += delta; blockAnimTimer += delta; if(blockAnimTimer > 100){ map[i].switchBlockColor(type); blockAnimTimer = 0; } blockBreakTimer += delta; if(blockBreakTimer > map[i].breakTime){ playerInv.addItem(type); map[i].type = 0; blockBreakTimer = 0; } } } }
6170fa54-91ad-43e0-9560-2fa9ec22041f
5
public void movePlayer (int playerID, Location l) { Player p = playerIDs.get(playerID); if (board.canTraverse(l) && p != null && this.isFree(l)) { if (p.move(l)) { for (int id: playerIDs.keySet()) { server.queuePlayerUpdate(new MoveEvent(playerID, l), id); } } } }
3d8bc317-cd69-45ac-87c6-d4416b0dfefc
9
public void update(double timestep) { if (this.state.equals("flipping")){ if(endPoint.getCenter().x()==flippedSpot.getCenter().x() && endPoint.getCenter().y()==flippedSpot.getCenter().y()){ //we are already in the flipped position state = "flipped"; } else { double deltaAngle = timestep*angularVelocity; double timeUntilStationary = Geometry.timeUntilRotatingCircleCollision(endPoint, pivot.getCenter(), angularVelocity, flippedSpot, new Vect(0,0)); if (timestep>=timeUntilStationary){ //we will stop rotating during the timestep endPoint = new Circle(flippedSpot.getCenter().x(), flippedSpot.getCenter().y(), 0.0); flipper = new LineSegment(flippedFlipper.p1().x(), flippedFlipper.p1().y(), flippedFlipper.p2().x(), flippedFlipper.p2().y()); state = "flipped"; } else { endPoint = Geometry.rotateAround(endPoint, pivot.getCenter(), new Angle(deltaAngle)); flipper = Geometry.rotateAround(flipper, pivot.getCenter(), new Angle(deltaAngle)); } } } else if (this.state.equals("deflipping")){ if(endPoint.getCenter().x()==initialSpot.getCenter().x() && endPoint.getCenter().y()==initialSpot.getCenter().y()){ //we are already in the initial position state = "initial"; } else { double deltaAngle = timestep*(-1)*angularVelocity; double timeUntilStationary = Geometry.timeUntilRotatingCircleCollision(endPoint, pivot.getCenter(), -angularVelocity, initialSpot, new Vect(0,0)); if (timestep>=timeUntilStationary){ //we will stop rotating during the timestep endPoint = new Circle(initialSpot.getCenter().x(), initialSpot.getCenter().y(), 0.0); flipper = new LineSegment(initialFlipper.p1().x(), initialFlipper.p1().y(), initialFlipper.p2().x(), initialFlipper.p2().y()); state="initial"; } else { endPoint = Geometry.rotateAround(endPoint, pivot.getCenter(), new Angle(deltaAngle)); flipper = Geometry.rotateAround(flipper, pivot.getCenter(), new Angle(deltaAngle)); } } } double pivotX = pivot.getCenter().x(); double pivotY = pivot.getCenter().y(); double initX = initialSpot.getCenter().x(); double initY = initialSpot.getCenter().y(); double endX = endPoint.getCenter().x(); double endY = endPoint.getCenter().y(); Vect initVect = new Vect(initX-pivotX, initY-pivotY); Vect endVect = new Vect(endX-pivotX, endY-pivotY); Angle initAngle = initVect.angle(); Angle endAngle = endVect.angle(); double currentAngle = Math.abs((endAngle.minus(initAngle)).radians()); if (currentAngle>Math.PI/2){ currentAngle = Math.PI*2-currentAngle; } this.currentAngle = (-1)*currentAngle; }
d57cdae4-70d1-4d53-9d18-40ea064a2d32
0
public void windowDeiconified(WindowEvent e) { // TODO Auto-generated method stub }
d275396d-721e-4188-a16f-6d1a6267ed23
7
public static void spielen() { int i; int versuche = Ratespiel.versuche; boolean erraten = false; char[] eingabe = new char[6]; char[] loesungswort = Ratespiel.woerter[Ratespiel.zufall(0, Ratespiel.woerter.length)].toCharArray(); while (!erraten && versuche>0) { System.out.println((Ratespiel.versuche-versuche+1)+". Versuch: "); eingabe = Console.readString().toUpperCase().toCharArray(); erraten = true; for(i=0;i<6;i++) { if(eingabe.length>=6 && eingabe[i] == loesungswort[i]) { System.out.print(loesungswort[i]); } else { System.out.print("_"); erraten = false; } } System.out.println(); versuche--; } if(erraten) { System.out.println("RICHTIG!"); } else { System.out.print("Du hast leider verloren. Das Loesungswort war "); for(i=0;i<6;i++) { System.out.print(loesungswort[i]); } System.out.println("."); } }
6012e0c8-2f29-43ff-8712-971eab2e3719
3
private void store_granule_info(){ // // for(int ch = 0; ch < max_gr; ch++){ // for(int gr1 = 0; gr1 < channels; gr1++){ // format.store_in_array(gr[gr1].ch[ch].part2_3_length, 12); // format.store_in_array(gr[gr1].ch[ch].big_values, 9); // format.store_in_array(gr[gr1].ch[ch].global_gain, 8); // format.store_in_array(gr[gr1].ch[ch].scalefac_compress, 4); // format.store_in_array(gr[gr1].ch[ch].window_switching_flag, 1); // // if(gr[gr1].ch[ch].window_switching_flag == 1){ // format.store_in_array(gr[gr1].ch[ch].block_type, 2); // format.store_in_array(gr[gr1].ch[ch].mixed_block_flag, 1); // format.store_in_array(gr[gr1].ch[ch].table_select[0], 5); // format.store_in_array(gr[gr1].ch[ch].table_select[1], 5); // format.store_in_array(gr[gr1].ch[ch].subblock_gain[0], 3); // format.store_in_array(gr[gr1].ch[ch].subblock_gain[1], 3); // format.store_in_array(gr[gr1].ch[ch].subblock_gain[2], 3); // format.store_in_array(gr[gr1].ch[ch].preflag, 1); // format.store_in_array(gr[gr1].ch[ch].scalefac_scale, 1); // format.store_in_array(gr[gr1].ch[ch].count1table_select, 1); // } else { // format.store_in_array(gr[gr1].ch[ch].table_select[0], 5); // format.store_in_array(gr[gr1].ch[ch].table_select[1], 5); // format.store_in_array(gr[gr1].ch[ch].table_select[2], 5); // format.store_in_array(gr[gr1].ch[ch].region0_count, 4); // format.store_in_array(gr[gr1].ch[ch].region1_count, 3); // format.store_in_array(gr[gr1].ch[ch].preflag, 1); // format.store_in_array(gr[gr1].ch[ch].scalefac_scale, 1); // format.store_in_array(gr[gr1].ch[ch].count1table_select, 1); // } // } // } for(int granule = 0; granule < max_gr; granule++){ for(int ch = 0; ch < channels; ch++){ EChannel t = gr[granule].ch[ch]; format.store_in_array(t.part2_3_length, 12); format.store_in_array(t.big_values, 9); format.store_in_array(t.global_gain, 8); format.store_in_array(t.scalefac_compress, 4); format.store_in_array(t.window_switching_flag, 1); if(t.window_switching_flag == 1){ format.store_in_array(t.block_type, 2); format.store_in_array(t.mixed_block_flag, 1); format.store_in_array(t.table_select[0], 5); format.store_in_array(t.table_select[1], 5); format.store_in_array(t.subblock_gain[0], 3); format.store_in_array(t.subblock_gain[1], 3); format.store_in_array(t.subblock_gain[2], 3); format.store_in_array(t.preflag, 1); format.store_in_array(t.scalefac_scale, 1); format.store_in_array(t.count1table_select, 1); } else { format.store_in_array(t.table_select[0], 5); format.store_in_array(t.table_select[1], 5); format.store_in_array(t.table_select[2], 5); format.store_in_array(t.region0_count, 4); format.store_in_array(t.region1_count, 3); format.store_in_array(t.preflag, 1); format.store_in_array(t.scalefac_scale, 1); format.store_in_array(t.count1table_select, 1); } } } }
11d014e1-6b4f-4e0a-908e-7374c0645366
8
public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String linea; while(!(linea=bf.readLine()).equals("0 0")){ String[] numeros = linea.split(" "); tam = (numeros[0].length() > numeros[1].length()) ? numeros[0].length(): numeros[1].length(); a=new int[tam]; b=new int[tam]; Arrays.fill(a, 0); Arrays.fill(b, 0); for (int i = (tam-1), j=numeros[0].length()-1; i >= 0 ; i--, j--) { if(j>=0) a[i]=Integer.parseInt(numeros[0].charAt(j)+""); } for (int i = (tam-1), j=numeros[1].length()-1; i >= 0 ; i--, j--) { if(j>=0) b[i]=Integer.parseInt(numeros[1].charAt(j)+""); } int carry = solve(); if(carry == 0) System.out.println("No carry operation."); else if(carry == 1) System.out.println("1 carry operation."); else System.out.println(carry+ " carry operations."); } }
6e57ba41-230a-4623-99cb-d9ffc53fa3fb
2
public void schemeEditorDelContact() { if(ce_circuit2.getSelectionIndex() == -1 || ce_drain.getSelectionIndex() == -1) return; String circuitName = ce_circuit2.getText(); String contactName = ce_drain.getText(); scheme.getCircuits().get(circuitName).getContacts().remove(new Contact(contactName)); schemeEditorSchemeChanged(); }
3e696ce3-d680-4c9b-b209-93a1b259a02c
8
public static void decompressFile(String input, String output){ byte[] data = new byte[0];//All the bytes from the input //Read the input try{ data = Files.readAllBytes(Paths.get(input)); }catch(Exception e){ e.printStackTrace(); } ArrayList<Character> unique = new ArrayList<Character>();//Local unique character list HashMap<Character, Integer> frequencies = new HashMap<Character, Integer>();//Local frequency map int i;//need indexing for later //Create the frequency map for(i = 0; i < data.length; i+= 5){ int freq = data[i+1] + data[i+2] + data[i+3] + data[i+4]; if(freq == 0) break;//If reach a frequency of zero, we know this character does not exist so this is the end of header frequencies.put((char) data[i], freq); unique.add((char)data[i]); } i+=5;//Shift the index to the start of the code translate = buildTrie(frequencies, unique);//Create the Huffman Trie StringBuilder sb = new StringBuilder();//StringBuilder for the binary representation int a; for(; i<data.length; i++){ a = data[i] & 0xFF;//Fixes negative integers to be representable as a byte String binaryString = Integer.toBinaryString(a); StringBuilder binaryStringBuilder = new StringBuilder(binaryString);//Builder for byte length //Extends ensures that the binary String is 8 bits long while(binaryStringBuilder.length() < 8){ binaryStringBuilder.insert(0, '0'); } sb.append(binaryStringBuilder.toString()); } char[] decypher = sb.toString().toCharArray();//Character array of all the bits Node temp = root;//Temporary Node for traversal StringBuilder result = new StringBuilder();//String builder for the final result for(int j = 0; j < decypher.length; j++){ temp = temp.traverse(Integer.parseInt(decypher[j] + ""));//Traverse either 1 or 0 //If we are at a leaf then this is a character and we reset the pointer to the root if(temp instanceof Leaf){ result.append(((Leaf) temp).getChar()); temp = root; } } //Write the translation to the file try{ FileWriter fw = new FileWriter(output); fw.write(result.toString()); fw.close(); }catch(Exception e){ e.printStackTrace(); } }
fba12658-a54b-4ba7-aab9-89dad376b4e6
8
public void searchByName (LYNXsys system, String query, int page) { // search for students by by name for (int i = 0; i < system.getUsers().size(); i ++) { // loop through arraylist of students if ((system.getUsers().get(i).getFirstName().equalsIgnoreCase(query)) || (system.getUsers().get(i).getLastName().equalsIgnoreCase(query)) || (system.getUsers().get(i).getFirstName() + " " + system.getUsers().get(i).getLastName()).equalsIgnoreCase(query)){ // check if book title matches search query displayedSearchResults.add(new StudentSearchResult (system.getUsers().get(i), system.getUsers().get(i).getID() + ": " + system.getUsers().get(i).getLastName() + ", " + system.getUsers().get(i).getFirstName() + ". ")); } } for(int i = ((page-1)*13); i < page*13; i++){ if (i < displayedSearchResults.size()) { displayedSearchResults.get(i).getDisplayText().setEditable(false); displayedSearchResults.get(i).getDisplayText().setBackground(Color.pink); displayedSearchResults.get(i).getDisplayText().setBounds(500,270 + (21*(i-(13*(page-1)))),400,20); displayedSearchResults.get(i).getUserButton().setBounds(460,270 + (21*(i-(13*(page-1)))),32,20); add(displayedSearchResults.get(i).getDisplayText(),0); add(displayedSearchResults.get(i).getUserButton(),0); } } for (int i = 12; i < displayedSearchResults.size(); i = i + 13) { if (displayedSearchResults.size() > i) { pages.add(new JButton()); pages.get(pages.size() - 1).setBounds(620 + (45*(((i-12)/13)+1)),547,43,19); add(pages.get((((i-12)/13)+1)),0); pages.get((((i-12)/13)+1)).addActionListener(getAction()); } } repaint(460,270,510,500); lastSearch = 1; }
6049cdad-26b7-404d-98fc-af4624660e7a
4
@Override public synchronized Object read() throws NetworkException { if(toAppStream != null) { throw new NetworkException(this, "Receiving is done via input stream. Do not call Connection.read."); } if(toAppBuffer != null) { if(!toAppBuffer.isEmpty()) { // return data from buffer although the connection might be closed return toAppBuffer.removeFirst(); } } if(!isConnected()) { throw new NetworkException("Connection is broken."); } else { // connection alive but no data available return null; } }
d2263e90-c7aa-40c7-bae9-a22b5e7e1293
2
public GuiDriver() { createGui(); imageChooser = new JFileChooser(); imageChooser.addChoosableFileFilter(new ImageFileFilter()); imageChooser.setAcceptAllFileFilterUsed(false); imageChooser.setCurrentDirectory(Paths.get(".").toFile()); loadImageButton.addMouseListener( new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int result = imageChooser.showOpenDialog(panel1); if (result == JFileChooser.APPROVE_OPTION) { try { runCircleDetection(imageChooser.getSelectedFile()); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } } } ); radiusSlider.addChangeListener( new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { progressBarLabel.setText("Max Circle Radius: " + radiusSlider.getValue()); } } ); }
48dad373-75b8-47a2-8deb-e7babddb8846
3
public Environment<K,V> createChild( String name ) { //System.out.println( "Creating new child: "+name ); // First: locate the container List<Environment<K,V>> tmpList = this.children.get( name ); // Create new container if none exists if( tmpList == null ) { tmpList = new ArrayList<Environment<K,V>>( 1 ); this.children.put( name, tmpList ); } else if( !allowsMultipleChildNames() && tmpList.size() == 1 ) { // Child already exists and NO multiple names allowed return tmpList.get(0); } // Child count was not 1 so far // --> create new child Environment<K,V> child = new DefaultEnvironment<K,V>( this.mapFactory, this.keyComparator, this, // parentEnvironment this.allowsMultipleChildNames ); // Add to internal list tmpList.add( child ); this.childCount++; return child; }
bae66723-598b-4f07-ab99-d9788b52a95c
5
final void method2439(int i, AnimatableToolkit class64) { try { anInt10205++; int i_115_ = ((Class264) aClass264_10315).anInt3370; if (i >= -110) ((Mob) this).anInt10325 = 90; int i_116_ = ((Class264) aClass264_10316).anInt3370; if (i_115_ != 0 || i_116_ != 0) { int i_117_ = class64.fa() / 2; class64.H(0, -i_117_, 0); class64.VA(0x3fff & i_115_); class64.FA(0x3fff & i_116_); class64.H(0, i_117_, 0); } } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("kda.GB(" + i + ',' + (class64 != null ? "{...}" : "null") + ')')); } }
705994f9-fe2f-426e-8133-e21d620233eb
9
private final void timeOutStrayHandlers() { List<HTTPIOHandler> handlersToShutDown = null; synchronized(handlers) { // remove any stray handlers from time to time if(handlers.size() == 0) return; final Iterator<HTTPIOHandler> i; try { i=handlers.iterator(); } catch(java.lang.IndexOutOfBoundsException x) { handlers.clear(); throw x; } for(; i.hasNext(); ) { try { final HTTPIOHandler handler=i.next(); if(handler.isCloseable()) { if(handlersToShutDown == null) { handlersToShutDown = new LinkedList<HTTPIOHandler>(); } handlersToShutDown.add(handler); i.remove(); } } catch(NullPointerException e) { try { i.remove(); } catch(Exception xe){ } } } } if(handlersToShutDown != null) { for(final HTTPIOHandler handler : handlersToShutDown) { handler.closeAndWait(); } } }
d8b7ff07-61f1-4b01-b3cf-10ca15756599
0
public void addDoctor(Doctor doctor){ this.doctor.add(doctor); }
0f541d41-78bd-437d-b578-005421d82e3d
0
public static void main(String[] args) { new Circle(5); }
e3686498-0a8f-45f6-b051-b8ab26f8146a
0
public ArrayList<PersonApplication> getPersonApplicantions() { return PersonApplications; }
c9785741-c69a-4177-befa-6298e3501d2f
9
public Component getRendererComponent(GraphColoring coloring) { final GraphColoring myColoring = new GraphColoring(coloring.graph); myColoring.vertexColors = new HashMap<Vertex, Integer>(coloring.vertexColors); myColoring.edgeColors = new HashMap<Edge, Integer>(coloring.edgeColors); myColoring.label = coloring.label; String txt = ""; txt = "<HTML><BODY>"; if (myColoring.label != null && !myColoring.label.equals("")) { txt = txt + "<B>" + myColoring.label + ": </B>"; } if (myColoring.vertexColors != null && myColoring.vertexColors.size() > 0) { txt = txt + "<B>Vertex colors: </B> "; for (Map.Entry<Vertex, Integer> p : myColoring.vertexColors.entrySet()) { txt = txt + p.getKey().getLabel() + ":" + p.getValue() + " , "; } } if (myColoring.edgeColors != null && myColoring.edgeColors.size() > 0) { txt = txt + "<br/><B>Edge colors: </B> "; for (Map.Entry<Edge, Integer> p : myColoring.edgeColors.entrySet()) { txt = txt + p.getKey().getLabel() + ":" + p.getValue() + " , "; } } txt = txt + "</BODY></HTML>"; JLabel l = new JLabel(txt){ @Override public void setForeground(Color fg) { super.setForeground(fg); if (fg== GCellRenderer.SELECTED_COLOR) showOnGraph(myColoring); } }; l.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { showOnGraph(myColoring); } }); return l; }
19ccf606-3213-462d-82fc-54eb2c21666b
8
private boolean displayModesMatch(DisplayMode mode1, DisplayMode mode2) { if(mode1.getWidth() != mode2.getWidth() || mode1.getHeight() != mode2.getHeight()){ return false; } if(mode1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && mode1.getBitDepth() != mode2.getBitDepth()){ return false; } if(mode1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && mode1.getRefreshRate() != mode2.getRefreshRate()){ return false; } return true; }
b22fff3a-a280-4009-b611-7254fdb74b73
7
public boolean exists(String name) { Connection conn = null; ResultSet rs = null; PreparedStatement ps = null; boolean exists = false; try { conn = iConomy.getiCoDatabase().getConnection(); ps = conn.prepareStatement("SELECT * FROM " + Constants.SQLTable + " WHERE username = ? LIMIT 1"); ps.setString(1, name); rs = ps.executeQuery(); exists = rs.next(); } catch (Exception ex) { exists = false; } finally { if (ps != null) try { ps.close(); } catch (SQLException ex) { } if (rs != null) try { rs.close(); } catch (SQLException ex) { } if (conn != null) try { conn.close(); } catch (SQLException ex) { } } return exists; }
48ed1bef-66be-4be3-aa3a-3f3b527e9d19
4
public void gainXP(int exp){ _xp += exp; while (_xp > 100){ _level++; //ding! _xp-=100; _health*=1.3; _damage*=1.3; _shield++; if (_level == 2) learnSkillOne(); if (_level == 5) learnSkillTwo(); if (_level == 10) learnSkillThree(); } }
f2471b5b-fbc6-4c1d-9c9d-af0d939e7d4b
9
/* package private */ ShallowTrace(final String name, final boolean hidden, final boolean systemHidden, final ResultType resultType, final String value, final Long startNanos, final Long pendingNanos, final Long endNanos, final Map<String, String> attributes) { assert name != null; assert resultType != null; _name = name; _hidden = hidden; _value = value; _resultType = resultType; _startNanos = startNanos; _pendingNanos = pendingNanos; _endNanos = endNanos; _systemHidden = systemHidden; if (!attributes.isEmpty()) { Map<String, String> attributeMap = new HashMap<String, String>(attributes); _attributes = Collections.unmodifiableMap(attributeMap); } else { _attributes = Collections.emptyMap(); } switch (resultType) { case EARLY_FINISH: if (value != null) { throw new IllegalArgumentException("value cannot be set if the task is finished early"); } ArgumentUtil.notNull(startNanos, "startNanos"); ArgumentUtil.notNull(pendingNanos, "pendingNanos"); ArgumentUtil.notNull(endNanos, "endNanos"); break; case ERROR: case SUCCESS: ArgumentUtil.notNull(startNanos, "startNanos"); ArgumentUtil.notNull(pendingNanos, "pendingNanos"); ArgumentUtil.notNull(endNanos, "endNanos"); break; case UNFINISHED: if (value != null) { throw new IllegalArgumentException("value cannot be set if the task is UNFINISHED"); } break; default: throw new IllegalArgumentException("Unexpected result type: " + resultType); } if (startNanos != null && resultType != ResultType.UNFINISHED) { ArgumentUtil.notNull(pendingNanos, "pendingNanos"); ArgumentUtil.notNull(endNanos, "endNanos"); } }
a2630c85-fe12-4ddf-998a-53a9b0fe985f
0
public int getEventId() { return eventId; }
2abc7891-f471-4184-b096-64384ad982dd
5
@EventHandler(priority = EventPriority.NORMAL) public void onSignChange(final SignChangeEvent event) { if (!event.isCancelled()) { if (ChatColor.stripColor(event.getLine(1)).equalsIgnoreCase( "[KarmicLotto]")) { boolean valid = false; if(plugin.getPerm().has(event.getPlayer(), Permission.CREATE.getNode())) { if(plugin.getLotto().validateLotto(event.getPlayer(), event.getLine(2), event.getLine(3))) { //Colorize to tell that it has gone into effect event.setLine(1, ChatColor.GOLD + "[KarmicLotto]"); final String name = ChatColor.AQUA + event.getLine(2); final String amount = ChatColor.GREEN + event.getLine(3); event.setLine(2, name); event.setLine(3, amount); event.getPlayer().sendMessage(ChatColor.GREEN + KarmicLotto.prefix + " Successully made lotto sign"); valid = true; } else { event.getPlayer().sendMessage(ChatColor.RED + KarmicLotto.prefix + " Not a valid lotto sign"); } } else { event.getPlayer().sendMessage(ChatColor.RED + KarmicLotto.prefix + " Lack permission: " + Permission.CREATE.getNode()); } if(!valid) { // Reformat sign event.setLine(0, ""); event.setLine(1, ""); event.setLine(2, ""); event.setLine(3, ""); } } } }
187cac2c-6202-4187-9a30-f40f16976e1a
9
public ArchiveData take() throws ClosedChannelException, InterruptedException, ProtocolException { // Das ArchiveData Objekt ist in dem Byte-Array kodiert. byte[] dataByteArray = _streamDemultiplexer.take(_indexOfStream); if (dataByteArray != null) { // Es wurde ein Datensatz empfangen InputStream in = new ByteArrayInputStream(dataByteArray); //deserialisieren Deserializer deserializer = SerializingFactory.createDeserializer(in); StreamedArchiveData streamedArchiveData = null; try { // archiveDataKind final int archiveDataKindCode = deserializer.readInt(); ArchiveDataKind archiveDataKind = ArchiveDataKind.getInstance(archiveDataKindCode); // dataTime, steht in der Archivantwort final long dataTime = deserializer.readLong(); // archiveTime, steht in der Archivantwort final long archiveTime = deserializer.readLong(); // dataIndex, steht in der Archivantwort final long dataIndex = deserializer.readLong(); // DataState, steht in der Archivantwort final int codeArchiveDataType = deserializer.readInt(); final DataState dataState = DataState.getInstance(codeArchiveDataType); // Serializer-Version, mit dem der Datensatz erzeugt werden kann, auslesen final int serializerVersion = deserializer.readInt(); // Wurde der Datensatz gepackt final byte byteCompression = deserializer.readByte(); final ArchiveDataCompression compression = ArchiveDataCompression.getInstance(byteCompression); // Größe des Datensates, der als Byte-Array verschickt wurde. Ist die Größe 0, so // war auf Archivseite das byte-Array <code>null</code>. final int sizeOfData = deserializer.readInt(); // Datensatzobjekt, das erzeugt werden soll. Der intitale Wert ist null, somit muss der else-Zweig von // <code>if(sizeOfData > 0)</code> nicht betrachtet werden, da dort nur data=null ausgeführt werden würde. Data data = null; if (dataState == DataState.DATA) { if (sizeOfData > 0) { // Der Datensatz in einem Byte-Array (dieser kann gepackt sein). // Wenn der Datensatz gepackt war, steht der entpackte Datensatz ebenfalls in dieser Variablen. byte[] byteData = deserializer.readBytes(sizeOfData); if (compression == ArchiveDataCompression.ZIP) { ByteArrayInputStream inputStream = new ByteArrayInputStream(byteData); InflaterInputStream unzip = new InflaterInputStream(inputStream); // In diesem Stream werden die entpackten Daten gespeichert ByteArrayOutputStream unzippedData = new ByteArrayOutputStream(); try { // Speichert die ungepackten Daten byte[] byteArray = new byte[1000]; // Ergebnis, nach dem die Daten eingelesen wurden (-1 bedeutet, dass es keine // Daten mehr gibt, die gepackt sind) int readResult = unzip.read(byteArray); while (readResult != -1) { unzippedData.write(byteArray, 0 , readResult); readResult = unzip.read(byteArray); } unzip.close(); } catch (IOException e) { e.printStackTrace(); } // Der Datensatz wurde entpackt und kann deserialisiert werden. Das alte byte-Array wird an dieser // Stelle überschrieben, da es nicht mehr benötigt wird. byteData = unzippedData.toByteArray(); } else if (compression == ArchiveDataCompression.NONE) { // Alles in Ordnung, es wurde nicht gepackt } else { // Der Datensatz wurde mit einer unbekannte Version gepackt throw new RuntimeException("Entpacken von Datensätzen nicht möglich, da die Version des Packers nicht unterstützt wird, geforderte Version " + compression.toString()); } // Das Byte-Array wird nun in einen Datensatz umgewandelt. Dafür muss ein neuer Deserializer // erzeugt werden. Dieser benutzt die übertragene Serializer-Version. // Dies ist nötig, da gerade alte Archivdaten mit einer älteren Serializer-Version // verpackt wurden. InputStream newUnpackedByteArray = new ByteArrayInputStream(byteData); //deserialisieren, diesmal mit einer anderen Serializer-Version try { Deserializer deserializerNewVersion = SerializingFactory.createDeserializer(serializerVersion, newUnpackedByteArray); data = deserializerNewVersion.readData(_archiveDataSpecification.getDataDescription().getAttributeGroup()); } catch (NoSuchVersionException e) { e.printStackTrace(); throw new IllegalStateException("Ein Archivdatensatz kann nicht deserialisiert werden, da das Archiv eine für die Applikation unbekannte Version zum serialisieren benutzt hat. Serializer-Version: " + serializerVersion); } } } // Objekt erzeugen, dies ist nun ein Archivdatensatz streamedArchiveData = new StreamedArchiveData(dataTime, archiveTime, dataIndex, dataState, archiveDataKind, data, _archiveDataSpecification.getObject(), _archiveDataSpecification.getDataDescription()); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return streamedArchiveData; } else { // Das null-Paket wurde empfangen, somit hat das Archiv alle Datensätze versandt, die zu der Archivanfrage // gehörten. _query.countFinishedStream(); return null; } }
7c9f8734-54a1-4588-b2a9-b002056fde49
4
private void reset() { synchronized (sequenceQueueLock) { if (sequenceQueue != null) sequenceQueue.clear(); } // Check if we have a sequencer: if (sequencer == null) { // nope, try and get one now: getSequencer(); } else { // We have a sequencer. Stop it now: sequencer.stop(); // rewind to the beginning: sequencer.setMicrosecondPosition(0); // Stop listening for a moment: sequencer.removeMetaEventListener(this); // wait a bit for the sequencer to shut down and rewind: try { Thread.sleep(100); } catch (InterruptedException e) { } } // We need to have a sequencer at this point: if (sequencer == null) { errorMessage("Unable to set the sequence in method " + "'reset', because there wasn't " + "a sequencer to use."); return; } // set the new sequence to be played: setSequence(filenameURL(GET, null).getURL()); // start playing again: sequencer.start(); // make sure we play at the correct volume: // (TODO: This doesn't always work??) resetGain(); // start listening for end of track event again: sequencer.addMetaEventListener(this); }
721c8230-209e-46ef-a77c-3d5cfb0ad57e
8
private boolean safeAdd(Token token) { //end{check} Token last = tokens.empty() ? null : tokens.peek(); boolean safe = true; if (last !=null && (last.isNumber() || last.isOperator(')'))) { safe = token.isOperator('+') || token.isOperator('-') || token.isOperator(')'); } else { safe = token.isNumber() || token.isOperator('('); } if (safe) { tokens.add(token); } else { System.out.println(token + " can't follow " + tokens.peek()); } return safe; }
03282736-e7cb-414d-8232-0dae729a3576
3
public OutputStragegy getOutputStrategy(String simName) { OutputStragegy st = null; if (scheme == SIMPLE) { st = new SimpleDirectoryOutput(getDir(), simName); } else if (scheme == NUMBERED) { st = new NumDirectoryOutput(getDir(), simName); } else if (scheme == TIME) { st = new DateDirectoryOutput(getDir()); } return st; }
21a66e91-9682-435e-9520-f8b4408a1e2f
1
@Test public void getAllRecipesTest() throws Exception { Recipe recipe = new Recipe(); recipe.setName("borscht"); recipe.setCategory(CategoryEnum.chicken); try { recipe.canSave(); } catch (SaveError e) { e.printStackTrace(); } }
d5f3c0b0-2e97-4fef-afea-7683a0cb0380
6
private int sumValue(ArrayList<Piece> thePieces) { int answer=0; for(Piece p : thePieces) { if(p instanceof Pawn) { answer+=1; }else if(p instanceof Knight|| p instanceof Bishop) { answer+=3; }else if(p instanceof Rook) { answer+=5; }else if(p instanceof Queen) { answer+=9; } } return answer; }
fa2231e4-7bdb-4063-bf5d-bc06933b4e09
0
public int GetInputBuffer() { return inputBuffer; }
a6d1797e-e2f2-433c-8c67-444af9e008ee
8
private boolean readFiretrap(Element element, int houseNumber) { //declare variables int x = -1; int y = -1; //check for non-specified attributes NamedNodeMap trapAttr = element.getAttributes(); for(int i = 0; i < trapAttr.getLength(); i++) { Node attr = trapAttr.item(i); //get attribute //check if attribute is part of specified attributes if(!attr.getNodeName().equals("x") && !attr.getNodeName().equals("y")) { errorFlag = 1; errorString = "Unspecified attribute for 'firetrap' in house " + houseNumber + "."; return false; } } //set values if attributes are valid if(element.getAttribute("x").matches(numReg)) x = Integer.parseInt(element.getAttribute("x")); if(element.getAttribute("y").matches(numReg)) y = Integer.parseInt(element.getAttribute("y")); //check for missing required attributes if(x < 1 || y < 1) { errorFlag = 1; errorString = "Invalid or missing 'firetrap' attribute in house " + houseNumber + "."; return false; } //if we got here, create firetrap if(!houseList.get(houseNumber).createFirettrap(x, y)) { errorFlag = 1; errorString = "Could not place 'firetrap' in house " + houseNumber + "."; return false; } return true; }
357362c0-b5da-4e2d-9ff1-0b8c4dd984ff
0
public String getTitle() { return this.title; }