method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
9dbb43c4-3dfc-4dcc-bbd6-8764f8ce681a
2
public JokerScherm(final SpeelScherm speelscherm, final Spel spel) { setBackground(new Color(0, 0, 0, 150)); setBounds(0, 0, 800, 600); setLayout(new MigLayout("", "[grow][530,center][grow]", "[grow][200px,center][grow]")); JPanel panel = JPanelFactory.createBackgroundJPanel(); add(panel, "cell 1 1,grow"); panel.setLayout(new MigLayout("", "[66px][12px][226px][4px][13px][93px][85px]", "[27px][28px][19px][19px][19px][29px]")); JLabel lblNewLabel = JLabelFactory.createJokerLabel("Hoeveel jokers wil je inzetten?"); panel.add(lblNewLabel, "cell 0 0 5 1,alignx left,aligny top"); final JSpinner spinner = new JSpinner(); panel.add(spinner, "cell 0 1,growx,aligny top"); spinner.setModel(new SpinnerNumberModel(0, 0, spel.getMaxJokers(), 1)); JLabel lblJokers = JLabelFactory.createJokerLabel("jokers"); JLabel lblJokersOver = JLabelFactory.createJokerLabel("Je hebt nog " + spel.getMaxJokers() + " jokers"); JLabel lblJokerkosten = JLabelFactory.createJokerLabel("Een joker kost " + spel.getJokerKosten() + " seconden"); JLabel lblHoeveelGoedVerplicht = JLabelFactory.createJokerLabel("Je moet deze ronde " + spel.getHoeveelGoedVerplicht() + " vragen goed hebben"); JLabel lblHuidigeScore = JLabelFactory.createJokerLabel("Je huidige score is: " + spel.getScore()); panel.add(lblHuidigeScore, "cell 0 4 3 1,alignx left,aligny top"); panel.add(lblJokers, "cell 2 1,alignx left,growy"); panel.add(lblJokersOver, "cell 0 2 3 1,alignx left,aligny top"); panel.add(lblJokerkosten, "cell 4 2 3 1,alignx left,aligny top"); panel.add(lblHoeveelGoedVerplicht, "cell 0 3 3 1,alignx left,aligny top"); NiceButton btnNewButton = new NiceButton("Verder"); panel.add(btnNewButton, "cell 6 5,growx,aligny top"); btnNewButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { try { int jokers = (Integer) spinner.getValue(); if (jokers > spel.getMaxJokers()) { spinner.setBackground(Color.red); return; } spel.zetJokersIn(jokers); } catch (LogicException e) { // TODO Auto-generated catch block // zoveel jokers heeft de gebruiker niet.. e.printStackTrace(); } speelscherm.openResultaten(); } }); }
65ebae4e-19fc-4949-8d0d-31b1d9e8825d
5
public Main() { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { try { UIManager.setLookAndFeel(info.getClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e1) { e1.printStackTrace(); } break; } } setResizable(false); setFont(new Font("Arial", Font.PLAIN, 12)); setIconImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/images/icn.png"))); setTitle("Area Calculator"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 304, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); final JLabel lblValue1 = new JLabel("Value 1:"); lblValue1.setFont(new Font("Arial", Font.PLAIN, 11)); lblValue1.setBounds(85, 33, 67, 14); contentPane.add(lblValue1); lblValue1.setText(""); final JLabel lblValue2 = new JLabel("Value 2:"); lblValue2.setFont(new Font("Arial", Font.PLAIN, 11)); lblValue2.setBounds(85, 59, 67, 14); contentPane.add(lblValue2); lblValue2.setText(""); final JLabel lblValue3 = new JLabel("Value 3:"); lblValue3.setFont(new Font("Arial", Font.PLAIN, 11)); lblValue3.setBounds(85, 85, 67, 14); contentPane.add(lblValue3); lblValue3.setText(""); final JTextArea txtOutput = new JTextArea(); txtOutput.setEditable(false); txtOutput.setFont(new Font("Tahoma", Font.PLAIN, 14)); txtOutput.setWrapStyleWord(true); txtOutput.setLineWrap(true); txtOutput.setBounds(106, 122, 182, 104); contentPane.add(txtOutput); final JRadioButton radioButtonCircle = new JRadioButton("Circle"); radioButtonCircle.setFont(new Font("Arial", Font.PLAIN, 11)); radioButtonCircle.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { lblValue1.setText("Radius:"); txtValue1.setEnabled(true); lblValue2.setText(unused); txtValue2.setEnabled(false); lblValue3.setText(unused); txtValue3.setEnabled(false); } }); radioButtonCircle.setBounds(6, 29, 73, 23); contentPane.add(radioButtonCircle); selection.add(radioButtonCircle); final JRadioButton radioButtonSquare = new JRadioButton("Square"); radioButtonSquare.setFont(new Font("Arial", Font.PLAIN, 11)); radioButtonSquare.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { lblValue1.setText("Side:"); txtValue1.setEnabled(true); lblValue2.setText(unused); txtValue2.setEnabled(false); lblValue3.setText(unused); txtValue3.setEnabled(false); } }); radioButtonSquare.setBounds(6, 55, 73, 23); contentPane.add(radioButtonSquare); selection.add(radioButtonSquare); final JRadioButton radioButtonTrapezoid = new JRadioButton("Trapezoid"); radioButtonTrapezoid.setFont(new Font("Arial", Font.PLAIN, 11)); radioButtonTrapezoid.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { lblValue1.setText("Top edge:"); txtValue1.setEnabled(true); lblValue2.setText("Bottom edge:"); txtValue2.setEnabled(true); lblValue3.setText("Height:"); txtValue3.setEnabled(true); } }); radioButtonTrapezoid.setBounds(6, 81, 73, 23); contentPane.add(radioButtonTrapezoid); selection.add(radioButtonTrapezoid); final JRadioButton radioButtonTriangle = new JRadioButton("Triangle"); radioButtonTriangle.setFont(new Font("Arial", Font.PLAIN, 11)); radioButtonTriangle.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { lblValue1.setText("Height:"); txtValue1.setEnabled(true); lblValue2.setText("Base:"); txtValue2.setEnabled(true); lblValue3.setText(unused); txtValue3.setEnabled(false); } }); radioButtonTriangle.setBounds(6, 107, 73, 23); contentPane.add(radioButtonTriangle); selection.add(radioButtonTriangle); final JRadioButton radioButtonSector = new JRadioButton("Sector"); radioButtonSector.setFont(new Font("Arial", Font.PLAIN, 11)); radioButtonSector.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { lblValue1.setText("Radius:"); txtValue1.setEnabled(true); lblValue2.setText("Angle:"); txtValue2.setEnabled(true); lblValue3.setText(unused); txtValue3.setEnabled(false); } }); radioButtonSector.setBounds(6, 133, 73, 23); contentPane.add(radioButtonSector); selection.add(radioButtonSector); final JRadioButton radioButtonEllipse = new JRadioButton("Ellipse"); radioButtonEllipse.setFont(new Font("Arial", Font.PLAIN, 11)); radioButtonEllipse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { lblValue1.setText("Major axes:"); txtValue1.setEnabled(true); lblValue2.setText("Minor axes:"); txtValue2.setEnabled(true); lblValue3.setText(unused); txtValue3.setEnabled(false); } }); radioButtonEllipse.setBounds(6, 159, 73, 23); contentPane.add(radioButtonEllipse); selection.add(radioButtonEllipse); final JRadioButton radioButtonParallelogram = new JRadioButton("Parallelogram"); radioButtonParallelogram.setFont(new Font("Arial", Font.PLAIN, 11)); radioButtonParallelogram.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { lblValue1.setText("Height:"); txtValue1.setEnabled(true); lblValue2.setText("Base:"); txtValue2.setEnabled(true); lblValue3.setText(unused); txtValue3.setEnabled(false); } }); radioButtonParallelogram.setBounds(6, 185, 89, 23); contentPane.add(radioButtonParallelogram); selection.add(radioButtonParallelogram); final JRadioButton radioButtonRectangle = new JRadioButton("Rectangle"); radioButtonRectangle.setFont(new Font("Arial", Font.PLAIN, 11)); radioButtonRectangle.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { lblValue1.setText("Height:"); txtValue1.setEnabled(true); lblValue2.setText("Width:"); txtValue2.setEnabled(true); lblValue3.setText(unused); txtValue3.setEnabled(false); } }); radioButtonRectangle.setBounds(6, 211, 89, 23); contentPane.add(radioButtonRectangle); selection.add(radioButtonRectangle); final JRadioButton radioButtonRhombus = new JRadioButton("Rhombus"); radioButtonRhombus.setFont(new Font("Arial", Font.PLAIN, 11)); radioButtonRhombus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { lblValue1.setText("Height:"); txtValue1.setEnabled(true); lblValue2.setText("Width:"); txtValue2.setEnabled(true); lblValue3.setText(unused); txtValue3.setEnabled(false); } }); radioButtonRhombus.setBounds(6, 237, 73, 23); contentPane.add(radioButtonRhombus); selection.add(radioButtonRhombus); JButton btnCompute = new JButton("Compute"); btnCompute.setFont(new Font("Arial", Font.PLAIN, 11)); btnCompute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RunCalculations rc = new RunCalculations(); rc.runCalculations( radioButtonRectangle, radioButtonCircle, radioButtonSquare, radioButtonParallelogram, radioButtonEllipse, radioButtonSector, radioButtonTriangle, radioButtonTrapezoid, radioButtonRhombus, txtOutput, txtValue1, txtValue2, txtValue3); } }); btnCompute.setBounds(106, 237, 182, 23); contentPane.add(btnCompute); txtValue1 = new JTextField(); txtValue1.setFont(new Font("Arial", Font.PLAIN, 11)); txtValue1.setEnabled(false); txtValue1.setColumns(10); txtValue1.setBounds(162, 27, 126, 26); contentPane.add(txtValue1); txtValue2 = new JTextField(); txtValue2.setFont(new Font("Arial", Font.PLAIN, 11)); txtValue2.setEnabled(false); txtValue2.setColumns(10); txtValue2.setBounds(162, 56, 126, 26); contentPane.add(txtValue2); txtValue3 = new JTextField(); txtValue3.setFont(new Font("Arial", Font.PLAIN, 11)); txtValue3.setBounds(162, 85, 126, 26); contentPane.add(txtValue3); txtValue3.setColumns(10); txtValue3.setEnabled(false); JMenuBar menuBar = new JMenuBar(); menuBar.setFont(new Font("Arial", Font.PLAIN, 12)); menuBar.setBounds(-4, 0, 302, 21); contentPane.add(menuBar); JMenu mnFile = new JMenu("File"); mnFile.setFont(new Font("Arial", Font.PLAIN, 12)); menuBar.add(mnFile); final JCheckBoxMenuItem mnCbAot = new JCheckBoxMenuItem("Always on Top"); mnCbAot.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (mnCbAot.getState()) { setAlwaysOnTop(true); } else { setAlwaysOnTop(false); } } }); mnCbAot.setFont(new Font("Arial", Font.PLAIN, 12)); mnFile.add(mnCbAot); JMenuItem mntmExit = new JMenuItem("Exit"); mntmExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); dispose(); } }); mntmExit.setFont(new Font("Arial", Font.PLAIN, 12)); mnFile.add(mntmExit); JMenu mnAbout = new JMenu("About"); mnAbout.setFont(new Font("Arial", Font.PLAIN, 12)); menuBar.add(mnAbout); JMenuItem mntmCs = new JMenuItem("CS-5"); mntmCs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Desktop.getDesktop().browse(new URL(website).toURI()); } catch (Exception e1) { e1.printStackTrace(); } } }); mntmCs.setFont(new Font("Arial", Font.PLAIN, 12)); mnAbout.add(mntmCs); }
bf50bdd0-476e-4bdd-8adc-69b7e6a0f6df
6
public static String downloadStringResource(HttpURLConnection connection) { StringBuffer content; InputStream inputstream = getSafeInputStream(connection); if (inputstream == null) { return null; } // load the Stream in a StringBuffer // Check encoding String contentType = connection.getContentType(); String charset = ""; for (String value : contentType.split(";")) { value = value.trim(); if (value.toLowerCase().startsWith("charset=")) charset = value.substring("charset=".length()); } if ("".equals(charset)) charset = "UTF-8"; String result = ""; try { InputStreamReader isr = new InputStreamReader(inputstream, charset); content = new StringBuffer(); // Write bytes into buffer char buf[] = new char[STREAM_BUFFER_SIZE]; int cnt = 0; while ((cnt = isr.read(buf, 0, STREAM_BUFFER_SIZE)) != -1) { content.append(buf, 0, cnt); } isr.close(); inputstream.close(); result = content.toString(); } catch (Exception ioexception) { System.out.println(ioexception); } return result; }
9fa1c110-5010-42b5-b602-64e0d98131a1
9
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String args[]) { if(cmd.getName().equalsIgnoreCase("freeze")) { if(args.length < 1) { sender.sendMessage(new StringBuilder(pre).append("Please specify a player you would like to freeze!").toString()); return true; } if(sender.hasPermission("bh.freeze")) { Player arr[] = plugin.getServer().getOnlinePlayers(); int len = arr.length; for(int i = 0; i < len; i++) { Player player2 = arr[i]; if(player2.getName().equalsIgnoreCase(args[0])) { if(player2.hasPermission("bh.bypass")) { sender.sendMessage(new StringBuilder(pre).append("You can not freeze this player!").toString()); return true; } if(plugin.freezePlayer(player2)) { sender.sendMessage(new StringBuilder(pre).append(player2.getName()).append(" has been frozen!").toString()); if(!sender.getName().equalsIgnoreCase(args[0])) { player2.sendMessage(new StringBuilder(pre).append("You have been frozen!").toString()); } }else { sender.sendMessage(new StringBuilder(pre).append(player2.getName()).append(" has been unfrozen!").toString()); if(!sender.getName().equalsIgnoreCase(args[0])) { player2.sendMessage(new StringBuilder(pre).append("You have been unfrozen!").toString()); } } return true; } } sender.sendMessage(new StringBuilder(pre).append(args[0]).append(" is not online!").toString()); } } return true; }
c176c6d3-3527-4a67-a787-448651cb10b0
0
public void setFname(String fname) { this.fname = fname; }
0f282fed-b61d-4a1a-9731-ec1ca5e90301
4
@Override public void onCollide(CollisionBox tempBox) { if(tempBox.getCollisionType() == CollisionType.PLAYER) { if(biteWait == 0) { int tempH = GameCore.spawnEngine.getPlayer().currentHealth - 1; GameCore.spawnEngine.getPlayer().setCurrentHealth(tempH); biteWait++; } if(biteWait == 15) { biteWait = 0; } else { biteWait++; } } if(tempBox.getCollisionType() == CollisionType.BULLET) { int tempH = this.getCurrentHealth() - 1; this.setCurrentHealth(tempH); } }
ddec295c-548e-4d67-a41e-7e668978e3b5
4
public void setHSBColor(int row, int col, double hue, double saturation, double brightness) { if (row >=0 && row < rows && col >= 0 && col < columns) { grid[row][col] = makeHSBColor(hue,saturation,brightness); drawSquare(row,col); } }
13f367de-2abc-4be1-af71-0fb4d9059429
9
protected void cleanFiles() throws Exception { final Logger log = log(); if (null == epoch) { log.fine("Epoch is not set, cleanup skipped"); return; } Manager db = getDb(); PathFilter filter; try { filter = getEffectiveFilter(); } catch (IOException invalid) { throw new RuntimeException("Unexpected exception probing a null replica", invalid); } final long estimatedCount = stats.countFiles(); FileDAO fileDAO = db.findDAO(FileDAO.class); NodeNameDAO nameDAO = db.findDAO(NodeNameDAO.class); VersionDAO versionDAO = db.findDAO(VersionDAO.class); Cursor<FileDTO> files = fileDAO.fetchAllFiles(); long deleted = 0L; try { log.info("Removing versions prior to " + epoch + " from shared storage ..."); for (long count = 0L, threshold = 10L;;) { FileDTO file = files.next(); if (null == file) break; String[] splitPath = nameDAO.toSplitPath(file.getNameId()); if (filter.pathMatches(splitPath)) { if (versionDAO.isFileObsolete(file, epoch)) deleted += purgeObsoleteFile(file); else deleted += purgeNonObsoleteFile(file); } count++; if (count >= threshold) { log.info("Cleaned up " + count + " file(s), " + (100L * count / estimatedCount) + '%' + ", deleted " + deleted + " version(s)"); threshold += estimatedCount / 10L; if (count >= threshold) threshold = estimatedCount; } } } finally { try { files.close(); } catch (DBException ex) { log().log(Level.WARNING, "Error closing cursor over all shared files", ex); } } }
85be2ccb-c436-44f1-be9d-5ff6415ace98
3
public int minMaxIndexLookback( int optInTimePeriod ) { if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) ) optInTimePeriod = 30; else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) ) return -1; return (optInTimePeriod-1); }
a7863b1e-5757-43af-b559-5c30c313b648
9
private ExtendedPolygon[] convertWorldToScreen2(GameObject that, int width, int height) { ExtendedPolygon[] poly = new ExtendedPolygon[3]; double[][][] faces = that.getBounds().getFaces(); double[][] faceX; double[][] faceY; double[][] faceZ; Color xFaceColor; Color yFaceColor; Color zFaceColor; // System.out.println("Chosing faces :: "); // if(camera.distanceToXY(faces[3][4][0], faces[3][4][1]) < // camera.distanceToXY(faces[4][4][0], faces[4][4][1])) if (camera.distanceToXYZ(faces[3][4]) < camera .distanceToXYZ(faces[4][4])) { // System.out.println("Face 3"); faceX = faces[3]; xFaceColor = that.texture.get(3); } else { // System.out.println("Face 4"); faceX = faces[4]; xFaceColor = that.texture.get(4); } // if(camera.distanceToXY(faces[1][4][0], faces[1][4][1]) < // camera.distanceToXY(faces[2][4][0], faces[2][4][1])) { if (camera.distanceToXYZ(faces[1][4]) < camera .distanceToXYZ(faces[2][4])) { // System.out.println("Face 1"); faceY = faces[1]; yFaceColor = that.texture.get(1); } else { // System.out.println("Face 2"); faceY = faces[2]; yFaceColor = that.texture.get(2); } // System.out.println(camera.getDeltaZ(faces[0][4][2]) + " " + // camera.getDeltaZ(faces[5][4][2]) ); // if(camera.getDeltaZ(faces[0][4][2]) < 0) { // System.out.println(camera.distanceToXYZ(faces[0][4])); if (camera.distanceToXYZ(faces[0][4]) < camera .distanceToXYZ(faces[5][4])) { // System.out.println("Face 0"); faceZ = faces[0]; zFaceColor = that.texture.get(0); } else { // System.out.println("Face 5"); faceZ = faces[5]; zFaceColor = that.texture.get(5); } for (int i = 0; i < faceX.length; i++) { // System.out.printf("FaceX point %d "); // double[] tempPoint = pointToScreenNew(faceX[i], width, height); double[] tempPoint = pointToScreen2(faceX[i], width, height); faceX[i] = tempPoint; } for (int i = 0; i < faceY.length; i++) { // System.out.printf("FaceX point %d "); // double[] tempPoint = pointToScreenNew(faceY[i], width, height); double[] tempPoint = pointToScreen2(faceY[i], width, height); faceY[i] = tempPoint; } for (int i = 0; i < faceZ.length; i++) { // System.out.printf("FaceX point %d "); double[] tempPoint = pointToScreen2(faceZ[i], width, height); faceZ[i] = tempPoint; } // Xface polygon creation int[] tempX = new int[4]; int[] tempY = new int[4]; // System.out.println(faceX.length); // -1 is to get rid of the midpoint... for (int i = 0; i < faceX.length - 1; i++) { // System.out.println(i); tempX[i] = (int) faceX[i][0]; tempY[i] = (int) faceX[i][1]; } poly[2] = new ExtendedPolygon(tempX, tempY, 4, xFaceColor); // Yface polygon creation tempX = new int[4]; tempY = new int[4]; for (int i = 0; i < faceY.length - 1; i++) { tempX[i] = (int) faceY[i][0]; tempY[i] = (int) faceY[i][1]; } poly[1] = new ExtendedPolygon(tempX, tempY, 4, yFaceColor); // Zface polygon creation tempX = new int[4]; tempY = new int[4]; for (int i = 0; i < faceZ.length - 1; i++) { tempX[i] = (int) faceZ[i][0]; tempY[i] = (int) faceZ[i][1]; } poly[0] = new ExtendedPolygon(tempX, tempY, 4, zFaceColor); return poly; }
dea919b5-1491-4929-af0f-a471bac5de93
1
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; }
fc3c4a4f-0b80-4996-9278-cee72808b8fa
1
public ResultSet getAllProcessorsOfType(int processorType) { ResultSet res = null; try{ String query = "SELECT * FROM processor_types WHERE processorBrandID=?"; stmnt = CONN.prepareStatement(query); // Bind Parameters stmnt.setInt(1, processorType); res = stmnt.executeQuery(); } catch (SQLException ex) { handleSqlExceptions(ex); } return res; }
b02207cf-3eb8-4379-8e8c-bbf477fc6cd3
3
@Override public void deserialize(Buffer buf) { mapId = buf.readInt(); int limit = buf.readUShort(); npcsIdsWithQuest = new int[limit]; for (int i = 0; i < limit; i++) { npcsIdsWithQuest[i] = buf.readInt(); } limit = buf.readUShort(); questFlags = new GameRolePlayNpcQuestFlag[limit]; for (int i = 0; i < limit; i++) { questFlags[i] = new GameRolePlayNpcQuestFlag(); questFlags[i].deserialize(buf); } limit = buf.readUShort(); npcsIdsWithoutQuest = new int[limit]; for (int i = 0; i < limit; i++) { npcsIdsWithoutQuest[i] = buf.readInt(); } }
af366265-9c1f-48f2-ae02-66d57bbc7991
3
@Override public void onCombatTick(int x, int y, Game game) { List<Entity> neighbors = ((SinglePlayerGame) game) .getSquareNeighbors(x, y, 1); for (Entity neighbor : neighbors) { if (neighbor.id == EntityType.archer.id) { ((MortalEntity) neighbor).damage(1); wizard.damageDealt++; } else if (neighbor.id == EntityType.warrior.id) { ((MortalEntity) neighbor).damage(3); wizard.damageDealt += 3; } } }
ff162aa0-305a-4a33-9304-0534300b53d0
3
public ReturnObject remove(int index) { ReturnObjectImpl returnValue = new ReturnObjectImpl(); if (index < 0 || index >= size()) { returnValue.value = ErrorMessage.INDEX_OUT_OF_BOUNDS; return returnValue; } for (int i = index; i < size(); i++) { array[i] = array[i + 1]; } return null; }
d008c043-7e10-4740-8e2d-881226778c91
2
public static void toggleWordWrap(IEditorPart editor) { if (editor == null) { return; } // editor (IEditorPart) adapter returns StyledText Object text = editor.getAdapter(Control.class); if (text instanceof StyledText) { StyledText styledText = (StyledText) text; // toggle wrapping styledText.setWordWrap(!styledText.getWordWrap()); } }
dd07e12e-83e6-4ea6-88e5-bd2ab64588b2
6
private void initializeQueryPropertiesNew() { synchronized (defaultQueryProperties) { defaultQueryProperties.clear(); try { final InferenceParameterDescriptions desc = DefaultInferenceParameterDescriptions.loadInferenceParameterDescriptions(this, 10000); final InferenceParameters defaults = desc.getDefaultInferenceParameters(); final CycList allQueryProperties = converseList(makeSubLStmt("ALL-QUERY-PROPERTIES")); for (final Object property : allQueryProperties) { if (property instanceof CycSymbol && defaults.containsKey((CycSymbol) property)) { final Object value = defaults.get((CycSymbol) property); defaultQueryProperties.put((CycSymbol) property, value); } } } catch (UnknownHostException ex) { Logger.getLogger(CycAccess.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(CycAccess.class.getName()).log(Level.SEVERE, null, ex); } catch (CycApiException ex) { Logger.getLogger(CycAccess.class.getName()).log(Level.SEVERE, null, ex); } } queryPropertiesInitialized = true; }
2bffb86e-40da-4eaf-98f4-c3e5ba28cae5
3
public RetCode RestoreCandleDefaultSettings( CandleSettingType settingType) { int i; if (settingType.ordinal() > CandleSettingType.AllCandleSettings .ordinal()) return RetCode.BadParam; if (settingType == CandleSettingType.AllCandleSettings) { for (i = 0; i < CandleSettingType.AllCandleSettings.ordinal(); ++i) { candleSettings[i].CopyFrom(TA_CandleDefaultSettings[i]); } } else { candleSettings[settingType.ordinal()] .CopyFrom(TA_CandleDefaultSettings[settingType.ordinal()]); } return RetCode.Success; }
a05faf08-24ab-4daf-b053-f6ac67c75cb4
2
public boolean IDscanner(int trackingNumber){ int loop; for (loop = 0; loop < enemiesPresent.size(); loop++){ if (enemiesPresent.get(loop).getID() == trackingNumber){ return true; } } return false; }
dcfcebbd-de42-46b6-80c9-b7c0a64b6b5f
1
private static void checkFA(Object fa, Object o, String field) { if (fa == null) { throw new ComponentException("No such field '" + o.getClass().getCanonicalName() + "." + field + "'"); } }
e7a32701-8617-49df-9a9c-84576ab8cbbe
9
public void actionPerformed(ActionEvent ae) { if(ae.getSource() == jRegisterPanel.getCancelButton()) { setVisible(false); jLoginFrame.setVisible(true); dispose(); } else if (ae.getSource() == jRegisterPanel.getRegisterButton()) { String szEmail = jRegisterPanel.getEmailField(); String szUsername = jRegisterPanel.getUsernameField(); String szPasscode = jRegisterPanel.getPasscodeField(); String szAnswer = jRegisterPanel.getSecurityAnswerField(); String szQuestion = jRegisterPanel.getSecurityQuestionField(); if(! (szEmail.isEmpty() || szUsername.isEmpty() || szPasscode.isEmpty() || szAnswer.isEmpty() || szQuestion.isEmpty()) ) { try { if(!ub.register(szUsername,szPasscode, szEmail,szQuestion, szAnswer)) JOptionPane.showMessageDialog(null,"Account: "+szUsername+" already exists.","Duplicate Username",JOptionPane.INFORMATION_MESSAGE); else { JOptionPane.showMessageDialog(null,"Account: "+ szUsername+" created successfully!"); setVisible(false); jLoginFrame.setVisible(true); dispose(); } } catch(IOException ioe) { JOptionPane.showMessageDialog(null,ioe.getMessage()); } } else JOptionPane.showMessageDialog(null,"Registration fields can not be empty"); } }
9a97ab7e-4fc5-4682-b8b8-20de44139711
5
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SondageReponse other = (SondageReponse) obj; if (this.id != other.id) { return false; } if (this.id_sondage != other.id_sondage) { return false; } if (this.choix != other.choix) { return false; } return true; }
a6f86063-4f4e-4c63-9874-f14f0de6120e
1
private static void run(String sourceName, InputStream in, ImageInfo imageInfo, boolean verbose) { imageInfo.setInput(in); imageInfo.setDetermineImageNumber(true); imageInfo.setCollectComments(verbose); if (imageInfo.check()) { print(sourceName, imageInfo, verbose); } }
1684d2d6-7096-4630-9e76-3f420e7755c0
4
int guessPoleIndex(int poleCellId) { if (alreadyIncludes(poleCellId)) { return cellIds.indexOf(poleCellId); } int cenRow = getCenterRow(); int cenCellId = cellIds.get(getCenterIndex()); int cellsToPole = mesh.getDistanceInCells(poleCellId, cenCellId); int poleRow; if (poleCellId == 0) { poleRow = cenRow - cellsToPole; // South Pole } else { poleRow = cenRow + cellsToPole; // North Pole } if ((poleRow < 0) || (poleRow >= numRows)) { return -1; } int cenCol = getCenterColumn(); return getIndex(poleRow, cenCol); }
45bbca1d-e633-4149-82b7-5fe815d0ccbd
0
public double getEccentricity() { return Math.sqrt(1 - b * b / a * a); }
e2418b5a-1901-4898-b0f6-dab41fb74ff2
4
public Mask multiplyBy(Mask mask) { if (this.getWidth() != mask.getHeight()) { throw new IllegalArgumentException("Incompatible matrix"); } Mask result = new Mask(this.getHeight(), mask.getWidth()); for (int i = -1 * this.getHeight() / 2; i <= this.getHeight() / 2; i++) { for (int j = -1 * mask.getWidth() / 2; j <= mask.getWidth() / 2; j++) { int ijValue = 0; for (int k = -1 * this.getWidth() / 2; k <= mask.getHeight() / 2; k++) { ijValue += this.getValue(i, k) * mask.getValue(k, j); } result.setPixel(i, j, ijValue); } } return result; }
4ad0db64-3110-4b38-865d-5b6531c6da1e
1
private void write(BufferedWriter out) { StringBuffer sb = new StringBuffer(); sb.append("db." + JSONWriter.COLLECTION_NAME + ".insert({"); sb.append("stationId: \"" + _stationId + "\""); sb.append(", stationName: \"" + Stations.getName(_stationId) + "\""); sb.append(", latitude: \"" + Stations.getLat(_stationId) + "\""); sb.append(", longitude: \"" + Stations.getLon(_stationId) + "\""); sb.append(", elevation: \"" + Stations.getElevation(_stationId) + "\""); sb.append(", state: \"" + Stations.getState(_stationId) + "\""); sb.append(", year: \"" + _year + "\""); sb.append(", month: \"" + _month + "\""); sb.append(", day: \"" + _day + "\""); sb.append(", rainfall: \"" + _rainfall + "\""); sb.append("});\n"); try { out.write(sb.toString()); } catch (IOException e) { e.printStackTrace(); } //System.out.println(sb.toString()); }
878a57e4-8e16-48fc-b51b-351a83c77bef
7
protected void readCommentHeader() throws Exception { readOggHeader(); byte[] headerTest = new byte[7]; // unfortunately we need to look for the vorbis header do { raf.read(headerTest); raf.seek(raf.getFilePointer() - 6); } while (headerTest[0] != 0x03 && // comment header ident headerTest[1] != 0x76 && // 'v' headerTest[2] != 0x6F && // 'o' headerTest[3] != 0x72 && // 'r' headerTest[4] != 0x62 && // 'b' headerTest[4] != 0x69 && // 'i' headerTest[4] != 0x73 // 's' ); // assume, we found the header - skip until after the ident string raf.skipBytes(6); }
f26a29a6-20f9-486c-8ad6-359a9fdb23f8
4
private void appendFrameTypes( final boolean local, final int n, final Object[] types) { for (int i = 0; i < n; ++i) { Object type = types[i]; AttributesImpl attrs = new AttributesImpl(); if (type instanceof String) { attrs.addAttribute("", "type", "type", "", (String) type); } else if (type instanceof Integer) { attrs.addAttribute("", "type", "type", "", TYPES[((Integer) type).intValue()]); } else { attrs.addAttribute("", "type", "type", "", "uninitialized"); attrs.addAttribute("", "label", "label", "", getLabel((Label) type)); } addElement(local ? "local" : "stack", attrs); } }
2e50b7f1-c327-4e89-84ec-df4f5b741e62
4
public static void countChar(String string) { if (string == null || string.isEmpty()) { System.out.println("Null or empty"); return; } for (int i = 0; i < string.length(); i++) { char asd = string.charAt(i); if (treeMap.get(asd) == null){ treeMap.put(string.charAt(i), 1); }else{ treeMap.put(asd, treeMap.get(string.charAt(i)) + 1); } } }
efa6dc01-5051-4769-8c80-b75256abb854
4
public static int getDashboardTensionUnit() throws ClassNotFoundException { int weightUnit = 0; try{ //Class derbyClass = RMIClassLoader.loadClass("lib/", "derby.jar"); Class.forName(driverName); Class.forName(clientDriverName); }catch(java.lang.ClassNotFoundException e) { throw e; } try (Connection connect = DriverManager.getConnection(databaseConnectionName)) { Statement stmt = connect.createStatement(); ResultSet thePilots = stmt.executeQuery("SELECT tension_unit " + "FROM DashboardUnits " + "WHERE unit_set = 0"); while(thePilots.next()) { try { weightUnit = Integer.parseInt(thePilots.getString(1)); }catch(NumberFormatException e) { //TODO What happens when the Database sends back invalid data JOptionPane.showMessageDialog(null, "Number Format Exception in reading from DB"); } } thePilots.close(); stmt.close(); }catch(SQLException e) { JOptionPane.showMessageDialog(null, e.getMessage()); return -1; } return weightUnit; }
16203dc8-9628-4565-a4eb-e2ad4c2fcafc
2
public static void main(String[] args) { try { Logger.getAnonymousLogger().info("Starting."); final CycAccess cycAccess = new CycAccess("public1.cyc.com", 3600); Logger.getAnonymousLogger().info("Connected to: " + cycAccess.getHostName() + ":" + cycAccess.getBasePort()); // cycAccess.traceOn(); for (int i = 0; i < 2; i++) { Thread.sleep(2000); final String script = "(sleep 1)"; Logger.getAnonymousLogger().info("About to talk to Cyc: " + script); cycAccess.converseVoid(script); Logger.getAnonymousLogger().info("Finished talking to Cyc."); } Logger.getAnonymousLogger().info("About to close CycAccess."); cycAccess.close(); Logger.getAnonymousLogger().info("Closed CycAccess."); } catch (Exception e) { Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage(), e); Logger.getAnonymousLogger().info("Finished."); System.exit(1); } Logger.getAnonymousLogger().info("Finished."); // @note if the main method hangs, then there is an issue with threads // lingering that should be investigated. }
1b2b8ed0-a796-4a03-8b75-9a1d92201ef5
2
private static DecimalImpl mulInt(final long d1Base, final long d2Base, final int d2Factor) { final long d1_1 = d1Base / MUL_COMPONENT; final long d1_2 = d1Base % MUL_COMPONENT; final long d2_1 = d2Base / MUL_COMPONENT; final long d2_2 = d2Base % MUL_COMPONENT; final long r11 = d1_1 * d2_1; final long r12 = d1_1 * d2_2; final long r21 = d1_2 * d2_1; final long r22 = d1_2 * d2_2; if (r11 == 0) { // few numbers only final long r2 = r12 + r21; final int scale2 = DPU.findFactorByLimit(r2); final long base2 = DPU.getScaledBase(r2, scale2); final int scale3 = MUL_SCALE_2 - scale2; final long base3 = DPU.getScaledBase(r22, -scale3); return safegetInstance(base2 + base3, d2Factor - MUL_SCALE_2 + scale2); } else { final int scale1 = DPU.findFactorByLimit(r11); final long base1 = DPU.getScaledBase(r11, scale1); final int scale2 = MUL_SCALE_2 - scale1; final long base2 = DPU.getScaledBase(r12 + r21, -scale2); final int scale3 = MUL_SCALE_2 + scale2; final long base3 = DPU.getScaledBase(r22 + (scale2 > 0 ? ((r12 + r21) % DPU.getScale(scale2)) : 0), -scale3); return safegetInstance(base1 + base2 + base3, d2Factor - MUL_SCALE_2 - MUL_SCALE_2 + scale1); } }
4cc8ecd2-65f4-4181-9bed-d294640f048b
2
@Override public List<Object> getAll(int gameID){ XStream xStream = new XStream(new DomDriver()); List<Object> model=new ArrayList<Object>(); Object temp=null; Statement stmt=null; try { stmt = db.getConnection().createStatement(); ResultSet rs = stmt.executeQuery("SELECT command FROM MoveCommand where game = " + gameID); db.getConnection().commit(); while (rs.next()) { /*byte[] st = (byte[]) rs.getObject(1); ByteArrayInputStream baip = new ByteArrayInputStream(st); ObjectInputStream ois = new ObjectInputStream(baip); temp = (Object) ois.readObject(); model.add(temp);*/ String xml = (String)rs.getString(1); model.add((Object) xStream.fromXML(xml)); } rs.close(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); } return model; }
96d89d3b-0e0f-40df-998d-f6a2e788c688
5
public boolean bateCom(Aula aula2) { if(this.diaDaSemana != aula2.getDiaDaSemana()){ return false; } Periodo p1 = this.getPeriodo(); Periodo p2 = aula2.getPeriodo(); if((p1.getLimiteSuperior().after(p2.getLimiteInferior()) && p1.getLimiteSuperior().before(p2.getLimiteSuperior())) || ( p1.getLimiteInferior().after(p2.getLimiteInferior()) && p1.getLimiteInferior().before(p2.getLimiteSuperior()) ) ){ return true; } return false; }
524a5d28-5c62-4c5a-a76f-dfd9f71815e5
7
public byte[] handleRequest(byte[] request) { try { String req = Utils.byteToString(request); if (req.startsWith(HEARTBEAT_COMMAND)) { req = req .substring((HEARTBEAT_COMMAND + COMMAND_PARAM_SEPARATOR) .length()); logger.info(myInfo + " recieved heartbeat ping with server list " + req); List<Machine> machinesToAdd = Machine.parseList(req); Set<Machine> currentMachines = getMachineList(); for (Machine machine : machinesToAdd) { if (!currentMachines.contains(machine)) { this.addMachine(machine); logger.info(this.myInfo + " added " + machine + " to known server list"); } else { currentMachines.remove(machine); } } for (Machine machine : currentMachines) { this.removeMachine(machine.getId()); logger.info(this.myInfo + " removed " + machine + " from known server list"); } return Utils.stringToByte(COMMAND_SUCCESS); } else if (req.startsWith(START_ELECTION_COMMAND)) { // TODO: handle election. SHould block all writes; return null; } else if (req.startsWith(END_ELECTION_COMMAND)) { // TODO: handle election ends. start new coordinator and start // acceptign reqs after coordinator return null; } return handleSpecificRequest(req); } catch (Exception e) { logger.error("Exception handling request in replica server", e); return Utils.stringToByte(COMMAND_FAILED + COMMAND_PARAM_SEPARATOR + e.getMessage()); } }
d331985e-107d-444b-ade3-297d36e3cfb0
2
Map<String, ArrayList<ArrayList<String>>> datasOfClass(ArrayList<ArrayList<String>> datas){ Map<String, ArrayList<ArrayList<String>>> map = new HashMap<String, ArrayList<ArrayList<String>>>(); ArrayList<String> t; String c; for (ArrayList<String> data : datas) { t = data; c = t.get(t.size() - 1); if (map.containsKey(c)) { map.get(c).add(t); } else { ArrayList<ArrayList<String>> nt = new ArrayList<ArrayList<String>>(); nt.add(t); map.put(c, nt); } } return map; }
9ae26036-e6a1-4d1a-b45d-741c03c5f896
8
private void setConfigFile(String conf) throws FileNotFoundException, IOException { this.configFile = conf; File f = new File(configFile); if (!f.exists()) { return; } try { BufferedReader reader = new BufferedReader(new FileReader(f)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } reader.close(); this.conf = new JSONObject(stringBuilder.toString()); String build_root = this.conf.optString(Semantics.DEP_BUILD_ROOT); if (build_root != null && !build_root.equals("")) { this.buildFile(build_root); } String def_file = this.conf.optString(Semantics.GLOBAL_DEFINE); if (def_file != null && !def_file.equals("")) { this.def_hdr(def_file); } } catch (JSONException e) { System.err.println("File " + configFile + " can't be parsed!"); this.conf = null; this.configFile = null; } catch (IOException e) { e.printStackTrace(); } }
cb2dbade-19ae-4558-b71f-4aa94b231b28
2
public double[] rawItemMeans(){ if(!this.dataPreprocessed)this.preprocessData(); if(!this.variancesCalculated)this.meansAndVariances(); return this.rawItemMeans; }
b17b016a-ddb2-456f-b2cb-38c102f8a915
6
public static Boolean CheckMapsize(int players, int mapsize) { if ((mapsize > 50) || (mapsize <= 0)) { System.out.println("Invalid Map Size"); return false; } else { if (players >= 2 && players <= 4) { if (mapsize < 5) { System.out .println("Minimum size of map for the number of players is 5"); return false; } else { return true; } } else { if (mapsize < 8) { System.out .println("Minimum size of the map for this number of players is 8 "); return false; } else { return true; } } } }
88b2e29f-4c88-410c-a5c3-e30c4f8a5d76
1
public void keyPressed(KeyEvent e) { if (stage != null) { stage.keyPressed(e); } }
9f92901f-6ef7-4949-ad55-925b60e7cdb7
1
public boolean rateReview(String isbn, String reviewer, int score) throws SQLException { if (reviewer.equals(username)) { return false; } LinkedList<String> columns = new LinkedList<String>(); LinkedList<String> values = new LinkedList<String>(); columns.add("ISBN"); values.add(isbn); columns.add("Reviewer"); values.add(reviewer); columns.add("Rater"); values.add(username); columns.add("Score"); values.add(String.valueOf(score)); return insertSpecificValues("Usefulness", columns, values); }
2af5c05a-809f-4a24-aeef-55f1acaee4a3
2
private static void postQueryCleanup(Connection c, Statement st, ResultSet rs) { try { if(rs != null) { rs.close(); st.close(); c.close(); } } catch(Exception e) { Actions.addAction(new Action(ActionType.WARNING, "Unable to close Database connections " + "post query.")); } }
2b88b219-46f3-44e3-a89f-76d81cc2f97d
6
private String getServerSetting(String tagName) { String val = ""; // try { NodeList nodeList = m_root.getElementsByTagName( "MyServer" ); if ( nodeList == null ) { return val; } Element child = (Element)nodeList.item(0); NodeList childNodeList = child.getElementsByTagName( tagName ); Element child2 = (Element)childNodeList.item(0); if ( child2 != null ) { if ( tagName.equals("FrontServer") || tagName.equals("MiddleServer") ) { val = child2.getAttribute("URL"); } else { Node node = child2.getFirstChild(); if ( node != null ) { val = node.getNodeValue(); } } if ( val == null ) { val = ""; } } // } // catch ( ArrayIndexOutOfBoundsException e ) { // e.printStackTrace(); // } LOGGER.info(tagName + " <-> " + val); return val; }
f6b1f79b-93a0-4030-8327-1e6e438fcddf
0
@Override public Object clone() { return this; }
f81bd3b1-28a9-4b10-a047-67ebb45e9028
7
public boolean canImportTransferable(DataFlavor[] transferFlavors) { boolean result = false; for (DataFlavor df:transferFlavors) { if (DataFlavor.javaFileListFlavor.equals(df) || DataFlavor.imageFlavor.equals(df) || (urlListDataFlavor != null && urlListDataFlavor.equals(df)) ) { result = true; break; } else if (urlListDataFlavor != null && urlListDataFlavor.equals(df)) { result = true; break; } } return result; }
bbbd681e-e09d-4cab-ae8e-9526166c8825
1
private void renderThings(Graphics2D g){ g.clearRect(0,0,screenWidth,screenHeight); //render field g.setColor(Color.WHITE); //The base measurement g.fillRect(worldXToScreen(1000), worldYToScreen(4000), (int)(4000*screenXFactor), (int)(2000*screenYFactor)); //entity draw loop for(int i=0; i<playerArray.length; i++){ int[] entity = playerArray[i]; AffineTransform xform = new AffineTransform(); Image image = imageIdToImage((int) (entity[3] + Math.floor(i/5))); xform.translate(worldXToScreen(entity[0]), worldYToScreen(entity[1])); xform.scale(400/(255*magnification), 400/(255*magnification)); xform.rotate(Math.toRadians(360 - entity[2])); xform.translate(-(image.getWidth(null))/2, -(image.getHeight(null))/2); //draws the entity g.drawImage(image, xform, null); } g.setColor(Color.YELLOW); g.drawString(mouseWorld.x + ", " + mouseWorld.y, worldXToScreen(mouseWorld.x), worldYToScreen(mouseWorld.y)); }//end operate entities
eadec721-0fe4-48ae-a6ca-0b8110fc9016
4
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dateOfBirth == null) ? 0 : dateOfBirth.hashCode()); result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); result = prime * result + patientCardId; result = prime * result + ((patronymic == null) ? 0 : patronymic.hashCode()); return result; }
34f47177-d7c1-4043-b312-83797ca5a3a8
0
private void setData() { ArrayList<String> list = campaignRef.getSettings(); background1Field.setText(list.get(0)); background2Field.setText(list.get(1)); background3Field.setText(list.get(2)); logoField.setText(list.get(3)); buttonField.setText(list.get(4)); }
ab666ec8-abe4-44f5-a72a-7ae37dfbd239
8
public boolean searchForPyro() { // look for a Pyro in the same Room Pyro target_pyro = null; double smallest_angle_to_pyro = Math.PI; for (Pyro pyro : current_room.getPyros()) { if (pyro.isVisible()) { double abs_angle_to_pyro = Math.abs(MapUtils.angleTo(bound_object, pyro)); if (abs_angle_to_pyro < smallest_angle_to_pyro) { target_pyro = pyro; smallest_angle_to_pyro = abs_angle_to_pyro; } } } if (target_pyro != null) { markPyroAsTarget(target_pyro); return true; } // look for a visible Pyro in a neighbor Room for (Entry<RoomSide, RoomConnection> entry : current_room.getNeighbors().entrySet()) { RoomConnection connection = entry.getValue(); for (Pyro pyro : connection.neighbor.getPyros()) { if (pyro.isVisible() && MapUtils.canSeeObjectInNeighborRoom(bound_object, pyro, entry.getKey())) { markPyroAsTarget(pyro); target_object_room_info = entry; return true; } } } return false; }
51c4d8fd-0073-4c29-afbd-92f853d182d0
1
public int onEnd() { if(log.isLoggable(Logger.WARNING)) log.log(Logger.WARNING, "onEnd"); return transition; }
5abfb047-a03b-4e7f-8cf4-7073fe7a1e1c
8
private void balanceOut(){ int balance = hoehe(rechts) - hoehe(links); assert (balance <= 2); assert (balance >= -2); if (balance == -2) { int ll = (links.links == null) ? 0 : links.links.hoehe; int lr = (links.rechts == null) ? 0 : links.rechts.hoehe; if (ll >= lr) // >= ?? rechtsRotation(); else doppelteLinksRotation(); } else if (balance == 2) { int rr = (rechts.rechts == null) ? 0 : rechts.rechts.hoehe; int rl = (rechts.links == null) ? 0 : rechts.links.hoehe; if (rr > rl) // >= ?? linksRotation(); else doppelteRechtsRotation(); } }
f93f6b57-ac1b-4ee5-8051-3bb8099ce95e
4
public void body() { initializeResultsFile(); createGridlet(super.get_id(), NUM_GRIDLETS); // schedule the initial sending of gridlets. // The sending will start in a ramdom time within 5 min Random random = new Random(); int init_time = random.nextInt(5*60); // sends a reminder to itself super.send(super.get_id(), init_time, SUBMIT_GRIDLET); System.out.println(super.get_name() + ": initial SUBMIT_GRIDLET event will be at clock: " + init_time + ". Current clock: " + GridSim.clock()); //////////////////////////////////////////////////////////// // Now, we have the framework of the entity: while (Sim_system.running()) { Sim_event ev = new Sim_event(); super.sim_get_next(ev); // get the next event in the queue switch (ev.get_tag()) { // submit a gridlet case SUBMIT_GRIDLET: processGridletSubmission(ev); // process the received event break; // Receive a gridlet back case GridSimTags.GRIDLET_RETURN: processGridletReturn(ev); break; case GridSimTags.END_OF_SIMULATION: System.out.println("\n============== " + super.get_name() + ". Ending simulation..."); break; default: System.out.println(super.get_name() + ": Received an event: " + ev.get_tag()); break; } // switch } // while // wait for few seconds before printing the output super.sim_pause( super.get_id()*2 ); // remove I/O entities created during construction of this entity super.terminateIOEntities(); // prints the completed gridlets printGridletList(GridletReceiveList_, super.get_name(), false, gridletLatencyTime); } // body()
7017406b-fc4a-47b6-84d8-74f751cc7ba6
0
public void setAgencia(String ag) { this.agencia = ag ; }
6732bbcc-d58d-4123-88c4-f0c41ac7dab5
2
private JPanel createMatrixPanel() { JPanel panel = new JPanel(); for (int i = 0; i < bMatrix.length; i++) { for (int j = 0; j < bMatrix[0].length; j++) { panel.add(bMatrix[i][j]); } } return panel; }
39db61af-07b5-4306-a75f-d4fd21a319da
0
public void insert(TestBean bean) { jdbcTemplate.update("insert into TEST VALUES ( ?, ? )", bean.getId(), bean.getName()); }
b5ebbb58-9786-4d2f-827e-8a2f8431dafa
8
public static void main(String [] args) { ExperimentDao experimentDao = new JpaExperimentDao(); // ExperimentDataStore cache = new RedisABSeeCache(); ExperimentDataStore cache = new MemcachedExperimentDataStore(); // ExperimentDataStore cache = new HashMapABSeeCache(); cache.flush(); // Clear down from previous runs. Experiments experiments = new DefaultExperimentsImpl(cache, experimentDao); RandomIdentitySource randomIdentitySource = new RandomIdentitySource(); ABSee absee = new ABSee(experiments, randomIdentitySource); String testName = "red or blue checkout button"; Random rand = new Random(System.currentTimeMillis()); for (int x = 0; x < 2000; x++) { //absee.test("red or blue checkout button", new String [] {"red", "blue"}, null); //absee.test(testName, 10, null); String alternative = absee.test(testName, "'bob' => 0.9, 'sam' => 0.1", null); int randomNum = rand.nextInt(10); if (randomNum < 6 || (randomNum < 7 && alternative.equals("sam"))) { absee.conversion(testName); } randomIdentitySource.next(); } experimentDao.beginTransaction(); Experiment experiment = experimentDao.findOrCreateByTestName(testName); System.out.println(experiment.getName()); System.out.println("Best Alternative:" + experiment.bestAlternative().getContent()); ExperimentResults results = experiment.results(); Stats bestStats = results.getStats().get(experiment.bestAlternative().getContent()); if (bestStats != null) { if (bestStats.getValue() <= 0.05) { System.out.println(String.format("Statistically significant with a confidence level of %s (%s)", bestStats.getPercentage(), bestStats.getDescription())); } else { System.out.println("Not statistically significant, suggest continuing testing."); } } System.out.println("Alternative breakdown:"); boolean control = true; for (Alternative alternative : experiment.getAlternatives()) { Stats stat = results.getStats().get(alternative); if (control) { control = false; stat = Stats.NOT_APPLICABLE; } System.out.println(String.format(" %s[%.2f]: p/c/r/confidence %s/%s/%.2f%%/%s(%s)", alternative.getContent(), alternative.getWeight(), alternative.getParticipantCount(), alternative.getConversionCount(), alternative.conversionRate() * 100, stat.getPercentage(), stat.getDescription())); } System.out.println("Total Participants: " + experiment.participantCount()); System.out.println("Total Conversions: " + experiment.conversionCount()); experimentDao.rollback(); }
1312ee48-0510-4571-b691-0ae556a8939f
5
public void copyFile(String copyFrom,String copyTo){ File file1 = new File(copyFrom); File file2 = new File(copyTo); try { if(!file1.exists()){ throw new SecurityException(); } if(file2.exists()){ System.out.println("The file you are trying to write to already exists - would you like to overwrite it (y/n)"); String response = System.console().readLine(); if(response.equals("y")){ duplicate(file1,file2); } else if(response.equals("n")){ System.out.println("Exiting progam - nothing done"); } else { System.out.println("Invalid selection - exiting program"); } } else { duplicate(file1,file2); } } catch (SecurityException ex) { System.out.println("This file does not exist: " + file1); ex.printStackTrace(); } }
f24d45f2-b71b-473d-adcb-672f4cbb8a65
1
public boolean add(Libros l){ PreparedStatement ps; try { ps = mycon.prepareStatement("INSERT INTO Libros VALUES(?,?,?,?,?,?)"); ps.setString(1, l.getCodigolibro()); ps.setString(2, l.getNombrelibro()); ps.setString(3, l.getTitulolibro()); ps.setString(4, l.getAutorlibro()); ps.setInt(5, l.getCantidad()); ps.setInt(6, l.getPrestados()); return (ps.executeUpdate()>0); } catch (SQLException ex) { Logger.getLogger(LibrosCRUD.class.getName()).log(Level.SEVERE, null, ex); } return false; }
7cea10af-a275-42b6-a60a-26f31f45fbbf
8
public static void main(String[] args) { String[] texts = new String[] { "kiedy xP x-D :-D :( :(((( ;)kierowca samochodu stracił panowanie? :) I Ci ludzie ciągle piją do wszystkich, że nie chcą ich przepuszczać na skrzyżowaniach, że kierowcy samochodów nie chcą wjeżdżać na chodniki, aby przepuścić przepychającego się w korku motocykla? CO ZA HIPOKRYZJA!", "co ci podać, Panie? ;) :-D co tam słcyhać? tak. PoKemon pOkemon" }; Object[] keys = FeaturesExtractor.features("").keySet().toArray(); FileWriter fstream = null; try { fstream = new FileWriter("features.csv"); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < keys.length; ++i) { try { out.write(keys[i].toString()); if (i < keys.length - 1) out.write(","); } catch (IOException e) { e.printStackTrace(); } } out.write("\n"); for (String text : texts) { Map<String, Double> f = FeaturesExtractor.features(text); for (int i = 0; i < keys.length; ++i) { try { out.write(f.get(keys[i]).toString()); if (i < keys.length - 1) out.write(","); } catch (IOException e) { e.printStackTrace(); } } out.write("\n"); } out.close(); } catch (IOException e1) { e1.printStackTrace(); } }
0b475cf8-d571-4471-a1c1-130dceb92a3e
9
public void updateLabels(Label l, ArrayList<String> labels) throws RollbackException { for(String s : labels) { if(s.equals("funny")) l.setFunny(l.getFunny() + 1); else if(s.equals("cute")) l.setCute(l.getCute() + 1); else if(s.equals("animal")) l.setAnimal(l.getAnimal() + 1); else if(s.equals("nature")) l.setNature(l.getNature() + 1); else if(s.equals("architecture")) l.setArchitecture(l.getArchitecture() + 1); else if(s.equals("art")) l.setArt(l.getArt() + 1); else if(s.equals("fiction")) l.setFiction(l.getFiction() + 1); else if(s.equals("life")) l.setLife(l.getLife() + 1); else l.setPeople(l.getPeople() + 1); } update(l); }
b8d9e18b-02ac-444e-ba91-16b519dff321
1
private void doIndex() throws IOException { for (int i = 0; i < files.size(); i++) { InputStream is = files.get(i); String s = new BufferedReader(new InputStreamReader(is)).readLine(); tokenize(s, i); } }
e823757d-cad7-4dca-8094-9032899e4970
5
protected ModReader(){ try { unimodController = new UnimodDataAccessController(unimodUrl); psiModController = new PSIModDataAccessController(psiModUrl); prideModController = new PRIDEModDataAccessController(prideModdUrl); } catch (Exception e) { String msg = "Exception while trying to read Database files.."; logger.error(msg, e); throw new DataAccessException(msg, e); } finally { try { if(unimodUrl!= null){ unimodUrl.close(); } if(psiModUrl!= null){ psiModUrl.close(); } if(psiModUrl!= null){ psiModUrl.close(); } } catch (IOException e) { e.printStackTrace(); } } }
2d63fff3-6ada-4e94-aabe-0b131c9680ff
2
private void loadChidren() { Iterable<T> iterable = _selector.select(_ancestor); if(iterable != null) { _children = iterable.iterator(); if(_children.hasNext()) { _childIterator = new FlatternerIterator<T>(_children.next(), this._selector); _state = 1; } else { _state = 2; } } else { _state = 2; } }
63855df4-630c-4c76-b960-f14e4ca2c3d7
7
public Warrior(Grid g, Patch p) { super(g, p); setFriendly(true); setMove(3); setRange(0); setHealth(100); setShield(5); setDamage(20); setMaxHealth(110); try { getStates().add(ImageIO.read(new File("res/Warrior/Warrior.gif"))); } catch (IOException e) { } try { getStates().add(ImageIO.read(new File("res/Warrior/Warrior2.gif"))); } catch (IOException e) { } try { setActive(ImageIO.read(new File("res/Warrior/Warrior-Active.gif"))); } catch (IOException e) { } try { setExhausted(ImageIO.read(new File( "res/Warrior/Warrior-Exhausted.gif"))); } catch (IOException e) { } try { setAttacking(ImageIO.read(new File( "res/Warrior/Warrior-Attacking.gif"))); } catch (IOException e) { } try { // defending image nonexistent? setDefending(ImageIO.read(new File( "res/Warrior/Warrior-Attacking.gif"))); } catch (IOException e) { } try { setInfoPic(ImageIO.read(new File( "res/Warrior/WarriorInfo.gif"))); } catch (IOException e) { } setImage(getStates().get(0)); }
c9b19a55-7dfc-4ab1-a3b7-8c995662f7b5
4
public void sql_add_account() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver").newInstance(); Statement s = GUI.con.createStatement(); //CHANGE FUNCTIONS DEPENDING ON HIERARCHY if(GUI.Level == 1) { s.executeUpdate ("INSERT INTO all_users VALUES(default,"+ hierarchy_input.getText() +","+"\'"+f_name_input.getText()+"\',"+"\'"+l_name_input.getText()+"\',"+"\'"+username_input.getText()+"\',"+"\'"+password_input.getText()+"\',"+"\'"+access_code_input.getText()+"\',"+ "\'" + group_input.getText()+"\'"+");"); } else if(GUI.Level == 2) { s.executeUpdate ("INSERT INTO all_users VALUES(default,"+ "3" +","+"\'"+f_name_input.getText()+"\',"+"\'"+l_name_input.getText()+"\',"+"\'"+username_input.getText()+"\',"+"\'"+password_input.getText()+"\',"+"\'"+access_code_input.getText()+"\',"+ "\'" + GUI.ugn +"\'"+");"); } //The New Account will have a group name, if this group name exists, increment the count of the group by 1. If not, add the new group to groups s.executeQuery ("SELECT Member_Count FROM groups WHERE G_Name = \'"+group_input.getText()+"\';"); ResultSet rs = s.getResultSet(); int count = 0; while(rs.next()) { count = rs.getInt("Member_Count"); count++; } if (count == 0) s.executeUpdate("INSERT INTO groups VALUES(default," +"\'"+group_input.getText()+"\',"+"1"+");"); else s.executeUpdate("UPDATE groups SET Member_Count = \'"+count+"\' WHERE G_NAME = \'"+group_input.getText()+"\';"); rs.close(); s.close(); }
1d1bb1f3-7465-44a9-8f47-88839fa9c590
1
public void startWorkers (int workersNum) { for (int i = 0; i < workersNum; ++i) { Worker worker = new Worker(this, i); workers.add(worker); (new Thread(worker)).start(); } }
80d33bac-e71c-4d7b-b1e1-239df5a6c082
4
public static List<Interval> merge(List<Interval> intervals) { Collections.sort(intervals, new Comparator<Interval>() { @Override public int compare(Interval o1, Interval o2) { // TODO Auto-generated method stub return o1.start-o2.start; } }); for (int i = 0; i < intervals.size() - 1; i++) { Interval o1 = intervals.get(i); Interval o2 = intervals.get(i + 1); if (o1.end < o2.start) continue; if (o1.end >= o2.start && o1.end <= o2.end) { Interval o = new Interval(o1.start, o2.end); intervals.add(i, o); intervals.remove(i + 1); intervals.remove(i + 1); i--; } else { intervals.remove(i + 1); i--; } } return intervals; }
1090e4db-ea57-4c17-b798-bfd99ca5995a
6
public static void zeigeBmiAn (double bmi) { // Ausgabe System.out.print("Der BMI ist: " + bmi + ", dass ist "); // mit Zusatzinfo if(bmi < 20){ System.out.println("Untergewicht"); } else if(bmi >= 20 && bmi <= 24){ System.out.println("Idealgewicht"); } else if(bmi >= 25 && bmi <= 30){ System.out.println("leichtes Uebergewicht"); } else if(bmi > 30){ System.out.println("Uebergewicht"); } }
38f87c3d-c4ab-4fcf-86d5-e532e7f26a5f
4
public void deleteDupNodeInPlace(ListNode head){ if(head == null) return; ListNode current = head; while(current != null){ ListNode runner = current; while(runner.next!=null){ if(current.val == runner.next.val) runner.next = runner.next.next; runner = runner.next; } current = current.next; } }
571791f6-92d9-4cb9-9411-93affd26d422
9
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (hashCode() == o.hashCode()) return true; NaturalSatellite that = (NaturalSatellite) o; if (population != that.population) return false; if (mineralResources != null ? !mineralResources.equals(that.mineralResources) : that.mineralResources != null) return false; if (spacePorts != null ? !spacePorts.equals(that.spacePorts) : that.spacePorts != null) return false; return true; }
4d49b550-588f-40cd-a9dd-2eb86b0c39d5
1
public boolean isLeaf() { return (this.fDroit == null && this.fGauche == null); }
851970fb-e4af-42a3-bce3-0b2cfadcd994
4
public MethodVisitor visitMethod( final int access, final String name, final String desc, final String signature, final String[] exceptions) { buf.setLength(0); buf.append("{\n"); buf.append("mv = cw.visitMethod("); appendAccess(access); buf.append(", "); appendConstant(name); buf.append(", "); appendConstant(desc); buf.append(", "); appendConstant(signature); buf.append(", "); if (exceptions != null && exceptions.length > 0) { buf.append("new String[] {"); for (int i = 0; i < exceptions.length; ++i) { buf.append(i == 0 ? " " : ", "); appendConstant(exceptions[i]); } buf.append(" }"); } else { buf.append("null"); } buf.append(");\n"); text.add(buf.toString()); ASMifierMethodVisitor acv = createASMifierMethodVisitor(); text.add(acv.getText()); text.add("}\n"); return acv; }
9da7bb4c-e065-40f4-a1e1-548f249b3974
2
public static ArrayList<Question> getQuestionsByQuizID(int quizID) { ArrayList<Question> questionList = new ArrayList<Question>(); try { String statement = new String("SELECT * FROM " + DBTable + " WHERE quizid = ?"); PreparedStatement stmt = DBConnection.con.prepareStatement(statement); stmt.setInt(1, quizID); ResultSet rs = stmt.executeQuery(); while (rs.next()) { ArrayList<String> questionStringList = getParsedStrings(rs.getString("question")); String answerString = rs.getString("answer"); MultipleChoiceQuestion q = new MultipleChoiceQuestion( rs.getInt("questionid"), rs.getInt("quizid"), rs.getInt("position"), questionStringList, answerString, rs.getDouble("score")); questionList.add(q); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } return questionList; }
485fc822-6ef6-41e9-a5b7-b59154cf9222
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ElementScore elementScore = (ElementScore) o; if (element != null ? !element.equals(elementScore.element) : elementScore.element != null) return false; if (score != null ? !score.equals(elementScore.score) : elementScore.score != null) return false; return true; }
b9127648-8e36-42fe-9c67-9817a496614d
0
@Id @Column(name = "PCA_GENERICO") public Integer getPcaGenerico() { return pcaGenerico; }
b015bb40-7eaf-4e1c-8120-2b4b2cfb4261
7
public void paint1(Graphics g) { //g.drawImage(introImagen, 0, 0, this); g.drawImage(background, 8, 30, this); g.setFont(new Font("Serif", Font.BOLD, 34)); g.drawString("Score: " + score, 44, 195); g.setColor(Color.red); g.drawString("Vidas: " + vidas, 44, 250); if (cantBloques == 0) { perdio = true; } if (canasta != null) { if (!perdio) { g.drawImage(canasta.animacion.getImagen(), (int) canasta.getPosX(), (int) canasta.getPosY(), this); g.drawImage(pelota.animacion.getImagen(), (int) pelota.getPosX(), (int) pelota.getPosY(), this); if (instrucciones) { g.drawImage(tableroInstrucciones, getWidth() / 2 - new ImageIcon(tableroInstrucciones).getIconWidth() / 2, getHeight() / 2 - new ImageIcon(tableroInstrucciones).getIconHeight() / 2, this); // Tablero de instrucciones } if (vidas == 0) { perdio = true; g.drawImage(gameOver, 0, 0, this); } for (Bloques bloque : listaBloques) { g.drawImage(bloque.animacion.getImagen(), (int) bloque.getPosX(), (int) bloque.getPosY(), this); } } else { g.drawImage(gameOver, 8, 30, this); } } if (pausa) { g.drawImage(pausaImagen, getWidth() / 2 - new ImageIcon(pausaImagen).getIconWidth() / 2, getHeight() / 2 - new ImageIcon(pausaImagen).getIconHeight() / 2, this); } }
a679eb81-9345-48ca-a2ed-4e743829f845
4
@Test public void test_insertions() { int m = 3; int n = 5; Matrix m1 = new MatrixList(m, n); for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) m1.insert(i, j, (double) (i * j)); } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) assertEquals(m1.get(i, j), (double) (i * j), 0.01); } }
6454681a-6dc4-4f77-b8b5-64cc23ea4fe2
5
private void subledger2(ArrayList<ArrayList> arrayL) throws SQLException { String query3; this.getORDTLID(); System.out.println("sub2 size "+arrayL.size()); Statement stmt = null; this.connect(); conn = this.getConnection(); stmt = conn.createStatement(); for(int i=0; i<arrayL.size(); i++){ arrayTemp=arrayL.get(i); if(arrayTemp.get(0).matches("reg")){ query3 = "insert into subledger_reg(ordtlid, loanid, loandtlid, mon_premium_prev, mon_interest_prev, premium_pay, interest_pay) " + "values('"+ordtlid+"', '"+arrayTemp.get(1)+"', '"+arrayTemp.get(2)+"', '"+arrayTemp.get(3)+"', '"+arrayTemp.get(4)+"', '"+arrayTemp.get(5)+"', '"+arrayTemp.get(6)+"')"; stmt.addBatch(query3); //paramDB.accessLoopDatabase(query3); query3= "update loan_dtl set mon_premium_bal=mon_premium_bal-"+arrayTemp.get(5)+", mon_interest_bal=mon_interest_bal-"+arrayTemp.get(6)+ " where loandtlid="+arrayTemp.get(2); stmt.addBatch(query3); //paramDB2.accessLoopDatabase(query3); System.out.println("in reg insert"+ordtlid+" "+arrayTemp.get(1)+" "+arrayTemp.get(2)+" "+arrayTemp.get(3)+" "+arrayTemp.get(4)+" "+arrayTemp.get(5)+" "+arrayTemp.get(6)); query3= "update loan_hdr set balance=balance-"+arrayTemp.get(5)+"-"+arrayTemp.get(6)+ " where loanid="+arrayTemp.get(1); stmt.addBatch(query3); //paramDB.accessLoopDatabase(query3); stmt.executeBatch(); } else if(arrayTemp.get(0).matches("ed")){ query3 = "insert into subledger_educ(ordtlid, loanid, loandtlid, mon_premium_prev, mon_interest_prev, premium_pay, interest_pay) " + "values('"+ordtlid+"', '"+arrayTemp.get(1)+"', '"+arrayTemp.get(2)+"', '"+arrayTemp.get(3)+"', '"+arrayTemp.get(4)+"', '"+arrayTemp.get(5)+"', '"+arrayTemp.get(6)+"')"; stmt.addBatch(query3); //paramDB.accessLoopDatabase(query3); query3= "update loan_dtl set mon_premium_bal=mon_premium_bal-"+arrayTemp.get(5)+", mon_interest_bal=mon_interest_bal-"+arrayTemp.get(6)+ " where loandtlid="+arrayTemp.get(2); stmt.addBatch(query3); //paramDB2.accessLoopDatabase(query3); System.out.println("in edinsert"+ordtlid+" "+arrayTemp.get(1)+" "+arrayTemp.get(2)+" "+arrayTemp.get(3)+" "+arrayTemp.get(4)+" "+arrayTemp.get(5)+" "+arrayTemp.get(6)); query3= "update loan_hdr set balance=balance-"+arrayTemp.get(5)+"-"+arrayTemp.get(6)+ " where loanid="+arrayTemp.get(1); stmt.addBatch(query3); //paramDB.accessLoopDatabase(query3); stmt.executeBatch(); } else if(arrayTemp.get(0).matches("cal")){ //System.out.println("2size"+arrayTemp.size()); query3 = "insert into subledger_cal (ordtlid, loanid, loandtlid, mon_premium_prev, mon_interest_prev, premium_pay, interest_pay) " + "values('"+ordtlid+"', '"+arrayTemp.get(1)+"', '"+arrayTemp.get(2)+"', '"+arrayTemp.get(3)+"', '"+arrayTemp.get(4)+"', '"+arrayTemp.get(5)+"', '"+arrayTemp.get(6)+"')"; stmt.addBatch(query3); //paramDB.accessLoopDatabase(query3); query3= "update loan_dtl set mon_premium_bal=mon_premium_bal-"+arrayTemp.get(5)+", mon_interest_bal=mon_interest_bal-"+arrayTemp.get(6)+ " where loandtlid="+arrayTemp.get(2); stmt.addBatch(query3); //paramDB2.accessLoopDatabase(query3); System.out.println("in calinsert"+ordtlid+" "+arrayTemp.get(1)+" "+arrayTemp.get(2)+" "+arrayTemp.get(3)+" "+arrayTemp.get(4)+" "+arrayTemp.get(5)+" "+arrayTemp.get(6)); query3= "update loan_hdr set balance=balance-"+arrayTemp.get(5)+"-"+arrayTemp.get(6)+ " where loanid="+arrayTemp.get(1); stmt.addBatch(query3); //paramDB.accessLoopDatabase(query3); stmt.executeBatch(); } else if(arrayTemp.get(0).matches("em")){ query3 = "insert into subledger_emer(ordtlid, loanid, loandtlid, mon_premium_prev, mon_interest_prev, premium_pay, interest_pay) " + "values('"+ordtlid+"', '"+arrayTemp.get(1)+"', '"+arrayTemp.get(2)+"', '"+arrayTemp.get(3)+"', '"+arrayTemp.get(4)+"', '"+arrayTemp.get(5)+"', '"+arrayTemp.get(6)+"')"; stmt.addBatch(query3); //paramDB.accessLoopDatabase(query3); query3= "update loan_dtl set mon_premium_bal=mon_premium_bal-"+arrayTemp.get(5)+", mon_interest_bal=mon_interest_bal-"+arrayTemp.get(6)+ " where loandtlid="+arrayTemp.get(2); System.out.println("in eminsert"+ordtlid+" "+arrayTemp.get(1)+" "+arrayTemp.get(2)+" "+arrayTemp.get(3)+" "+arrayTemp.get(4)+" "+arrayTemp.get(5)+" "+arrayTemp.get(6)); stmt.addBatch(query3); //paramDB2.accessLoopDatabase(query3); query3= "update loan_hdr set balance=balance-"+arrayTemp.get(5)+"-"+arrayTemp.get(6)+ " where loanid="+arrayTemp.get(1); stmt.addBatch(query3); //paramDB.accessLoopDatabase(query3); stmt.executeBatch(); } } }
82e62d86-7afe-4a4b-ba9d-1ae24c7a7084
7
public void actionPerformed(ActionEvent e) { System.out.println(e.getActionCommand() + " pressed."); if (e.getActionCommand() == "BOXSELECT") { boxSelect(); } else if (e.getActionCommand() == "BRUSH") { brush(); } else if (e.getActionCommand() == "ERASER") { eraser(); } else if (e.getActionCommand() == "LINE") { line(); } else if (e.getActionCommand() == "RECT") { rect(); } else if (e.getActionCommand() == "ELLIPSE") { ellipse(); } else if (e.getActionCommand() == "BUCKET") { bucket(); } }
e607c466-3700-4e37-8167-7be4c6bb2c58
0
public void addChangeListener(ChangeListener listener) { changeListeners.add(listener); }
0c9bf9a8-7fac-483a-beef-3106c034695f
9
public int ladderLength(String beginWord, String endWord, Set<String> wordList) { Set<String> beginSet = new HashSet<String>(); Set<String> endSet = new HashSet<String>(); int len = 1; HashSet<String> visited = new HashSet<String>(); beginSet.add(beginWord); endSet.add(endWord); while (!beginSet.isEmpty() && !endSet.isEmpty()) { if (beginSet.size() > endSet.size()) { Set<String> set = beginSet; beginSet = endSet; endSet = set; } Set<String> temp = new HashSet<String>(); // loop all the words in beginSet and find possible mutations for (String word : beginSet) { char[] chars = word.toCharArray(); // mutate each character for (int i = 0; i < chars.length; i++) { // mutate the character from a to z for (char c = 'a'; c <= 'z'; c++) { char original = chars[i]; // we need to change back to original chars[i] = c; String target = String.valueOf(chars); if (endSet.contains(target)) { return len + 1; } if (!visited.contains(target) && wordList.contains(target)) { temp.add(target); visited.add(target); } chars[i] = original; } } } beginSet = temp; len++; } return 0; }
0802b16b-c23c-4e7b-b456-f19a5f357043
6
private final int getHpFilter() { int[] hps = { 0, 1000, 5000, 10000, 20000, 50000, 100000, 150000, 200000, 250000, 300000, 350000, 400000, 450000, 500000, 600000, 700000, 800000, 900000, 1000000, 1200000, 1400000, 1600000, 1800000, 2000000, 2250000, 2500000, 2750000, 3000000, 3500000, 4000000, 4500000, 5000000, 6000000, 7000000, 8000000, 9000000, 10000000 }; if (hpMax < 1) return 0; if (hpMax < 1000) return 1; if (hpMin < 1) return 0; for (int j = 1; j < hps.length; j++) { if (hps[j - 1] > hpMin && hps[j] < hpMax) { return j; } } return 0; }
7cae7b68-f185-4c84-88ac-401caf7a0c79
8
protected void paintButtonPressed(Graphics g, AbstractButton b) { boolean divider = b.getName() == null ? false : b.getName().equals("dividerButton"); if(divider) { return; } int lenText = b.getFontMetrics(b.getFont()).stringWidth(b.getText() == null ? "" : b.getText()); int startText = (b.getWidth() - lenText) / 2; int endText = startText + lenText; int heightText = b.getFontMetrics(b.getFont()).getHeight(); int topText = (b.getHeight() - heightText) / 2; int bottomText = topText + heightText; int j = 0; int rim = 2; for(int i = rim; i < b.getWidth() - rim - 1; i++) { if(i % 2 == 0) { g.setColor(new Color(255, 255, 255)); j = i < b.getWidth() / 2 ? j + 1 : j - 1; } else { g.setColor(new Color(55, 25, 163)); } if(i < startText - 1 || i > endText + 1) { g.drawLine(i, rim, i, b.getHeight() - rim - 1); } else { g.drawLine(i, rim, i, topText - 1); g.drawLine(i, bottomText + 1, i, b.getHeight() - rim - 1); } } }
e6dbda70-67e9-426c-a2f4-7055bac7e162
5
public boolean move(){ int x =getPlayerposX(); int y=getPlayerposY(); boolean hite = false; System.out.println(x); if (x<=x+1&&x>=x-1&&x==x){ System.out.println("estoy aqui dentro de los margenes"); if(y>=y+1&&y>=y-1){ System.out.println("estoy aqui dentro de los margenes"); hite=true; } }else { hite=false; } return hite; }
1baae296-aa26-4303-af8a-54827abb2ccc
8
static boolean isCongruent(Class<?>[] params, Object[] args){ boolean ret = false; if(args == null) return params.length == 0; if(params.length == args.length){ ret = true; for(int i = 0; ret && i < params.length; i++){ Object arg = args[i]; Class<?> argType = (arg == null) ? null : arg.getClass(); Class<?> paramType = params[i]; ret = paramArgTypeMatch(paramType, argType); } } return ret; }
3f2ca5ff-634d-4051-947b-fe32cfa4090b
5
private void mc(int itr) { List<P> wybrane = new ArrayList<P>(); Random r = new Random(); P wybrane_n = new P(); for (int i = 0; i < this.tabSizeX; i++) { for (int j = 0; j < this.tabSizeY; j++) { //if ( this.naGranicy(i, j) ) continue; // nie biez pod uwage gotowych ziaren wybrane.clear(); int E = this.countEnergy(i,j); int E_new = -1; do { do { wybrane_n = kolory.get(r.nextInt(kolory.size())); } while(wybrane.contains(wybrane_n)); wybrane.add(wybrane_n); this.P[i][j].recolor(wybrane_n); E_new = this.countEnergy(i,j); } while (E_new>E && wybrane.size()<kolory.size()); }//j }//i //System.out.println("psr = "+psr+"; p_all="+p_all+" ("+p+"); p_krytyczne = "+p_krytyczne); }//---------------------------
4ead9cea-cfb1-4140-9565-d390fa02dce6
7
public static void recv(String provider, String server, String user, String password) { Store store = null; Folder folder = null; try { // -- Get hold of the default session -- Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props, null); // -- Get hold of a POP3 message store, and connect to it -- store = session.getStore(provider); store.connect(server, user, password); // -- Try to get hold of the default folder -- folder = store.getDefaultFolder(); if (folder == null) { throw new Exception("No default folder"); } // -- ...and its INBOX -- folder = folder.getFolder("INBOX"); if (folder == null) { throw new Exception("No POP3 INBOX"); } // -- Open the folder for read only -- folder.open(Folder.READ_ONLY); // -- Get the message wrappers and process them -- Message[] msgs = folder.getMessages(); for (int msgNum = 0; msgNum < msgs.length; msgNum++) { printMessage(msgs[msgNum]); } } catch (Exception ex) { ex.printStackTrace(); } finally { // -- Close down nicely -- try { if (folder != null) { folder.close(false); } if (store != null) { store.close(); } } catch (Exception ex2) { ex2.printStackTrace(); } } }
4e6ef4d3-d49c-4abe-869d-ac91477585db
7
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(InstallmentTermGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(InstallmentTermGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(InstallmentTermGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(InstallmentTermGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { new InstallmentTermGUI().setVisible(true); } catch (ParseException ex) { Logger.getLogger(InstallmentTermGUI.class.getName()).log(Level.SEVERE, null, ex); } } }); }
07429e7a-2583-46e3-863c-3090787f63a7
5
public double[][] cholesky(double[][] matriz) { double temp[][] = new double[linhas][colunas]; for (int i = 0; i < linhas; i++) { for (int j = 0; j <= i; j++) { double soma = 0.0; for (int k = 0; k < j; k++) { soma += temp[i][k] * temp[j][k]; } if (i == j) temp[i][i] = Math.sqrt(matriz[i][i] - soma); else temp[i][j] = 1.0 / temp[j][j] * (matriz[i][j] - soma); } if (temp[i][i] <= 0) { System.err.println("Diagonal Principal não é positiva"); } } return temp; }
cafd508c-fe48-4e93-badf-fc34858fead9
0
public static void send(String message){ }
365dd69d-c138-4ee3-9604-eac312d26988
6
public static void main(String[] args) { IMamifer mamifer1 = new AnimalSalbatic("leu", false, 5); IMamifer mamifer2 = new AnimalDomestic("vaca", true, "Andrei"); Animale animal1 = new AnimalSalbatic("zebra", false, 0); AnimalSalbatic salbatic = new AnimalSalbatic("hiena", false, 2); AnimalDomestic domestic = new AnimalDomestic("caine", true, "Andreea"); try { mamifer1.Mamifer(); } catch (MamiferException e) { e.printStackTrace(); } try { mamifer1.info(); } catch (MamiferException e) { e.printStackTrace(); } System.out.println(salbatic.getDenumire() + " este un animal domestic?\n" + (salbatic.EDomestic("hiena") ? "Yes!" : "No!")); System.out.println(domestic.getDenumire() + " este un animal domestic?\n" + (domestic.EDomestic("caine") ? "Yes!" : "No!")); try { animal1.Mamifer(); } catch (MamiferException e) { e.printStackTrace(); } try { animal1.info(); } catch (MamiferException e) { e.printStackTrace(); } }
92aa8db8-5332-4c45-9060-57b68c2ddd0b
2
public void add_bits (int bitstring, int length) { int bitmask = 1 << (length - 1); do if (((crc & 0x8000) == 0) ^ ((bitstring & bitmask) == 0 )) { crc <<= 1; crc ^= polynomial; } else crc <<= 1; while ((bitmask >>>= 1) != 0); }
1517c34c-ddd3-458f-af63-22ebed956fe3
1
private int lengthOfCurrentString() { int i = 0; while (bytes[streamPosition + i] != 0) { i++; } return i; }
646a4753-0927-4ea9-9b7b-f7d2a678ff8d
5
public void updateGroup(Group f) { if (groups == null) { updateGroups(); } //save changes to db MongoHelper.save(f, MongoHelper.GROUP_COLLECTION); if (!user.getGroups().contains(f.getId())) { //user doesn't have the group yet user.addGroup(f.getId()); //brand new group, just store it in our map and save it groups.put(f.getName(), f); groupIdNameMap.put(f.getId(), f.getName()); //add to our name list groupNames = groups.keySet().toArray(new String[0]); if (groupNames.length > 1) { Arrays.sort(groupNames); } //save user to DB MongoHelper.save(user, MongoHelper.USER_COLLECTION); } //update local group else if (f.getName().equals(groupIdNameMap.get(f.getId()))) { //no name change groups.put(f.getName(), f); } else { //update with new name //remove old maping groups.remove(groupIdNameMap.get(f.getId())); //put in new maping groups.put(f.getName(), f); groupIdNameMap.put(f.getId(), f.getName()); groupNames = groups.keySet().toArray(new String[0]); if (groupNames.length > 1) { Arrays.sort(groupNames); } } }
6d7f2bc7-bf79-44c3-9340-2e3d5ac6c9ec
7
public boolean mouseDrag (Event event, int x, int y) { boolean firstDrag = false; if (!dragged) { if (x > dragStart.x+dragThreshhold || x < dragStart.x-dragThreshhold || y > dragStart.y+dragThreshhold || y < dragStart.y-dragThreshhold) { dragged = true; firstDrag = true; } } if (!dragged) return true; if (selectingFlag) { rubberBand.move (getGraphics(), x, y); } else return super.mouseDrag (event, x, y); return true; }
8d3427a1-357f-42e1-9d31-169b6f0ad8b1
7
public N getCeilingNode(T payload) { N p = m_root; while (p != null) { int cmp = compare(payload, p.getPayload()); if (cmp < 0) { if (p.getLeft() != null) p = p.getLeft(); else return p; } else if (cmp > 0) { if (p.getRight() != null) { p = p.getRight(); } else { N parent = p.getParent(); N ch = p; while (parent != null && ch == parent.getRight()) { ch = parent; parent = parent.getParent(); } return parent; } } else return p; } return null; }
30448abd-0147-4248-80f2-ef3579e56beb
5
private JMenu getBoardsMenu() { //add List of Boards final JMenu boards = new JMenu("Board(s)"); //clicking the new board button brings up the new board dialog JMenuItem newBoardButton = new JMenuItem("New Board"); boards.add(newBoardButton); newBoardButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { client.getClientGUI().newBoardDialog(); } }); boards.addSeparator(); //List of Boards String[] listBoards = {}; try { listBoards = client.getBoards(); } catch (Exception e) { e.printStackTrace(); } //when a board is clicked, the client should switch the current board to that board for (final String board: listBoards) { JMenuItem boardChoice = new JMenuItem(board); boardChoice.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { canvas.switchBoard(board); } }); boards.add(boardChoice); } boards.addMenuListener(new MenuListener() { @Override public void menuCanceled(MenuEvent arg0) { } @Override public void menuDeselected(MenuEvent arg0) { } @Override public void menuSelected(MenuEvent arg0) { //refresh the boards list whenever the boards list is clicked for (int i=boards.getItemCount()-1; i>1; i--) { boards.remove(i); } try { for (final String board: client.getBoards()) { JMenuItem boardChoice = new JMenuItem(board); boardChoice.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { canvas.switchBoard(board); } }); boards.add(boardChoice); } } catch (Exception e) { e.printStackTrace(); } } }); return boards; }
72765058-89b1-431e-9346-35e1e1e365aa
6
private void recursiveDelete(File file) { if (file == null || !file.exists()) { return; } if (file.isDirectory()) { File[] files = file.listFiles(); if (files == null || files.length == 0) { return; } for (File f : files) { recursiveDelete(f); } } file.delete(); }
0263c411-c128-4cd9-bcd9-586cff087fce
8
public void checks() { if (Mouse.isButtonDown(0)) { Vector3D vector = new Vector3D(0, 0, 0); vector.y = ((float) -Math.sin(Math.toRadians(camera.pitch))); float v = (float) Math.cos(Math.toRadians(camera.pitch)); vector.x = ((float) (Math.sin(Math.toRadians(camera.yaw)) * -v)); vector.z = ((float) (Math.cos(Math.toRadians(camera.yaw)) * v)); BlockIterator iter = new BlockIterator(vector, new Vector3D(camera.position), 0, 20); Block block = iter.next(); ChunkManager.setBlockAt(block.x, block.y, block.z); } if (Keyboard.isKeyDown(Keyboard.KEY_W)) { camera.walkForward(movementSpeed * movementmultiplayer); } if (Keyboard.isKeyDown(Keyboard.KEY_S)) { camera.walkBackwards(movementSpeed * movementmultiplayer); } if (Keyboard.isKeyDown(Keyboard.KEY_A)) { camera.strafeLeft(movementSpeed * movementmultiplayer); } if (Keyboard.isKeyDown(Keyboard.KEY_D)) { camera.strafeRight(movementSpeed * movementmultiplayer); } if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) { camera.walkUp(movementSpeed * movementmultiplayer); } if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) { camera.walkDown(movementSpeed * movementmultiplayer); } if (Keyboard.isKeyDown(Keyboard.KEY_Q)) { println(ChunkManager.blockcount()); } }