method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
522c1824-82f3-4ca1-a96b-91208b380c61
7
protected final short get_action(int state, int sym) { short tag; int first, last, probe; short[] row = action_tab[state]; /* linear search if we are < 10 entries */ if (row.length < 20) for (probe = 0; probe < row.length; probe++) { /* is this entry labeled with our Symbol or the default? */ tag = row[probe++]; if (tag == sym || tag == -1) { /* return the next entry */ return row[probe]; } } /* otherwise binary search */ else { first = 0; last = (row.length-1)/2 - 1; /* leave out trailing default entry */ while (first <= last) { probe = (first+last)/2; if (sym == row[probe*2]) return row[probe*2+1]; else if (sym > row[probe*2]) first = probe+1; else last = probe-1; } /* not found, use the default at the end */ return row[row.length-1]; } /* shouldn't happened, but if we run off the end we return the default (error == 0) */ return 0; }
09bda170-e5bf-4027-855a-1c672dbbc842
5
@Override public void onDraw(Graphics G, int viewX, int viewY) { if (X>viewX-houseW&&X<viewX+houseW+300&&Y>viewY-(houseH)&&Y<viewY+houseH+300) { if (chimney) { G.setColor(Color.black); G.fillRect((int)(houseX+(houseW/1.5))-viewX, (int)(houseY-(houseH/2.2))-viewY,(int)(houseW*.2),houseH/2); } G.setColor(roof); P.translate(-viewX,-viewY); G.fillPolygon(P); P.translate(viewX,viewY); G.setColor(Color.black); // G.fillRect((int)(houseX+(houseW/1.5))-viewX, (int)(houseY-(houseH/2.2))-viewY,(int)(houseW*.2),houseH/2); G.drawRect(houseX-viewX,houseY-viewY,houseW,houseH); G.drawLine(houseX-viewX, houseY-viewY, houseX+(houseW/2)-viewX, houseY-(viewY+(houseH/2))); G.drawLine(houseX+houseW-viewX, houseY-viewY, houseX+(houseW/2)-viewX, houseY-(viewY+(houseH/2))); G.setColor(wall); G.fillRect(houseX+1-viewX,houseY+1-viewY,houseW-1,houseH-1); G.setColor(door); G.fillRect(houseX+(houseW/6)-viewX,houseY+houseH/2-viewY,(houseW/9),houseH/2); G.setColor(window); G.fillRect((int)(houseX+(houseW/1.5)-viewX),houseY+houseH/6-viewY,(houseW/4),houseH/3); } }
607e7aec-4991-4f77-ab05-d48f2b430bd3
7
private void triFusion(int debut, int fin) { // tableau o� va aller la fusion int[] tFusion = new int[fin - debut + 1]; int milieu = (debut + fin) / 2; // Indices des �l�ments � comparer int i1 = debut, i2 = milieu + 1; // indice de la prochaine case du tableau tFusion � remplir int iFusion = 0; while (i1 <= milieu && i2 <= fin) { if (t[i1] < t[i2]) { tFusion[iFusion++] = t[i1++]; } else { tFusion[iFusion++] = t[i2++]; } } if (i1 > milieu) { // la 1�re tranche est �puis�e for (int i = i2; i <= fin; ) { tFusion[iFusion++] = t[i++]; } } else { // la 2�me tranche est �puis�e for (int i = i1; i <= milieu; ) { tFusion[iFusion++] = t[i++]; } } // Copie tFusion dans t for (int i = 0, j = debut; i <= fin - debut; ) { t[j++] = tFusion[i++]; } }
cd579c71-24eb-4b06-a430-3ed18f67eda7
9
public Model getInventoryModel(int amount) { if (stackableIds != null && amount > 1) { int stackableId = -1; for (int i = 0; i < 10; i++) if (amount >= stackableAmounts[i] && stackableAmounts[i] != 0) stackableId = stackableIds[i]; if (stackableId != -1) return getDefinition(stackableId).getInventoryModel(1); } Model stackedModel = Model.getModel(modelId); if (stackedModel == null) return null; if (modifiedModelColors != null) { for (int c = 0; c < modifiedModelColors.length; c++) stackedModel.recolour(modifiedModelColors[c], originalModelColors[c]); } return stackedModel; }
58cdb13d-a8db-409a-adaf-61c6d87e0af9
8
@Override public void run() { while (!stop) { try { selector.select(1000); Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectionKeys.iterator(); SelectionKey key; while (it.hasNext()) { key = it.next(); it.remove(); try { handleInput(key); } catch (Exception e) { if (key != null) { key.cancel(); if (key.channel() != null) { key.channel().close(); } } } } } catch (IOException e) { e.printStackTrace(); } } if (selector != null) { try { selector.close(); } catch (IOException e) { e.printStackTrace(); } } }
e1fb46b3-ca8d-447e-9ec0-c39b10405528
4
public static void main(String[] args) { // vytvorit vlakno serveru a klienta String name = args[0]; int port = Integer.parseInt(args[1]); String file = (args.length > 2) ? args[2] : null; try { Thread serverTh; InetAddress localhost = InetAddress.getLocalHost(); Node serverNode = new Node(name, localhost, port); IStdOut stdOut = new StdOutImpl(); try { Packet packet = PacketFileReader.readPacketFromFile(file, serverNode); //client se spusti jen pokud lze nacist soubor System.out.println("MainOPSWI.main starting client"); Client client = new Client(stdOut, packet); new Thread(client).start(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (NullPointerException e) { System.out.println("MainOPSWI.main not starting client"); } //server System.out.println("MainOPSWI.main starting server"); final Server server = new Server(serverNode, stdOut); serverTh = new Thread(server); serverTh.start(); // Ukonceni aplikace, zavre server socket /*Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("konec"); server.closeChannels(); } });*/ } catch (UnknownHostException e) { e.printStackTrace(); } }
4c662828-8122-42b5-b113-fca13535ba0d
4
public frmVenda() throws ErroValidacaoException, ParseException { initComponents(); dao = new VendaDao(); pgdao = new PagamentoDao(); pdao = new ProdutoDao(); cdao = new ClienteDao(); fdao = new FuncionarioDao(); //============ List<Pagamento> pagamentos = pgdao.listarTodos(); jcbPagamentoVend.removeAllItems(); for(Pagamento pg: pagamentos){ jcbPagamentoVend.addItem(pg.getNome()); } //============ List<Cliente> clientes = cdao.listarTodos(); jbcClienteVend.removeAllItems(); for(Cliente c: clientes){ jbcClienteVend.addItem(c.getNome()); } //============ List<Funcionario> funcionarios = fdao.listarTodos(); jcbFuncionarioVend.removeAllItems(); for(Funcionario f: funcionarios){ jcbFuncionarioVend.addItem(f.getNome()); } //============ List<Produto> produtos = pdao.listarTodos(); jcbItemVend.removeAllItems(); for(Produto p: produtos){ jcbItemVend.addItem(p); } }
0fbafeeb-41ae-48aa-9e25-f6b624e28459
2
public Object get(int index) { if (index < 0 || index >= instructionCount) throw new IllegalArgumentException(); return get0(index); }
f17065b9-8c80-4b9e-a881-ba5b205edadb
5
protected void move(final int x, final int y, final Piece piece) throws InvalidMoveException{ if (0 <= x && x <= Board.DIM && 0 <= y && y <= Board.DIM && canMove(x, y, piece)) { cells[x][y].addPiece(piece); } else { throw new InvalidCellException(); } }
873efda8-9972-453e-bee6-4f13c03763f1
6
private void ajout_dispoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ajout_dispoActionPerformed // TODO add your handling code here: int n; switch(etat){ case Intervenant: this.intervenant = new Intervenant(this.nom.getText(),this.prenom.getText(),this.email.getText(),this.telephone.getText(),true,true); this.intervenant.save(); n = 1; if(this.recurrence.isSelected()){ n = Integer.parseInt(this.periode.getText()); } for(int i = 0;i< n; i++){ this.creneauInt = new Creneau_Intervenant( this.intervenant.getId(), afficherTimestamp(this.date.getText(), Integer.parseInt(this.h_debut.getSelectedItem().toString()), Integer.parseInt(this.m_debut.getSelectedItem().toString()), i*7), afficherTimestamp(this.date.getText(), Integer.parseInt(this.h_fin.getSelectedItem().toString()), Integer.parseInt(this.m_fin.getSelectedItem().toString()), i*7)); this.creneauInt.save(); } refreshRecurence(); this.etat = Etat.Intervenant1; break; case Intervenant1: n = 1; if(this.recurrence.isSelected()){ n = Integer.parseInt(this.periode.getText()); } for(int i = 0;i< n; i++){ this.creneauInt = new Creneau_Intervenant( this.intervenant.getId(), afficherTimestamp(this.date.getText(), Integer.parseInt(this.h_debut.getSelectedItem().toString()), Integer.parseInt(this.m_debut.getSelectedItem().toString()), i*7), afficherTimestamp(this.date.getText(), Integer.parseInt(this.h_fin.getSelectedItem().toString()), Integer.parseInt(this.m_fin.getSelectedItem().toString()), i*7)); this.creneauInt.save(); } refreshRecurence(); this.etat = Etat.Intervenant1; break; } }//GEN-LAST:event_ajout_dispoActionPerformed
58c21d35-539b-411f-b0ae-a2882d6aad28
3
private void addFileAppender(String appenderName, String level) throws IOException { if ((config.getLoggerName() == null) || (config.getLoggerName().equals("log4j"))) { RollingFileAppender fileAppndr = (RollingFileAppender)Logger.getRootLogger().getAppender(appenderName); if (fileAppndr != null) { fileAppndr.setFile(getFileName()); fileAppndr.activateOptions(); appenders.add(appenderName); } else { fileAppndr = new RollingFileAppender(new PatternLayout(getPattern()), getFileName(), true); fileAppndr.setName(appenderName); fileAppndr.setThreshold(Level.toLevel(level)); //Level.DEBUG fileAppndr.setMaxFileSize(config.getMaxFileSize()); fileAppndr.setMaxBackupIndex(config.getMaxBackupCount()); Logger.getRootLogger().addAppender(fileAppndr); appenders.add(appenderName); } } else { throw new IllegalArgumentException("Logger " + config.getLoggerName() + " not suppoted."); } }
8ea29096-c122-4938-a717-ae56296a9bcd
2
@Override public boolean extensionExists(String ext) { Iterator it = getExtensions(); while (it.hasNext()) { String key = (String) it.next(); if (ext.equals(key)) { return true; } } return false; }
5c150d89-8829-4ffa-91fd-b4ca259997fc
1
public void notifyObservers() { for (Observer observer : mObservers) { observer.update(); } }
8e3d6766-f744-452b-9421-8dc67b9021f1
8
private LinkedList<String> parseInfix(LinkedList<String> input){ LinkedList<String> stack= new LinkedList<>(); LinkedList<String> outputQueue= new LinkedList<>(); input.stream().forEach( token ->{ if(token.equals("(")){ stack.push(token); }else if(isOperator(token)){ while(!stack.isEmpty()&&isOperator(stack.peek()) && (getPriority(stack.peek())<getPriority(token) ) ){ outputQueue.add(stack.pop()); } stack.push(token); }else if(token.equals(")")){ while(!stack.peek().equals("(")){ outputQueue.add(stack.pop()); } stack.pop(); }else{ outputQueue.add(token); } } ); while(!stack.isEmpty()){ outputQueue.add(stack.pop()); } return outputQueue; }
cde5bf06-8f4d-419a-aad2-50e82fca53fb
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(MenuRelatorios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MenuRelatorios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MenuRelatorios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MenuRelatorios.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 MenuRelatorios().setVisible(true); } }); }
97514f5b-c8eb-4811-ac13-db697df428d3
3
@Override public void drawPanel(Graphics g) { g.drawRect(position.width-width/2, position.height-height/2, width, height); Font font = g.getFont(); int posX = position.width - font.getSize()*operator.toString().length()/4; int posY = position.height + font.getSize()/2; g.drawString(operator.toString(), posX, posY); if(operator.pred != null && operator.type != S){//TODO допрацювати для висячих вершин g.drawLine(this.points[1].width, this.points[1].height-(int)(heightCell*0.3), this.points[1].width, this.points[1].height); drawDownArrow(g, this.points[1].width, this.points[1].height); } if(operator.next() != null){ g.drawLine(this.points[3].width, this.points[3].height, this.points[3].width, this.points[3].height+(int)(heightCell*0.2)); } }
837c8c4a-1293-40d7-a1cf-e2a79513a7c2
7
protected static Font setFont(Font font, boolean bold, boolean italic) { if (font == null) { return null; } if ((font.getStyle() & Font.BOLD) != 0) { if (!bold) { return font.deriveFont(font.getStyle() ^ Font.BOLD); } } else { if (bold) { return font.deriveFont(font.getStyle() | Font.BOLD); } } if ((font.getStyle() & Font.ITALIC) != 0) { if (!italic) { return font.deriveFont(font.getStyle() ^ Font.ITALIC); } } else { if (italic) { return font.deriveFont(font.getStyle() | Font.ITALIC); } } return font; }
e4d40a93-502e-430c-90c1-97827cfbfe07
0
public String goToAdminProductDetails() { this.product = this.userFacade.getProductById(this.id); return "adminProductDetails"; }
2054eb4b-fcef-4af0-82aa-4aa6a0b072c9
7
private void recTree(int[][] processingField_prievious, int depth, int depth_current, Node currentNode, int player) { int[][] processingField_current; // End-Kondition für Rekursion. Dann wird aktuelle Node mit ihrem Tiefenwert und Score bestückt if (depth == depth_current) { processingField_current = VierGewinntAi.cloneArray((processingField_prievious)); //Hier evaluate aufrufen, um werte zu bekommen currentNode.nodeDepth = depth_current; currentNode.value = ArtificialIntelligence.evaluate(processingField_current, player); } // next depth-step else { // go through columns from left to right for (int column = 0; column < 7; column++) { // processingField zurückseten von vorigem Rekursionsschritt processingField_current = VierGewinntAi.cloneArray((processingField_prievious)); // go through rows of the current column until a free space to set a new coin // in the end "row" represents the coin that was set int row = 0; while (row < 6 && processingField_current[column][row] != 0) { row++; } //detect if the column is full and skip if (row > 5) { currentNode.addChild(new Node()); currentNode.children.getLast().empty = true; continue; } // depending on current depth player 1 or player 2 is chosen // depth is odd (1,3,5,...) = current player // depth is even (2,4,6,...) = opponent int nextPiece; if (player == 2) { nextPiece = (depth_current + 1) % 2 + 1; } else { nextPiece = 2 - (depth_current + 1) % 2; } // processingField_current[column][row] = depth_current % 2 +1; processingField_current[column][row] = nextPiece; // processingField_current[column][row] = player; // save current depth value to orientate in which tree depth it is currentNode.nodeDepth = depth_current; if (VierGewinntAi.mainGameEngine.checkWin(processingField_current)) { currentNode.children.add(new Node()); currentNode.children.getLast().value = ArtificialIntelligence.evaluate(processingField_current, player); currentNode.children.getLast().nodeDepth = depth_current +1; } else { // new children for currentNode to operate the next recursion step currentNode.children.add(new Node()); recTree(processingField_current, depth, depth_current + 1, currentNode.children.getLast(), player); } } } }
30b8daa3-a2c6-47f0-bc04-f23e8ee56833
5
public void setProfession(Profession newProf) { resetExp(); switch (newProf) { case Warrior: getEquipment().сhangeWeapon(Equipment.StandartEquipment.Weapons.Sword); getEquipment().сhangeArmor(Equipment.StandartEquipment.Armors.MediumArmor); getEquipment().сhangeCash(10); setStrategy(new WarriorStrategy()); setReview( 90); setSpeed(80); setProfession( Warrior); setStatus(PersonState.LastActionCompleted); break; case Trader: setEquipment(new Equipment(Equipment.StandartEquipment.Weapons.Hands, Equipment.StandartEquipment.Armors.NoneArmor, 100)); setStrategy( new TraderStrategy()); setReview(100); setSpeed(100); setProfession(Trader); setStatus(PersonState.Moving); break; case Robber: getEquipment().newCash(10); setReview(110); setSpeed( 125); setStatus(PersonState.LastActionCompleted); setStrategy(new RobberStrategy()); setProfession(Robber); break; case Peasant: getEquipment().сhangeWeapon(Equipment.StandartEquipment.Weapons.Hands); getEquipment().сhangeArmor(Equipment.StandartEquipment.Armors.NoneArmor); getEquipment().newCash(10); setStatus(PersonState.LastActionCompleted); setReview( 100); setSpeed( 100); setStrategy(new PeasantStrategy()); setProfession(Peasant); break; case Craftsman: setSpeed(80); getEquipment().сhangeWeapon(Equipment.StandartEquipment.Weapons.Hands); getEquipment().сhangeArmor(Equipment.StandartEquipment.Armors.UsualArmor); getEquipment().newCash(10); setReview(100); setStatus(PersonState.LastActionCompleted); setStrategy(new CraftsmanStrategy()); setProfession(Craftsman); break; } }
16ad29c4-ce8a-42a9-a03a-592c796a55de
0
public Player(boolean isWhite) { this.isWhite = isWhite; }
b01b8764-708c-4059-ba83-5219d0ce6c5e
6
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Names) { Names other = (Names) obj; return this.firstName.equals(other.firstName) && this.lastName.equals(other.lastName) && ( this.middleName == null ? other.middleName == null : this.middleName.equals(other.middleName) ) && this.gender == other.gender; } return false; }
86037736-5a55-4db2-a244-d38daa16b031
8
private void loadFile(String fileName) throws CWRCException { childrenFound = false; file = new File(fileName); if (file.exists()) { } else { try { FileOutputStream fileOut = new FileOutputStream(file); XMLStreamWriter out = XMLOutputFactory.newInstance().createXMLStreamWriter(new OutputStreamWriter(fileOut, "UTF-8")); out.writeStartDocument(); out.writeStartElement(TitleModsMerger.MAIN_NODE); out.writeEndElement(); out.writeEndDocument(); out.close(); } catch (FileNotFoundException ex) { throw new CWRCException(CWRCException.Error.DATASOURCE_CREATE, ex); } catch (IOException ex) { throw new CWRCException(CWRCException.Error.DATASOURCE_CREATE, ex); } catch (XMLStreamException ex) { throw new CWRCException(CWRCException.Error.DATASOURCE_CREATE, ex); } } try { DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); String systemId = file.toURI().toURL().toString(); doc = docBuilder.parse(new InputSource(systemId)); } catch (ParserConfigurationException ex) { throw new CWRCException(CWRCException.Error.DATASOURCE_LOAD, ex); } catch (MalformedURLException ex) { throw new CWRCException(CWRCException.Error.DATASOURCE_LOAD, ex); } catch (SAXException ex) { throw new CWRCException(CWRCException.Error.DATASOURCE_LOAD, ex); } catch (IOException ex) { throw new CWRCException(CWRCException.Error.DATASOURCE_LOAD, ex); } }
274a280d-550c-464f-ac41-13c489851772
3
@SuppressWarnings("unchecked") @Override public Boolean compareAnswer(Object input) { HashMap<Integer, Integer> inputMap; try{ inputMap = (HashMap<Integer, Integer>) input; }catch(ClassCastException e){ return false; } for (Integer key: inputMap.keySet()){ if (!inputMap.get(key).equals(answer.get(key))) return false; } return true; }
2614c024-c0ac-4400-8cee-4f9570085505
2
public static String applyRelativePath(String path, String relativePath) { int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR); if (separatorIndex != -1) { String newPath = path.substring(0, separatorIndex); if (!relativePath.startsWith(FOLDER_SEPARATOR)) { newPath += FOLDER_SEPARATOR; } return newPath + relativePath; } else { return relativePath; } }
edb64dbe-32f4-4418-8dd4-1d9d562a66ae
0
@RequestMapping(value = "/createEntity", method = RequestMethod.GET) public ModelAndView welcome() { ModelAndView mav = new ModelAndView("create-entity"); EntityForm entityForm = new EntityForm(); mav.addObject(entityForm); return mav; }
415f578d-809a-4401-b663-14d26a018104
0
@Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) { LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean(); lef.setDataSource(dataSource); lef.setJpaVendorAdapter(jpaVendorAdapter); lef.setPackagesToScan("com.joseph.california.domain"); return lef; }
248969de-1eb1-4fdd-91ec-306ea644204d
2
public static int parseSize(String value) throws ParseException{ Pattern p = Pattern.compile("\\s*(((?<mb>[1-9][0-9]*)\\s*(M[Bb])?)|((?<gb>[1-9][0-9]*)\\s*G[Bb]))\\s*"); Matcher m = p.matcher(value); if (m.matches()){ String mb = m.group("mb"); String gb = m.group("gb"); if (null != mb){ return Integer.parseInt(mb); } else { return Integer.parseInt(gb) * 1024; } } throw new ParseException("Size doesn't match pattern"); }
3c16b0d9-3c1f-43e5-adcc-aa9d67c3a608
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(BuscaUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(BuscaUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(BuscaUser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(BuscaUser.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 BuscaUser().setVisible(true); } }); }
a7db0ece-529e-4742-9171-c8720660209d
8
private ArrayList<DayEvents> readStats(String eventStatsFile, String ijStatsFile) { ArrayList<DayEvents> dayEventsList = new ArrayList<DayEvents>(); ArrayList<double[]> eventRateStatsList = new ArrayList<double[]>(); ArrayList<double[]> ijStatsList = new ArrayList<double[]>(); int ijDyadsWithNoEdges = 0; DayEvents dayEvents = new DayEvents(); System.out.println("Reading in event stats"); //read in event stats try{ BufferedReader bufferedReader = new BufferedReader( new FileReader(eventStatsFile)); String line = null; while ((line = bufferedReader.readLine()) != null) { //NOTE! //first item is the time period indicator String[] stat_strings = line.split("\t"); double[] stats = new double[stat_strings.length]; for(int i = 0; i < stat_strings.length; i++) stats[i] = Double.parseDouble(stat_strings[i]); dayEvents.addEventRateStats(stats); //eventRateStatsList.add(stats); } bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Counting lines in ij stats"); long totalLines = countLines(ijStatsFile); System.out.println("Reading in ij stats"); //read in ijstats //NOTE! // first item in each time period is the number of edgeless dyads try{ BufferedReader bufferedReader = new BufferedReader( new FileReader(ijStatsFile)); //boolean bFirstLine = true; long linecount = 1; String line = null; while ((line = bufferedReader.readLine()) != null) { String[] stat_strings = line.split("\t"); if( linecount == 1) { ijDyadsWithNoEdges = Integer.parseInt(stat_strings[0]); linecount++; //bFirstLine = false; continue; } else if (linecount % 10000 == 0) { System.out.println("ijStats line: " + (((double) linecount / totalLines) * 100.0)); } double[] stats = new double[stat_strings.length]; for(int i = 0; i < stat_strings.length; i++) stats[i] = Double.parseDouble(stat_strings[i]); ijStatsList.add(stats); linecount++; } bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } dayEvents.set_ijRateStats(ijStatsList); dayEvents.set_ijDyadsWithNoEdges(ijDyadsWithNoEdges); dayEventsList.add(dayEvents); return dayEventsList; }
c675050e-a524-4249-ba30-be6fa513eea2
8
private boolean isTwoByteVal(int valCode) { switch (valCode) { case ValCodes.LITERAL: return true; case ValCodes.POINTER: return true; case ValCodes.atA_plusLiteral: return true; case ValCodes.atB_plusLiteral: return true; case ValCodes.atC_plusLiteral: return true; case ValCodes.atX_plusLiteral: return true; case ValCodes.atY_plusLiteral: return true; case ValCodes.atZ_plusLiteral: return true; default: return false; } }
1f87f0ff-ff68-41ee-9c0e-6fcfd97275de
3
public float ms_per_frame() // E.B { if (h_vbr == true) { double tpf = h_vbr_time_per_frame[layer()] / frequency(); if ((h_version == MPEG2_LSF) || (h_version == MPEG25_LSF)) tpf /= 2; return ((float) (tpf * 1000)); } else { float ms_per_frame_array[][] = {{8.707483f, 8.0f, 12.0f}, {26.12245f, 24.0f, 36.0f}, {26.12245f, 24.0f, 36.0f}}; return(ms_per_frame_array[h_layer-1][h_sample_frequency]); } }
1afb56ba-a2d9-4daa-b277-e96fa8b72942
1
public void startLoops(){ timer = new Timer(); new Timer().schedule(new TimerTask() { public void run() { gameLoop(); if(!running){cancel();} } }, 0, (long) (1000*period)); }
a083d73f-0c06-4558-ad2e-54d6aec4c23b
2
public boolean containsValue(Object value) { for (Iterator iter = map.keySet().iterator(); iter.hasNext(); ) { Object key = iter.next(); Object val = map.get(key); if (val.equals(value)) { touch(key); return true; }//if }//for iter return false; }//containsValue
7e730cd4-d643-490a-9833-bd44eea661a5
5
public static ArrayList<DyeParent> getDyeParents() throws SQLException { ArrayList<DyeParent> dyeParents = new ArrayList<DyeParent>(); Statement stm = conn.createStatement(); ResultSet rs = stm.executeQuery("select d.name_dyeparent, d.price_dyeparent, dt.name_dyetype from DyeParent d " + "INNER JOIN DyeType dt ON d.id_dyetype = dt.id_dyetype"); while (rs.next()) { if (rs.getString("name_dyetype").equals("Dye")){ dyeParents.add(new Dye(rs.getString("name_dyeparent"), rs.getDouble("price_dyeparent"), null, 0)); //parameters given by user }else if (rs.getString("name_dyetype").equals("Lakk")){ dyeParents.add(new Lakk(rs.getString("name_dyeparent"), rs.getDouble("price_dyeparent"), null, 0)); }else if (rs.getString("name_dyetype").equals("Metal")){ dyeParents.add(new Metal(rs.getString("name_dyeparent"), rs.getDouble("price_dyeparent"), null, 0)); }else if (rs.getString("name_dyetype").equals("Fluo")){ dyeParents.add(new Fluo(rs.getString("name_dyeparent"), rs.getDouble("price_dyeparent"), null, 0)); } } stm.close(); rs.close(); return dyeParents; }
44271003-3788-40ad-841b-d6bcad9d0762
9
public Position getMovePosition() { if (this.getWorld() == null) return null; double bestAngle = this.getAngle(); double bestDistance = 0; Position bestPos = this.getPosition(); for (double currentAngle = this.getAngle() - 0.7875; currentAngle <= this.getAngle() + 0.7875; currentAngle += 0.0175) { double distance = 0.1; boolean found = false; while (distance <= this.getRadius() && !found) { double posX = distance * Math.cos(currentAngle) + this.getPosition().getX(); double posY = distance * Math.sin(currentAngle) + this.getPosition().getY(); Position pos = new Position(posX, posY); if (!this.getWorld().isImpassable(pos, this.getRadius())) distance += 0.1*this.getRadius(); else found = true; } distance -= 0.1*this.getRadius(); Position newPos = new Position(distance * Math.cos(currentAngle) + this.getPosition().getX(), distance * Math.sin(currentAngle) + this.getPosition().getY()); if (distance >= 0.1) { if(distance > bestDistance) { bestDistance = distance; bestAngle = currentAngle; bestPos = newPos; } else if(Util.fuzzyEquals(bestDistance, distance, 1E-4)) { if(Math.abs(this.getAngle() - currentAngle) < Math.abs(this.getAngle() - bestAngle)) { bestDistance = distance; bestAngle = currentAngle; bestPos = newPos; } } } } return bestPos; }
adaafbd6-efcf-4ee6-ad6f-5d9869c0d8ab
2
public int add(sols.Model.SubSection subSection){ int generated_Subsec_ID=-1; StringBuffer sql=new StringBuffer(); sql.append("INSERT INTO SubSection"); sql.append("(`SubSection_ID`,"); sql.append("`Section_ID`,"); sql.append("`SubSection_Name`)"); sql.append("VALUES"); sql.append("(null,"); sql.append("'"+subSection.getSection_ID()+"',"); sql.append("'"+subSection.getSubSection_Name()+"');"); SQLHelper sQLHelper=new SQLHelper(); sQLHelper.sqlConnect(); ResultSet rs=sQLHelper.runUpdate2(sql.toString()); try { if (rs.next()) { generated_Subsec_ID=rs.getInt(1); } } catch (SQLException ex) { Logger.getLogger(Subsection_DAO.class.getName()).log(Level.SEVERE, null, ex); } return generated_Subsec_ID; }
f318d63f-e091-4993-882d-b3c19dad7a5e
3
public char skipTo(char to) throws JSONException { char c; try { long startIndex = this.index; long startCharacter = this.character; long startLine = this.line; this.reader.mark(1000000); do { c = this.next(); if (c == 0) { this.reader.reset(); this.index = startIndex; this.character = startCharacter; this.line = startLine; return c; } } while (c != to); } catch (IOException exc) { throw new JSONException(exc); } this.back(); return c; }
63d8c7f7-e1b0-48d4-afac-fc0f52570b00
0
public boolean isAlive() { return alive; }
7c83560e-fd8b-4f1a-ad1d-aa4818eeead0
7
private static void reboot() { String jarLocation = System.getProperty("java.class.path"); if (IS_MAC) { jarLocation = ModelerUtilities.validateJarLocationOnMacOSX(jarLocation); } else if (System.getProperty("os.name").startsWith("Windows")) { jarLocation = "\"" + jarLocation + "\""; } String maxHeap = System.getProperty("mw.maxHeapSize"); String s; if (maxHeap != null) { s = "java -Xmx" + maxHeap + " -jar " + jarLocation; } else { s = "java -Xmx128M -jar " + jarLocation; } s += hostIsLocal ? " local" : " remote"; if (startingURL != null) s += " " + startingURL; try { // MUST close this ServerSocket, or it will remain blocked even after shutdown if (serverSocket != null) serverSocket.close(); Runtime.getRuntime().exec(s); } catch (Exception e) { e.printStackTrace(); } finally { System.exit(0); } }
cc9df154-d870-415e-8e27-d387a818ce20
1
@Override public void actionPerformed(ActionEvent event) { PrintProxy proxy = getTarget(PrintProxy.class); if (proxy != null) { print(proxy); } }
7963ca16-423d-4720-ac7b-915a2b09e563
7
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("ANNOTATION= {"); java.util.Enumeration keys = entries.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); Object value = entries.get(key); sb.append(key.toString()); sb.append('='); if (value == null) sb.append("null"); else if (value instanceof StringObject) sb.append(((StringObject) value).getDecryptedLiteralString(library.securityManager)); else sb.append(value.toString()); sb.append(','); } sb.append('}'); if (getPObjectReference() != null) { sb.append(" "); sb.append(getPObjectReference()); } for (int i = sb.length() - 1; i >= 0; i--) { if (sb.charAt(i) < 32 || sb.charAt(i) >= 127) sb.deleteCharAt(i); } return sb.toString(); }
4b652c04-f83d-4bb2-8ab9-86655a2b4295
0
protected void execute() {}
16102810-1c23-4b26-9343-d4d7968f96bb
1
public String[] dequeStringArray() { Deque<String> dequelist = new ArrayDeque(); dequelist.add("equity"); dequelist.addFirst("Derivative"); dequelist.addLast("commondities"); Iterator<String> iter = dequelist.iterator(); String[] tmp = new String[dequelist.size()]; int i = 0; while (iter.hasNext()) { tmp[i] = iter.next(); i++; } return tmp; }
62cd2110-bd3a-4c50-832e-287aca97b69f
6
private Object parseArray() throws StreamCorruptedException { int arrayLen = readLength(); indexPlus(1); Map<String, Object> result = new LinkedHashMap<String, Object>(); Object resultObj; for (int i = 0; i < arrayLen; i++) { Object tmp = parse(); String key = ""; try { key = tmp.toString(); } catch (Throwable e) { continue; } Object value = parse(); result.put(key, value); objHistory.add(value); } indexPlus(1); // result is a hashmap, let's see if it's actually a normal array if (result.containsKey("_DRClassName")) { String className = (String) result.get("_DRClassName"); result.remove("_DRClassName"); resultObj = Reflection.wakeUp(className,result); } else { if (result.size() > 0 && !Functions.isAssociativeArray(result)) { ArrayList<Object> resultArr = new ArrayList<Object>(); Map<String,Object> map = result; for (Map.Entry<String,Object> entry : map.entrySet()) { resultArr.add(entry.getValue()); } resultObj = resultArr; } else { resultObj = result; } } objHistory.add(resultObj); return resultObj; }
159b6522-41e6-484a-b747-47b7134b9e2c
0
public Game(GameMaster master, Board board) { this.master = master; this.board = board; attemptsCount = 0; targetFound = false; gameid = UUID.randomUUID(); }
d85480dd-b7ca-4592-9fb3-883099247ef8
9
public void draw(Object obj, Component comp, Graphics2D g2, Rectangle rect) { Color color = (Color) AbstractDisplay.getProperty(obj, "color"); if (color == null && obj instanceof Color) color = (Color) obj; Color textColor = (Color) AbstractDisplay.getProperty(obj, "textColor"); if (textColor == null) textColor = Color.BLACK; if (color != null) { g2.setPaint(color); g2.fill(rect); if (color.equals(textColor)) { textColor = new Color( 255 - textColor.getRed(), 255 - textColor.getGreen(), 255 - textColor.getBlue()); } } String text = (String) AbstractDisplay.getProperty(obj, "text"); if (text == null && !(obj instanceof Color)) { text = "" + obj; } if (text == null) return; if (text.length() > MAX_TEXT_LENGTH) text = text.substring(0, MAX_TEXT_LENGTH) + "..."; paintCenteredText(g2, text, rect, 0.8, textColor); }
89048fba-c9bd-45e7-b6a0-fb1c4d48a660
6
public void drawObjectsWithID(BufferedImage canvas, boolean fill) { BufferedImage image = new BufferedImage(_width, _height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.drawImage(VisionUtils.convert2grey(canvas), 0, 0, null); g.setFont(new Font("TimesRoman", Font.PLAIN, 10)); // draw ground level for (int x = 0; x < _width; x++) { image.setRGB(x, _ground, 0xff0000); } if (fill) { //draw connected components for (ConnectedComponent d : _draw) d.draw(image, false, false); } // for (Body b : _drawShape) for(Body b : _drawShape) if (b != null) { b.draw(g, false, Color.RED); g.setColor(Color.black); if(b.id != unassigned) { g.drawString(b.id + "", (int)b.centerX - 5, (int)b.centerY + 5);// 10: font size } } canvas.createGraphics().drawImage(image, 0, 0, null); }
2dfde3b1-4edf-40d9-9f7a-8e2c130366b0
5
@EventHandler public void onBlockPlace(BlockPlaceEvent event) { System.out.println(tracks); Block b = event.getBlock(); Player p = event.getPlayer(); if (builderList.containsKey(p.getName())) { Track t = getTrack(builderList.get(p.getName())); if (b.getType() == Material.WOOL) { Wool wool = new Wool(b.getType(), b.getData()); if (wool.getColor() == DyeColor.BLACK) { ArrayList<Location> temp = t.getFinishLine(); temp.add(b.getLocation()); t.setFinishLine(temp); t.saveTrack(); } if (wool.getColor() == DyeColor.WHITE) { ArrayList<Location> temp = t.getStartLine(); temp.add(b.getLocation()); t.setStartLine(temp); t.saveTrack(); } } if (b.getType() == Material.LAPIS_BLOCK) { ArrayList<Location> temp = t.getCheckpoints(); temp.add(b.getLocation()); t.setCheckpoints(temp); t.saveTrack(); } t.reloadTrack(); } }
5cc87d3d-b196-4fa6-aafc-43c8f34b35d2
5
private Component getHeader() { JButton jbSaveOutput = new JButton("<html>Save<br>output</html>"); jbSaveOutput.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String outputText = getParsedText("\n"); if (outputText.length() == 0) { JOptionPane.showMessageDialog(frame, "Output is empty", "File Error", JOptionPane.WARNING_MESSAGE); return; } JFileChooser saveResultsToFileWindow = new JFileChooser(); int result = saveResultsToFileWindow.showSaveDialog(frame); if (result == JFileChooser.CANCEL_OPTION) { return; } File file = saveResultsToFileWindow.getSelectedFile(); try { BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(outputText); bw.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame, e.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } } }); jbRemoveDuplicates = new JButton("Remove duplicates"); jbRemoveDuplicates.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { Set<Object> listElements = ListUtils.highlightDuplicates(jlOutputText); DefaultListModel model = (DefaultListModel) jlOutputText.getModel(); cleanOutputs(); for (Object object : listElements) { appendLineToOutput((String)object, model); } } }); jcbSortOutput = new JCheckBox("Sort output"); jcbWordWrap = new JCheckBox("Word wrap"); jcbWordWrap.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { inputText.setLineWrap(jcbWordWrap.isSelected()); inputText.setWrapStyleWord(jcbWordWrap.isSelected()); } }); jcbHighlightDuplicates = new JCheckBox("Highlight duplicates"); jcbHighlightDuplicates.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if (jcbHighlightDuplicates.isSelected()) { jtpOutputTabs.setSelectedIndex(LIST_TAB_INDEX); ListUtils.highlightDuplicates(jlOutputText); } else { jlOutputText.getSelectionModel().clearSelection(); } } }); JLabel jlRegex = new JLabel(" Regex: "); DefaultComboBoxModel parseExpressionComboBoxModel = new DefaultComboBoxModel(DEFAULT_REGEXES); jtfParseExpression = new JComboBox(parseExpressionComboBoxModel);//TODO add history of regexes jtfParseExpression.setEditable(true); JButton jbCleanRegex = new JButton("Clean"); jbCleanRegex.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { inputText.setText(""); //jtfParseExpression.setText(""); } }); final JButton jb = new JButton(".."); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { new RegexSelectPopupWindow(jb); } }); Box boxButtons2 = Box.createHorizontalBox(); //boxButtons2.add(jb);//TODO implement this boxButtons2.add(jbCleanRegex); JPanel jpnlParseExpression = new JPanel(new BorderLayout()); jpnlParseExpression.add(jlRegex, BorderLayout.WEST); jpnlParseExpression.add(jtfParseExpression, BorderLayout.CENTER); jpnlParseExpression.add(boxButtons2, BorderLayout.EAST); jpnlParseExpression.setBorder(BorderFactory.createEtchedBorder()); JPanel jpnlControls = new JPanel(new BorderLayout()); jpnlControls.add(jpnlParseExpression, BorderLayout.NORTH); jpnlControls.add(getResizableToolbarPanel(), BorderLayout.CENTER); JPanel jpnlMainButtons = new JPanel(new FlowLayout()); //Box jpnlMainButtons = Box.createHorizontalBox(); //JPanel jpnlMainButtons = new JPanel(new GridLayout(1,3)); Component jbParseButton = getParseButton(); addBigButtonToPanel(jbSaveOutput, jpnlMainButtons); addBigButtonToPanel(jbParseButton, jpnlMainButtons); JPanel jpnlHeader = new JPanel(new BorderLayout()); jpnlHeader.add(jpnlControls, BorderLayout.CENTER); jpnlHeader.add(jpnlMainButtons, BorderLayout.EAST); return jpnlHeader; }
3354e341-d03a-4b78-b116-c647f7c15928
0
@Override public JSONObject main(Map<String, String> params, Session session) throws Exception { long newTimestamp = Long.parseLong(params.get("timestamp")); TimeMachine.setNow(newTimestamp); JSONObject rtn = new JSONObject(); rtn.put("rtnCode", this.getRtnCode(200)); return rtn; }
06d2cb01-58d4-4b2a-8030-57a53faa235a
4
@Override public boolean bajaDepartamento(int id) { EntityManager em = null; boolean correcto = false; try { EntityManagerFactory ef = Persistence.createEntityManagerFactory("MerkaSoftPU"); em = ef.createEntityManager(); em.getTransaction().begin(); Departamento persistentDepartamento = em.find(Departamento.class, id); List results = em.createNamedQuery("Empleado.findByDepartamento") .setParameter("dep", persistentDepartamento) .getResultList(); if (results.size() == 0 && persistentDepartamento.isDisponible()) { persistentDepartamento.setDisponible(false); em.merge(persistentDepartamento); em.getTransaction().commit(); correcto = true; } else { System.out.println("No se puede dar de baja un departamento con empleados asociados"); em.getTransaction().rollback(); } } catch (Exception ex) { correcto = false; ex.printStackTrace(); } finally { if (em != null) { em.close(); } } return correcto; }
57747e9b-27db-4be3-923a-a2ad5262ebca
8
public boolean isMatched(TreeNode T1, TreeNode T2) { if (T2 == null && T1 == null) return true; else if (T2 == null && T1 != null) return false; else if (T1 == null && T2 != null) return false; else if (T1.value != T2.value) return false; else return isMatched(T1.leftChild, T2.leftChild) && isMatched(T1.rightChild, T2.rightChild); }
9f5569bd-3feb-43a9-b773-60edbe6b26df
6
public Object transform(String input) { String[] split = StringUtils.split(input, " "); // Single provided argument (cannot be split) which is the word 'status' // - return status of all lines if (split.length == 1 && input.equals("status")) { log.info("Request [" + input + "] resulted in a status request"); return new TrackernetStatusRequest(); } // Two provided elements and the second is help // The first argument should be a line if (split.length == 2 && split[0].equals("help")) { log.info("Request [" + input + "] resulted in a Help request for line [" + split[1] + "]."); StationHelpRequest stationHelpRequest = new StationHelpRequest(); stationHelpRequest.getStations().addAll(StationsByLine.stationsByLine.get(new Line("", split[1], ""))); return stationHelpRequest; } if (split[0].equals("prediction") && split.length == 3) { String station = transformStation(split[1]); String line = transformLine(split[2]); log.info("Request [" + input + "] resulted in a prediction request for station [" + station + "] and line [" + line + "]"); return new TrackernetPredictionRequest(station, line); } throw new IllegalArgumentException("Could not create a valid Trackernet request from the supplied request"); }
66f2d16e-9434-4106-a22a-b055f456f98d
2
public void mouseWheelMoved(MouseWheelEvent e) { if(Global.isRunning) { return; } // block mouse input while simulating int clicks = e.getWheelRotation(); if(clicks < 0) { gui.zoom(1.08); // zoom In } else { gui.zoom(1.0 / 1.08); // zoom out } }
adfe4200-c9c9-445d-93d8-3486fb8fa5c6
7
public boolean onoff(Model2D model) { float power = powerSource.getPower(); if (power == 0) return false; boolean refresh = false; float t = 0; if (thermometer != null) { t = thermometer.getCurrentData(); } else { Rectangle2D bounds = powerSource.getShape().getBounds2D(); t = model.getTemperatureAt((float) bounds.getCenterX(), (float) bounds.getCenterY()); } if (power > 0) { // if it is a heater if (t > setpoint + deadband) { powerSource.setPowerSwitch(false); refresh = true; } else if (t < setpoint - deadband) { powerSource.setPowerSwitch(true); refresh = true; } } else { // if it is a cooler if (t < setpoint - deadband) { powerSource.setPowerSwitch(false); refresh = true; } else if (t > setpoint + deadband) { powerSource.setPowerSwitch(true); refresh = true; } } return refresh; }
b0c19204-2d7c-4c64-b749-686e9b7cf4cc
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; PSkill pSkill = (PSkill) o; return skill == pSkill.skill && (name != null ? name.equals(pSkill.name) : pSkill.name == null) && scheme == pSkill.scheme; }
50198b0c-5775-40e2-92b8-619a1f3de165
1
public void checkProduction(Production production) { if (production.getLHS().length() == 0) { throw new IllegalArgumentException( "The left hand side cannot be empty."); } }
7eccdb23-8adc-49b7-8b48-9634096bf225
1
private int evalState(State s) { if (me.equals("red")) return s.getnRed() - s.getnBlue(); return s.getnBlue() - s.getnRed(); }
724a412e-396e-4fd6-95ed-1b0523f04054
3
static void preprocess(char[] p) { int i = 0, j = -1, m = p.length; b = new int[p.length + 1]; b[0] = -1; while (i < m) { while (j >= 0 && p[i] != p[j]) j = b[j]; i++; j++; b[i] = j; } }
6b9de019-e2f2-4d48-b5f7-6b66319e96f0
5
private void button10MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_button10MouseClicked if(numberofpins < 4) { if(numberofpins == 0) { Login_form.setString1("1"); } if(numberofpins == 1) { Login_form.setString2("1"); } if(numberofpins == 2) { Login_form.setString3("1"); } if(numberofpins == 3) { Login_form.setString4("1"); } numberofpins +=1; jLabel2.setText(Integer.toString(numberofpins)); } else { System.out.print(Timetable_main_RWRAF.checkDelete()); JOptionPane.showMessageDialog(null,"You've already entered your 4 digit pin!", "Timetable Management Program", JOptionPane.INFORMATION_MESSAGE); }// TODO add your handling code here:// TODO add your handling code here: }//GEN-LAST:event_button10MouseClicked
f3d29242-c61f-4079-b042-59efae421cde
7
private void resolveLine(Node parentNode) { validateTagsOnlyOnce(parentNode, new String[]{"datasource", "color", "legend", "width"}); String datasource = null, legend = null; Paint color = null; float width = 1.0F; Node[] childNodes = getChildNodes(parentNode); for (Node childNode : childNodes) { String nodeName = childNode.getNodeName(); if (nodeName.equals("datasource")) { datasource = getValue(childNode); } else if (nodeName.equals("color")) { color = getValueAsColor(childNode); } else if (nodeName.equals("legend")) { legend = getValue(childNode); } else if (nodeName.equals("width")) { width = (float) getValueAsDouble(childNode); } } if (datasource != null) { if (color != null) { rrdGraphDef.line(datasource, color, legend, width); } else { rrdGraphDef.line(datasource, BLIND_COLOR, legend, width); } } else { throw new IllegalArgumentException("Incomplete LINE settings"); } }
15302171-90a8-45e7-aec6-1cebec6ef630
8
public boolean isSameTree(TreeNode p, TreeNode q) { if(p == null && q == null) return true; if(p == null && q != null) return false; if(p != null && q == null) return false; if(p.val == q.val) { return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } else { return false; } }
0c2d9617-3a66-4971-8461-7cd4529a7d84
8
private HashSet<String> loadFile(String name) { HashSet<String> words = new HashSet<String>(); FileReader reader = null; BufferedReader br = null; File file = new File(this.getDataFolder(), name); if(!file.exists()) { try { file.createNewFile(); } catch (IOException e) { logger.severe("[" + pdfdescription + "] Unable to create login config file!"); logger.severe(e.getMessage()); } words = new HashSet<String>(); }else{ try{ reader = new FileReader(file); br = new BufferedReader(reader); String line; while((line = br.readLine()) != null) words.add(line); br.close(); reader.close(); }catch (IOException e){ logger.severe("[" + pdfdescription + "] Unable to read quote config file!"); logger.severe(e.getMessage()); } finally { if (br != null) try{ br.close(); } catch (IOException e2) {} if (reader != null) try { reader.close(); } catch (IOException e2) {} } } return words; }
675597ad-42c9-4d52-9f6f-5f0211bde7f2
2
public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) { System.out.println("onMessage received in SHSMessageBean.java"); msg = (TextMessage) inMessage; Thread.sleep(100); processing(msg); } else { System.out.println("SHSMessageBean.onMessage:" + " Message of wrong type: " + inMessage.getClass().getName()); } } catch (Exception ex){ System.out.println("SHS_MessageBean.onMessage: "+ "Exception: "+ex.toString()); } }
c201fa6a-8faa-4cb9-a2f6-acc895276226
2
public EncryptedCommunityCards requestDecryptComCards( EncryptedCommunityCards encComCards, final User usr) throws InvalidSubscriptionException, IOException, InterruptedException { final Subscription encSub = elvin.subscribe(NOT_TYPE + " == '" + DECRYPT_COM_CARDS_REPLY + "' && " + GAME_ID + " == '" + gameHost.getID() + "' && " + REQ_USER + " == '" + user.getID() + "'"); Notification not; encryptedHand = null; encSub.addListener(new NotificationListener() { public void notificationReceived(NotificationEvent e) { System.out .println("Got reply from requesting user to decrypt com cards."); byte[] tmpBytes = (byte[]) e.notification .get(ENCRYPTED_COM_CARDS); try { encryptedCommunityCards = (EncryptedCommunityCards) Passable .readObject(tmpBytes); if (!sigServ.validateSignature(encryptedCommunityCards, usr.getPublicKey())) { // sig failed! callCheat(SIGNATURE_FAILED); System.exit(0); } } catch (Exception e1) { shutdown(); System.exit(0); } synchronized (encSub) { encSub.notify(); } } }); not = new Notification(); not.set(NOT_TYPE, DECRYPT_COM_CARDS_REQUEST); not.set(GAME_ID, gameHost.getID()); not.set(SOURCE_USER, user.getID()); not.set(REQ_USER, usr.getID()); not.set(ENCRYPTED_COM_CARDS, encComCards.writeObject()); synchronized (encSub) { elvin.send(not); // wait until received reply encSub.wait(); } encSub.remove(); return encryptedCommunityCards; }
7eb23be5-649b-41b3-97fc-202fcb4d51b6
5
private long toHours() { switch (type) { case SECONDS: return value / 3600; case MINUTES: return value / 60; case HOURS: return value; case DAYS: return value * 24; case MILLISECONDS: default: return value / (3600 * 1000); } }
dff5509f-950b-478a-bd85-388a8ec84ddb
2
static void input(double[][] matrix){ for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[i].length; j++){ matrix[i][j] = scan.nextDouble(); } } }
09bc6249-f065-4e23-9b7b-c0efa051dcd7
1
public String getUrl() { if ( this.url == null ) return ""; return url; }
21f734cc-51e6-4344-a3fb-9f2d0efb4c41
7
GF256Poly(GF256 field, int[] coefficients) { if (coefficients == null || coefficients.length == 0) { throw new IllegalArgumentException(); } this.field = field; int coefficientsLength = coefficients.length; if (coefficientsLength > 1 && coefficients[0] == 0) { // Leading term must be non-zero for anything except the constant polynomial "0" int firstNonZero = 1; while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) { firstNonZero++; } if (firstNonZero == coefficientsLength) { this.coefficients = field.getZero().coefficients; } else { this.coefficients = new int[coefficientsLength - firstNonZero]; System.arraycopy(coefficients, firstNonZero, this.coefficients, 0, this.coefficients.length); } } else { this.coefficients = coefficients; } }
4e6b94a8-a507-4c04-b971-c00e3a0aa32a
4
public List<ProductManagerDto> getProductManagerDtos(){ List<ProductManagerDto> productManagerDtos=null; PreparedStatement stmt = null; ResultSet rs = null; try { stmt = conn .prepareStatement("select mgrName,phoneNumber from ProductManager"); rs = stmt.executeQuery(); String mgrName = ""; String phoneNumber = ""; productManagerDtos = new ArrayList<ProductManagerDto>(); while (rs.next()) { mgrName = rs.getString(1); phoneNumber = rs.getString(2); ProductManagerDto productManagerDto = new ProductManagerDto(); productManagerDto.setName(mgrName); productManagerDto.setPhoneNumber(phoneNumber); productManagerDtos.add(productManagerDto); } if (stmt != null) stmt.close(); if (rs != null) rs.close(); } catch (Exception e) { // TODO: handle exception logger.debug(e.getMessage()); } return productManagerDtos; }
8a126984-f07c-4ce5-825d-0182cafe5d47
2
@Override public int compareTo(Arbre otherArbre) { return (this.poids < otherArbre.getPoids()) ? -1: (this.poids > otherArbre.getPoids()) ? 1:0; }
1c5160d7-c0a1-47d3-a8c2-6ad5e90d5b77
2
public String select(String whereClause, String... columns) { String format = null; if (null == whereClause || whereClause.isEmpty()) { format = String.format("SELECT %s FROM `%s`.`%s`", wrap(columns), schema, table); } else { format = String.format("SELECT %s FROM `%s`.`%s` WHERE %s", wrap(columns), schema, table, whereClause); } System.out.println(format); return format; }
228aaca0-bc2f-4299-8f4e-ceab07f054d2
4
private void completeFinalBuffer(ByteBuffer buffer) { if(finalBuffer.position() == 0) return; while(buffer.remaining() > 0 && finalBuffer.remaining() > 0) { finalBuffer.put(buffer.get()); } if(finalBuffer.remaining() == 0) { transform(finalBuffer.array(),0); finalBuffer.rewind(); } }
c29804fb-6099-4a63-b7e2-a7fd3e6a4277
0
public void setCityName(String cityName) { this.cityName = cityName; }
0448b281-23d3-462f-842e-6e8fc91230c6
8
private static void begin() { Scanner sc = new Scanner(System.in); int noTestCases = Integer.parseInt(sc.nextLine()); for (int t = 0; t < noTestCases; t++) { Map<Integer, String> table = new HashMap<Integer, String>(); int noTurtles = Integer.parseInt(sc.nextLine()); List<Integer> sourceList = new LinkedList<Integer>(); List<Integer> destList = new LinkedList<Integer>(); // Read in the source list. Left is top of the stack. // Associate turtle names with numbers for quick comparison. for (int i = 0; i < noTurtles; i++) { String turtle = sc.nextLine(); int key = turtle.hashCode(); table.put(key, turtle); sourceList.add(key); } // Read in the destination list. left is top of the stack. for (int i = 0; i < noTurtles; i++) { destList.add(sc.nextLine().hashCode()); } StringBuilder sb = new StringBuilder(); ListIterator<Integer> sourceItr = sourceList.listIterator(noTurtles); ListIterator<Integer> destItr = destList.listIterator(noTurtles); /* * Bottom up approach (from right to left). Find the element in the destination * list in the source list. As long as the element is left to the previous * element, no crawling needs to be done. Otherwise, the remaining elements in * the destination list from right to left need to crawl to achieve the desired order. e.g., * ABCDEFG -> source list * BCADEFG -> destination list * G,F,E,D,A is found. The C is not left to A in the source list which is left to * A in the destination list. So, it will not be found. Hence, we store the values * from right to left of A from the destination list. These are C and B. * Thus, by just letting C turtle crawl to the top and then the B turtle, we achieve * the desired order. */ while (destItr.hasPrevious()) { int turtleKey = destItr.previous(); boolean found = false; while (sourceItr.hasPrevious()) { int sourceTurtleKey = sourceItr.previous(); if (sourceTurtleKey == turtleKey) { found = true; break; } } if (!found) { destItr.next(); while (destItr.hasPrevious()) { sb.append(table.get(destItr.previous())).append("\n"); } } } System.out.println(sb); } }
c408afb3-61dd-4cf5-854e-f97301614afd
5
private DoubleDoors getDoor(int id, int x, int y, int z) { for (DoubleDoors d : doors) { if (d.doorId == id) { if (d.x == x && d.y == y && d.z == z) { return d; } } } return null; }
20198822-5222-4867-a5a0-a9b516ee2632
8
public Grammar parseGrammarFromFile(String filePath) throws IOException { //Create new Grammar and set up file to be read parsedGrammar = new Grammar(); BufferedReader reader = (BufferedReader) GrammarReader.readFromFile(filePath); //Create boolean flag to indicate if the file is currently in the first few lines of parsing (The lines before the rules) boolean initialSetup = true; //Read through file and parse each line accordingly String currentLine = reader.readLine(); while (currentLine != null && !currentLine.isEmpty() && !(currentLine.trim().equals(""))) { if (initialSetup) { //If the line is the list of states, parse it accordingly if (currentLine.startsWith("V:")) { parseStates((currentLine.split(":")[1]).trim()); } //If the line is the list of terminals, parse it accordingly else if (currentLine.startsWith("T:")) { parseTerminals(currentLine.split(":")[1].trim()); } //If the line contains the start state, parse it accordingly else if (currentLine.startsWith("S:")) { parseStartState(currentLine.split(":")[1].trim()); } //With the current file format, all lines after 'P:' should be rules, so there is //no need to keep checking for these first four cases. else if (currentLine.startsWith("P:")) { initialSetup = false; } } //If initialSetup is set to false, we know that all that remains in the file (If the correct format is followed) //are the list of the rules in the form of (<State> -> <derivation>|<derivation>). This eliminates the need //to waste time checking the above four conditions when we already know that they will not be seen again. else { parseRules(currentLine.trim()); } currentLine = reader.readLine(); } //Close bufferedreader and return finished grammar reader.close(); return parsedGrammar; }
bc48797d-1be2-4108-8b43-41baa9710f4f
9
private void button14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button14ActionPerformed if (order2code3tf.getText().equals("1001")) { o2c3destf.setText("Chicken Nugget"); } if (order2code3tf.getText().equals("1002")) { o2c3destf.setText("Fries"); } if (order2code3tf.getText().equals("1003")) { o2c3destf.setText("Salad"); } if (order2code3tf.getText().equals("1004")) { o2c3destf.setText("Cheese Burger"); } if (order2code3tf.getText().equals("1005")) { o2c3destf.setText("Bacon Cheese Burger"); } if (order2code3tf.getText().equals("1006")) { o2c3destf.setText("Hamburger"); } if (order2code3tf.getText().equals("1007")) { o2c3destf.setText("Soda"); } if (order2code3tf.getText().equals("1008")) { o2c3destf.setText("Tea"); } if (order2code3tf.getText().equals("1009")) { o2c3destf.setText("Coffee"); } }//GEN-LAST:event_button14ActionPerformed
7290a6c4-e47b-450e-8358-4ad76419a3f1
8
public static String preprocessWikiText(String text) { if (text==null) return ""; text=text.trim(); int length=text.length(); char[] chars=new char[length]; text.getChars(0, length, chars, 0); StringBuilder sb=new StringBuilder(); boolean blankLine=true; StringBuilder spaces=new StringBuilder(); for (int p=0; p<length; p++) { char c=chars[p]; if (c=='\r') { // "\r\n" -> "\n"; then "\r" -> "\n" if (p+1<length && chars[p+1]=='\n') p++; sb.append('\n'); spaces.delete(0, spaces.length()); // discard spaces if there is nothing else on the line blankLine=true; } else if (c=='\n') { sb.append(c); spaces.delete(0, spaces.length()); // discard spaces if there is nothing else on the line blankLine=true; } else if (blankLine) { if (c<=' '/* && c!='\n'*/) { spaces.append(c); } else { sb.append(spaces); blankLine=false; sb.append(c); } } else { sb.append(c); } } return sb.toString(); }
bdfc06d4-212a-4820-a59e-28b7967ebe32
2
public void visitMultiANewArrayInsn(final String desc, final int dims) { mv.visitMultiANewArrayInsn(desc, dims); if (constructor) { for (int i = 0; i < dims; i++) { popValue(); } pushValue(OTHER); } }
14e3938b-265a-4f67-84e3-b2ee8d64cda5
8
public int characterAt(int at) throws JSONException { int c = get(at); if ((c & 0x80) == 0) { return c; } int character; int c1 = get(at + 1); if ((c1 & 0x80) == 0) { character = ((c & 0x7F) << 7) | c1; if (character > 0x7F) { return character; } } else { int c2 = get(at + 2); character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF && (character < 0xD800 || character > 0xDFFF)) { return character; } } throw new JSONException("Bad character at " + at); }
fb30f086-2daa-405b-9f47-7e8eb87db184
3
private void acao143() throws SemanticError{ numeroParametrosAtuais++; if(contextoExpressao == ContextoExpressao.PARAMETROS_ATUAIS) verificarParametro(); else if(contextoExpressao == ContextoExpressao.IMPRESSAO) if(tipoExpressao == Tipo.BOOLEANO) throw new SemanticError("Tipo inválido para impressão"); parametroAtualPodeSerReferencia = true; }
b948f489-d95f-4e0a-86e1-035fd0e40868
3
public List<Message> fetchUserFriendMessages(User user) { initConnection(); String preparedString = null; PreparedStatement preparedQuery = null; List<Message> messageList = null; try { /* Union query produces a list of email addresses - the logged-in user for plus all people he's following */ //Prepare Statement preparedString = "SELECT id, `timestamp`, user, firstname, lastname, content " + /* First part of the UNION returns friends messages */ "FROM " + "messages " + "INNER JOIN " + "(SELECT ? AS email " + "UNION " + "SELECT friend AS email FROM friends WHERE email = ?) user_and_friends ON messages.user = user_and_friends.email " + /* Plus all his friends into one list joined against messages */ "INNER JOIN users ON user_and_friends.email = users.email " + /* Join against the users table for name info */ "ORDER BY `timestamp` DESC;"; preparedQuery = (PreparedStatement) connection.prepareStatement(preparedString); preparedQuery.setString(1, user.getEmail()); preparedQuery.setString(2, user.getEmail()); //TODO: Remove debug System.out.println("Get all messages with SQL: [" + preparedQuery.toString() + "] "); //Execute Statement ResultSet resultSet = preparedQuery.executeQuery(); messageList = new ArrayList<Message>(); //Extract messages into list of Beans while (resultSet.next()) { //Add new message to list for each message from the user Message newMessage = new Message(); newMessage.setId(resultSet.getInt("id")); newMessage.setTimeStamp(resultSet.getTimestamp("timestamp")); newMessage.setContent(resultSet.getString("content")); //Get author as User object User author = new User(); author.setEmail(resultSet.getString("user")); author.setFirstName(resultSet.getString("firstname")); author.setLastName(resultSet.getString("lastname")); newMessage.setAuthor(author); messageList.add(newMessage); } } catch (SQLException e) { e.printStackTrace(); } finally { try { //Finally close stuff to return connection to pool for reuse preparedQuery.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } return messageList; }
5fe75692-2f2f-4ea2-832a-8d54cdc27a17
9
private void doFirePropertyChange(PropertyChangeEvent event) throws PropertyVetoException { String propName = event.getPropertyName(); Object oldValue = event.getOldValue(); Object newValue = event.getNewValue(); if (newValue != null && oldValue != null && newValue.equals(oldValue)) { return; } /* Take note of who we are going to notify (and potentially un-notify) */ VetoableChangeListener[] listensToAll; VetoableChangeSupport listeners = null; // property change synchronized (this) { listensToAll = globalListeners .toArray(new VetoableChangeListener[0]); String propertyName = event.getPropertyName(); if (propertyName != null) { listeners = children.get(propertyName); } } try { for (VetoableChangeListener listener : listensToAll) { listener.vetoableChange(event); } } catch (PropertyVetoException pve) { // Tell them we have changed it back PropertyChangeEvent revertEvent = createPropertyChangeEvent( propName, newValue, oldValue); for (VetoableChangeListener listener : listensToAll) { try { listener.vetoableChange(revertEvent); } catch (PropertyVetoException ignored) { // expected } } throw pve; } if (listeners != null) { listeners.fireVetoableChange(event); } }
3e356b2f-da83-4302-bdef-013b827b7598
2
public void printNodesStack() { for (int i = 0; i < topOfStack; i++) { System.out.print((nodesStack[i] + 1) + " "); if (i % 100 == 0) System.out.println(); } }
baa3869c-45b1-4d46-a136-c5c6d6739201
5
@SuppressWarnings ("unchecked") protected final void update(final BaseItem item) throws NullPointerException, IllegalStateException, IllegalArgumentException { switch (item.state()) { case Item.REMOVE_STATE: case Item.CREATE_STATE: if (!this.equals(item.pool())) throw new IllegalArgumentException(); this.doUpdate((GItem)item); case Item.UPDATE_STATE: return; case Item.APPEND_STATE: throw new IllegalStateException(); default: throw new IllegalArgumentException(); } }
c4b7f9ec-bab7-4451-a155-d86284f7c9ae
1
public JPanel getUsertileImageMenu() { if (!isInitialized()) { IllegalStateException e = new IllegalStateException("Call init first!"); throw e; } return this.usermenuImageMenu; }
c3278b6a-347d-43d0-a25f-7ec18fd1734e
1
public void enol(int... overlays) { for (int ol : overlays) visol[ol]++; }
582c9326-2cb6-4354-9d47-307fd06d6063
0
public List<IrcUser> getUsers(){ return Users; }
e706c4a3-3025-45f5-9f79-ab647d1788d5
1
private boolean jj_3_2() { if (jj_3R_20()) return true; return false; }
a3ae52f0-f220-4a5e-bc16-b800426b7d4e
8
public String getOutputKeyword() { Dialog currentDialog = DialogManager.giveDialogManager().getCurrentDialog(); switch((KitchenAssistance)getCurrentState()) { case KA_ENTRY: setQuestion(true); return "<" + currentDialog.getCurrentSession().getCurrentUser().getUserData().getUserName() + ">"; case KA_EXIT: setQuestion(false); return null; case KA_TELL_INGREDIENT_FOUND: setQuestion(false); String output = "<" + ((KitchenAssistanceDialog)currentDialog).getRequestedObjectName() + ">"; output = output + ";{" + ((Ingredient)((KitchenAssistanceDialog)currentDialog).getRequestedObject()).getIngredientData().getIngredientLocation() + "}"; return output; case KA_TELL_INGREDIENT_NOT_FOUND: setQuestion(false); return "<" + ((KitchenAssistanceDialog)currentDialog).getRequestedObjectName() + ">"; case KA_TELL_TOOL_FOUND: setQuestion(false); String output2 = "<" + ((KitchenAssistanceDialog)currentDialog).getRequestedObjectName() + ">"; output2 = output2 + ";{" + ((Tool)((KitchenAssistanceDialog)currentDialog).getRequestedObject()).getToolData().getLocation() + "}"; return output2; case KA_TELL_TOOL_NOT_FOUND: setQuestion(false); return "<" + ((KitchenAssistanceDialog)currentDialog).getRequestedObjectName() + ">"; case KA_WAITING_FOR_TYPE: setQuestion(true); return "<" + ((KitchenAssistanceDialog)currentDialog).getRequestedObjectName() + ">"; case KA_WAITING_FOR_LOCATION: setQuestion(true); return "<" + ((KitchenAssistanceDialog)currentDialog).getRequestedObjectName() + ">"; default: return null; } }
fc9bfaaa-34cb-4014-a3e7-08a533e7a1d2
4
@Test public void testConstructor() throws SQLException, IOException, ClassNotFoundException { // Make new clean database new File("testConstructor.db").delete(); Timeflecks.getSharedApplication().setDBConnector( new SQLiteConnector(new File("testConstructor.db"), true)); ArrayList<File> files = new ArrayList<File>(); files.add(new File("testSwitchDatabase1.db")); files.add(new File("testSwitchDatabase2.db")); files.add(new File("testSwitchDatabase3.db")); // Positive tests new SQLiteConnector(files.get(0), true).serializeAndSave(new Task( "task1")); new SQLiteConnector(files.get(1), true).serializeAndSave(new Task( "task2")); Task task = new Task("task3"); SQLiteConnector conn = new SQLiteConnector(files.get(2), true); conn.serializeAndSave(task); Task returnTask = conn.getSerializedTask(task.getId()); assertEquals("Names should match", task.getName(), returnTask.getName()); // Negative tests try { new SQLiteConnector(new File("test1.notdb"), true); fail("Expected IllegalArgumentException because " + "of wrong extension"); } catch (IllegalArgumentException i) { // expected } try { new SQLiteConnector(new File(""), true); fail("Expected IllegalArgumentException because " + "of no extension"); } catch (IllegalArgumentException i) { // expected } try { new SQLiteConnector(new File("asdf"), true); fail("Expected IllegalArgumentException because " + "of wrong extension"); } catch (IllegalArgumentException i) { // expected } for (File f : files) { Files.delete(f.toPath()); } // Clean up new File("testConstructor.db").delete(); }
68445f02-9d18-4e20-be29-59a463053263
1
public int totalNQueens2(int n){ List<Integer> perm = new ArrayList<Integer>(n); for (int i = 0; i < n; ++i) perm.add(i); totalNQueens2Rec(0, perm); return res; }
0ae521a6-9692-4008-9725-670dc62214ae
8
private double functionVal(MinimaxNode node) { Player[] players = node.getGame().getPlayers(); double functionVal = 0; boolean hasWon = true; for(Player enemy : players) { if(enemy.getLoyalty() != player.getLoyalty()) { if(!enemy.isDefeated()) { hasWon = false; } } } if(hasWon) { return Double.MAX_VALUE; } if(player.isDefeated()) { return Double.MIN_VALUE; } for(Node gridNode : node.getBoard().getNodes()) { Piece piece = gridNode.getPiece(); if(piece != null) { if(piece.getLoyalty() == player.getLoyalty()) { functionVal += piece.getWorth(); } else { functionVal -= piece.getWorth(); } } } return functionVal; }
31e29103-9801-4ada-a079-c8cd17f9eadb
9
public boolean doTransformations() { if (instr == null) return false; /* * Do on the fly access$ transformation, since some further operations * need this. */ if (instr instanceof InvokeOperator) { Expression expr = ((InvokeOperator) instr).simplifyAccess(); if (expr != null) instr = expr; } StructuredBlock last = flowBlock.lastModified; return CreateNewConstructor.transform(this, last) || CreateAssignExpression.transform(this, last) || CreateExpression.transform(this, last) || CreatePrePostIncExpression.transform(this, last) || CreateIfThenElseOperator.create(this, last) || CreateConstantArray.transform(this, last) || CreateCheckNull.transformJavac(this, last); }
189cd885-da53-48da-adf6-9cc2ec0a17a4
1
public void draw(Graphics2D g, TreeNode node) { g.fill(NODE_SHAPE); Color c = g.getColor(); g.setColor(Color.black); g.draw(NODE_SHAPE); MinimizeTreeNode m = (MinimizeTreeNode) node; g.setColor(c); drawBox(g, getStateString(m), new Point2D.Float(0.0f, 0.0f)); g.setColor(c); drawBox(g, m.getTerminal(), new Point2D.Float(0.0f, 20.0f)); g.setColor(c); String label = getLabel(node); if (label == null) return; drawBox(g, label, new Point2D.Float(0.0f, -20.0f)); g.setColor(c); }
89aa1159-b93a-4c81-a66f-4f00f2f4f801
7
public void radixSort(int[] data){ int max = data[0] , radix = 1;; for (int i = 0; i < data.length; i++) { if(max < data[i]){ max = data[i]; } } Node[] bucket = new Node[10]; for (int i = 0; i < bucket.length; i++) { bucket[i] = new Node(); } while( max/radix > 0 ){ for (int i = 0; i < data.length; i++) { bucket[ (data[i] / radix)%10 ].list.add(data[i]); } int pos = 0 ; for (int i = 0; i < bucket.length; i++) { for (int j = 0; j < bucket[i].list.size(); j++) { data[pos++] = bucket[i].list.get(j); } bucket[i].list.clear(); } radix *= 10; } }
f61481c9-00d6-4403-960a-2136596ced9e
6
protected synchronized void parserNode(Node node, WebPage wp) throws Exception { if (node instanceof TextNode) {// 判斷是否是文本結點 // srb.addText(((TextNode) node).getText()); } else if (node instanceof Tag) {// 判斷是否是標籤庫結點 Tag atag = (Tag) node; if(wp.getCharSet().equalsIgnoreCase("ISO-8859-1")){ //抓此連結的 charSet if(atag instanceof MetaTag){ final MetaTag metaTag = (MetaTag) atag; if(metaTag.getMetaContent().contains("charset=")){ final String charSet = metaTag.getMetaContent().split("charset=")[1]; wp.setCharSet(EncodingSet.vauleOf(charSet).getValue()); } } } if (atag instanceof LinkTag) { // 判斷是否是標LINK結點 final LinkTag linkatag = (LinkTag) atag; String newUrl = linkatag.getLink(); WebPage newWp = new WebPage(); newWp.setDepth(wp.getDepth() + 1); newWp.setUrl(newUrl); cobweb.checkLink(newWp); } dealTag(atag, wp); atag = null; } }
fe28c3fd-3402-4948-8c90-923db37a399a
5
public static Carte getCarte (Label label, Couleur couleur) { Carte carte; switch (label) { case JOKER: carte = new Joker(); break; case PLUS2: carte = new Plus2(couleur); break; case PLUS4: carte = new Plus4(); break; case SINT: carte = new SensInterdit(couleur); break; case CHSENS: carte = new ChangerSens(couleur); break; default: carte = new Carte(label, couleur); break; } return carte; }