text
stringlengths
14
410k
label
int32
0
9
public static void oldVisualizer(String file_name) { int days = 4; //days in the data int frame_width = 800; int frame_height = 480; JFrame frame=new JFrame("CS 498 Data"); frame.setSize(frame_width,frame_height); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JCanvas canvas=new JCanvas(); frame.add(canvas); frame.setVisible(true); int vx=2,vy=2,x=0,y=50,d=10; int vMin = 4, dMin = 0; int row = 1; int rows_in_days = 15*24; // To Store data for trailing edges (old movements) int [][] data1 = new int[800][480]; int [][] data2 = new int[800][480]; int [][] data3 = new int[800][480]; int [][] data4 = new int[800][480]; // To Record which x, and which y, values have been visited ArrayList<Integer> data1_x = new ArrayList<Integer>(); ArrayList<Integer> data1_y = new ArrayList<Integer>(); ArrayList<Integer> data2_x = new ArrayList<Integer>(); ArrayList<Integer> data2_y = new ArrayList<Integer>(); ArrayList<Integer> data3_x = new ArrayList<Integer>(); ArrayList<Integer> data3_y = new ArrayList<Integer>(); ArrayList<Integer> data4_x = new ArrayList<Integer>(); ArrayList<Integer> data4_y = new ArrayList<Integer>(); for (int h = 0; h < 800; h++) { for (int w = 0; w < 480; w++) { data1[h][w] = 0; data2[h][w] = 0; data3[h][w] = 0; data4[h][w] = 0; } } try { //Create a workbook object from <span id="IL_AD5" class="IL_AD">the file</span> at specified location. //Change the path of the file as per the location on your computer. //FileInputStream file = new FileInputStream(new File("M0110.xlsx")); //Get the workbook instance for XLS file //HSSFWorkbook workbook = new HSSFWorkbook(file); //Get first sheet from the workbook //HSSFSheet sheet = workbook.getSheetAt(0); Workbook wrk1 = Workbook.getWorkbook(new File(file_name)); // Workbook wrk1 = Workbook.getWorkbook(new File("movement_data.xls")); //Obtain the reference to the first sheet in the workbook Sheet sheet1 = wrk1.getSheet(0); while(dMin < 60*24){ canvas.startBuffer(); canvas.clear(); //canvas.setBackground(Color.black); canvas.setPaint(Color.green); /** DAY 1 **/ //Obtain reference to the Cell using getCell(int col, int row) method of sheet Cell x_cell = sheet1.getCell(1, row); Cell y_cell = sheet1.getCell(2, row); //Read the contents of the Cell using getContents() method, which will return //it as a String String x_string = x_cell.getContents(); String y_string = y_cell.getContents(); Double x_double = Double.parseDouble(x_string) - 317900; Double y_double = Double.parseDouble(y_string) - 4367500; int x_int = x_double.intValue(); int y_int = y_double.intValue(); data1[y_int][x_int]++; data1_y.add(y_int); data1_x.add(x_int); int y_item; int x_item; for (int i = 0; i < data1_y.size(); i++) { y_item = data1_y.get(i); x_item = data1_x.get(i); Color test = new Color(0, 255, 255, 50); canvas.setPaint(test); canvas.fillOval(x_item, y_item,d,d); } canvas.setPaint(Color.green); canvas.fillOval(x_int, y_int,d,d); /** DAY 2 **/ //Obtain reference to the Cell using getCell(int col, int row) method of sheet Cell x_cell2 = sheet1.getCell(1, row+rows_in_days); Cell y_cell2 = sheet1.getCell(2, row+rows_in_days); //Read the contents of the Cell using getContents() method, which will return //it as a String String x_string2 = x_cell2.getContents(); String y_string2 = y_cell2.getContents(); Double x_double2 = Double.parseDouble(x_string2) - 317900; Double y_double2 = Double.parseDouble(y_string2) - 4367500; int x_int2 = x_double2.intValue()+200; int y_int2 = y_double2.intValue(); data2[y_int2][x_int2-200]++; data2_y.add(y_int2); data2_x.add(x_int2-200); for (int i = 0; i < data2_y.size(); i++) { y_item = data2_y.get(i); x_item = data2_x.get(i)+200; Color test = new Color(0, 255, 255, 50); canvas.setPaint(test); canvas.fillOval(x_item, y_item,d,d); } canvas.setPaint(Color.green); canvas.fillOval(x_int2, y_int2,d,d); /** DAY 3 **/ //Obtain reference to the Cell using getCell(int col, int row) method of sheet Cell x_cell3 = sheet1.getCell(1, row+(rows_in_days*2)); Cell y_cell3 = sheet1.getCell(2, row+(rows_in_days*2)); //Read the contents of the Cell using getContents() method, which will return //it as a String String x_string3 = x_cell3.getContents(); String y_string3 = y_cell3.getContents(); Double x_double3 = Double.parseDouble(x_string3) - 317900; Double y_double3 = Double.parseDouble(y_string3) - 4367500; int x_int3 = x_double3.intValue()+400; int y_int3 = y_double3.intValue(); data3[y_int3][x_int3-400]++; data3_y.add(y_int3); data3_x.add(x_int3-400); for (int i = 0; i < data3_y.size(); i++) { y_item = data3_y.get(i); x_item = data3_x.get(i)+400; Color test = new Color(0, 255, 255, 50); canvas.setPaint(test); canvas.fillOval(x_item, y_item,d,d); } canvas.setPaint(Color.green); canvas.fillOval(x_int3, y_int3,d,d); /** DAY 4 **/ //Obtain reference to the Cell using getCell(int col, int row) method of sheet Cell x_cell4 = sheet1.getCell(1, row+(rows_in_days*3)); Cell y_cell4 = sheet1.getCell(2, row+(rows_in_days*3)); //Read the contents of the Cell using getContents() method, which will return //it as a String String x_string4 = x_cell4.getContents(); String y_string4 = y_cell4.getContents(); Double x_double4 = Double.parseDouble(x_string4) - 317900; Double y_double4 = Double.parseDouble(y_string4) - 4367500; int x_int4 = x_double4.intValue()+600; int y_int4 = y_double4.intValue(); data4[y_int4][x_int4-600]++; data4_y.add(y_int4); data4_x.add(x_int4-600); for (int i = 0; i < data4_y.size(); i++) { y_item = data4_y.get(i); x_item = data4_x.get(i) + 600; Color test = new Color(0, 255, 255, 50); canvas.setPaint(test); canvas.fillOval(x_item, y_item,d,d); } canvas.setPaint(Color.green); canvas.fillOval(x_int4, y_int4,d,d); canvas.setPaint(Color.red); canvas.drawString("Day 1", 85, 420); canvas.drawString("Day 2", 285, 420); canvas.drawString("Day 3", 485, 420); canvas.drawString("Day 4", 685, 420); canvas.setPaint(Color.black); canvas.drawLine(200, 0, 200, 430); canvas.drawLine(400, 0, 400, 430); canvas.drawLine(600, 0, 600, 430); canvas.drawLine(0, 400, 800, 400); canvas.drawLine(0, 430, 800, 430); dMin += vMin; canvas.drawString("Time: " + (dMin/60)%24 + ":" + dMin%60, 360, 450); row++; canvas.endBuffer(); canvas.sleep(50); } } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
9
public ListNode swapPairs2(ListNode head) { if (head == null || head.next == null) return head; ListNode pre = null; ListNode ppre = null; ListNode p = head; boolean change = true; while (p.next != null) { ppre = pre; pre = p; p = p.next; if (change) { if (pre == head) { head = p; } else { ppre.next = p; } pre.next = p.next; p.next = pre; p = pre; change = false; } else { change = true; } } return head; }
5
private void dijkstra(int source, int[] dist, HashMap<Integer, HashMap<Integer, Integer>> g){ dist[source]=0; PriorityQueue<NodeWithDist> q = new PriorityQueue<NodeWithDist>(); q.add(new NodeWithDist(source, dist[source])); while(!q.isEmpty()){ int node = q.poll().node; for(int neighbor:g.get(node).keySet()){ if(dist[node] + g.get(node).get(neighbor) < dist[neighbor]){ dist[neighbor] = dist[node] + g.get(node).get(neighbor); q.add(new NodeWithDist(neighbor, dist[neighbor])); } } } }
3
private void addTable() { tableModel = new DefaultTableModel(new String[] { "id", "czas domyslny", "domyslne punkty", "nazwa" }, 0); table = new JTable(tableModel); table.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1) { JTable target = (JTable) e.getSource(); rowNum = target.getSelectedRow(); colNum = target.getSelectedColumn(); } } }); contentPane.setLayout(new BorderLayout()); table.setBounds(400, 22, 0, 0); tablePanel = new JPanel(new BorderLayout()); tablePanel.add(table.getTableHeader(), BorderLayout.NORTH); tablePanel.add(table, BorderLayout.CENTER); scrollPanel = new JScrollPane(tablePanel); contentPane.add(scrollPanel); }
1
public Character getPlayerCharacter(String info) { String[] parsedInstructions = info.split(" "); if(parsedInstructions[0].compareTo("Player") != 0) { System.out.println("Error: Incorrect Player Character creation syntax"); return null; } Character c; if(parsedInstructions.length == 3) { //c = new Player(parsedInstructions[1], 20, 10, 10, 10, 10); //parse the instructions switch(parsedInstructions[2]) { case "Rogue": subFactory = new RogueFactory(); c = subFactory.getCharacter(parsedInstructions[2]); break; case "Mage": subFactory = new MageFactory(); c = subFactory.getCharacter(parsedInstructions[2]); break; case "Cleric": subFactory = new ClericFactory(); c = subFactory.getCharacter(parsedInstructions[2]); break; case "Warrior": subFactory = new WarriorFactory(); c = subFactory.getCharacter(parsedInstructions[2]); break; default: c = new NullPlayer(parsedInstructions[2]); } } else { System.out.println("Error: Incorrect number of arguments"); return new NullPlayer("Null Character"); } return c; }
6
private static void loadOrganizationFromFile() { // get filename from user. System.out.print("\nEnter the filename used (q to exit): "); String filename = user_input.nextLine(); File file = new File(filename); String[] path = filename.split("/"); String orgName = path[path.length - 1]; // get name of file, not path BufferedReader reader = null; // cancel if organization name is invalid. if (orgName.equals("q") || orgName.equals("l")) { System.out.println("Organization name cannot be q or l"); return; } try { reader = new BufferedReader(new FileReader(file)); System.out.println("File found."); // create new organization with name. Organization org = new Organization(orgName); // if the organization does not already exist if (db.queryByExample(org).hasNext() == false) { System.out.println("Creating organization: " + orgName); // each line has a new person // e.g. // person@website.com;team,team,team,team String person; while ((person = reader.readLine()) != null) { String[] info = person.split(";"); String email = info[0]; String teamsUnsplit = info[1]; String[] teams = teamsUnsplit.split(","); // add member to specified teams for (String teamName : teams) { org.addMemberToTeam(email, teamName, true); } } saveDatabase(org); System.out.println("\n" + org); } else { System.out.println("The organization already exists. Halting."); } } catch (FileNotFoundException e) { System.out.println("File not found."); } catch (IOException e) { System.err.println("There was an error reading the file."); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { // it's fine. } } }
9
public double[][] LUDecomposition(double[][] matrix) { int n = matrix.length; // Luodaan ja alustetaan matriisit L ja U. double[][] matrixL = new double[n][n]; double[][] matrixU = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrixL[i][j] = 0; matrixU[i][j] = 0; if (i == j) { matrixL[i][j] = 1; } } } // Lasketaan hajotelma L- ja U-matriiseihin syötematriisin avulla. for (int k = 0; k < n; k++) { Double luku = Double.valueOf(matrix[k][k]); matrixU[k][k] = Double.valueOf(luku); for (int i = k + 1; i < n; i++) { matrixL[k][i] = matrix[k][i] / matrixU[k][k]; Double luku2 = Double.valueOf(matrix[i][k]); matrixU[i][k] = Double.valueOf(luku2); } for (int i = k + 1; i < n; i++) { for (int j = k + 1; j < n; j++) { matrix[j][i] = matrix[j][i] - matrixL[k][i] * matrixU[j][k]; } } } // Palautetaan hajotelman algoritmin tuottama U-matriisi. return matrixU; }
7
public void generateImage() { int image_width, image_height; try { //Get the dimensions of the screen in order to determine how large to render the image Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //Define the width and height of the image image_width = (int) (screenSize.getWidth() / 3); image_height = (int) (screenSize.getHeight() / 3); } catch (Exception e) { //If there was an error getting the screen size, set default width and height values image_width = 1920; image_height = 1080; } /* For reasons as yet unknown, the Java PNG reader freaks out when it tries to read PNG files whose dimensions are not divisible by 4. Thus, add a few pixels to the width and height if necessary to enforce divisibility by 4. */ if (image_width % 4 != 0) { image_width += 4 - image_width % 4; } if (image_height % 4 != 0) { image_height += 4 - image_height; } //Call the C-Backend to render the image and save it to a file ProcessBuilder processBuilder = new ProcessBuilder(new String[]{ "C-Genetics/aesthetics", "-save", "-p", "100000", "-s", "" + image_width, "" + image_height, IMAGE_PATH + id, x.toString(), y.toString(), z.toString(), r.toString(), g.toString(), b.toString()}); try { Process p = processBuilder.start(); p.waitFor(); p.destroy(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { } }
5
public synchronized void deleteWay(int pos, long wayId){ if (poligons.size()>pos) ways.get(pos).remove(wayId); }
1
private void resetAll() { clear(); try { System.out.println("CAUTION!"); System.out.println("If continuing with resetting, all groups and matches will be deleted!"); System.out.println("Do you want to continue? Y/N"); Scanner sc = new Scanner(System.in, "iso-8859-1"); String further = sc.nextLine(); switch (further) { case "Y": teammgr.resetAll(); break; case "y": teammgr.resetAll(); break; case "N": System.out.println("You have selected no."); break; case "n": System.out.println("You have selected no."); break; default: System.out.println("Y or N Required"); break; } } catch (Exception e) { System.out.println("ERROR - " + e.getMessage()); } pause(); }
5
public static boolean inGrid(int x, int y) { return x >= xOff && y >= yOff && x < fieldWidth + xOff && y < fieldHeight + yOff; }
3
static public double incompleteGammaComplement(double a, double x) throws ArithmeticException { double ans, ax, c, yc, r, t, y, z; double pk, pkm1, pkm2, qk, qkm1, qkm2; if (x <= 0 || a <= 0) { return 1.0; } if (x < 1.0 || x < a) { return 1.0 - incompleteGamma(a, x); } ax = a * Math.log(x) - x - logGamma(a); if (ax < -MAXLOG) { return 0.0; } ax = Math.exp(ax); /* continued fraction */ y = 1.0 - a; z = x + y + 1.0; c = 0.0; pkm2 = 1.0; qkm2 = x; pkm1 = x + 1.0; qkm1 = z * x; ans = pkm1 / qkm1; do { c += 1.0; y += 1.0; z += 2.0; yc = y * c; pk = pkm1 * z - pkm2 * yc; qk = qkm1 * z - qkm2 * yc; if (qk != 0) { r = pk / qk; t = Math.abs((ans - r) / r); ans = r; } else { t = 1.0; } pkm2 = pkm1; pkm1 = pk; qkm2 = qkm1; qkm1 = qk; if (Math.abs(pk) > big) { pkm2 *= biginv; pkm1 *= biginv; qkm2 *= biginv; qkm1 *= biginv; } } while (t > MACHEP); return ans * ax; }
8
public int getFloorValue(int[] arr, int start, int end, int number) { // base case if (start > end) { return -1; } // if number less than start, no number found if (number < arr[start]) { return -1; } // if number is greater than end index number ,return last number if (number >= arr[end]) { return end; } // get mid value int mid = (start + end) / 2; // if mid is same as number, return mid if (arr[mid] == number) { return mid; // if number is less than mid number } else if (arr[mid] > number) { // if number is between mid and mid-1 numbers ,return mid-1 if (mid - 1 >= start && arr[mid - 1] < number) { return mid - 1; // else search first part } else { return getFloorValue(arr, start, mid - 1, number); } // if number is greater than mid number } else { // if number is between mid and mid+1 numbers , return mid if (mid + 1 <= end && arr[mid + 1] > number) { return mid; // search second part } else { return getFloorValue(arr, mid + 1, end, number); } } }
9
private boolean jj_scan_token(int kind) { if (jj_scanpos == jj_lastpos) { jj_la--; if (jj_scanpos.next == null) { jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); } else { jj_lastpos = jj_scanpos = jj_scanpos.next; } } else { jj_scanpos = jj_scanpos.next; } if (jj_rescan) { int i = 0; Token tok = token; while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } if (tok != null) jj_add_error_token(kind, i); } if (jj_scanpos.kind != kind) return true; if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; return false; }
9
public int stochRsiLookback( int optInTimePeriod, int optInFastK_Period, int optInFastD_Period, MAType optInFastD_MAType ) { int retValue; if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) ) optInTimePeriod = 14; else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) ) return -1; if( (int)optInFastK_Period == ( Integer.MIN_VALUE ) ) optInFastK_Period = 5; else if( ((int)optInFastK_Period < 1) || ((int)optInFastK_Period > 100000) ) return -1; if( (int)optInFastD_Period == ( Integer.MIN_VALUE ) ) optInFastD_Period = 3; else if( ((int)optInFastD_Period < 1) || ((int)optInFastD_Period > 100000) ) return -1; retValue = rsiLookback ( optInTimePeriod ) + stochFLookback ( optInFastK_Period, optInFastD_Period, optInFastD_MAType ); return retValue; }
9
@Override protected DataOut doInBackground() throws Exception { return runTest(); }
0
@Override public Success<Expression> parse(String s, int p) { Success<Expression> resBase = AtomParser.singleton.parse(s, p); if (resBase == null) return null; Expression exp = resBase.value; p = resBase.rem; p = optWS(s, p); // Parse any invocations. Success<GenericsAndArgumentsParser.GenericsAndArgs> resGenericsAndArgs; for (;;) { resGenericsAndArgs = GenericsAndArgumentsParser.singleton.parse(s, p); if (resGenericsAndArgs == null) break; GenericsAndArgumentsParser.GenericsAndArgs val = resGenericsAndArgs.value; exp = new Invocation(exp, val.genericArgs, val.arguments); p = resGenericsAndArgs.rem; p = optWS(s, p); } // Parse any selectors attached to this base expression. for (;;) { // Parse the '.'. if (s.charAt(p) != '.') break; p = optWS(s, p + 1); // Parse the member name. Success<String> resMember = IdentifierOrOpParser.singleton.parse(s, p); if (resMember == null) throw new NiftyException("Expecting member name after '.'."); exp = new MemberAccess(exp, resMember.value); p = resMember.rem; p = optWS(s, p); // Parse any invocations. for (;;) { resGenericsAndArgs = GenericsAndArgumentsParser.singleton.parse(s, p); if (resGenericsAndArgs == null) break; GenericsAndArgumentsParser.GenericsAndArgs val = resGenericsAndArgs.value; exp = new Invocation(exp, val.genericArgs, val.arguments); p = resGenericsAndArgs.rem; p = optWS(s, p); } } return new Success<Expression>(exp, p); }
8
@Override public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("Save")) { Contact contact = createContact(); if (!contact.getFirstName().equals("")){ this.contacts.add(contact); this.gui.clearFields(); } else { JOptionPane.showMessageDialog(null, "All contacts must have a first name. Please try again", "Missing first name" ,JOptionPane.ERROR_MESSAGE ); } } else if (command.equals("Save as")) { int returnState = fc.showSaveDialog(null); if (returnState == JFileChooser.APPROVE_OPTION) { this.contactWriter.setFile(fc.getSelectedFile()); try { this.contactWriter.writeContacts(contacts); } catch (IOException e1) { JOptionPane.showMessageDialog(null, "An error occured while saving. Please try again", "File not found" ,JOptionPane.ERROR_MESSAGE); } } } }
5
private boolean transmitPacket(byte[] buf, int j) { int i = 0; boolean packet_sent = false; DatagramPacket ack_dtg = new DatagramPacket(new byte[1024], 1024); while (i < 3 || packet_sent) { DATAPacket data_packet = new DATAPacket(buf, this.getIp(), this.getPort_dest(), j); try { System.out.println("DATA :" + Arrays.toString(data_packet.getData())); this.getSocket().send(data_packet.getDtg()); this.getSocket().receive(ack_dtg); //Test if the answer is correct if (ACKPacket.isACKPacket(ack_dtg) && j == ACKPacket.getBlockNb(ack_dtg)) { System.out.println("ACK :" + Arrays.toString(ack_dtg.getData())); packet_sent = true; fireProccessingSend((int) (((float) j / (file.length() / 512)) * 100)); return true; } } catch (IOException ex) { System.out.println("Echec transfert du paquet"); fireErrorOccured("Echec transfert du paquet"); } i++; } return packet_sent; }
5
public void registerEffect(MapleStatEffect effect, long starttime, ScheduledFuture<?> schedule) { if (effect.isHide()) { this.hidden = true; getClient().getSession().write(MaplePacketCreator.sendGMOperation(16, 1)); getMap().broadcastMessage(this, MaplePacketCreator.removePlayerFromMap(getId()), false); } else if (effect.isDragonBlood()) { prepareDragonBlood(effect); } else if (effect.isBerserk()) { checkBerserk(); } else if (effect.isBeholder()) { prepareBeholderEffect(); } for (Pair<MapleBuffStat, Integer> statup : effect.getStatups()) { effects.put(statup.getLeft(), new MapleBuffStatValueHolder(effect, starttime, schedule, statup.getRight())); } stats.recalcLocalStats(); }
6
private void jBtGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtGravarActionPerformed if (jTextFieldCdForma.getText().equals("")) { JOptionPane.showMessageDialog(null, "A forma de pagamento é obrigatória!"); jTextFieldCdForma.grabFocus(); } else if (jTextFieldDescrição.getText().equals("")) { JOptionPane.showMessageDialog(null, "A descrição é obrigatória"); jTextFieldDescrição.grabFocus(); } else if (jTextFieldValor.getText().equals("") || valor < 1) { JOptionPane.showMessageDialog(null, "Informe o valor da conta!"); jTextFieldValor.setText(""); jTextFieldValor.grabFocus(); } else if (!rdata.dataValida(jFormattedTextFieldDataVencimento.getText())) { JOptionPane.showMessageDialog(null, "Informe uma data válida!"); jFormattedTextFieldDataVencimento.grabFocus(); } else { gravarConta(); if (rotina == Rotinas.incluir) { contas.incluir(contas, false); JOptionPane.showMessageDialog(null, "Conta gravada com sucesso!"); jTextFieldCdConta.setText(contas.getCdConta().toString()); // mostra as parcelas geradas ConsultaParcelas consulta = new ConsultaParcelas(); consulta.setModalExclusionType(Dialog.ModalExclusionType.APPLICATION_EXCLUDE); consulta.setVisible(true); consulta.exibirParcelas(); } else if (rotina == Rotinas.alterar) { if (jTextFieldCdConta.getText().equals("")) { JOptionPane.showMessageDialog(null, "É preciso informar o código da conta que deseja alterar!"); jTextFieldCdConta.grabFocus(); } else { try { contas.setCdConta(Integer.parseInt(jTextFieldCdConta.getText())); contas.alterar(contas); JOptionPane.showMessageDialog(null, "Conta alterada com sucesso!"); } catch (NumberFormatException ex) { } } } rotina = Rotinas.padrao; botoes.validaBotoes(jPanelBotoes, rotina); carregarUsuario(); } }//GEN-LAST:event_jBtGravarActionPerformed
9
public void testSwarm(File file){ System.out.println("shit"); swarm.setNumberOfParticles(numberOfParticles); System.out.println(haltingCriteria.size()); int counter = 0; for(int i = 0; i < haltingCriteria.size(); i++){ swarm.setHaltingCriteria(haltingCriteria.get(i)); System.out.println("halt"); counter++; for(int k = 0; k < velocityUpdate.size(); k++){ setVelocityUpdate(velocityUpdate.get(k)); System.out.println("vel"); counter++; for(int n = 0; n < neighbourhood.size(); n++){ System.out.println(n); swarm.setNeighbourhood(neighbourhood.get(n)); for(int m = 0; m < function.size(); m++){ Function f = function.get(m); Vector<Double> resultVector = swarm.optimise(f); System.out.println(resultVector.toString()); double result = f.CalculateFitness(resultVector); System.out.println(result); System.out.println(swarm.toString()); manager.writeTofile(swarm.toString(), file); System.out.println(resultVector.toString()); manager.writeTofile("result Vector :" + resultVector.toString(), file); System.out.println(result); manager.writeTofile("result :" + result, file); } } } } }
4
private boolean equals(byte[] a1, int offs1, byte[] a2, int offs2, int num) { while (num-- > 0) { if (a1[offs1++] != a2[offs2++]) { return false; } } return true; }
2
public void run(){ while(flag){ second++; if(second==60){ second= 0; minute++; } if(minute==60){ minute= 0; hour++; } if(hour==24){ hour= 0; } System.out.println(this); try{ Thread.sleep(1000); }catch(InterruptedException ex){ ex.printStackTrace(); } } }
5
public List<Bill> findBillsByHousehold(Household household) throws BillNotFoundException { Set<Bill> bills = household.getBills(); List<Bill> result = new ArrayList<Bill>(); if (bills.size() == 0) { throw new BillNotFoundException(household, "Bill"); } result.addAll(bills); Collections.sort(result); return result; }
1
public void init() { String colorstr = getParameter("pagecolor"); if (colorstr == null) colorstr = "ffffff"; this.pageColor = new Color(Integer.parseInt(colorstr, 16)); colorstr = getParameter("bgcolor"); if (colorstr != null) setBackground(new Color(Integer.parseInt(colorstr, 16))); String cp = getParameter("classpath"); if (cp != null) jodeWin.setClassPath(cp); String cls = getParameter("class"); if (cls != null) jodeWin.setClass(cls); }
4
private void randomFood() { FoodList listOfFood = null; try { ObjectInputStream listIn = new ObjectInputStream(new FileInputStream(new File("foodList.dat"))); listOfFood = (FoodList) listIn.readObject(); listIn.close(); } catch (FileNotFoundException e) { System.err.println("Food List Not Found."); } catch (IOException e) { System.err.println("File Corrupted."); } catch (ClassNotFoundException e) { System.err.println("Project Incomplete."); } //make random number int randomNumber = new Random().nextInt(numberOfChoices); if (listOfFood != null) { switch (randomNumber) { case 0: this.infoString = getRandomInfo(listOfFood.getSnacks()); this.type = "Snack"; break; case 1: this.infoString = getRandomInfo(listOfFood.getDrinks()); this.type = "Drink"; break; default: System.err.println("Check Random Number Generator Seed in Dispenser"); } } // for (String str : infoString) { // System.out.println(str); // } // }
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(HelpFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(HelpFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(HelpFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(HelpFrame.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 HelpFrame().setVisible(true); } }); }
6
private Vector<String> loadTableEntry(final SettingsData settingsData) { Vector<String> v = new Vector<String>(); v.add(settingsData.getModuleName()); AttributeGroup atg = settingsData.getAttributeGroup(); if(atg != null) { v.add(atg.getNameOrPidOrId()); } else { v.add(""); } Aspect asp = settingsData.getAspect(); if(asp != null) { v.add(asp.getNameOrPidOrId()); } else { v.add(""); } int simulationVariant = settingsData.getSimulationVariant(); if(simulationVariant == -1) { v.add(""); } else { v.add(String.valueOf(simulationVariant)); } List objects = settingsData.getObjects(); StringBuilder builder = new StringBuilder(objects.size() * 10); for(int i = 0, objectsSize = objects.size(); i < objectsSize; i++) { final Object object = objects.get(i); SystemObject systemObject = (SystemObject)object; builder.append(systemObject.getNameOrPidOrId()); builder.append("; "); if(builder.length() > 50 && objectsSize - i > 1) { builder.append("... (insgesamt "); builder.append(objectsSize); builder.append(" Objekte); "); break; //Der String wird nur zur Darstellung benutzt, es macht keinen Sinn, hier zigtausende Objekte einzufügen } } String result = ""; if(builder.length() > 1) { result = builder.substring(0, builder.length() - 2); } v.add(result); return v; }
7
public ArrayList<String> getTechTitles() { return TechTitles; }
0
public static ArrayList<String[]> cars() { String JDBC_DRIVER = "com.mysql.jdbc.Driver"; String DB_URL = "jdbc:mysql://localhost:1234/cars"; // Database credentials String USER = "root"; String PASS = "wps14042"; Set<String> data = new HashSet<String>(); ArrayList<String[]> data2 = new ArrayList<String[]>(); ResultSet rs = null; Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName(JDBC_DRIVER); //STEP 3: Open a connection conn = DriverManager.getConnection(DB_URL, USER, PASS); stmt = conn.createStatement(); String sql = ("SELECT Classification FROM cars"); rs = stmt.executeQuery(sql); while (rs.next()) { String send = rs.getString(1); for (int i = 0; i < 24; i++) { data.add(send.split("\\| 2")[0].toString()); } } }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try for (String dat : data) { data2.add(dat.replace(" ", "").split("\\|")); } return data2; }
9
public void setNumeroInt(TNumeroInt node) { if(this._numeroInt_ != null) { this._numeroInt_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._numeroInt_ = node; }
3
public List<ReportEntry> getReport(Long from, Long to) { if (from == null) { throw new IllegalArgumentException("report start date cannot be null"); } if (to == null) { throw new IllegalArgumentException("report end date cannot be null"); } if (to < from) { throw new IllegalArgumentException("Report end date must be after start date"); } ResultSet results = null; try { if (preparedStatement == null) { preparedStatement = connection.prepareStatement(REPORT_QUERY); } connection.setAutoCommit(false); preparedStatement.setLong(1, from); preparedStatement.setLong(2, to); results = preparedStatement.executeQuery(); long t1 = System.currentTimeMillis(); List<ReportEntry> reportEntries = new LinkedList<ReportEntry>(); while (results.next()) { ReportEntry reportEntry = new ReportEntry(); reportEntry.setEmployeeId(results.getLong(1)); reportEntry.setWorkingHours(results.getDouble(2)); reportEntries.add(reportEntry); } long t2 = System.currentTimeMillis(); long diff = t2 - t1; System.out.println("diff = " + diff); return reportEntries; } catch (SQLException e) { throw new RuntimeException(e); } finally { try { if (results != null) { results.close(); } } catch (SQLException ex) { ex.printStackTrace(); } } }
8
public static void stringInDetail(String s) { System.out.println(s + " length: " + s.length()); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); System.out.printf("i : %2d \u202B%c\u202B \u202B%4X\u202B \n", i, s.charAt(i), (int) c);// Character.getNumericValue(c) } }
1
private boolean validarCampos (){ boolean validos = true; if (jTextField3.getText().equals("")){ jTextField3.requestFocus(); msj_Error("Ingrese una Razon Social."); validos=false; } else{ if (!control_f .isFechaValida(campoFecha.getText())){ msj_Error("La Fecha de Apertura no es valida."); campoFecha.requestFocus(); validos=false; } else{ if (!control_f .isFechaValida(campoFecha1.getText())){ msj_Error("La Fecha de Cierre no es valida."); campoFecha1.requestFocus(); validos=false; } else{ if (control_f.menorFechas(campoFecha.getText(), campoFecha1.getText())==2){ msj_Error("La Fecha de Apertura es mayor a la de Cierre."); campoFecha.requestFocus(); validos=false; } else{ if (jTextField4.getText().equals("")){ msj_Error("Ingrese un Usuario Administrador."); jTextField4.requestFocus(); validos=false; } else{ this.vaciarMensaje(); } } } } } return validos; }
5
@Override public void addClientConnectEventListener(ConnectListener listener) { connectEventListenerList.add(ConnectListener.class, listener); }
0
protected void addDocumentEnd() { try { h.endDocument(); } catch (SAXException ex) { throw new RuntimeException(ex.toString()); } }
1
public static Aikaslotti haeAikaslottiIdlla(int id) throws NamingException, SQLException { Yhteys tietokanta = new Yhteys(); Connection yhteys = tietokanta.getYhteys(); String sql = "SELECT * FROM Aikaslotti WHERE id = ?"; PreparedStatement kysely = yhteys.prepareStatement(sql); kysely.setInt(1, id); ResultSet rs = kysely.executeQuery(); Aikaslotti a = null; if (rs.next()) { a = new Aikaslotti(rs); } try { rs.close(); } catch (Exception e) {} try { kysely.close(); } catch (Exception e) {} try { yhteys.close(); } catch (Exception e) {} return a; }
4
void printSprite() { //Get the current sprite path NodeList listOfMovesSprites = sprites_doc.getElementsByTagName("Move"); boolean sprite_found=false; for(int s=0; s<listOfMovesSprites.getLength() ; s++) { Node move_node = listOfMovesSprites.item(s); Element move_element = (Element)move_node; if(move_element.getAttribute("name").equals(list_moves.getSelectedValue())) { for(Node sprite=move_node.getFirstChild();sprite!=null;sprite=sprite.getNextSibling())//Sprite loop { if(sprite.getNodeName().equals("Sprite")) { String frame_number = "frame " + ((Element)sprite).getAttribute("frame_number"); if(frame_number.equals((String)list_frames.getSelectedValue()) ) { sprite_found=true; String sprite_path="/"+((Element)sprite).getAttribute("path"); int align_x=Integer.parseInt(((Element)sprite).getAttribute("align_x")); int align_y=Integer.parseInt(((Element)sprite).getAttribute("align_y")); double scale=(double)Integer.parseInt(((Element)sprite).getAttribute("scale")); //Print sprite ((ImagePanel)image_panel).setImage(directory_path+sprite_path,align_x,align_y,scale); label_current_sprite.setText(sprite_path); } } } } } if(!sprite_found) { ((ImagePanel)image_panel).setImage("assets/LogoEngine.png"); label_current_sprite.setText("assets/LogoEngine.png"); } }
6
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed int i = 0; int numPalabras = 0; String texto = textArea.getText(); texto += " "; if(texto.length() > 0) { do { if(texto.charAt(i) != ' ' && texto.charAt(i+1) == ' ') { numPalabras++; } i++; } while(i < texto.length() - 1); campoPalabras.setText(String.valueOf(numPalabras)); } }//GEN-LAST:event_jButton1ActionPerformed
4
protected void rotateLeft(Node<T> node) { Position parentPosition = null; Node<T> parent = node.parent; if (parent != null) { if (node.equals(parent.lesser)) { // Lesser parentPosition = Position.LEFT; } else { // Greater parentPosition = Position.RIGHT; } } Node<T> greater = node.greater; node.greater = null; Node<T> lesser = greater.lesser; greater.lesser = node; node.parent = greater; node.greater = lesser; if (lesser != null) lesser.parent = node; if (parent!=null && parentPosition != null) { if (parentPosition == Position.LEFT) { parent.lesser = greater; } else { parent.greater = greater; } greater.parent = parent; } else { root = greater; greater.parent = null; } }
6
public AboutDialog() { contentPane.setBorder(DefaultUIProvider.getDefaultEmptyEtchedBorder()); setContentPane(contentPane); setModal(true); getRootPane().setDefaultButton(buttonOK); try { aboutTextPane.setPage(getClass().getResource("/config/about.html")); } catch (IOException e) { LOGGER.error("Cannot get about page!", e); } aboutTextPane.setFont(DefaultUIProvider.getQuestionFont()); aboutTextPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { try { desktop.browse(e.getURL().toURI()); } catch (Exception e1) { LOGGER.error("Cannot open URL!", e1); } } } } }); contentPane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onOK(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); buttonOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onOK(); } }); setSize(400, 300); }
6
private static Calendar convertToCalendar(String value, int killId) { Calendar output; try { int year = Integer.parseInt(value.substring(0, 4)); int month = Integer.parseInt(value.substring(5, 7)) - 1; int day = Integer.parseInt(value.substring(8, 10)); int hour = Integer.parseInt(value.substring(11, 13)); int minute = Integer.parseInt(value.substring(14, 16)); int second = Integer.parseInt(value.substring(17, 19)); output = new GregorianCalendar(year, month, day, hour, minute, second); } catch (Exception e) { output = new GregorianCalendar(0, 0, 0, 0, 0, 0); System.out.println(" Calendar Failed on killID:" + killId + " !"); } return output; }
1
public static Predicate.Op getOp(String s) throws simpledb.ParsingException { if (s.equals("=")) return Predicate.Op.EQUALS; if (s.equals(">")) return Predicate.Op.GREATER_THAN; if (s.equals(">=")) return Predicate.Op.GREATER_THAN_OR_EQ; if (s.equals("<")) return Predicate.Op.LESS_THAN; if (s.equals("<=")) return Predicate.Op.LESS_THAN_OR_EQ; if (s.equals("LIKE")) return Predicate.Op.LIKE; if (s.equals("~")) return Predicate.Op.LIKE; if (s.equals("<>")) return Predicate.Op.NOT_EQUALS; if (s.equals("!=")) return Predicate.Op.NOT_EQUALS; throw new simpledb.ParsingException("Unknown predicate " + s); }
9
@Override public void run() { myThread = Thread.currentThread(); log.debug("SystemThread: thread starting"); watchdog.start(); synchronized (this) { state = recalcMode(); // Bring up the OCP Links for (Link link : links) { link.linkManager.connect(watchdog); } while (true) { watchdog.pat(); internalRun(); if (shutdownThread) { break; } try { this.wait(1 * MILLISECONDS); } catch (InterruptedException e) { // CSIGNORE: EmptyBlock } } log.debug("SystemThread: shutting down"); // Shutdown the OCP links for (Link link : links) { link.linkManager.disconnect(); } } watchdog.stop(); log.debug("SystemThread: thread exiting"); }
5
public static void Kuhn(Graph input) { input.setState(States.ARR_ADJ); Log.print(Log.system, "Kuhn algorithm:"); // init int n = input.getNodeCountFirstPartite(); int k = input.getVertexCount() - n; mt = new int[k]; used = new boolean[n]; Arrays.fill(mt, -1); for (int i = 0; i < n; i++) { Arrays.fill(used, false); tryKuhn(input, i); } for (int i = 0; i < k; i++) if (mt[i] != -1) System.out.println((mt[i] + 1) + " " + (i + 1)); }
3
public String getColumnName(int columnIndex) { // Devuelve el nombre de cada columna. Este texto aparecerá en la // cabecera de la tabla. switch (columnIndex) { case 0: return "PID"; case 1: return "PD"; case 2: return "PE"; case 3: return "Quantum"; default: return null; } }
4
private void relaxDriveTime(Edge e, Node prevNode) { Node nextNode; if (prevNode.equals(e.getFromNode())) { nextNode = e.getToNode(); } else { nextNode = e.getFromNode(); } double g_Score = prevNode.getDistTo() + e.getWeight(); if (g_Score < nextNode.getDistTo()) { edgeTo.put(nextNode, e); double h_Score = Math.sqrt(Math.pow((toNode.getxCoord() - nextNode.getxCoord()), 2) + Math.pow(toNode.getyCoord() - nextNode.getyCoord(), 2)) / (130000); // 130*1000 double f_Score = h_Score + g_Score; pQueue.remove(nextNode); nextNode.setDistTo(g_Score); nextNode.setHeuristic(f_Score); pQueue.add(nextNode); } /* if (nextNode.getDistTo() >= prevNode.getDistTo() + e.getWeight()) { nextNode.setDistTo(prevNode.getDistTo()+e.getWeight() + Math.sqrt(Math.pow((toNode.getxCoord()-nextNode.getxCoord()), 2)+Math.pow(toNode.getyCoord()-nextNode.getyCoord(), 2))/(130*1000)); edgeTo.put(nextNode, e); if (pQueue.contains(nextNode)){ pQueue.remove(nextNode);pQueue.add(nextNode);} else pQueue.add(nextNode); } */ }
2
public int diferencaEmSegundos(Tempo t) { return Math.abs(segundos() - t.segundos()); }
0
public void init(byte player_mode){ players = new Player[2]; boolean hasP1 = (player_mode & PLAYER_MODE_P1_ONLY)==PLAYER_MODE_P1_ONLY; boolean hasP2 = (player_mode & PLAYER_MODE_P2_ONLY)==PLAYER_MODE_P2_ONLY; if (hasP1) players[PLAYER_ID_P1] = new Player(PLAYER_ID_P1); if (hasP2) players[PLAYER_ID_P2] = new Player(PLAYER_ID_P2); stageId = 1; CityMap cmap = new CityMap(stageId); curStage = new Stage(this); curStage.loadCityMap(cmap); startStage(); }
2
private int waehleZeile() { int zahl = 0; while (zahl < 1 || zahl > 16) { try { zahl = scan.nextInt(); } catch (InputMismatchException e) { GamePrinter.printEingabeFehler(); scan.nextLine(); return waehleZeile(); } if (zahl < 1 || zahl > 16) { GamePrinter.printEingabeFehler(); } } return (zahl - 1); }
5
public ArrayList<Processo> Consultar(String situacao){ //("") - Pesquisa sem precisar de id. ArrayList<Processo> processos = new ArrayList(); try { if(situacao.equals("")){ String sql = "SELECT * FROM tb_processo"; ConsultarSQL(sql,true); while (rs.next()) { Processo processo = new Processo(); processo.setIdProcesso(rs.getString("id")); processo.setProcesso(rs.getString("processo")); processo.setCliente(rs.getString("nome_cliente")); processo.setSituacao(rs.getString("situacao")); processo.setIdCliente(rs.getInt("id_cliente")); processo.setIdAdvogado(rs.getInt("id_advogado")); processo.setIdAssessoria(rs.getInt("id_assessoria")); processo.setLocal_arquivo(rs.getString("local_anexo")); processos.add(processo); } }else if(situacao.equals("ABERTO")){ String sql = "SELECT id,processo, nome_cliente,situacao FROM tb_processo WHERE situacao = '"+situacao+"'"; ConsultarSQL(sql,true); while (rs.next()) { Processo processo = new Processo(); processo.setIdProcesso(rs.getString("id")); processo.setProcesso(rs.getString("processo")); processo.setCliente(rs.getString("nome_cliente")); processo.setSituacao(rs.getString("situacao")); processos.add(processo); } }else if(situacao.equals("ARQUIVADO")){ String sql = "SELECT id,nome_cliente,processo,situacao FROM tb_processo WHERE situacao = '"+situacao+"'"; ConsultarSQL(sql,true); while (rs.next()) { Processo processo = new Processo(); processo.setIdProcesso(rs.getString("id")); processo.setProcesso(rs.getString("processo")); processo.setCliente(rs.getString("nome_cliente")); processo.setSituacao(rs.getString("situacao")); processos.add(processo); } }else{ String sql = "SELECT * FROM tb_processo WHERE id = '"+situacao+"'"; ConsultarSQL(sql,true); while (rs.next()) { Processo processo = new Processo(); processo.setIdProcesso(rs.getString("id")); processo.setProcesso(rs.getString("processo")); processo.setData_inicio(rs.getString("data_inicio")); processo.setData_termino(rs.getString("data_termino")); processo.setIdCliente(rs.getInt("id_cliente")); processo.setIdAdvogado(rs.getInt("id_advogado")); processo.setAcao(rs.getString("acao")); processo.setSituacao(rs.getString("situacao")); processo.setSituacao_atual(rs.getString("situacao_atual")); processo.setVara(rs.getString("vara")); processo.setComarca(rs.getString("comarca")); processo.setIdAssessoria(rs.getInt("id_assessoria")); processo.setCliente(rs.getString("nome_cliente")); processo.setLocal_arquivo(rs.getString("local_anexo")); processos.add(processo); } return processos; } } catch (SQLException ex) { Logger.getLogger(DaoCliente.class.getName()).log(Level.SEVERE, null, ex); } return processos; }
8
public void render3(Graphics g) { if(window != null) { window.render(g); } else if(cX >= 0 && cY >= 0 && cX < Game.fieldWidth && cY < Game.fieldHeight) //Highlights the grid that the mouse is hovering over { g.setColor(selectColor); g.fillRect(Game.MAPOFFX + cX * Game.TILESIZE, Game.MAPOFFY + cY * Game.TILESIZE, Game.TILESIZE, Game.TILESIZE); } //Renders mouse pointer if(inWindow) { if(slot != -1 && cSelect.getInventory().getItem(slot) != null) { //Draw dragged item instead of mouse pointer cSelect.getInventory().getItem(slot).render(x - Game.TILESIZE / 2, y - Game.TILESIZE / 2, g); } else if(nBt != null) { //Hand pointer g.drawImage(sprite.cursor[mouse][1], x - 7, y, 32, 32, null); } else { //Normal pointer g.drawImage(sprite.cursor[mouse][0], x, y, 32, 32, null); } } }
9
public Enemy(int startX) throws SlickException{ // Initialises things. this.startX = startX; location = new Ellipse2D.Float((float)startX, (float)0,10,10); location.setFrame((float)startX, 0, 10, 10); // Sets the speed based on difficulty. if(Settings.difficulty == 4){speed = 5;} else if(Settings.difficulty == 3){speed = 10;} else if(Settings.difficulty == 2){speed = 15;} else if(Settings.difficulty == 1){speed = 20;} // Sets the word to be attached to the enemy. setWord(); }
4
public String getIsSortByName() { if(sortByName){ return "true";} else{ return "false";} }
1
public static void main(String[] args) throws SQLException { File file = new File(HOSPITALOUT); conn = DriverManager.getConnection("jdbc:derby://localhost:1527/hospital", "sa", "sa"); dao = new PatientDAOJdbc(conn); List<Patient> list = dao.findAll(); Scanner keyboard = new Scanner(System.in); petla_glowna: while (true) { showMainMenu(); int option = readKeyboard(keyboard); System.out.println("wybrano " + option); //list.add("ala ma kota"); switch (option) { case 1: Patient p = readPatientFromKeyboard(keyboard); list.add(p); dao.save(p); break; case 2: for(int i = 0; i < list.size(); i++) { Patient tmp = list.get(i); System.out.println(tmp.getName() + " " + tmp.getLastName()); } break; case 3 : System.out.println("auto save jest już włączony");; break; case 0: conn.close(); break petla_glowna; default: System.out.println("nieistniejąca opcja"); } } System.out.println("Koniec."); }
6
private static byte[] readClass(final InputStream is) throws IOException { if (is == null) throw new IOException("Class not found"); try { byte[] b = new byte[is.available()]; int len = 0; while (true) { int n = is.read(b, len, b.length - len); if (n == -1) { if (len < b.length) { byte[] c = new byte[len]; System.arraycopy(b, 0, c, 0, len); b = c; } return b; } len += n; if (len == b.length) { int last = is.read(); if (last < 0) return b; byte[] c = new byte[b.length + 1000]; System.arraycopy(b, 0, c, 0, len); c[len++] = (byte) last; b = c; } } } finally { try { is.close (); } catch (IOException ignored) {} } }
7
@Override public void execute(CommandSender sender, String[] args) { if (args.length == 0) { sender.sendMessage(new TextComponent(ChatColor.RED + "Usage: /say <message ...>")); return; } StringBuilder msg = new StringBuilder(); for (String a : args) msg.append(a); plugin.getProxy().broadcast(new TextComponent(ChatColor.translateAlternateColorCodes('&', BungeeRelay.getConfig().getString("formats.saycommand").replace("{MESSAGE}", msg.toString())))); if (!IRC.sock.isConnected()) { sender.sendMessage(new TextComponent(ChatColor.RED + "The proxy is not connected to IRC.")); return; } for (String c : Util.getChannels()) IRC.out.println(":" + IRC.mainUid + " PRIVMSG " + c + " :" + msg.toString()); }
4
private String getPOS(String label) { if (ADJECT.contains(label)) { return "ADJECT"; } else if (DET.contains(label)) { return "DET"; } else if (PREP.contains(label)) { return "PREP"; } else if (NOUNS.contains(label)) { return "NOUNS"; } else if (VERBS.contains(label)) { return "VERBS"; } else if (ADVERBS.contains(label)) { return "ADVERBS"; } else { return "MISC"; } }
6
public Sound(String path) throws Exception { InputStream in = new FileInputStream(path); // create an audiostream from the inputstream AudioStream audioStream = new AudioStream(in); // play the audio clip with the audioplayer class AudioPlayer.player.start(audioStream); }
0
public static void main(String[] args) { int turn = -1; Player[] players = {null, null}; Scanner in = new Scanner(System.in); // set the number of games System.out.println("Input the number of games to be played:"); turn = in.nextInt(); // set player objects for (int i = 0; i < players.length; i++) { while (players[i] == null) { String idx = (i == 0) ? "first" : "second"; System.out.println("Enter the name of " + idx + " player's class:"); String s = in.next(); try { players[i] = Player.getInstance(PLAYERS_PACKAGE_NAME + "." + s); } catch (ReflectiveOperationException e) { System.out.println("Player " + s + " doesn't exist."); } } } CUIController controller = new CUIController(turn, players[0], players[1]); controller.run(); }
4
private Transition createOpenAnimation(final RadialMenuItem newSelectedItem) { // Children slide animation final List<RadialMenuItem> children = itemToValues.get(newSelectedItem); double startAngleEnd = 0; final double startAngleBegin = newSelectedItem.getStartAngle(); final ParallelTransition transition = new ParallelTransition(); itemToGroupValue.get(newSelectedItem).setVisible(true); int internalCounter = 1; for (int i = 0; i < children.size(); i++) { final RadialMenuItem it = children.get(i); if (i % 2 == 0) { startAngleEnd = startAngleBegin + internalCounter * it.getLength(); } else { startAngleEnd = startAngleBegin - internalCounter * it.getLength(); internalCounter++; } final Animation itemTransition = new Timeline(new KeyFrame( Duration.ZERO, new KeyValue(it.startAngleProperty(), startAngleBegin)), new KeyFrame( Duration.millis(400), new KeyValue(it.startAngleProperty(), startAngleEnd))); transition.getChildren().add(itemTransition); final ImageView image = itemAndValueToIcon.get(it); image.setOpacity(0.0); final Timeline iconTransition = new Timeline(new KeyFrame( Duration.millis(0), new KeyValue(image.opacityProperty(), 0)), new KeyFrame( Duration.millis(300), new KeyValue(image.opacityProperty(), 0)), new KeyFrame(Duration.millis(400), new KeyValue(image.opacityProperty(), 1.0))); transition.getChildren().add(iconTransition); } // Selected item background color change final DoubleProperty backgroundColorAnimValue = new SimpleDoubleProperty(); final ChangeListener<? super Number> listener = new ChangeListener<Number>() { @Override public void changed(final ObservableValue<? extends Number> arg0, final Number arg1, final Number arg2) { final Color c = hoverColor.interpolate(selectionColor, arg2.floatValue()); newSelectedItem.setBackgroundFill(c); newSelectedItem.setStrokeFill(c); newSelectedItem.setBackgroundMouseOnFill(c); newSelectedItem.setStrokeMouseOnFill(c); } }; backgroundColorAnimValue.addListener(listener); final Animation itemTransition = new Timeline(new KeyFrame( Duration.ZERO, new KeyValue(backgroundColorAnimValue, 0)), new KeyFrame(Duration.millis(300), new KeyValue( backgroundColorAnimValue, 1.0))); transition.getChildren().add(itemTransition); // Selected item image icon color change final FadeTransition selectedItemImageBlackFade = FadeTransitionBuilder .create().node(itemAndValueToIcon.get(newSelectedItem)) .duration(Duration.millis(400)).fromValue(1.0).toValue(0.0) .build(); final FadeTransition selectedItemImageWhiteFade = FadeTransitionBuilder .create().node(itemAndValueToWhiteIcon.get(newSelectedItem)) .duration(Duration.millis(400)).fromValue(0).toValue(1.0) .build(); transition.getChildren().addAll(selectedItemImageBlackFade, selectedItemImageWhiteFade); // Unselected items fading final FadeTransition notSelectedTransition = FadeTransitionBuilder .create().node(notSelectedItemEffect) .duration(Duration.millis(200)).delay(Duration.millis(200)) .fromValue(0).toValue(0.8).build(); notSelectedItemEffect.setOpacity(0); notSelectedItemEffect.setVisible(true); transition.getChildren().add(notSelectedTransition); return transition; }
4
public ItemSelectorDialog(LegendaryCardMakerFrame parent) { super(parent); setSize(400, 500); setTitle("Select Items"); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); checklist = new JCheckList<LegendaryItem>(); for (Hero h : LegendaryCardMakerFrame.lcmf.lcm.heroes) { checklist.addCheckListItem("Hero - " + h.name, h); } for (Villain h : LegendaryCardMakerFrame.lcmf.lcm.villains) { if (h.name.equals("system_bystander_villain")) { for (VillainCard vc : h.cards) { checklist.addCheckListItem("Bystander - " + h.name, h); } } else if (h.name.equals("system_wound_villain")) { for (VillainCard vc : h.cards) { checklist.addCheckListItem("Wound - " + h.name, h); } } else if (h.name.equals("system_bindings_villain")) { for (VillainCard vc : h.cards) { checklist.addCheckListItem("Bindings - " + h.name, h); } } else { checklist.addCheckListItem("Villain - " + h.name, h); } } for (SchemeCard h : LegendaryCardMakerFrame.lcmf.lcm.schemes) { checklist.addCheckListItem("Scheme - " + h.name + " (" + h.cardType.getDisplayString() + ")", h); } this.add(checklist); this.setModal(true); this.setVisible(true); }
9
public static int computeStoredBoundOnRoleset(NamedDescription relation, Stella_Object instance, Keyword lowerorupper) { { Skolem roleset = NamedDescription.getRolesetOf(relation, instance); Stella_Object cardinality = null; edu.isi.powerloom.pl_kernel_kb.IntervalCache intervalcache = null; Stella_Object bound = null; if (roleset == null) { return (Stella.NULL_INTEGER); } cardinality = Logic.accessBinaryValue(roleset, Logic.SGT_PL_KERNEL_KB_CARDINALITY); if (cardinality != null) { { Surrogate testValue000 = Stella_Object.safePrimaryType(cardinality); if (Surrogate.subtypeOfIntegerP(testValue000)) { { IntegerWrapper cardinality000 = ((IntegerWrapper)(cardinality)); return (cardinality000.wrapperValue); } } else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_SKOLEM)) { { Skolem cardinality000 = ((Skolem)(cardinality)); { intervalcache = edu.isi.powerloom.pl_kernel_kb.PlKernelKb.getIntervalCache(cardinality000); if (intervalcache != null) { if (lowerorupper == Logic.KWD_LOWER) { bound = intervalcache.lowerBound; } else if (lowerorupper == Logic.KWD_UPPER) { bound = intervalcache.upperBound; } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + lowerorupper + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } if ((bound != null) && Stella_Object.isaP(bound, Logic.SGT_STELLA_INTEGER_WRAPPER)) { return (IntegerWrapper.unwrapInteger(((IntegerWrapper)(bound)))); } } } } } else { { OutputStringStream stream001 = OutputStringStream.newOutputStringStream(); stream001.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace())); } } } } return (Stella.NULL_INTEGER); } }
9
public VueConnexion getVue() { return vue; }
0
public static TreeMap<String, Integer> getShiptypesNameOccurrence( ArrayList<Kill> killBoard, String attribute) { ItemIdList.getInstance(); TreeMap<Integer, Integer> intermediary = getShiptypesIDOccurrence( killBoard, attribute); TreeMap<String, Integer> result = new TreeMap<String, Integer>(); Iterator<Map.Entry<Integer, Integer>> entries = intermediary.entrySet() .iterator(); while (entries.hasNext()) { Entry<Integer, Integer> tmpEntry = entries.next(); int key = tmpEntry.getKey(); int value = tmpEntry.getValue(); result.put(ItemIdList.lookup(key), value); } return result; }
1
private static void writeSetPrimitiveBeanPropertyFromArray(final Class cl, final CodeVisitor mw, final Method setter, final Class returnType, final int beanIdx, final int valueArrayIdx, final int colPos) { mw.visitVarInsn(ALOAD, beanIdx); mw.visitVarInsn(ALOAD, valueArrayIdx); mw.visitIntInsn(SIPUSH, colPos); mw.visitInsn(AALOAD); if (returnType == boolean.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Boolean.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Boolean.class), "booleanValue", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[]{}) ); } else if (returnType == char.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Character.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Character.class), "charValue", Type.getMethodDescriptor(Type.CHAR_TYPE, new Type[]{}) ); } else if (returnType == byte.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Byte.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Byte.class), "byteValue", Type.getMethodDescriptor(Type.BYTE_TYPE, new Type[]{}) ); } else if (returnType == short.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Short.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Short.class), "shortValue", Type.getMethodDescriptor(Type.SHORT_TYPE, new Type[]{}) ); } else if (returnType == int.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Integer.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Integer.class), "intValue", Type.getMethodDescriptor(Type.INT_TYPE, new Type[]{})); } else if (returnType == long.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Long.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Long.class), "longValue", Type.getMethodDescriptor(Type.LONG_TYPE, new Type[]{}) ); } else if (returnType == float.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Float.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Float.class), "floatValue", Type.getMethodDescriptor(Type.FLOAT_TYPE, new Type[]{}) ); } else if (returnType == double.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Double.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Double.class), "doubleValue", Type.getMethodDescriptor(Type.DOUBLE_TYPE, new Type[]{}) ); } mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(cl), setter.getName(), Type.getMethodDescriptor(setter)); }
8
boolean leaf() { int count = 0; if ( null != parentEdge) count++; if ( null != leftEdge) count++; if ( null != rightEdge) count++; if ( null != middleEdge) count++; if ( count > 1 ) return false; return true; }
5
public int getDlc() { return dlc; }
0
public void walk(String path, FilenameFilter filter) { File root = new File(path); File[] list = root.listFiles(); if (list == null) return; for (File f : list) { if (f.isDirectory()) { walk(f.getAbsolutePath(), filter); // System.out.println("Dir:" + f.getAbsoluteFile()); } else { // System.out.println("File:" + f.getParentFile().getAbsolutePath()); if (filter.accept(f.getParentFile(), f.getName())) { if (this.fileList == null) { this.fileList = new ArrayList<String>(); } this.fileList.add(f.getAbsolutePath()); } } } }
5
public void createGenFile( GenKbAuthorization Authorization, GenKbGenFileBuff Buff ) { GenKbGenItemPKey pkey = schema.getFactoryGenItem().newPKey(); pkey.setClassCode( Buff.getClassCode() ); pkey.setRequiredCartridgeId( Buff.getRequiredCartridgeId() ); pkey.setRequiredItemId( Buff.getRequiredItemId() ); GenKbGenFileBySrcBundleIdxKey keySrcBundleIdx = schema.getFactoryGenFile().newSrcBundleIdxKey(); keySrcBundleIdx.setRequiredCartridgeId( Buff.getRequiredCartridgeId() ); keySrcBundleIdx.setOptionalSourceBundleGelId( Buff.getOptionalSourceBundleGelId() ); GenKbGenFileByBasePackageIdxKey keyBasePackageIdx = schema.getFactoryGenFile().newBasePackageIdxKey(); keyBasePackageIdx.setRequiredCartridgeId( Buff.getRequiredCartridgeId() ); keyBasePackageIdx.setOptionalBasePackageGelId( Buff.getOptionalBasePackageGelId() ); GenKbGenFileBySubPackageIdxKey keySubPackageIdx = schema.getFactoryGenFile().newSubPackageIdxKey(); keySubPackageIdx.setRequiredCartridgeId( Buff.getRequiredCartridgeId() ); keySubPackageIdx.setOptionalSubPackageGelId( Buff.getOptionalSubPackageGelId() ); GenKbGenFileByExpClassIdxKey keyExpClassIdx = schema.getFactoryGenFile().newExpClassIdxKey(); keyExpClassIdx.setRequiredCartridgeId( Buff.getRequiredCartridgeId() ); keyExpClassIdx.setOptionalExpansionClassNameGelId( Buff.getOptionalExpansionClassNameGelId() ); GenKbGenFileByExpKeyNameIdxKey keyExpKeyNameIdx = schema.getFactoryGenFile().newExpKeyNameIdxKey(); keyExpKeyNameIdx.setRequiredCartridgeId( Buff.getRequiredCartridgeId() ); keyExpKeyNameIdx.setOptionalExpansionKeyNameGelId( Buff.getOptionalExpansionKeyNameGelId() ); GenKbGenFileByExpFileNameIdxKey keyExpFileNameIdx = schema.getFactoryGenFile().newExpFileNameIdxKey(); keyExpFileNameIdx.setRequiredCartridgeId( Buff.getRequiredCartridgeId() ); keyExpFileNameIdx.setOptionalExpansionFileNameGelId( Buff.getOptionalExpansionFileNameGelId() ); // Validate unique indexes if( dictByPKey.containsKey( pkey ) ) { throw CFLib.getDefaultExceptionFactory().newPrimaryKeyNotNewException( getClass(), "createGenFile", pkey ); } // Validate foreign keys { boolean allNull = true; allNull = false; allNull = false; if( ! allNull ) { if( null == schema.getTableGenRule().readDerivedByItemIdIdx( Authorization, Buff.getRequiredCartridgeId(), Buff.getRequiredItemId() ) ) { throw CFLib.getDefaultExceptionFactory().newUnresolvedRelationException( getClass(), "createGenFile", "Superclass", "SuperClass", "GenRule", null ); } } } // Proceed with adding the new record dictByPKey.put( pkey, Buff ); SortedMap< GenKbGenItemPKey, GenKbGenFileBuff > subdictSrcBundleIdx; if( dictBySrcBundleIdx.containsKey( keySrcBundleIdx ) ) { subdictSrcBundleIdx = dictBySrcBundleIdx.get( keySrcBundleIdx ); } else { subdictSrcBundleIdx = new TreeMap< GenKbGenItemPKey, GenKbGenFileBuff >(); dictBySrcBundleIdx.put( keySrcBundleIdx, subdictSrcBundleIdx ); } subdictSrcBundleIdx.put( pkey, Buff ); SortedMap< GenKbGenItemPKey, GenKbGenFileBuff > subdictBasePackageIdx; if( dictByBasePackageIdx.containsKey( keyBasePackageIdx ) ) { subdictBasePackageIdx = dictByBasePackageIdx.get( keyBasePackageIdx ); } else { subdictBasePackageIdx = new TreeMap< GenKbGenItemPKey, GenKbGenFileBuff >(); dictByBasePackageIdx.put( keyBasePackageIdx, subdictBasePackageIdx ); } subdictBasePackageIdx.put( pkey, Buff ); SortedMap< GenKbGenItemPKey, GenKbGenFileBuff > subdictSubPackageIdx; if( dictBySubPackageIdx.containsKey( keySubPackageIdx ) ) { subdictSubPackageIdx = dictBySubPackageIdx.get( keySubPackageIdx ); } else { subdictSubPackageIdx = new TreeMap< GenKbGenItemPKey, GenKbGenFileBuff >(); dictBySubPackageIdx.put( keySubPackageIdx, subdictSubPackageIdx ); } subdictSubPackageIdx.put( pkey, Buff ); SortedMap< GenKbGenItemPKey, GenKbGenFileBuff > subdictExpClassIdx; if( dictByExpClassIdx.containsKey( keyExpClassIdx ) ) { subdictExpClassIdx = dictByExpClassIdx.get( keyExpClassIdx ); } else { subdictExpClassIdx = new TreeMap< GenKbGenItemPKey, GenKbGenFileBuff >(); dictByExpClassIdx.put( keyExpClassIdx, subdictExpClassIdx ); } subdictExpClassIdx.put( pkey, Buff ); SortedMap< GenKbGenItemPKey, GenKbGenFileBuff > subdictExpKeyNameIdx; if( dictByExpKeyNameIdx.containsKey( keyExpKeyNameIdx ) ) { subdictExpKeyNameIdx = dictByExpKeyNameIdx.get( keyExpKeyNameIdx ); } else { subdictExpKeyNameIdx = new TreeMap< GenKbGenItemPKey, GenKbGenFileBuff >(); dictByExpKeyNameIdx.put( keyExpKeyNameIdx, subdictExpKeyNameIdx ); } subdictExpKeyNameIdx.put( pkey, Buff ); SortedMap< GenKbGenItemPKey, GenKbGenFileBuff > subdictExpFileNameIdx; if( dictByExpFileNameIdx.containsKey( keyExpFileNameIdx ) ) { subdictExpFileNameIdx = dictByExpFileNameIdx.get( keyExpFileNameIdx ); } else { subdictExpFileNameIdx = new TreeMap< GenKbGenItemPKey, GenKbGenFileBuff >(); dictByExpFileNameIdx.put( keyExpFileNameIdx, subdictExpFileNameIdx ); } subdictExpFileNameIdx.put( pkey, Buff ); }
9
public static HashMap<String, byte[]> unpackZip(byte[] data) throws IOException { ByteArrayInputStream inputStream = new ByteArrayInputStream(data); ZipInputStream zipInputStream = new ZipInputStream(inputStream); HashMap<String, byte[]> zipData = new HashMap<>(); try { ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { String fileName = zipEntry.getName(); if (fileName.startsWith("/")) { fileName = fileName.substring(1); } // Can't use readStreamToMemory because it closes zipInputStream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024 * 80); IOUtils.copy(zipInputStream, outputStream); zipData.put(fileName, outputStream.toByteArray()); zipEntry = zipInputStream.getNextEntry(); } } finally { IOUtils.closeQuietly(zipInputStream); } return zipData; }
2
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DictionaryInfo that = (DictionaryInfo) o; if (description != null ? !description.equals(that.description) : that.description != null) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; return true; }
7
public void preferenceToLongerPaths() { Comparator<Route> comp = new Comparator<Route>() { @Override public int compare(Route o1, Route o2) { // TODO Auto-generated method stub if(o1.getRouteTravelTime() > o2.getRouteTravelTime()) { return -1; } return 1; } }; Route.setTotalHops(0); //For each source find the shortest available path to a destination. PriorityQueue<Route> preRQ = new PriorityQueue<Route>(srcList.size(), comp); Map<Node, Route> map = new HashMap<Node, Route>(); int totalEvacuees = 0; System.out.println("A1"); for(int i=0;i<srcList.size();i++) { Node src = srcList.get(i); totalEvacuees += src.getInitialOccupancy(); clearNodeData(src); Route r = shortestPath(src); preRQ.add(r); map.put(src, r); } System.out.println("A2"); double totalEgressTime = 0; while(totalEvacuees > 0) { Route r = preRQ.poll(); int assignedPath = findMinimumCapacity(r, map); //totalEgressTime = reserveAllPaths(r); Node src = r.getRouteNodeList().get(0); if(src.getCurrentOccupancy() == 0) { src.setNodeType(Node.NORMAL); srcList.remove(src); } totalEvacuees -= assignedPath; if(totalEvacuees == 0) break; preRQ.clear(); map.clear(); for(int i=0;i<srcList.size();i++) { src = srcList.get(i); clearNodeData(src); Route rr = shortestPath(src); preRQ.add(rr); map.put(src, rr); } } System.out.println("Egress Time : " + totalEgressTime); System.out.println("RouteList Size : " + pathList.size()); //System.out.println("Average Evacuation Time : " + 1.0*evacuationTime/count); System.out.println("Avg Hops : " + 1.0*Route.getTotalHops()/pathList.size()); System.out.println("Max Hops : " + Route.getMaxHops()); System.out.println("No of Distinct Routes : " + this.getDistinctRoutes().size()); int maxWaitingTimeAtANode = 0; String nodeName; double totalWaitingTime = 0; for(int i=0;i<graph.getNodeList().size();i++) { totalWaitingTime += graph.getNodeList().get(i).getWaitingTimeAtThisNode(); if(graph.getNodeList().get(i).getWaitingTimeAtThisNode() > maxWaitingTimeAtANode) { maxWaitingTimeAtANode = graph.getNodeList().get(i).getWaitingTimeAtThisNode(); nodeName = graph.getNodeList().get(i).getNodeName(); } } System.out.println("Max. Waiting Time at a node : " + maxWaitingTimeAtANode); System.out.println("Average. Waiting Time at a node : " + totalWaitingTime/graph.getNodeList().size()); //System.out.println("Count:" + count); }
8
public String next() { current++; return "'prefix" + (current - 1) + "'"; }
0
public void createTask( String id, String name, String date, String status, String required, String description, String attendants) throws JAXBException, IOException{ //Probind that the data is comming correctly /*System.out.println( "Id: "+id+ "Name: "+name+ "date: "+date+ "status: "+status+ "required: "+required+ "descriptino: "+description+ "attendants: "+attendants);*/ //trying to write into file FileInputStream stream = new FileInputStream("C:/Users/Efrin Gonzalez/Documents/task-manager-xml.xml"); String path="C:/Users/Efrin Gonzalez/Documents/task-manager-xml.xml"; //First Let's try to get all the info from the file and the include the new info JAXBContext jaxbContext = JAXBContext.newInstance(Cal.class); // Deserialize university xml into java objects. Cal cal = (Cal) jaxbContext.createUnmarshaller().unmarshal(stream); // Let's create the new task to be written in the file. Task task = new Task(); task.id = id; task.name = name; task.date = date; task.status = status; task.required = required; task.description = description; task.attendants = attendants; //if the task does not existe, let's add it //With the iterator we can full fill the list that will be sent in response ListIterator<Task> listIterator = cal.tasks.listIterator(); //list to full fill with the requested id //List<Task> tasksList = new ArrayList<Task>(); int existingTask=0; //flag to see whether the element exist while (listIterator.hasNext()) { Task taskList = listIterator.next(); if((taskList.id.equals(id))&&(taskList.name.equals(name)) ){ existingTask = 1; System.out.println("The task id: "+ id +" name: "+name+" already exist. It is not allowed to create repeted tasks."); } } if (existingTask == 0){ cal.tasks.add(task); // Serialize university object into xml. StringWriter writer = new StringWriter(); // We can use the same context object, as it knows how to //serialize or deserialize University class. jaxbContext.createMarshaller().marshal(cal, writer); SaveFile(writer.toString(), path); System.out.println("The task id: "+ id +" name: "+name+" has been saved. "); } }
4
public static String escapeHTML(String text) { text = StringTools.replace(text,"&","&amp;"); text = StringTools.replace(text,"<","&lt;"); text = StringTools.replace(text,">","&gt;"); text = StringTools.replace(text,"\"","&quot;"); return text; }
0
@Override public final boolean shouldSpawn() { if (mobTime < 0) { return false; } // regular spawnpoints should spawn a maximum of 3 monsters; immobile spawnpoints or spawnpoints with mobtime a // maximum of 1 if (((mobTime != 0 || immobile) && spawnedMonsters.get() > 0) || spawnedMonsters.get() > 1) { return false; } return nextPossibleSpawn <= System.currentTimeMillis(); }
5
public Color getColor() { switch(type) { case COPPER: return new Color(219, 63, 45); case ALUMINUM: return new Color(134, 134, 134); case SILVER: return new Color(180, 180, 180); case GOLD: return Color.YELLOW; case BISMUTH: return new Color(242, 242, 242); case PLATINUM: return new Color(219, 237, 219); case EINSTEINIUM: return new Color(138, 90, 170); } return Color.BLUE; }
7
@Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("HashtableNaive {\n"); for (int i = 0; i < currentSize; i++) { sb.append(" " + keys[i] + " => " + values[i] + "\n"); } sb.append("}"); return sb.toString(); }
1
@Override public void finishPopulate() { }
0
@org.junit.Test public void testSerialiseInt() { for (int size = 1; size <= 8; size++) { int[] numvals = new int[]{0, 10, 127, 128, 255}; for (int idx = 0; idx != numvals.length; idx++) { byte[] barr = ByteOps.encodeInt(numvals[idx], size); int val = ByteOps.decodeInt(barr, 0, size); org.junit.Assert.assertEquals("size="+size+"/idx="+idx, numvals[idx], val); org.junit.Assert.assertEquals("size="+size+"/idx="+idx, size, barr.length); } } for (int size = 2; size <= 8; size++) { int[] numvals = new int[]{256, 0x0102, 0x8192, 0xffff, 0x7fff, 0x8000}; for (int idx = 0; idx != numvals.length; idx++) { byte[] barr = ByteOps.encodeInt(numvals[idx], size); int val = ByteOps.decodeInt(barr, 0, size); org.junit.Assert.assertEquals("size="+size+"/idx="+idx, numvals[idx], val); org.junit.Assert.assertEquals("size="+size+"/idx="+idx, size, barr.length); } } for (int size = 4; size <= 8; size++) { int[] numvals = new int[]{-1, Integer.MAX_VALUE, 0xef028104, 0x12345678, Integer.MIN_VALUE, Integer.MIN_VALUE+500, Integer.MAX_VALUE-500}; for (int idx = 0; idx != numvals.length; idx++) { byte[] barr = ByteOps.encodeInt(numvals[idx], size); int val = ByteOps.decodeInt(barr, 0, size); org.junit.Assert.assertEquals("size="+size+"/idx="+idx, numvals[idx], val); org.junit.Assert.assertEquals("size="+size+"/idx="+idx, size, barr.length); } } for (int size = 4; size <= 8; size++) { long[] numvals = new long[]{ByteOps.INTMASK, Integer.MAX_VALUE, Integer.MIN_VALUE&ByteOps.INTMASK, 0xef028104L, 0x12345678L, Integer.MAX_VALUE+1L, Integer.MAX_VALUE+500L}; for (int idx = 0; idx != numvals.length; idx++) { byte[] barr = ByteOps.encodeInt(numvals[idx], size); long val = ByteOps.decodeLong(barr, 0, size); org.junit.Assert.assertEquals("size="+size+"/idx="+idx, numvals[idx], val); org.junit.Assert.assertEquals("size="+size+"/idx="+idx, size, barr.length); } } //Values with non-zero upper byte set require the full 8-byte encoding long[] numvals = new long[]{-1L, Long.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE+500L, Long.MAX_VALUE-500L}; int size = 8; for (int idx = 0; idx != numvals.length; idx++) { byte[] barr = ByteOps.encodeInt(numvals[idx], size); long val = ByteOps.decodeLong(barr, 0, size); org.junit.Assert.assertEquals("size="+size+"/idx="+idx, numvals[idx], val); org.junit.Assert.assertEquals("size="+size+"/idx="+idx, size, barr.length); } int numval = 0xef028104; byte[] barr = new byte[6]; size = 4; int off = 1; int off2 = ByteOps.encodeInt(numval, barr, off, size); int val = ByteOps.decodeInt(barr, off, size); org.junit.Assert.assertEquals(numval, val); org.junit.Assert.assertEquals(off + size, off2); }
9
public static boolean segmentSuportSeparatesPoints(Segment s, Point P, Point Q) { Point v1 = getVectorFromTo(P, s.P); Point u1 = getVectorFromTo(P, s.Q); Point v2 = getVectorFromTo(Q, s.P); Point u2 = getVectorFromTo(Q, s.Q); double prodV1U1 = crossProd(v1, u1); double prodV2U2 = crossProd(v2, u2); return (prodV1U1 < 0 && prodV2U2 > 0) || (prodV1U1 > 0 && prodV2U2 < 0); }
3
@Override public void parse() { appendURL(); String result = WebUtils.source(url.toString()); result = result.substring(0, result.indexOf("]]")); String split[] = result.split("],\\["); StringBuilder builder = new StringBuilder(); for(String sub : split){ String[] subs = sub.split("\\\",\\\""); if(builder.length() > 0){ builder.append(" "); } builder.append(subs[0].replace("[", "").replace("]", "").replace("\"", "").replace(" .", ".").trim()); } Text output = textTranslate.getOutput(); output.setText(builder.toString()); }
2
public void setOption(String option, Collection values) { if (option.startsWith("keywords")) { keywords = (String[]) values.toArray(new String[values.size()]); } else if (option.startsWith("backup")) { if (values.size() != 1) throw new IllegalArgumentException("Only one backup is allowed"); backup = (Renamer) values.iterator().next(); } else throw new IllegalArgumentException("Invalid option `" + option + "'"); }
3
public void printNthFromLast(Node root, int n) { int i = n; if (root == null) { return; } if (i > size(root)) { System.out.println("Not enough elements"); return; } Node node = root; Node nodeback = root; while ((node.getLink() != null) && (--i > 0)) { node = node.getLink(); } if (node.getLink() != null) { while (node.getLink() != null) { nodeback = nodeback.getLink(); node = node.getLink(); } } System.out.println("N = " + n + " element from last is :" + nodeback.getData()); }
6
public double MacroPrecision() { if (computed == 0) countStuff(); double mprec = 0; for (int i=0; i<catnum; i++) { if ((tp[i] != 0) && (tp[i]+fp[i] != 0)) mprec += tp[i]/(tp[i]+fp[i]); } return mprec/catnum; }
4
protected void drawHighlightedNodes(Graphics2D g2d, DrawableNode root) { nodeStack.clear(); nodeStack.push(root); g2d.setColor(highlightColor); while(!nodeStack.isEmpty()) { DrawableNode n = nodeStack.pop(); int x = translateTreeToPixelX(n.getX()); int y = translateTreeToPixelY(n.getY()); if (n.isSelected()) { g2d.setColor(highlightColor); g2d.fillRect(x-2, y-2, 5, 5); if (n.getParent()!=null) { int x1 = translateTreeToPixelX(((DrawableNode)n.getParent()).getX() ); int y1 = translateTreeToPixelY(((DrawableNode)n.getParent()).getY() ); BranchPainter branchPainter = n.getBranchPainter(); if (branchPainter == null) branchPainter = defaultBranchPainter; //We paint the branches differently depending on the orientation of the tree if (tree.getOrientation()==DrawableTree.Direction.RIGHT || tree.getOrientation()==DrawableTree.Direction.LEFT) { branchPainter.setOrientation(BranchPainter.Direction.YFIRST); } else { branchPainter.setOrientation(BranchPainter.Direction.XFIRST); } branchPainter.paintBranch(g2d, x1, y1, x, y, highlightStroke, highlightColor); } } for(Node kid : n.getOffspring()) { nodeStack.push( (DrawableNode)kid); } } }
7
private static void countTodoAndFixmes(File directory) throws IOException { for (File file : directory.listFiles()) { if (file.isDirectory()) { countTodoAndFixmes(file); } else { for (String currentEnding : CONFIG.getFileEndingsToCheck()) { if (file.getAbsolutePath().endsWith(currentEnding) && !ignoreFile(file)) { FileInputStream fis = new FileInputStream(file); byte[] data = new byte[(int) file.length()]; fis.read(data); fis.close(); String fileContent = new String(data, "UTF-8"); int index = fileContent.indexOf("TODO"); while (index > 0) { TODOS.add(file.getAbsolutePath()); index = fileContent.indexOf("TODO", index + 3); } index = fileContent.indexOf("FIXME"); while (index > 0) { FIXMES.add(file.getAbsolutePath()); index = fileContent.indexOf("FIXME", index + 3); } index = fileContent.indexOf("@Deprecated"); while (index > 0) { DEPRECATEDS.add(file.getAbsolutePath()); index = fileContent.indexOf("@Deprecated", index + 3); } } } } } }
8
public AutoApagadoManager(){ // Use an appropriate Look and Feel try { //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { start(); } }); }
4
private Boolean setupEconomy() { if( getServer().getPluginManager().getPlugin("Vault") != null ) { RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } } return (economy != null); }
2
public boolean run() { sendEvent(new GameEvent(this, "RunFrame")); for (int snakeArrayPos = activeSnakeList.size() -1;snakeArrayPos >= 0; snakeArrayPos--) { Snake snake = activeSnakeList.get(snakeArrayPos); snake.sendEvent(new GameEvent(snake, "RunFrame")); Vector2d startPos = snake.getHead().getFirst(); boolean isDead = snake.advance(1); Vector2d endPos = snake.getHead().getFirst(); boolean collision = isDead || doCollision(snake, new LineSegment(startPos, endPos)); if (collision) { snake.setIsDead(); deadSnakeList.add(snake); activeSnakeList.remove(snakeArrayPos); } if (food != null && !food.isConsumed() && food.isColliding(snake.getHeadPos())) { snake.eat(food); snake.sendEvent(new GameEvent(snake, "EatFood")); sendEvent(new GameEvent(this, "EatFood")); } } if (food == null || food.isConsumed()) { createFood(10 + ((int) Math.random() * 10)); } return !activeSnakeList.isEmpty(); }
8
public void writeNewScore() { FileWriter fw = null; try { fw = new FileWriter(file); String str ="" + best; fw.write(str); fw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fw != null) fw.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fw != null) fw.close(); } catch (IOException e) { e.printStackTrace(); } } }
6
public boolean saveToFile(String Path){ try { FileWriter f = new FileWriter(Path); f.write(this.toString()); f.close(); return true; } catch (IOException e) { e.printStackTrace(); return false; } }
1
public static String numberToString(Number number) throws JSONException { if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
6
protected void calculeReveilsTerminaisons(List<Tache> taches, Simulation environnement) { for (Tache tache : taches) { int reveil = tache.getRi(); environnement.addEvent(new Event(reveil, KIWI_INSTRUCTIONS.START_LINE, tache)); environnement.addEvent(new Event(reveil, KIWI_INSTRUCTIONS.START, tache)); if (tache.isPeriodique()) { int echeance = ((TachePeriodique)tache).getDi(); environnement.addEvent(new Event(echeance, KIWI_INSTRUCTIONS.DEADLINE, tache)); int periode = ((TachePeriodique)tache).getPi(); while (reveil + periode <= hyperperiode) { reveil += periode; environnement.addEvent(new Event(reveil, KIWI_INSTRUCTIONS.START_LINE, tache)); environnement.addEvent(new Event(reveil, KIWI_INSTRUCTIONS.START, tache)); if (reveil + ((TachePeriodique)tache).getDi() <= hyperperiode) { echeance = reveil + ((TachePeriodique)tache).getDi(); environnement.addEvent(new Event(echeance, KIWI_INSTRUCTIONS.DEADLINE, tache)); } } } } }
4
public static void main(String[] args) { MyWorkerThreadFactory factory=new MyWorkerThreadFactory(); ForkJoinPool pool=new ForkJoinPool(4, factory, null, false); int array[]=new int[100000]; for (int i=0; i<array.length; i++){ array[i]=1; } MyRecursiveTask task=new MyRecursiveTask(array,0,array.length); pool.execute(task); task.join(); pool.shutdown(); try { pool.awaitTermination(1, TimeUnit.DAYS); System.out.printf("Main: Result: %d\n",task.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.printf("Main: End of the program\n"); }
3
@Override public boolean setAllOffline() { FileWriter writer = null; try { BufferedReader reader = new BufferedReader(new FileReader(new File(OnlineUsers.directory+OnlineUsers.flatfileData))); String line = ""; StringBuilder toSave = new StringBuilder(); while ((line = reader.readLine()) != null) { if (line.contains(":")) { String user = line.split(":")[0]; String time = line.split(":")[1]; toSave.append(user + ":" + time + ":" + String.valueOf(OFFLINE)); } } reader.close(); writer = new FileWriter(OnlineUsers.directory+OnlineUsers.flatfileData); writer.write(toSave.toString()); } catch (Exception e1) { log.log(Level.SEVERE, "Exception setting all offline from " + OnlineUsers.directory+OnlineUsers.flatfileData, e1); } finally { try { if (writer != null) { writer.close(); return regenFlatFile(); } } catch (IOException ex) { } } return false; }
5
public String getDepartmentName() { return departmentName; }
0
protected void setup() { int segundo = 5; //comportamento para solicitar ao diretório falicitador por algum motoboy disponível para entregar a pizza addBehaviour(new TickerBehaviour(this, segundo*1000) { protected void onTick() { //poll remove, por isso está sendo espiado String clienteLocalName = _clientesComPizzaPronta.peek(); //retorna null se vazio if(clienteLocalName != null) { System.out.println("Pizzaiolo vai verificar se algum motoboy poderia levar a pizza do " + clienteLocalName); _jframe.jTextFieldConversaPizzaioloMotoboys.setText("Buscando motoboy para entregar ao "+clienteLocalName); _jframe.PassoDormir(); //busca por quem fornece o serviço, passando o nome do cliente ServiceDescription servicoDelivery = new ServiceDescription(); servicoDelivery.setType("Transporte"); DFAgentDescription dfd = new DFAgentDescription(); dfd.addServices(servicoDelivery); try { DFAgentDescription[] resultado = DFService.search(myAgent, dfd); if (resultado.length != 0) { //envia pedido para motoboy disponível que presta o serviço de transporte ACLMessage msg = new ACLMessage(ACLMessage.PROPOSE); msg.addReceiver(resultado[0].getName()); msg.setContent(clienteLocalName); //nome do cliente myAgent.send(msg); _jframe.jTextFieldConversaPizzaioloMotoboys.setText(resultado[0].getName() + " Podes levar?"); _jframe.PassoDormir(); //Finaliza comportamento // stop(); } else { String contentMsg = "Nenhum motoboy disponível para levar a pizza do " + clienteLocalName; System.out.println(contentMsg); _jframe.jTextFieldConversaPizzaioloMotoboys.setText(contentMsg); _jframe.PassoDormir(); } } catch(FIPAException e) { System.out.println(e.getMessage()); } } } }); //comportamneto para receber mensagens addBehaviour(new CyclicBehaviour(this) { public void action() { ACLMessage msg = myAgent.receive(); if(msg != null) { //se pizzaiolo receber mensagem da telefonista sara vai fazer a pizza if(msg.getSender().getLocalName().equals("telefonistaSara")) { //reponder telefonista ACLMessage reply = msg.createReply(); reply.setPerformative(ACLMessage.INFORM); String contentMsg = "Recebi o pedido do "+msg.getContent()+"! Obrigado."; reply.setContent(contentMsg); myAgent.send(reply); _jframe.jTextFieldPizzaioloRespondeTelefonista.setText(contentMsg); _jframe.PassoDormir(); System.out.println("A telefonista " + msg.getSender().getName() + " avisou pizzaiolo de um pedido, ele vai fazer a pizza"); System.out.println("Pizza do cliente " + msg.getContent() + " pronta!"); _clientesComPizzaPronta.add(msg.getContent()); } else if(msg.getSender().getLocalName().contains("motoboy")) { //String content = msg.getContent(); if(msg.getPerformative() == ACLMessage.ACCEPT_PROPOSAL) { _clientesComPizzaPronta.poll(); } } } else { //com o block() bloqueamos o comportamento até que uma nova mensagem //chegue ao agente e assim evitamos consumir ciclos da cpu. block(); } } }); }
7