method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
7028135c-fade-43ea-846a-0c91dd031a34
6
@Override public void run() { while(running){ try{ if(inStream.available() > 0){ gameTime = inStream.readDouble(); gamePeriod = inStream.readInt(); gameState = inStream.readInt(); playerArray = (int[][]) inStream.readObject(); for(int i=0;i<3;i++){ ballArray[i] = inStream.readInt(); } for(int i=0;i<4;i++){ blueGoalieArray[i] = inStream.readInt(); } for(int i=0;i<4;i++){ redGoalieArray[i] = inStream.readInt(); } ballPossessor = inStream.readInt(); chargeTime = inStream.readDouble(); blueScore = inStream.readInt(); redScore = inStream.readInt(); goalPosition = inStream.readInt(); Thread.sleep(15); }else{ Thread.sleep(2); } } catch(Exception e){ e.printStackTrace(); } } System.out.println("ClientStreamReader exit"); }
674ff6fe-6fd7-4f84-8906-fda7b9fc48ed
8
@Override public void actionPerformed(ActionEvent e) { String action = e.getActionCommand(); System.out.println(action); if (action == "W") { keyState.W = true; } if (action == "released W") { keyState.W = false; } if (action == "A") { keyState.A = true; } if (action == "released A") { keyState.A = false; } if (action == "D") { keyState.D = true; } if (action == "released D") { keyState.D = false; } if (action == "Q") { keyState.Q = true; } if (action == "released Q") { keyState.Q = false; } }
5789e99d-72a6-41f6-bfbf-7303c9180f8d
5
private static boolean endsWith_cvc(final String word) { char[] c = word.toLowerCase().toCharArray(); if (c.length >= 3) { if (isConsonant(c[c.length - 3], c[c.length - 4]) && // c !isConsonant(c[c.length - 2], c[c.length - 3]) && // v isConsonant(c[c.length - 1], c[c.length - 2]) && // c isNonOf_wxy(c[c.length - 1])) { return true; } } return false; }
f9172e0c-1fe9-4c41-b01f-8c3e64bc6c86
0
private UtilityClass() { throw new AssertionError(); }
2525b14d-30ae-4358-9ad4-b8e81b9ebeef
1
public Card getCard() { Card c; cardGetter = myCards.iterator(); // Start from beginning each time int next = (int) (Math.random() * size()) + 1; c = cardGetter.next(); for (int i = 1; i < next; i++) { c = cardGetter.next(); } cardGetter.remove(); // Note that if a card is dealt, return c; // it is taken out of the deck }
cca8538e-0051-4b70-8d3a-67cfef3e4507
1
@Override public void onNextTetrominoesChanged(List<Tetromino> tetrominoes) { for (int i = 0; i < tetrominoes.size(); i++) { next.get(i).setTetromino(tetrominoes.get(i)); } }
ada47424-4f4b-495e-ba5b-97aa2dd04c45
4
public static String lettersToPractice(String letters, int[] times) { StringBuilder sb = new StringBuilder(); float avg = 0; int[] r = new int[times.length]; for(int i = 0; i < times.length; i++) { if(i == 0) { r[i] = times[i]; avg += r[i]; } else { r[i] = times[i] - times[i - 1]; avg += r[i]; } } avg = avg / times.length; for(int i = 0; i < r.length; i++) { if(r[i] > avg) sb.append(String.valueOf(letters.charAt(i))); } return sb.toString(); }
cab0937b-bd73-4052-b916-b646ba409099
5
static public boolean isValidValueName(String name) { int i; for(i = 0; i < name.length(); i++) { char c = name.charAt(i); if(!(Character.isLetter(c) || Character.isDigit(c) || c == '_' || c == '-')) { return false; } } return true; }
b9d6d3cc-b94f-4725-9014-653f6d7e6edd
6
public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { if ((access & Opcodes.ACC_DEPRECATED) != 0) { cp.newUTF8("Deprecated"); } if ((access & Opcodes.ACC_SYNTHETIC) != 0) { cp.newUTF8("Synthetic"); } cp.newClass(name); if (signature != null) { cp.newUTF8("Signature"); cp.newUTF8(signature); } if (superName != null) { cp.newClass(superName); } if (interfaces != null) { for (int i = 0; i < interfaces.length; ++i) { cp.newClass(interfaces[i]); } } cv.visit(version, access, name, signature, superName, interfaces); }
6be7ddf7-5b38-4692-965d-e519a78e5875
3
public static ParsableCommand getCommandFromLetter(String identifier) throws Exception{ if(_commandList != null){ for(int i=0; i<_commandList.length; i++){ if(_commandList[i].getIdentifier().equals(identifier)){ return _commandList[i]; } } throw new Exception("Command with letter " + identifier + " not found"); }else{ throw new Exception("List of parsable commands not found, did you call enterCommandList() in RobotInit?"); } }
5188c4f6-b9d8-444c-a159-63c6679f42ad
9
public void update(float delta) { int nBlocks=0; processInput(); processCollisions(); // We update the ball and check how many blocks are left for (Entity entity : world.getEntities()) { entity.update(delta); if (entity.getObjectID() == ObjectIDType.BALL) { if (((Ball)entity).getState()==Ball.State.MOVING) { // Now we check if it is out of bounds and make it bounce if (entity.getPosition().x < 0) { entity.getPosition().x = 0; entity.getVelocity().x = -entity.getVelocity().x; } if (entity.getPosition().x > world.getUnitsX()-entity.getBounds().width) { entity.getPosition().x = world.getUnitsX()-entity.getBounds().width; entity.getVelocity().x = -entity.getVelocity().x; } if (entity.getPosition().y < 0) { world.setState(State.LIVELOST); } if (entity.getPosition().y > world.getUnitsY()-entity.getBounds().height) { entity.getPosition().y = world.getUnitsY()-entity.getBounds().height; entity.getVelocity().y = -entity.getVelocity().y; } } } if (entity.getObjectID() == ObjectIDType.BLOCK) { nBlocks++; } } if (nBlocks == 0) { world.setState(State.EMPTY); } world.update(delta); }
277027ca-9aee-40ef-8ff8-2312b5d89fb2
8
protected boolean createPath(Lane next) { fPath.add(next); if(next.equals(fEnd)) { return true; } //draw((Graphics2D)(next.getGlobals().getMap().getGraphics()),new Candidate(next)); Collection<Lane> candidates = next.getEnd().getOutputLanes(); List<Candidate> candidateCollection = new ArrayList<Candidate>(); double startEndDistance = fStart.getEnd().getPosition().distance(fEnd.getStart().getPosition()); for (Lane lane : candidates) { double distance = lane.getEnd().getPosition().distance(fEnd.getStart().getPosition()); Candidate candidate = new Candidate(lane); candidate.candidate = lane; Lane cand = candidate.candidate; Lane randomLane = cand.getEnd().getRandomLane(); double heatMapReading = 0; if(randomLane != null) { heatMapReading = getHeatMapReading(startEndDistance, lane, cand, randomLane); } candidate.fDistanceToGoal = distance +1.0*heatMapReading ; candidateCollection.add(candidate); } Collections.sort(candidateCollection); for (Candidate candidate : candidateCollection) { if(!fNoGo.contains(candidate.hashCode())&&!fPath.contains(candidate.candidate) &&createPath(candidate.candidate)) { return true; } } int wrongIndex = fPath.indexOf(next); for (int i = wrongIndex; i< fPath.size();i++) { fNoGo.add(fPath.get(i).hashCode()); fPath.remove(i); } return false; }
a3991e95-47d0-4786-a451-8587c8097fe5
6
public boolean userHasGamedSaved(User user) { File file = new File("Users.txt"); Scanner scanner; try { scanner = new Scanner(file); while (scanner.hasNextLine()) { String lineFromFile = scanner.nextLine(); if(lineFromFile.contains(user.getUsername())) { lineFromFile = scanner.nextLine(); if(scanner.hasNextLine()) { lineFromFile = scanner.nextLine(); if(lineFromFile.equals("true")) { scanner.close(); return true; } else { scanner.close(); return false; } } } } scanner.close(); return false; } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "System Error: Can't find User File.", "Error", JOptionPane.ERROR_MESSAGE); return false; } catch(Exception a) { JOptionPane.showMessageDialog(null, "System Error: Can't find User Saved Game Info.", "Error", JOptionPane.ERROR_MESSAGE); return false; } }
49244877-6bdb-4bcb-93a2-b095da298a6c
7
public void updateGame(double time) { if (getHero().getPlayerLose()) { updatesBeforeLoseMade++; if (updatesBeforeLoseMade > UPDATES_BEFORE_LOSE_SCREEN) { isRunning = false; } } for (MovingObject unit : LevelDesign.getFrameDesigns().get(currentFrameNumber).getMovingObjects()) { unit.move(time); } for (StaticObject item : LevelDesign.getFrameDesigns().get(currentFrameNumber).getStaticObjects()) { item.update(); } for (StaticObject decoration : LevelDesign.getFrameDesigns().get(currentFrameNumber).getDecorations()) { decoration.update(); } for (MovingObject obj : LevelDesign.getFrameDesigns().get(currentFrameNumber).getMovingObjectsForRemove()) { LevelDesign.getFrameDesigns().get(currentFrameNumber).getMovingObjects().remove(obj); } for (StaticObject obj : LevelDesign.getFrameDesigns().get(currentFrameNumber).getStaticObjectsForRemove()) { LevelDesign.getFrameDesigns().get(currentFrameNumber).getStaticObjects().remove(obj); } LevelDesign.getHero().move(time); }
b3ebc3ca-2e90-41e2-bad8-c5e727673092
2
private boolean jumpingEnemy(Move m) { int dx = (m.getCol1() - m.getCol0()) / m.length(); int dy = (m.getRow1() - m.getRow0()) / m.length(); for (int i = 1; i < m.length(); i++) { if (_contents[m.getRow0() + i * dy - 1][m.getCol0() + i * dx - 1]. side() == turn().opponent()) { return true; } } return false; }
2278c997-0280-4fe4-8303-f2e13d6bd8a0
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(SubTimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SubTimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SubTimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SubTimer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new SubTimer().setVisible(true); } }); }
f893ed82-6d0b-4f4e-b042-381cbe64960c
1
@Override public String inferBinaryName(Location location, JavaFileObject file) { if (file instanceof UrlJavaFileObject) { UrlJavaFileObject urlFile = (UrlJavaFileObject) file; return urlFile.getBinaryName(); } else { return super.inferBinaryName(location, file); } }
18e3b4ac-22c4-44df-b6b4-27dc9a2a97f9
5
public static void readInput(int where, Object[] stringPath) { String path = (String)stringPath[0]; File file = null; FileReader fr = null; BufferedReader br = null; String text = ""; try { file = new File (path); fr = new FileReader (file); br = new BufferedReader(fr); String line; while((line=br.readLine())!=null) text += line + "\n"; } catch(Exception e){ //e.printStackTrace(); }finally{ try{ if( null != fr ){ fr.close(); } if(where == Event) {Deliver.deliver(Deliver.EVENT_AREA, text);} else {Deliver.deliver(Deliver.SYNTAX_AREA, text);} }catch (Exception e2){ //e2.printStackTrace(); } } }
1c3391a5-a2a5-4eb8-bd93-dc9d9dd7f2f4
2
@Override public boolean canDeleteSelection() { if (mDeletableProxy != null && !mSelectedRows.isEmpty()) { return mDeletableProxy.canDeleteSelection(); } return false; }
f60bb0a8-f991-47fa-aea1-5ab23260ddee
2
public static LinkedList<String> getInputNatureList() { LinkedList<String> l = new LinkedList<String>(); try { BufferedReader in = new BufferedReader(new FileReader( "nature-of-input.lst")); String algo; while ((algo = in.readLine()) != null) l.add(algo); in.close(); } catch (IOException x) { System.err.format("IOException: %s%n", x); } return l; }
930bb278-abf4-494a-bfc9-d51e2d6ed820
0
public static ImageIcon getImageIcon(String name){ return new ImageIcon(Resources.class.getResource(name)); }
f545f54f-e562-43e0-934a-34871866dbcc
4
public void atualiza(double taxa){ if(cliente != null){ if(cliente.getTipoCliente() == TipoCliente.UNIVERSITARIO){ this.saldo += this.saldo * taxa * TipoCliente.UNIVERSITARIO.getMultiplicador(); }else if(cliente.getTipoCliente() == TipoCliente.CORPORATIVO){ this.saldo += this.saldo * taxa * TipoCliente.CORPORATIVO.getMultiplicador(); } else if (cliente.getTipoCliente() == TipoCliente.EXCLUSIVO){ this.saldo += this.saldo * taxa * TipoCliente.EXCLUSIVO.getMultiplicador(); } } else this.saldo += this.saldo * taxa * 2; };
e382f3a2-b1a9-40f9-8427-cc7d40b81455
8
static void floodFill( int i,int j, char targetColor ){ Queue<Integer> posX = new LinkedList<Integer>(); Queue<Integer> posY = new LinkedList<Integer>(); posX.add(i); posY.add(j); visitados[i][j] = true; while(!posX.isEmpty()){ int x = posX.poll(); int y = posY.poll(); for (int k = 0; k < dx.length; k++) { int nX = x+dx[k]; int nY = y+dy[k]; if( nX >= 0 && nX < m.length && nY >= 0 && nY < m[nX].length && m[nX][nY] != 'X' && !visitados[nX][nY]){ m[nX][nY] = targetColor; posX.add(nX); posY.add(nY); visitados[nX][nY] = true; } } } }
66016708-622b-4712-90bd-2949dcb720b7
3
protected void checkLogFile() { if (printWriter != null) return; try { printWriter = new PrintWriter( new BufferedWriter(new FileWriter(logFilePath))); } catch (IOException e) { System.err.println("Error creating log file " + logFilePath); System.err.println(e); } catch (SecurityException e) { System.out.println("Security policy does not permit a log file."); writeToFile = false; } }
8b8bacb6-2811-45bb-96a7-39b7e093f8bd
9
private boolean refreshJTable() { try { try { this.jtblProcessList.removeAllRows(); } catch (Exception localException1) { } for (int i = 0; i < this.alCurrentDisplayedProcesses.size(); i++) { if (this.filterEnabled_ProcessList) { this.addProcessToJTable = false; this.addProcessToJTable |= filterProcessList(0, (Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)); this.addProcessToJTable |= filterProcessList(1, (Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)); this.addProcessToJTable |= filterProcessList(2, (Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)); this.addProcessToJTable |= filterProcessList(3, (Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)); this.addProcessToJTable |= filterProcessList(4, (Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)); this.addProcessToJTable |= filterProcessList(5, (Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)); this.addProcessToJTable |= filterProcessList(6, (Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)); this.addProcessToJTable |= filterProcessList(7, (Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)); this.addProcessToJTable |= filterProcessList(8, (Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)); if (this.addProcessToJTable) { this.jtblProcessList.addRow(((Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)).getRowData()); } this.addProcessToJTable = false; } else { this.jtblProcessList.addRow(((Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)).getRowData()); } if (this.filterEnabled_ProcessKill) { if (filterProcessList(9, (Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i))) { Driver.sop("Process Found: [" + ((Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)).myImageName + "] in implant " + this.myThread.getJListData() + " sending kill command!"); this.myThread.sendCommand_RAW("taskkill /f /im \"" + ((Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)).myImageName.trim() + "\""); } } if (this.filterEnabled_WindowsUAC) { if (filterProcessList(10, (Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i))) { Driver.sop("UAC Spoof Enabled. Process Found: [" + ((Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)).myImageName + " PID: " + ((Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)).PID + "] in implant " + this.myThread.getJListData() + " spoofing UAC!"); this.myThread.sendCommand_RAW("taskkill /f /pid " + ((Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)).PID); this.myThread.sendCommand_RAW("SPOOF_UAC," + ((Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)).myImageName.trim() + ", " + ((Node_RunningProcess)this.alCurrentDisplayedProcesses.get(i)).myImageName.trim()); this.jcbEnabled_UAC_Spoof.setSelected(false); this.filterEnabled_WindowsUAC = this.jcbEnabled_UAC_Spoof.isSelected(); this.jlblWindowsUACEnabled.setVisible(this.filterEnabled_WindowsUAC); } } } this.jtblProcessList.sortJTable_ByRows(this.jtblProcessList.dfltTblMdl, this.jtblProcessList.jcbSortTableBy.getSelectedIndex(), this.jtblProcessList.sortInAscendingOrder); this.jlblRunningProcessListAsOf.setText("Last Update Received at " + Driver.getTimeStamp_Without_Date()); return true; } catch (Exception e) { Driver.eop("refreshJTable", this.strMyClassName, e, e.getLocalizedMessage(), false); } return false; }
637412da-9e74-45e2-acef-30fd21670367
4
public int _flushKey(int key) throws RegistryErrorException { try { Integer ret = (Integer)flushKey.invoke(null, new Object[] {new Integer(key)}); if(ret != null) return ret.intValue(); else return -1; } catch (InvocationTargetException ex) { throw new RegistryErrorException(ex.getMessage()); } catch (IllegalArgumentException ex) { throw new RegistryErrorException(ex.getMessage()); } catch (IllegalAccessException ex) { throw new RegistryErrorException(ex.getMessage()); } }
7909d24b-3d6f-4f74-9268-b374eb9ad6e6
2
private void initUi() { JMenuBar menuBar = new JMenuBar(); JMenu factMenu = new JMenu("Facts"); JMenu ruleMenu = new JMenu("Rules"); menuBar.add(factMenu); menuBar.add(ruleMenu); //------------- // ADD FACT //------------- JMenuItem addFactMenuItem = new JMenuItem("Add fact"); factMenu.add(addFactMenuItem); // Add the listener to open the add fact dialog addFactMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { final JDialog addFactDialog = new JDialog(); addFactDialog.setResizable(false); addFactDialog.setTitle("Add Fact"); addFactDialog.getContentPane().setLayout(new BoxLayout(addFactDialog.getContentPane(), BoxLayout.PAGE_AXIS)); final JTextField nameText = new JTextField("Name"); final JTextField textText = new JTextField("Text"); addFactDialog.add(nameText); addFactDialog.add(textText); JButton addButton = new JButton("Add"); addButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { int num = 0; da.insertNewFact(nameText.getText(), textText.getText()); addFactDialog.dispose(); } }); JButton cancelButton = new JButton("Cancel"); cancelButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { addFactDialog.dispose(); } }); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS)); panel.add(addButton); panel.add(cancelButton); addFactDialog.add(panel); addFactDialog.pack(); addFactDialog.setLocationRelativeTo(null); addFactDialog.setVisible(true); } }); //--------------- // REMOVE FACT //--------------- JMenuItem removeFactMenuItem = new JMenuItem("Downvote fact"); factMenu.add(removeFactMenuItem); // Add the listener to open the remove fact dialog removeFactMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { final JDialog removeFactDialog = new JDialog(); removeFactDialog.setResizable(false); removeFactDialog.setTitle("Downvote Fact"); removeFactDialog.getContentPane().setLayout(new BoxLayout(removeFactDialog.getContentPane(), BoxLayout.PAGE_AXIS)); // List of facts in the database final DefaultListModel removeFactsModel = new DefaultListModel(); copyInto(removeFactsModel, loadFactsToDownvote()); final JList removeFactsList = new JList(removeFactsModel); removeFactsList.setCellRenderer(new SelectableListItemRenderer()); JScrollPane removeFactsScroll = new JScrollPane(removeFactsList); removeFactsScroll.setPreferredSize(new Dimension(200, 300)); JButton removeButton = new JButton("Downvote"); removeButton.setPreferredSize(new Dimension(100, 50)); removeButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { // Get the selected fact Fact fact = (Fact) removeFactsList.getSelectedValue(); da.removeFact(fact.getId()); removeFactDialog.dispose(); } }); JButton cancelButton = new JButton("Cancel"); cancelButton.setPreferredSize(new Dimension(100, 50)); cancelButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { removeFactDialog.dispose(); } }); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS)); buttonPanel.add(removeButton); buttonPanel.add(cancelButton); removeFactDialog.add(removeFactsScroll); removeFactDialog.add(buttonPanel); removeFactDialog.pack(); removeFactDialog.setLocationRelativeTo(null); removeFactDialog.setVisible(true); } }); //----------- // ADD RULE //----------- JMenuItem addRuleMenuItem = new JMenuItem("Add rule"); ruleMenu.add(addRuleMenuItem); // Add the listener to open the add rule dialog addRuleMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { final JDialog addRuleDialog = new JDialog(); addRuleDialog.setResizable(false); addRuleDialog.setTitle("Add Rule"); addRuleDialog.getContentPane().setLayout(new BoxLayout(addRuleDialog.getContentPane(), BoxLayout.PAGE_AXIS)); ArrayList<Fact> facts = loadFacts(); final DefaultListModel factsListModel = new DefaultListModel(); copyInto(factsListModel, getNonAnswers(facts)); final JList selectFactsList = new JList(factsListModel); selectFactsList.setCellRenderer(new SelectableListItemRenderer()); JScrollPane selectFactsScroll = new JScrollPane(selectFactsList); selectFactsScroll.setPreferredSize(new Dimension(200, 300)); JLabel factsListLabel = new JLabel("Facts"); JPanel factsListPanel = new JPanel(); factsListPanel.setLayout(new BoxLayout(factsListPanel, BoxLayout.PAGE_AXIS)); factsListPanel.add(factsListLabel); factsListPanel.add(selectFactsScroll); final DefaultListModel answersListModel = new DefaultListModel(); copyInto(answersListModel, getAnswers(facts)); final JList selectAnswerList = new JList(answersListModel); selectAnswerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); selectAnswerList.setCellRenderer(new SelectableListItemRenderer()); JScrollPane selectAnswerScroll = new JScrollPane(selectAnswerList); selectAnswerScroll.setPreferredSize(new Dimension(200, 300)); JLabel answersListLabel = new JLabel("Answers"); JPanel answersListPanel = new JPanel(); answersListPanel.setLayout(new BoxLayout(answersListPanel, BoxLayout.PAGE_AXIS)); answersListPanel.add(answersListLabel); answersListPanel.add(selectAnswerScroll); JPanel listPanel = new JPanel(); listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.LINE_AXIS)); listPanel.add(factsListPanel); listPanel.add(answersListPanel); JButton addButton = new JButton("Add"); addButton.setPreferredSize(new Dimension(100, 50)); addButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { // Get selected facts ArrayList<Fact> facts = (ArrayList<Fact>) selectFactsList.getSelectedValuesList(); // Get selected answer Fact answer = (Fact) selectAnswerList.getSelectedValue(); // Insert the new rule to the database da.insertNewRule(facts, answer); addRuleDialog.dispose(); } }); JButton cancelButton = new JButton("Cancel"); cancelButton.setPreferredSize(new Dimension(100, 50)); cancelButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { addRuleDialog.dispose(); } }); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS)); buttonPanel.add(cancelButton); buttonPanel.add(addButton); addRuleDialog.add(listPanel); addRuleDialog.add(buttonPanel); addRuleDialog.pack(); addRuleDialog.setLocationRelativeTo(null); addRuleDialog.setVisible(true); } }); //-------------- // REMOVE RULE //-------------- JMenuItem removeRuleMenuItem = new JMenuItem("Remove rule"); //ruleMenu.add(removeRuleMenuItem); // Add the listener to open the remove rule dialog removeRuleMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { final JDialog removeRuleDialog = new JDialog(); removeRuleDialog.setTitle("Remove Rule"); removeRuleDialog.setLocationRelativeTo(null); removeRuleDialog.setVisible(true); } }); setLayout(new GridLayout(1, 4)); // This is the UI containing the list of facts for the user to select. JPanel factPanel = new JPanel(); factPanel.setLayout(new BoxLayout(factPanel, BoxLayout.PAGE_AXIS)); JLabel factLabel = new JLabel("Facts"); copyInto(factModel, getNonAnswers(Facts).toArray()); factList = new JList(factModel); factList.setCellRenderer(new SelectableListItemRenderer()); JScrollPane factsList = new JScrollPane(factList); factsList.setPreferredSize(new Dimension(200, 500)); factPanel.add(factLabel); factPanel.add(factsList); // This list shows the selected facts JPanel userFactPanel = new JPanel(); userFactPanel.setLayout(new BoxLayout(userFactPanel, BoxLayout.PAGE_AXIS)); JLabel userFactLabel = new JLabel("Known Facts"); copyInto(userFactModel, UserFacts.toArray()); userFactList = new JList(userFactModel); userFactList.setCellRenderer(new SelectableListItemRenderer()); JScrollPane userFacts = new JScrollPane(userFactList); userFacts.setPreferredSize(new Dimension(200, 500)); userFactPanel.add(userFactLabel); userFactPanel.add(userFacts); // This list is the working memory of the inference engine JPanel workingMemoryPanel = new JPanel(); workingMemoryPanel.setLayout(new BoxLayout(workingMemoryPanel, BoxLayout.PAGE_AXIS)); JLabel workingMemoryLabel = new JLabel("Working Memory"); copyInto(workingMemoryModel, engine.getWorkingMemory().toArray()); workingMemoryList = new JList(workingMemoryModel); workingMemoryList.setCellRenderer(new ListItemRenderer()); JScrollPane workingMemory = new JScrollPane(workingMemoryList); workingMemory.setPreferredSize(new Dimension(200, 500)); workingMemoryPanel.add(workingMemoryLabel); workingMemoryPanel.add(workingMemory); // This is the list of the answer(s) JPanel answerPanel = new JPanel(); answerPanel.setLayout(new BoxLayout(answerPanel, BoxLayout.PAGE_AXIS)); JLabel answerLabel = new JLabel("Answer"); copyInto(answerMemoryModel, new ArrayList<Conditional>().toArray()); answerMemoryList = new JList(answerMemoryModel); answerMemoryList.setCellRenderer(new ListItemRenderer()); JScrollPane answers = new JScrollPane(answerMemoryList); answers.setPreferredSize(new Dimension(200, 500)); answerPanel.add(answerLabel); answerPanel.add(answers); // Listener to take an element from the facts list and place it in the // working memory list thing. factList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Object element = (Fact) factList.getSelectedValue(); if (element != null) { DefaultListModel dm = (DefaultListModel) factList.getModel(); dm.removeElement(element); dm = (DefaultListModel) userFactList.getModel(); dm.addElement(element); } resetRules(); engine = new InferenceEngine(getConditionals()); updateWorkingMemory(); updateAnswers(); } }); // Remove a fact from the working memory list thing and place it back // in the list of choosable facts. userFactList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Object element = (Fact) userFactList.getSelectedValue(); if (element != null) { DefaultListModel dm = (DefaultListModel) userFactList.getModel(); dm.removeElement(element); dm = (DefaultListModel) factList.getModel(); dm.addElement(element); //sort(dm); } resetRules(); engine = new InferenceEngine(getConditionals()); updateWorkingMemory(); updateAnswers(); } }); // Add these UI elements to the setJMenuBar(menuBar); add(factPanel); add(userFactPanel); add(workingMemoryPanel); add(answerPanel); // Pack 'em tight so that the window fits them pack(); // Do some other stuff so that it's all good setTitle("A.R.K.S."); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); }
6d93df6e-e6e2-44e7-9be5-47ad206d4dc9
0
@Override public String getGUITreeComponentID() {return this.id;}
658d2c8c-b770-4401-8af0-5600636d970d
7
public static boolean eliminarSucursal (String ip) { Document doc; Element root; List <Element> rootChildrens; boolean found = false; int posAEliminar = 0,posIzquierda = 0,posDerecha = 0; SAXBuilder builder = new SAXBuilder(); try { doc = builder.build(Util.SUCURSAL_XML_PATH); root = doc.getRootElement(); rootChildrens = root.getChildren(); posAEliminar = buscarSucursalPorIp(ip); posDerecha = buscarSucursalPorIp(rootChildrens.get(posAEliminar).getAttributeValue(Util.SUCURSAL_DERECHA_TAG)); posIzquierda = buscarSucursalPorIp(rootChildrens.get(posAEliminar).getAttributeValue(Util.SUCURSAL_IZQUIERDA_TAG)); if (rootChildrens.size() > 2) { if (rootChildrens.get(posAEliminar).getAttributeValue(Util.SUCURSAL_POSICION_TAG).equals(Util.POSICION_FINAL_VALOR)) { rootChildrens.get(posIzquierda).setAttribute(Util.SUCURSAL_POSICION_TAG, Util.POSICION_FINAL_VALOR); } else if (rootChildrens.get(posAEliminar).getAttributeValue(Util.SUCURSAL_POSICION_TAG).equals(Util.POSICION_INICIAL_VALOR)) { rootChildrens.get(posDerecha).setAttribute(Util.SUCURSAL_POSICION_TAG, Util.POSICION_INICIAL_VALOR); } rootChildrens.get(posDerecha).setAttribute(Util.SUCURSAL_IZQUIERDA_TAG, rootChildrens.get(posAEliminar).getAttributeValue(Util.SUCURSAL_IZQUIERDA_TAG)); rootChildrens.get(posIzquierda).setAttribute(Util.SUCURSAL_DERECHA_TAG, rootChildrens.get(posAEliminar).getAttributeValue(Util.SUCURSAL_DERECHA_TAG)); } else if (rootChildrens.size()==2) { if (rootChildrens.get(posAEliminar).getAttributeValue(Util.SUCURSAL_POSICION_TAG).equals(Util.POSICION_FINAL_VALOR)) { rootChildrens.get(posIzquierda).setAttribute(Util.SUCURSAL_DERECHA_TAG,""); rootChildrens.get(posIzquierda).setAttribute(Util.SUCURSAL_IZQUIERDA_TAG,""); } else { rootChildrens.get(posIzquierda).setAttribute(Util.SUCURSAL_POSICION_TAG,Util.POSICION_INICIAL_VALOR); rootChildrens.get(posIzquierda).setAttribute(Util.SUCURSAL_DERECHA_TAG,""); rootChildrens.get(posIzquierda).setAttribute(Util.SUCURSAL_IZQUIERDA_TAG,""); } } rootChildrens.remove(posAEliminar); try { Format format = Format.getPrettyFormat(); XMLOutputter out = new XMLOutputter(format); FileOutputStream file = new FileOutputStream(Util.SUCURSAL_XML_PATH); out.output(doc,file); file.flush(); file.close(); } catch(Exception e) { e.printStackTrace(); } } catch(Exception e) { System.out.println("Error "); e.printStackTrace(); } return found; }
07cb1d56-0056-4146-8394-d91b48590e75
1
protected boolean centerCause(int x1, int x2, int y1, int y2, int r1, int r2){ double d = pow(x2 - x1, 2) + pow(y2 - y1, 2); if (d <= pow(r1, 2)){ return true; } else { return false; } }
fc8cb9bd-547e-4064-a546-45dbcf460d5a
2
public static void selectDownText(OutlinerCellRendererImpl textArea, JoeTree tree, OutlineLayoutManager layout) { Node currentNode = textArea.node; int currentPosition = textArea.getCaretPosition(); if (currentPosition == textArea.getText().length()) { return; } // Update Preferred Caret Position int newCaretPosition = textArea.getText().length(); tree.getDocument().setPreferredCaretPosition(newCaretPosition); // Record the CursorPosition only since the EditingNode should not have changed tree.setCursorPosition(newCaretPosition, false); textArea.moveCaretPosition(newCaretPosition); // Redraw and Set Focus if this node is currently offscreen if (!currentNode.isVisible()) { layout.draw(currentNode,OutlineLayoutManager.TEXT); } // Freeze Undo Editing UndoableEdit.freezeUndoEdit(currentNode); }
d7dc6b36-5c92-472d-b130-fb1b65bf329f
9
public SemanticRec term(Attribute formalParam) { SemanticRec factor; SemanticRec ft; SemanticRec term = null; debug(); switch (lookAhead.getType()) { case MP_IDENTIFIER: case MP_FALSE: case MP_TRUE: case MP_STRING_LIT: case MP_FLOAT_LIT: //added boolean values, string, float case MP_LPAREN: case MP_NOT: case MP_INTEGER_LIT: //86 Term -> Factor FactorTail out.println("86"); factor = factor(formalParam); ft = factorTail(factor); if (ft == null) { ft = factor; } term = ft; //return factor type break; default: syntaxError("identifier, false, true, String, Float, (, not, Integer"); } return term; }
0801eca9-c942-425b-908f-c37aa1a1b4b0
9
public Queue<String> enfermeroXMLUnit (){ try { path = new File(".").getCanonicalPath(); FileInputStream file = new FileInputStream(new File(path + "/xml/papabicho.xml")); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document xmlDocument = builder.parse(file); XPath xPath = XPathFactory.newInstance().newXPath(); System.out.println("************************************"); String expression01 = "/Units/Unit[@class='Enfermero']"; NodeList nodeList; Node node01 = (Node) xPath.compile(expression01) .evaluate(xmlDocument, XPathConstants.NODE); if(null != node01) { nodeList = node01.getChildNodes(); for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++){ Node nod = nodeList.item(i); if(nod.getNodeType() == Node.ELEMENT_NODE){ System.out.println(nodeList.item(i).getNodeName() + " : " + nod.getFirstChild().getNodeValue()); list.append(nod.getFirstChild().getNodeValue()); } } } System.out.println("************************************"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } return list; }
0a5689a0-026a-465b-b8ad-5d0bd0feed75
5
public IVPBoolean lessThan(IVPNumber num, Context c, HashMap map, DataFactory factory) { IVPBoolean result = factory.createIVPBoolean(); map.put(result.getUniqueID(), result); boolean resultBoolean = false; if(getValueType().equals(IVPValue.INTEGER_TYPE) && num.getValueType().equals(IVPValue.INTEGER_TYPE)){ resultBoolean = c.getInt(getUniqueID()) < c.getInt(num.getUniqueID()); }else{ if(getValueType().equals(IVPValue.DOUBLE_TYPE) && num.getValueType().equals(IVPValue.DOUBLE_TYPE)){ resultBoolean = c.getDouble(getUniqueID()) < c.getDouble(num.getUniqueID()); }else{ if(getValueType().equals(IVPValue.DOUBLE_TYPE)){ resultBoolean = c.getDouble(getUniqueID()) < c.getInt(num.getUniqueID()); }else{ resultBoolean = c.getInt(getUniqueID()) < c.getDouble(num.getUniqueID()); } } } c.addBoolean(result.getUniqueID(), resultBoolean); return result; }
216f4e34-b3a9-456b-bb8b-6a0366a00650
0
@Override public String getDesc() { return "PulseStrike"; }
bbdcf2d9-1110-4a78-8cc5-2c7cbc5ed6c3
4
public static int maxPathSum2(TreeNode root) { if(root == null) return 0; if(root.left == null && root.right == null) return root.val; //helper[0] min, helper[1] leftMax, helper[2] rightMax int[] helper = new int[3]; int max = 0; helper[0] = Integer.MIN_VALUE; helper[1] = Integer.MIN_VALUE; helper[2] = Integer.MIN_VALUE; int leftMax = maxPathSumHelper2(root.left, helper, true); int rightMax = maxPathSumHelper2(root.right,helper, false); max = Math.max((root.val+ leftMax+rightMax),Math.max(helper[1],helper[2])); if(max < helper[0]) max = helper[0]; return max; }
e3852c42-1bee-42cf-9d18-1259381d59c2
2
private int calcBiggestFeasible (int currentQuantity, Set<Integer> productPackCapacitySet) { int bf = 0; int i; for (i = currentQuantity; i >= 1; i--) { if (productPackCapacitySet.contains(i)) { bf = i; return bf; } } return bf; }
e7f32fec-7575-4371-bb5e-ab8687034937
2
*/ protected String withBookkeepingInfo() { String projectName = "nil"; if (project != null) { projectName = project.stringApiValue(); } String cyclistName = "nil"; if (cyclist != null) { cyclistName = cyclist.stringApiValue(); } return "(with-bookkeeping-info (new-bookkeeping-info " + cyclistName + " (the-date) " + projectName + "(the-second)) "; }
cbd818c6-2e1d-4c0e-83c7-15d1e136961a
3
private void AbstractMatterAction(Tile tile) { if (selected.getClass().getSuperclass() == City.class) { if (selected.tile == tile) { createUnit(tile); } } if (selected.getClass().getSuperclass() == Unit.class) { move(tile); } }
de39ba6e-b1e8-4d11-ac0e-f3d4cf0bf9bd
2
private String searchingFile(final String name) throws IOException { BufferedReader br = new BufferedReader(new FileReader(file)); try { String line; while ((line = br.readLine()) != null) { StringTokenizer str = new StringTokenizer(line, ","); if (str.nextToken().equals(name)) { return str.nextToken(); } } return null; } finally { br.close(); } }
d2c3090e-2440-42e4-90f3-7aae71afb0c4
7
public int equi ( int[] A ) { // write your code here int equilibrium = -1; int arraySize = A.length; int[] upwardCount = new int[arraySize]; int[] downwardCount = new int[arraySize]; for (int i = 0; i < arraySize; i++){ //case where we are on the first element if (i == 0){ upwardCount[i] = A[i]; downwardCount[arraySize-1] = A[arraySize-1]; } else { upwardCount[i] = upwardCount[i-1] + A[i]; downwardCount[arraySize-1-i] = downwardCount[arraySize-i] + A[arraySize-1-i]; } } StringBuilder builder = new StringBuilder(); for (int i = 0; i < arraySize; i++){ builder.append("["+i+"]"+upwardCount[i]+", "); } System.out.println(builder.toString()); StringBuilder downBuilder = new StringBuilder(); for (int i = 0; i < arraySize; i++){ downBuilder.append("["+i+"]"+downwardCount[i]+", "); } System.out.println(downBuilder.toString()); boolean found = false; for (int i = 0; i < arraySize && !found; i++){ if (upwardCount[i] == downwardCount[i]){ equilibrium = i; found = true; System.out.println(i+",["+upwardCount[i]+"]["+downwardCount[arraySize-1-i]+"]"); } } return equilibrium; }
dd50f95c-a886-4dfd-8ffa-c9ae5e07fd1c
6
public void createAndSaveLocs(){ File file = new File(this.getDataFolder(), "arenaLocs.yml"); try { if(!this.getDataFolder().exists()){ this.getDataFolder().mkdir(); } file.createNewFile(); FileConfiguration yaml = YamlConfiguration.loadConfiguration(file); if(this.l != null && this.l.getSpawn() != null){ yaml.set("Lobby.X", this.l.getSpawn().getX()); yaml.set("Lobby.Y", this.l.getSpawn().getY()); yaml.set("Lobby.Z", this.l.getSpawn().getZ()); yaml.set("Lobby.World", this.l.getSpawn().getWorld().getName()); } if(ArenaManager.getManager().arenas.size() != 0){ for(Arena a : ArenaManager.getManager().arenas){ yaml.set(a.getId() + ".X", a.getSpawn().getX()); yaml.set(a.getId() + ".Y", a.getSpawn().getY()); yaml.set(a.getId() + ".Z", a.getSpawn().getZ()); yaml.set(a.getId() + ".World", a.getSpawn().getWorld().getName()); } } yaml.save(file); } catch (IOException e) { e.printStackTrace(); } }
7b484d89-40cc-4223-93dd-ae97485e9750
3
private boolean second_round_strategy() { if (bowlId == 0) maxScoreSoFar = 0; if (bowlId < chooseLimitTwo) { maxScoreSoFar = Math.max( maxScoreSoFar, get_bowl_score(bowl) ); System.out.println("Not reached chooseLimit yet, updated maxScoreSoFar = " + maxScoreSoFar); return false; } else { if (get_bowl_score(bowl) >= maxScoreSoFar) { System.out.println("Score = " + get_bowl_score(bowl) + " better than maxScoreSoFar = " + maxScoreSoFar + ", choose it!"); return true; } } System.out.println("Worse than maxScoreSoFar, pass it"); return true; }
c480af17-20c4-4589-88dd-1572be3bbb17
8
@Override public void updateTitle() { final List<Room> V=getAllTitledRooms(); final String owner=getOwnerName(); final int price=getPrice(); final boolean rental=rentalProperty(); final boolean gridLayout = gridLayout(); final int back=backTaxes(); String uniqueID="ROOMS_PROPERTY_"+this; if(V.size()>0) uniqueID="ROOMS_PROPERTY_"+CMLib.map().getExtendedRoomID(V.get(0)); for(int v=0;v<V.size();v++) { Room R=V.get(v); synchronized(("SYNC"+R.roomID()).intern()) { R=CMLib.map().getRoom(R); final LandTitle A=(LandTitle)R.fetchEffect(ID()); if((A!=null) &&((!A.getOwnerName().equals(owner)) ||(A.getPrice()!=price) ||(A.backTaxes()!=back) ||(A.rentalProperty()!=rental))) { A.setOwnerName(owner); A.setPrice(price); A.setBackTaxes(back); A.setRentalProperty(rental); A.setGridLayout(gridLayout); CMLib.database().DBUpdateRoom(R); } if(A instanceof Prop_RoomsForSale) ((Prop_RoomsForSale)A).uniqueLotID=uniqueID; } } }
15540cd3-04d6-4832-b148-e9fb6661bfac
8
private void splitHelper(String s, int pos, int seg) { if (seg == 4 && pos == s.length()) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { if (i > 0) sb.append("."); sb.append(buff[i]); } res.add(sb.toString()); return; } else if (seg == 4 || pos == s.length()) return; char c = s.charAt(pos); int possible = buff[seg] * 10 + (int)(c - '0'); if (possible < 256) { int temp = buff[seg]; buff[seg] = possible; if (buff[seg] > 0) splitHelper(s, pos + 1, seg); splitHelper(s, pos + 1, seg + 1); buff[seg] = temp; } }
9c6bafc1-73e7-4a98-87c8-8ace85895771
8
@Override protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawOval(WIDTH / 2 - TABLE_DIAMETER / 2, HEIGHT / 2 - TABLE_DIAMETER / 2, TABLE_DIAMETER, TABLE_DIAMETER); Rectangle discardPile = getDiscardPileBounds(0); g2d.drawRect(discardPile.x, discardPile.y, discardPile.width - 1, discardPile.height - 1); Rectangle drawPile = getDrawPileBounds(0); g2d.drawRect(drawPile.x, drawPile.y, drawPile.width - 1, drawPile.height - 1); if (model.getCurrentPlayer() == model.getLocalPlayerNumber()) { TurnContext cx = model.getPlayer(model.getCurrentPlayer()).getCurrentContext(); if (cx != null && !cx.choosingFaceUp) { int discardPileSize; int drawDeckSize; cardsReadLock.lock(); try { discardPileSize = discardPileEntitiesRange.getLength(); drawDeckSize = drawDeckEntitiesRange.getLength(); } finally { cardsReadLock.unlock(); } if (discardPileSize == 0) drawWrappedString(g2d, new Point(discardPile.x + 2, discardPile.y), "Drop card here", discardPile.width); else g2d.drawString("Drop card on previously played cards", discardPile.x, discardPile.y - 1); if (drawDeckSize == 0) { drawWrappedString(g2d, new Point(drawPile.x + 2, drawPile.y), "Click here to end turn", discardPile.width); } else { Point pt = getDrawDeckLocation(drawDeckSize - 1); g2d.drawString("Click the deck to end your turn", pt.x, pt.y + g2d.getFontMetrics().getAscent()); } } } cardsReadLock.lock(); try { for (CardEntity card : cards) if (!tempDrawOver.contains(card)) draw(card, g2d); } finally { cardsReadLock.unlock(); } for (CardEntity card : tempDrawOver) draw(card, g2d); }
9ea17d30-662f-4fdd-b99e-658b6bdf1e4f
4
public static String rotateAlgorithm(String alg) { List<Integer> FPos = new ArrayList<Integer>(); for (int i = 0; i < alg.length(); i++) { if (alg.charAt(i) == 'F') { FPos.add(i); } } alg = alg.replace('R', 'F'); alg = alg.replace('B', 'R'); alg = alg.replace('L', 'B'); for (int i : FPos) { alg = alg.substring(0, i) + "L" + alg.substring(i + 1, alg.length()); } return alg + (alg.endsWith(",") ? "" : ","); }
4bad861e-6107-4bf5-a89a-a9e336f1879f
4
private static String replaceSubstitutionVariables(String pParsedStatementString, PromotionFile pPromotionFile) throws ExLoader { //Replace variables only if one exists and a property has not been set instructing not to substitute if(pParsedStatementString.indexOf("$${") > 0){ if(!"true".equals(pPromotionFile.getPropertyMap().get(SKIP_SUBSTITUTION_PROPERTY_NAME))){ Logger.logDebug("Performing variable substitution for " + pPromotionFile.getFilePath()); StringBuffer lReplacedStatementString = new StringBuffer(); Matcher lMatcher = SUBSTITUTION_VARIABLE_PATTERN.matcher(pParsedStatementString); while (lMatcher.find()) { String lParamName = lMatcher.group(1).toLowerCase(); String lParamValue = pPromotionFile.getPropertyMap().get(lParamName); if(lParamValue == null){ throw new ExLoader("Parameter value for '" + lParamName + "' substitution variable not defined"); } lMatcher.appendReplacement(lReplacedStatementString, lParamValue); } lMatcher.appendTail(lReplacedStatementString); return lReplacedStatementString.toString(); } else { Logger.logDebug("Skipping variable substitution for " + pPromotionFile.getFilePath() + " because " + SKIP_SUBSTITUTION_PROPERTY_NAME + " was true"); } } //Skipping return pParsedStatementString; }
6db7cbad-1f89-4f54-b37e-838f2ed52bb3
0
public static void main(String[] args) { final int WIDTH = 800; final int HEIGHT = 600; final String TITLE = "Test frame 12345"; JFrame frame = new JFrame(); frame.setSize(WIDTH, HEIGHT); frame.setTitle(TITLE); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
38a8c2ac-00de-4d55-a4f7-1275c80ca7d6
9
public static Description findDuplicateComplexDescription(Description self) { { IntegerWrapper index = IntegerWrapper.wrapInteger(Proposition.propositionHashIndex(self.proposition, null, false)); List bucket = ((List)(Logic.$STRUCTURED_OBJECTS_INDEX$.lookup(index))); Module homemodule = self.homeContext.baseModule; KeyValueMap mapping = KeyValueMap.newKeyValueMap(); if (bucket == null) { Logic.$STRUCTURED_OBJECTS_INDEX$.insertAt(index, List.list(Cons.cons(self, Stella.NIL))); return (null); } bucket.removeDeletedMembers(); if ((((Vector)(KeyValueList.dynamicSlotValue(self.dynamicSlots, Logic.SYM_LOGIC_EXTERNAL_VARIABLES, null))) != null) && (((QueryIterator)(Logic.$QUERYITERATOR$.get())) != null)) { mapping = KeyValueMap.newKeyValueMap(); { PatternVariable v = null; Vector vector000 = ((Vector)(KeyValueList.dynamicSlotValue(self.dynamicSlots, Logic.SYM_LOGIC_EXTERNAL_VARIABLES, null))); int index000 = 0; int length000 = vector000.length(); for (;index000 < length000; index000 = index000 + 1) { v = ((PatternVariable)((vector000.theArray)[index000])); { Stella_Object temp000 = Logic.argumentBoundTo(v); mapping.insertAt(v, ((temp000 != null) ? temp000 : v)); } } } } { ContextSensitiveObject d = null; Cons iter000 = bucket.theConsList; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { d = ((ContextSensitiveObject)(iter000.value)); if (Stella_Object.isaP(d, Logic.SGT_LOGIC_DESCRIPTION) && (Description.equivalentDescriptionsP(self, ((Description)(d)), mapping) && Context.subcontextP(homemodule, d.homeContext.baseModule))) { return (((Description)(d))); } } } bucket.push(self); return (null); } }
c85fbc80-87bb-47ee-abb6-3bb50e60b557
9
public static Cons clTranslateMethodParameters(MethodSlot method) { { boolean functionP = method.methodFunctionP; boolean abstractP = method.abstractP; Cons otree = Stella.NIL; Stella_Object oparameter = null; Stella_Object firstparametertype = null; { Symbol parameter = null; Cons iter000 = method.methodParameterNames().theConsList; StandardObject ptype = null; Cons iter001 = method.methodParameterTypeSpecifiers().theConsList; int i = Stella.NULL_INTEGER; int iter002 = 1; for (;(!(iter000 == Stella.NIL)) && (!(iter001 == Stella.NIL)); iter000 = iter000.rest, iter001 = iter001.rest, iter002 = iter002 + 1) { parameter = ((Symbol)(iter000.value)); ptype = ((StandardObject)(iter001.value)); i = iter002; oparameter = Symbol.clTranslateLocalSymbol(parameter); if ((!functionP) && ((!abstractP) && (i == 1))) { firstparametertype = Stella_Class.clTranslateClassName(Surrogate.typeToClass(StandardObject.typeSpecToBaseType(ptype))); { Symbol testValue000 = Symbol.methodCallTypeForVectorStructs(method.slotName, method.slotOwner, functionP); if (testValue000 == Stella.SYM_STELLA_OBJECT_METHOD) { otree = Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_CLSYS_SELF, Cons.cons(firstparametertype, Cons.cons(Stella.NIL, Stella.NIL)))), otree); otree = Cons.cons(oparameter, otree); } else if (testValue000 == Stella.SYM_STELLA_NON_OBJECT_METHOD) { otree = Cons.cons(Cons.cons(oparameter, Cons.cons(firstparametertype, Stella.NIL)), otree); otree = Cons.cons(Stella.SYM_STELLA_CLSYS_DUMMY, otree); } else { otree = Cons.cons(Cons.cons(oparameter, Cons.cons(firstparametertype, Stella.NIL)), otree); } } } else { otree = Cons.cons(oparameter, otree); } } } if (((BooleanWrapper)(KeyValueList.dynamicSlotValue(method.dynamicSlots, Stella.SYM_STELLA_METHOD_VARIABLE_ARGUMENTSp, Stella.FALSE_WRAPPER))).wrapperValue && (!MethodSlot.passVariableArgumentsAsListP(method))) { otree.rest = Cons.cons(Stella.internCommonLispSymbol("&REST"), otree.rest.concatenate(Stella.NIL, Stella.NIL)); } return (otree.reverse()); } }
2cf29517-d873-4f9e-b41c-f8dae33ac093
5
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Hospede other = (Hospede) obj; if (this.IdHospede != other.IdHospede && (this.IdHospede == null || !this.IdHospede.equals(other.IdHospede))) { return false; } return true; }
96516d86-203a-41b4-bf69-949bf147adc9
2
@Override public String toString() { return (isLof() ? "LOF=" + toStringVcfLof() + " " : "") // + (isNmd() ? "NMD=" + toStringVcfNmd() : "") // ; }
895449eb-9a3f-4786-819a-3109c84a4fdc
1
public void Initialize() { try { Class.forName(this.dbDriver); } catch (ClassNotFoundException ex) { System.out.println("Impossible d'initialiser le driver.\n" + ex.getMessage()); } }
e7249ca7-4c37-490c-80fb-372660e34f2c
9
private ValCol negaMaxWithABPruning(int depth, int counter, int sign, int alpha, int beta) { if (isStopSignaled) { return null; } if (boardCopy.gameOver() || depth == depthLimit) { int util = (int) (Math.pow(discountFactor, depth) * sign * boardCopy.getAnalysis(counter)); return new ValCol(util, -1);// col doesn't matter since search depth // will never be 0 } int col = 0; int i = 0; while (i < 7 && alpha < beta) { if (boardCopy.findDepth(i) > -1) { if (sign == 1) { boardCopy.placeCounter(i, counter); } else { boardCopy.placeCounter(i, 3 - counter); } ValCol vc = negaMaxWithABPruning(depth + 1, counter, -sign, -beta, -alpha); if (vc == null) { return null; } boardCopy.undoMove(); int x = -vc.getVal(); if (x > alpha) { alpha = x; col = i; } } i++; } return new ValCol(alpha, col); }
71b7206d-6ca9-4b23-9a9c-60cc23ba0d77
8
private void BtGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtGravarActionPerformed if (camposobrigatoriospreenchidos()) { if (JOptionPane.showConfirmDialog(null, "Tem certeza que deseja Gravar esta operação e de que todas as informações estçao corretas?", "Deseja gravar?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { enviardados(); prodcompravenda.getCompravenda().incluir(); ClasseMvtoEstoque mvestoque = new ClasseMvtoEstoque(); final ClasseParcelas parcelas = new ClasseParcelas(); mvestoque.setCompravenda(prodcompravenda.getCompravenda()); mvestoque.setDtmvto(datas.retornadataehora()); mvestoque.setTpmvto(prodcompravenda.getCompravenda().getOperacao().getTpestoque()); if (TbProdutos.getRowCount() > 0){ for (int i = 0; i < TbProdutos.getRowCount(); i++) { prodcompravenda.getForneproduto().getProduto().setCodigo(Integer.parseInt(TbProdutos.getValueAt(i, 1).toString())); TfQuantidade.setText(TbProdutos.getValueAt(i, 3).toString()); prodcompravenda.setQuantidade(Float.parseFloat(TfQuantidade.getValue().toString())); TfValorUnitario.setText(TbProdutos.getValueAt(i, 4).toString()); prodcompravenda.setValorunit(Float.parseFloat(TfValorUnitario.getValue().toString())); TfValorProduto.setText(TbProdutos.getValueAt(i, 5).toString()); prodcompravenda.setValorprodut(Float.parseFloat(TfValorProduto.getValue().toString())); prodcompravenda.incluirprodutocompravenda(); mvestoque.getProduto().setCodigo(Integer.parseInt(TbProdutos.getValueAt(i, 1).toString())); TfQuantidade.setText(TbProdutos.getValueAt(i, 3).toString()); mvestoque.setQtmvto(Float.parseFloat(TfQuantidade.getValue().toString())); mvestoque.incluirmvto(); } parcelas.getConta().setTotal(Float.parseFloat(TfValorTotalOperacao.getValue().toString())); }else if (TbServicos.getRowCount() > 0){ for (int i = 0; i < TbServicos.getRowCount(); i++) { prodcompravenda.getForneproduto().getProduto().setCodigo(Integer.parseInt(TbServicos.getValueAt(i, 1).toString())); TfQuantidadeServ.setText(TbServicos.getValueAt(i, 3).toString()); prodcompravenda.setQuantidade(Float.parseFloat(TfQuantidadeServ.getValue().toString())); TfValorUnitarioServ.setText(TbServicos.getValueAt(i, 4).toString()); prodcompravenda.setValorunit(Float.parseFloat(TfValorUnitarioServ.getValue().toString())); TfValorServ.setText(TbServicos.getValueAt(i, 5).toString()); prodcompravenda.setValorprodut(Float.parseFloat(TfValorServ.getValue().toString())); prodcompravenda.incluirprodutocompravenda(); } parcelas.getConta().setTotal(Float.parseFloat(TfValorTotalOperacaoServ.getValue().toString())); } parcelas.getConta().setCompravenda(prodcompravenda.getCompravenda()); parcelas.getConta().setCondicao(prodcompravenda.getCompravenda().getCondicao()); parcelas.getConta().setOperacao(prodcompravenda.getCompravenda().getOperacao()); parcelas.getConta().setDescricao(prodcompravenda.getCompravenda().getDescricao()); parcelas.getConta().setDtconta(TfData.getText()); parcelas.getConta().setCodigopessoa(prodcompravenda.getCompravenda().getCodigopessoa()); parcelas.getConta().incluir(); parcelas.gerarparcelas(); final InterfaceAjusteDatasEPrecos tela = new InterfaceAjusteDatasEPrecos(getPrimeiratela(), true, parcelas); tela.setVisible(true); tela.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { HashMap filtro = new HashMap(); filtro.put("CD_COMPRA_VENDA", prodcompravenda.getCompravenda().getCodigo()); filtro.put("CD_OPERACAO", prodcompravenda.getCompravenda().getOperacao().getCodigo()); filtro.put("CD_CONTA", parcelas.getConta().getCodigo()); filtro.put("DS_NOTA", "EXTRATO DE "+prodcompravenda.getCompravenda().getOperacao().getDescricao()); if(CbPessoa.getSelectedItem().toString().equals("Fornecedor")) filtro.put("TP_PESSOA", "Fornecedor:"); else filtro.put("TP_PESSOA", "Cliente:"); ConexaoPostgre conexao = new ConexaoPostgre(); JDialog dialog = new JDialog(new javax.swing.JFrame(), "Visualização - Software Loja da Fátima", true); dialog.setSize(1000, 700); dialog.setLocationRelativeTo(null); try { JasperPrint print = JasperFillManager.fillReport("relatorios\\notaoperacaoestoquefinanceiro.jasper", filtro, conexao.conecta()); JasperViewer viewer = new JasperViewer(print, true); dialog.getContentPane().add(viewer.getContentPane()); dialog.setVisible(true); } catch (Exception ex) { System.out.println(ex); } } }); limpar.Limpar(jPanel1); limpar.Limpar(jPanel3); limpar.Limpar(jPanel4); limpar.Limpar(TbProdutos); limpar.Limpar(TbServicos); valida.validacamposCancelar(jPanel1, PnBotoes); valida.validacamposCancelar(jPanel3, PnBotoes); valida.validacamposCancelar(jPanel4, PnBotoes); } } }//GEN-LAST:event_BtGravarActionPerformed
988b8152-eaae-4bb4-905a-f1659385b840
7
public static void main(String args[]) { //********************************************************************************************************************** //********************************************************************************************************************** // <editor-fold defaultstate="collapsed" desc="// SETS WINDOWS STYLE IN WINDOWS SYSTEMS AND AQUA STYLE IN MAC SYSTEMS. FOR OTHER SYSTEMS SETS NIMBUS"> if (System.getProperty("os.name").startsWith("Mac OS")) { try { UIManager.setLookAndFeel("com.apple.laf.AquaLookAndFeel"); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(LibraryMain.class.getName()).log(Level.SEVERE, null, ex); } } else if (System.getProperty("os.name").startsWith("Windows")) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(LibraryMain.class.getName()).log(Level.SEVERE, null, ex); } } else { 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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LibraryMain.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 LibraryMain().setVisible(true); } }); }
66c635a9-bac9-4840-9fc8-5f84524c86ba
2
public static int getCRuleID(String name) { for(int i = 0; i < numCRules; i++) { if(cRules[i].name().equalsIgnoreCase(name)) { return i; } } return -1; }
507c39f9-b436-4cd9-a933-324b5692e8c8
1
public void tallennaTiedostoon(){ if (kasittelija.getFile() != null) { kasittelija.muokkaaTiedostonTiettyjaRiveja(kerrattavat); } }
363a6b77-54df-4ed9-a271-f3b2f29ef227
3
public static Attributed readAttrs2(Reader source){ Scanner in = new Scanner(source); Pattern COMMENT = Pattern.compile("#.*"); Pattern attrPat = Pattern.compile("(.*?)=(.*)$", Pattern.MULTILINE); String comment; AttributedImpl attrs = new AttributedImpl(); while(in.hasNext()){ if(in.hasNext(COMMENT)){ comment = in.findWithinHorizon(COMMENT, 0);//"|"shows the current position. #aaaa|\r\n in.nextLine();//"|"shows the current position. #aaaa\r\n| } else if(in.hasNext(attrPat)){ in.findInLine(attrPat); MatchResult m = in.match(); attrs.add(new Attr(m.group(1), m.group(2))); } } return attrs; }
7276b884-57ff-45cc-9d51-66e1e4c518bc
1
public void addCard(Card c) { if (c == null) throw new NullPointerException("Can't add a null card to a hand."); hand.add(c); }
1e0494c7-2778-45c8-9a44-1ab378e6ae56
0
public void setEventBranchList(final List<EventBranch> eventBranchList) { this.eventBranchList = eventBranchList; }
e4308b75-9bcd-4a40-b682-7dbdac1369ba
6
public boolean detachNext(Linkable paramLinkable) { boolean b = false; Object localObject; if ((paramLinkable instanceof Instruction)) { localObject = (Instruction)paramLinkable; if ((((Instruction)localObject).getPreviousInstruction() == null) && (this.CurrentProgram.getFirstInstruction() == localObject)) { this.CurrentProgram.setFirstInstruction(null); b = true; } } else if ((paramLinkable instanceof Conditional)) { localObject = (Conditional)paramLinkable; if ((((Conditional)localObject).getPreviousConditional() == null) && (this.CurrentProgram.getFirstConditional() == localObject)) { this.CurrentProgram.setFirstConditional(null); b = true; } } return b; }
be0a4ae3-bb95-41c5-9137-0f9e75137806
4
public void removeAttendantFromCourse(int courseId, int studentId) { if(!isValidId(courseId) || !isValidId(studentId)) { return; } Course course = courseDao.getCourse(courseId); Student student = studentDao.getStudent(studentId); if(course != null && student != null) { course.getAttendants().remove(student); //student.getCourses().remove(course); courseDao.saveCourse(course); //studentDao.saveStudent(student); } }
a95dcc48-0132-467a-bcce-572584faeaa8
1
public List<String> num2words(String phoneNum) { // List to store all words List<String> wordList = new ArrayList<String>(); // Extract number, ignore whitespace and punctuation String _phoneNum = extractPureNumbers(phoneNum); // Get Phone Number Combinations List<String> combinations = getNumCombinations(_phoneNum); for (int i = 0; i < combinations.size(); i++) { // Find match in the dictionary wordList.addAll(searchWords(combinations.get(i))); } System.out.println("WordList for <"+ phoneNum + ">: " + wordList); return wordList; }
bcdbba74-f7ab-4ceb-8a09-a80026a5cbd0
4
private final void gotoBand(final Git gitSession) { if (gitSession == null) { return; } try { final String branch = gitSession.getRepository().getBranch(); if (!branch.equals(this.BRANCH.value())) { this.io.printMessage( null, "Not on working branch \"" + this.BRANCH.value() + "\"\nCurrent branch is \"" + branch + "\"\nCheckout branch \"" + this.BRANCH.value() + "\" or work on branch \"" + branch + "\"", true); return; } if (this.master.isInterrupted()) { return; } checkForLocalChanges(gitSession); } catch (final IOException | GitAPIException | InterruptedException e) { this.io.handleException(ExceptionHandle.CONTINUE, e); } }
6715d539-3979-46f1-b2fc-7e8bc300c217
8
public static String preProcess(Reader reader) { int columnStart = 6; int columnEnd = 72; try { // FileInputStream propsStream = new FileInputStream("cb2xml.properties"); Properties props = new Properties(); // props.load(propsStream); // propsStream.close(); String columnStartProperty = props.getProperty("column.start"); String columnEndProperty = props.getProperty("column.end"); if (columnStartProperty != null) { columnStart = Integer.parseInt(columnStartProperty); } if (columnEndProperty != null) { columnEnd = Integer.parseInt(columnEndProperty); } } catch (Exception e) { e.printStackTrace(); } StringBuffer sb = new StringBuffer(); try { BufferedReader buffer = new BufferedReader(reader); String s = null; while ((s = buffer.readLine()) != null) { if (s.length() > columnStart) { int thisColumnStart = columnStart; if (s.charAt(columnStart) == '/') { sb.append('*'); thisColumnStart++; } if (s.length() < columnEnd) { sb.append(s.substring(thisColumnStart)); } else { sb.append(s.substring(thisColumnStart, columnEnd)); } } sb.append("\n"); } } catch (Exception e) { e.printStackTrace(); return null; } return sb.toString(); }
2db53ca0-7c73-4f70-b733-6ef4501a5004
1
public void NotifyRunModeChanged(boolean isLocalRunMode) { for (IRunModeChangedNotification rmc : runModeChangedNotificationListeners) { rmc.onRunModeChanged(isLocalRunMode); } }
eee6ea02-698d-47c5-85c1-51a2a881cd5c
3
public HashMap printCliche() throws Exception { ArrayList<Integer> answer = this.device.send(0x52, 3, new char[]{}); if (answer.size() == 0) throw new Exception("Пустой ответ"); HashMap<String, Integer> result = new HashMap<String, Integer>(); if (answer.get(0) == Status.OK) { if (answer.size() > 1) { result.put("error_code", answer.get(4)); result.put("operator", answer.get(5)); } } return result; }
fb31fb71-5dd8-4a52-a3dc-e8d4c6178d36
0
public void setSuccess(final Boolean success) { this.success = success; }
8feba7d3-1899-483a-93cc-307e484a6cfa
1
public static void toggleCommentText(Node currentNode, JoeTree tree, OutlineLayoutManager layout) { CompoundUndoablePropertyChange undoable = new CompoundUndoablePropertyChange(tree); toggleCommentForSingleNode(currentNode, undoable); if (!undoable.isEmpty()) { undoable.setName("Toggle Comment for Node"); tree.getDocument().getUndoQueue().add(undoable); } // Redraw layout.draw(currentNode, OutlineLayoutManager.TEXT); }
fa5404ed-62e3-495f-9a3a-4594e221ce91
1
public void testWithField_unknownField() { MonthDay test = new MonthDay(9, 6); try { test.withField(DateTimeFieldType.hourOfDay(), 6); fail(); } catch (IllegalArgumentException ex) {} }
9c7148cc-46a6-442a-bf25-afe96f083f64
6
public String getwinner(){ if(stateArrayList[0].size()>stateArrayList[1].size() && stateArrayList[0].size()>stateArrayList[2].size()) return "blue"; if(stateArrayList[1].size()>stateArrayList[0].size() && stateArrayList[1].size()>stateArrayList[2].size()) return "green"; if(stateArrayList[2].size()>stateArrayList[1].size() && stateArrayList[2].size()>stateArrayList[0].size()) return "yellow"; else return "no winner"; }
c9c4756d-3e8b-4cf1-831f-38eef7a24edd
1
private PreparedStatement buildUpdateStatement(Connection conn_loc, String tableName, List colDescriptors, String whereField) throws SQLException { StringBuffer sql = new StringBuffer("UPDATE "); (sql.append(tableName)).append(" SET "); final Iterator i = colDescriptors.iterator(); while (i.hasNext()) { (sql.append((String) i.next())).append(" = ?, "); } sql = new StringBuffer((sql.toString()).substring(0, (sql.toString()).lastIndexOf(", "))); ((sql.append(" WHERE ")).append(whereField)).append(" = ?"); final String finalSQL = sql.toString(); return conn_loc.prepareStatement(finalSQL); }
54348805-a04b-49af-a8aa-2448b0081df2
7
public static void main(String args[]){ int op = 6; //lea.useDelimiter(System.getProperty("line.separator")); do{ try{ System.out.println("1- Agregar Cuenta"); System.out.println("2- Agregar Amigo"); System.out.println("3- Informacion de Usuario"); System.out.println("4- Agregar Post"); System.out.println("5- Agregar Comentario"); System.out.println("6- Salir"); System.out.print("\nEscoja una opcion: "); op = lea.nextInt(); switch(op){ case 1: System.out.print("Ingrese Username: "); agregarCuenta(lea.next()); break; case 2: System.out.println("Id de usuario: "); int user = lea.nextInt(); System.out.println("Id de Amigo: "); int friend = lea.nextInt(); agregarAmigo(user, friend); break; case 3: System.out.println("Id de usuario: "); user = lea.nextInt(); verInfo(user); break; case 4: System.out.println("Id de usuario: "); user = lea.nextInt(); agregarPost(user); break; case 5: System.out.println("Id de usuario: "); user = lea.nextInt(); System.out.println("Id de Post: "); int post = lea.nextInt(); agregarComentario(user,post); break; default: System.out.println("ADIOS!"); } } catch(InputMismatchException e){ System.out.println("Escriba bien!"); lea.next(); } }while( op != 6); }
d8b7c828-61a1-4164-bf0f-e1793518d5f2
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Conta other = (Conta) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; }
215a978a-b122-462d-bf53-d0ace8868335
0
public static TypePraticien selectOne(EntityManager em, String code) throws PersistenceException { TypePraticien unTypePraticien = null; unTypePraticien = em.find(TypePraticien.class, code); return unTypePraticien; }
088aa052-dd8d-4782-9cfb-db70d4937587
3
@Override public int compareTo(Object o) { if (o instanceof Score) { long otherScore = ((Score) o).getScore(); if (otherScore > _score) return -1; else if (otherScore < _score) return 1; else { return -_date.compareTo(((Score) o).getDate()); } } else throw new IllegalArgumentException("Expected Score"); }
18546597-ba5f-449b-994e-b0d608b49d1d
4
public static ENCODE vauleOf(String value){ if(value.equalsIgnoreCase(ENCODE.Big5.getValue())){ return ENCODE.Big5; } else if(value.equalsIgnoreCase(ENCODE.UTF8.getValue())){ return ENCODE.UTF8; } else if(value.equalsIgnoreCase(ENCODE.MS950.getValue())){ return ENCODE.MS950; } else if(value.equalsIgnoreCase(ENCODE.GB2312.getValue())){ return ENCODE.GB2312; } // Default return ENCODE.UTF8; }
38ff4da3-7f56-4056-91c1-102f312ddb14
5
private float getRatioTop20() { BigDecimal elapsedTimeTop20 = new BigDecimal(0); BigDecimal elapsedTimeTotal = new BigDecimal(1); Connection connection = ConnectionPoolUtils.getConnectionFromPool(); try { PreparedStatement elapsedTop20Statement = connection.prepareStatement(ELAPSED_TIME_TOP20); ResultSet elapsedTop20ResultSet = elapsedTop20Statement.executeQuery(); if (elapsedTop20ResultSet != null) { while (elapsedTop20ResultSet.next()) { elapsedTimeTop20 = elapsedTop20ResultSet.getBigDecimal(1); } } elapsedTop20Statement.close(); PreparedStatement elapsedTotalStatement = connection.prepareStatement(ELAPSED_TIME_TOTAL); ResultSet elapsedTotalResultSet = elapsedTotalStatement.executeQuery(); if (elapsedTotalResultSet != null) { while (elapsedTotalResultSet.next()) { elapsedTimeTotal = elapsedTotalResultSet.getBigDecimal(1); } } elapsedTotalStatement.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, e); } finally { ConnectionPoolUtils.returnConnectionToPool(connection); } return elapsedTimeTop20.divide(elapsedTimeTotal, 4, BigDecimal.ROUND_HALF_UP).floatValue(); }
c48deea1-e225-4695-9770-18dc8ca8c9d2
7
private int merge(BufferedRandomAccessFile fin, DataOutputStream fout, long offset, long chunkSize, int[][] blocks) throws IOException { long size1 = fin.length(); if (offset >= size1) { return -1; } int chunkCount = 1; while (offset + chunkCount * chunkSize < size1 && chunkCount < blocks.length) chunkCount++; long[] chunkEnds = new long[chunkCount]; long[] chunkPointers = new long[chunkCount]; for (int i = 0; i < chunkCount; i++) { chunkPointers[i] = offset + i * chunkSize; chunkEnds[i] = Math.min(offset + (i + 1) * chunkSize, size1); } int[] blockSizes = new int[chunkCount]; int[] blockStarts = new int[chunkCount]; PriorityQueue<ValueToIndex> heap = new PriorityQueue<ValueToIndex>(blocks.length); for (int i = 0; i < chunkCount; i++) { refillBlock(i, chunkPointers, chunkEnds, blocks, blockSizes, blockStarts, heap, fin); } while (!heap.isEmpty()) { ValueToIndex min = heap.poll(); fout.writeInt(min.getValue()); if (blockStarts[min.index] + 1 < blockSizes[min.index]) { blockStarts[min.index] = blockStarts[min.index] + 1; min.setValue(blocks[min.index][blockStarts[min.index]]); heap.add(min); } else { chunkPointers[min.index] = chunkPointers[min.index] + blockSizes[min.index] * 4; refillBlock(min.index, chunkPointers, chunkEnds, blocks, blockSizes, blockStarts, heap, fin); } } fout.flush(); return chunkCount; }
fa88ad86-c947-484d-b622-fbc89035d697
3
public void setDateFormatString(String dateFormatString) { try { dateFormatter.applyPattern(dateFormatString); } catch (RuntimeException e) { dateFormatter = (SimpleDateFormat) DateFormat .getDateInstance(DateFormat.MEDIUM); dateFormatter.setLenient(false); } this.dateFormatString = dateFormatter.toPattern(); setToolTipText(this.dateFormatString); if (date != null) { ((JSpinner.DateEditor) getEditor()).getFormat().applyPattern( this.dateFormatString); } else { ((JSpinner.DateEditor) getEditor()).getFormat().applyPattern(""); } if (date != null) { String text = dateFormatter.format(date); ((JSpinner.DateEditor) getEditor()).getTextField().setText(text); } }
36f5e3f9-67d1-4f78-9355-527c8d21e580
6
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { int[] v = readInts(line); if (v[0] == 0 && v[1] == 0 && v[2] == 0 && v[3] == 0) break; GregorianCalendar c = new GregorianCalendar(v[3], v[2] - 1, v[1]); c.add(Calendar.DAY_OF_MONTH, v[0]); String ans = c.get(Calendar.DAY_OF_MONTH) + " "; ans += (c.get(Calendar.MONTH) + 1) + " "; ans += c.get(Calendar.YEAR); out.append(ans + "\n"); } System.out.print(out); }
09794c23-f22d-4707-ad58-be2a48d482ed
6
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ Mission mission = null; //如果获取输出对象有问题,不要往下运行了 OutputStream os = response.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); InputStream is = request.getInputStream(); ObjectInputStream ois = new ObjectInputStream(is); try{ Object object = ois.readObject(); mission = (Mission)object; Instruction instruction = mission.getInstruction(); Option[] requestOptions = mission.getRequestOptions(); Option[] responseOptions = process(instruction,requestOptions); mission.setResponseOptions(responseOptions); oos.writeObject(mission); oos.flush(); }catch(ClassNotFoundException cnfe){ returnInvalidParameterMission(oos,mission); }catch(ClassCastException cce){ returnInvalidParameterMission(oos,mission); }finally{ try{ if(null != ois) ois.close(); }catch(Exception e1){} try{ if(null != oos) oos.close(); }catch(Exception e2){} } }
95aa88d3-f50c-4998-959c-666a4a72668d
6
private void merge( int[] array, int b1, int e1, int b2, int e2 ) { int i = b1; int j = b2; int k = 0; int[] tempArray = new int[ e2-b1+1 ]; while( i <= e1 && j <= e2 ) { if( array[i] < array[j] ) { tempArray[k++] = array[i++]; } else { tempArray[k++] = array[j++]; } } while( i <= e1 ) { tempArray[k++] = array[i++]; } while( j <= e2 ) { tempArray[k++] = array[j++]; } for( int l = 0, s = tempArray.length; l < s; ++l ) { array[b1+l] = tempArray[l]; } }
dc394f41-3878-45c5-a63f-e18af2ad6d10
6
@Override public void keyReleased(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_UP) { palkki2.setNopeus(0); } else if (ke.getKeyCode() == KeyEvent.VK_DOWN) { palkki2.setNopeus(0); }if(ke.getKeyCode() == KeyEvent.VK_W){ if(peli.getClass()==kPeli.getClass()){ palkki1.setNopeus(0); } }else if(ke.getKeyCode() == KeyEvent.VK_S){ if(peli.getClass()==kPeli.getClass()){ palkki1.setNopeus(0); } } component.repaint(); }
b98f6de2-1375-4d75-8a7f-55e88f5051bf
8
public static void transferFiles(Cons files, Keyword outputLanguage) { if (Stella.stringEqlP(Stella.rootSourceDirectory(), Stella.rootNativeDirectory())) { return; } { String flotsamfilename = ""; String systemSubDirectory = (Stella.stringEqlP(((String)(Stella.$CURRENTSYSTEMDEFINITIONSUBDIRECTORY$.get())), "") ? "" : (((String)(Stella.$CURRENTSYSTEMDEFINITIONSUBDIRECTORY$.get())) + Stella.directorySeparatorString())); if (outputLanguage == Stella.KWD_JAVA) { flotsamfilename = Module.javaYieldFlotsamClassName(SystemDefinition.getCardinalModule(((SystemDefinition)(Stella.$CURRENTSYSTEMDEFINITION$.get())))); } { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, SystemDefinition.getCardinalModule(((SystemDefinition)(Stella.$CURRENTSYSTEMDEFINITION$.get())))); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); { StringWrapper f = null; Cons iter000 = files; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { f = ((StringWrapper)(iter000.value)); { String filename = f.wrapperValue; Keyword type = Stella.classifyFileExtension(filename); String relativefilename = Stella.relativizeFileName(filename, Stella.rootSourceDirectory()); String fromfilename = null; String tofilename = null; if (type == Stella.KWD_JAVA) { if (Stella.stringEqlP(Stella.fileBaseName(filename), flotsamfilename)) { { Stella.STANDARD_WARNING.nativeStream.println("Warning: Native Java filename `" + flotsamfilename + "'"); Stella.STANDARD_WARNING.nativeStream.println(" conflicts with the Java catchall class' filename"); } ; } } else { } fromfilename = Stella.rootSourceDirectory() + systemSubDirectory + filename; tofilename = Stella.makeFileName(relativefilename, type, true); if (!(Stella.fileYoungerThanP(tofilename, fromfilename) == Stella.TRUE_WRAPPER)) { if (((Integer)(Stella.$TRANSLATIONVERBOSITYLEVEL$.get())).intValue() >= 1) { { System.out.println("Copying `" + fromfilename + "'"); System.out.println(" to `" + tofilename + "' ..."); } ; } Stella.copyFile(fromfilename, tofilename); } } } } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } } }
bf80db3f-7fd0-4610-b225-6629fe4c563d
3
public static Portal getPortal( String name ) { for ( ArrayList<Portal> list : portals.values() ) { for ( Portal p : list ) { if ( p.getName().equalsIgnoreCase( name ) ) { return p; } } } return null; }
b46ab29d-d491-469e-b0ab-8c6aa0095b7f
0
public boolean isAttacking() { return attacking; }
b232ded1-4608-4776-a176-51fe9202fb9d
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Semaphore other = (Semaphore) obj; if (id == null) { if (other.id != null) return false; } else { if (!id.equals(other.id)) return false; } return true; }
67cef016-6386-4a80-a683-c5d6f7f98aa7
6
private void setAlpha(int delta){ int swing = 0; if (hours >= 20 || hours < 6){ alpha = max; } else if (hours >= 6 && hours <= 8){ swing = -1; } else if (hours >= 18 && hours < 20){ swing = 1; } else{ alpha = min; } alpha += swing * rate * delta / 1000.0; }
eb625844-2b87-4ddf-9f0a-066e59fad919
6
static boolean tagcompare(byte[] s1, byte[] s2, int n){ int c=0; byte u1, u2; while(c<n){ u1=s1[c]; u2=s2[c]; if('Z'>=u1&&u1>='A') u1=(byte)(u1-'A'+'a'); if('Z'>=u2&&u2>='A') u2=(byte)(u2-'A'+'a'); if(u1!=u2){ return false; } c++; } return true; }
08f9d996-3d84-4111-a935-2b253159d943
7
@Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub if(arg0.getSource() == close) { player.Stop(); controller.removePlayer(player); dead=true; newWindow.dispose(); } if(arg0.getSource() == static_Open || arg0.getSource() == addSong) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("MP3 Audio Files", "mp3"); chooser.setFileFilter(filter); chooser.grabFocus(); int returnVal = chooser.showOpenDialog(menu); if(returnVal == JFileChooser.APPROVE_OPTION) { String chosenFile = chooser.getSelectedFile().getAbsolutePath(); if(arg0.getSource() == static_Open)player.play(chosenFile); else table.addToList(chosenFile); } } else if(arg0.getSource() == controls) { shuffle.setSelected(player.shuffle.isSelected()); repeat.setSelected(player.repeat.isSelected()); recent.removeAll(); ArrayList<String> songs = controller.getSongHistory(); for(int i = 0; i < songs.size(); i++) { final JMenuItem jm = new JMenuItem(songs.get(i)); jm.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { //System.out.println(jm.getText()); player.play(jm.getText()); } }); recent.add(jm); } } }
3fd2a280-90e9-4c41-b092-98a4fbe1b2f9
8
private void openExperiment() { int returnVal = m_FileChooser.showOpenDialog(this); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File expFile = m_FileChooser.getSelectedFile(); // add extension if necessary if (m_FileChooser.getFileFilter() == m_ExpFilter) { if (!expFile.getName().toLowerCase().endsWith(Experiment.FILE_EXTENSION)) expFile = new File(expFile.getParent(), expFile.getName() + Experiment.FILE_EXTENSION); } else if (m_FileChooser.getFileFilter() == m_KOMLFilter) { if (!expFile.getName().toLowerCase().endsWith(KOML.FILE_EXTENSION)) expFile = new File(expFile.getParent(), expFile.getName() + KOML.FILE_EXTENSION); } else if (m_FileChooser.getFileFilter() == m_XMLFilter) { if (!expFile.getName().toLowerCase().endsWith(".xml")) expFile = new File(expFile.getParent(), expFile.getName() + ".xml"); } try { Experiment exp = Experiment.read(expFile.getAbsolutePath()); setExperiment(exp); System.err.println("Opened experiment:\n" + m_Exp); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(this, "Couldn't open experiment file:\n" + expFile + "\nReason:\n" + ex.getMessage(), "Open Experiment", JOptionPane.ERROR_MESSAGE); // Pop up error dialog } }
a11749b8-2a16-47d1-9690-363b6432bcb8
8
static final Class252 method2300(IndexLoader class45, String string, boolean bool, byte i) { try { anInt3877++; int i_0_ = class45.getArchiveId(string); if (i != -91) return null; if ((i_0_ ^ 0xffffffff) == 0) return new Class252(0); int[] is = class45.getActiveChildren(i_0_); Class252 class252 = new Class252(is.length); int i_1_ = 0; int i_2_ = 0; while (i_1_ < ((Class252) class252).anInt3241) { ByteBuffer class348_sub49 = new ByteBuffer(class45.getChildArchive(i_0_, is[i_2_++])); int i_3_ = class348_sub49.getDword(); int i_4_ = class348_sub49.getShort(); int i_5_ = class348_sub49.getUByte(); if (!bool && i_5_ == 1) ((Class252) class252).anInt3241--; else { ((Class252) class252).anIntArray3238[i_1_] = i_3_; ((Class252) class252).anIntArray3239[i_1_] = i_4_; i_1_++; } } return class252; } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("wt.A(" + (class45 != null ? "{...}" : "null") + ',' + (string != null ? "{...}" : "null") + ',' + bool + ',' + i + ')')); } }
349dfed4-2a25-4699-8bcd-fce031a4be49
7
public static Spell getAirSpell(int i) { switch (i) { default: case 0: return new Airbending(); case 1: return new AirbendingJump(); case 2: return new AirbendingTornado(); case 3: return new AirRun(); case 4: return new AirbendingGust(); case 5: return new AirbendingAir(); case 6: return new AirAffinity(); } }
c6afaed2-37dc-47e8-baa1-3c4dc9755b59
7
public int getRomanValue(char c) { switch (c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; } }
6ae5139a-c633-4aca-96db-6e1c6218d9b7
9
public static void Merge(int[] n, int start, int middle, int finish) { int i = start, j = middle + 1; int m[] = new int [finish - start + 1]; boolean jDone = false, iDone = false; for(int k = 0; k < m.length; k++) { if(!jDone && n[i] > n[j] || iDone) { m[k] = n[j]; j++; if(j > finish) jDone = true; } else if(!iDone || jDone) { m[k] = n[i]; i++; if(i > middle) iDone = true; } } for(int k = 0; k < m.length; k++) n[start + k] = m[k]; }
54320ff1-a9a4-4f39-9927-e180b13d0c55
4
public int stackSize() { switch (typecode) { case TC_VOID: return 0; case TC_ERROR: default: return 1; case TC_DOUBLE: case TC_LONG: return 2; } }
90925619-6a4a-488b-9338-0453704368b9
1
public void initializeDB() { try { // Load the JDBC driver Class.forName("org.postgresql.Driver"); System.out.println("Driver loaded"); // Establish a connection String url = "jdbc:postgresql://ozguryazilim.bilkent.edu.tr/projectsme"; /* String user = "user12"; String password = "34klq*"; String con = "jdbc:mysql://ozguryazilim.bilkent.edu.tr/projectsme";*/ //connection = DriverManager.getConnection(con,"osman","1269318+"); connection = DriverManager.getConnection(url,"osman","ozyaz.14"); System.out.println("Database connected"); } catch (Exception ex) { ex.printStackTrace(); } }