text
stringlengths
14
410k
label
int32
0
9
private void checkFlush() { for (int i = 0; i < 4; i++) { if (getNumberOfSuits(i) == 5) { myEvaluation[0] = 6; myEvaluation[1] = hand[0].getValue(); myEvaluation[2] = hand[4].getValue(); myEvaluation[3] = hand[0].getValue(); break; } } }
2
private static void quickSort(ArrayList<PERange> array, int start, int end) { int i = start; // index of left-to-right scan int k = end; // index of right-to-left scan if (end - start >= 1) { PERange pivot = array.get(start); while (k > i) { while (array.get(i).getBegin() <= pivot.getBegin() && i <= end && k > i) { i++; } while (array.get(k).getBegin() > pivot.getBegin() && k >= start && k >= i) { k--; } if (k > i) { swap(array, i, k); } } swap(array, start, k); quickSort(array, start, k - 1); // quicksort the left partition quickSort(array, k + 1, end); // quicksort the right partition } // if there is only one element in the partition, do not do any sorting else { // the array is sorted, so exit return; } }
9
public static int getGreatesProdDownRightDiagonal(int[][] arr, int maxDigits, int columns, int rows) { int prod = 0; for(int i = 0; i < (rows-(maxDigits - 1)); i++) { int tmp = 0; for(int j = 0; j < (columns-(maxDigits-1)); j++) { int tmpprod = 1; for(int k = 0; k < maxDigits; k++) { tmpprod = tmpprod * arr[k+i][k+tmp]; // System.out.print(k+i + ", "); // System.out.print(k+tmp + ":"); // System.out.print(arr[k+i][k+tmp] + " "); } if(prod < tmpprod) prod = tmpprod; tmp++; // System.out.println(" "); } // System.out.println("_________________________"); } return prod; }
4
public static void removeLibrary(Class<?> libraryClass) throws SoundSystemException { if (libraries == null || libraryClass == null) return; libraries.remove(libraryClass); }
3
public static void main(String[] args) throws Exception { String filename = args[0].trim().equals("") ? "A.txt" : args[0]; Scanner inp = new Scanner(new java.io.File(filename)); System.out.println("Lecture de données :" + filename); init(inp); tour(); if (VERBOSE) { System.out.println("Trajet découvert :"); for (Tour opt : soln) { System.out.println(opt); } } if (soln.isEmpty()) { System.out.println("Aucun trajet"); } System.out.println(Tour.nTours + " objets Tour générés "); Collections.sort(soln); System.out.println("Meilleur trajet : "); System.out.println(soln.get(0)); }
4
public void replaceTransition(Transition oldTrans, Transition newTrans) { if (!getTransitionClass().isInstance(newTrans)) { throw new IncompatibleTransitionException(); } if (oldTrans.equals(newTrans)) { return; } if (transitions.contains(newTrans)) { removeTransition(oldTrans); return; } if (!transitions.remove(oldTrans)) { throw new IllegalArgumentException( "Replacing transition that not already in the automaton!"); } transitions.add(newTrans); List list = (List) transitionFromStateMap.get(oldTrans.getFromState()); list.set(list.indexOf(oldTrans), newTrans); list = (List) transitionToStateMap.get(oldTrans.getToState()); list.set(list.indexOf(oldTrans), newTrans); transitionArrayFromStateMap.remove(oldTrans.getFromState()); transitionArrayToStateMap.remove(oldTrans.getToState()); cachedTransitions = null; distributeTransitionEvent(new AutomataTransitionEvent(this, newTrans, true, false)); }
4
public void checkUp(Node node) { this.up = -1; // reset value to -1 // Prevent out of bounds (negative coordinates) if((node.getX()-1) >= 0) { if(checkWall(new Node( (node.getX()-1), (node.getY()) ))) { if(this.closedNodes.size()==0) this.up = 1; else { for(int i = 0; i < this.closedNodes.size(); i++) { // Check with closed nodes to differenciate explored or not if(new Node(node.getX()-1, node.getY()).compareTo(this.closedNodes.get(i))==1) { this.up = 2; // explored node break; } else this.up = 1; // empty } } } else { this.up = 0; // set 0 to specify as wall } } }
5
private void initializeTextFields() { mNameHeading = new JTextField(); mNameHeading.setBounds(478, 22, 491, 14); panel.add(mNameHeading); mNameHeading.setEnabled(false); mNameHeading.setForeground(new Color(0, 0, 0)); mNameHeading.setText("NAME"); mNameHeading.setToolTipText(""); mNameHeading.setEditable(false); mNameHeading.setBackground(new Color(245, 245, 220)); mNameHeading.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11)); mNameHeading.setColumns(10); mAddressHeading = new JTextField(); mAddressHeading.setBounds(478, 88, 491, 14); panel.add(mAddressHeading); mAddressHeading.setEnabled(false); mAddressHeading.setText("ADDRESS"); mAddressHeading .setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11)); mAddressHeading.setEditable(false); mAddressHeading.setColumns(10); mAddressHeading.setBackground(new Color(245, 245, 220)); mPhoneNumberHeading = new JTextField(); mPhoneNumberHeading.setBounds(478, 263, 491, 14); panel.add(mPhoneNumberHeading); mPhoneNumberHeading.setEnabled(false); mPhoneNumberHeading.setText("CONTACT INFO"); mPhoneNumberHeading.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11)); mPhoneNumberHeading.setEditable(false); mPhoneNumberHeading.setColumns(10); mPhoneNumberHeading.setBackground(new Color(245, 245, 220)); mSexHeading = new JTextField(); mSexHeading.setBounds(478, 336, 491, 14); panel.add(mSexHeading); mSexHeading.setEnabled(false); mSexHeading.setText("SEX"); mSexHeading.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11)); mSexHeading.setEditable(false); mSexHeading.setColumns(10); mSexHeading.setBackground(new Color(245, 245, 220)); mFirstNameTextField = new JTextField(); mFirstNameTextField.setBounds(589, 38, 237, 20); panel.add(mFirstNameTextField); mFirstNameTextField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { mContactController.progressbarStatus(); } }); mFirstNameTextField.setColumns(10); mFirstNameTextField.setDocument(new UIServices(20)); mLastNameTextField = new JTextField(); mLastNameTextField.setBounds(589, 63, 237, 20); panel.add(mLastNameTextField); mLastNameTextField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { mContactController.progressbarStatus(); } }); mLastNameTextField.setColumns(10); mLastNameTextField.setDocument(new UIServices(20)); mMiddleInitialLabel = new JLabel("MIDDLE INITIAL"); mMiddleInitialLabel.setBounds(836, 63, 93, 14); panel.add(mMiddleInitialLabel); mMiddleInitialTextField = new JTextField(); mMiddleInitialTextField.setBounds(931, 60, 28, 20); panel.add(mMiddleInitialTextField); mMiddleInitialTextField.setColumns(10); mMiddleInitialTextField.setDocument(new UIServices(1)); mAddressLine1TextField = new JTextField(); mAddressLine1TextField.setBounds(589, 113, 380, 20); panel.add(mAddressLine1TextField); mAddressLine1TextField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { mContactController.progressbarStatus(); } }); mAddressLine1TextField.setColumns(10); mAddressLine1TextField.setDocument(new UIServices(35)); mAddressLine2TextField = new JTextField(); mAddressLine2TextField.setBounds(589, 138, 380, 20); panel.add(mAddressLine2TextField); mAddressLine2TextField.setColumns(10); mAddressLine2TextField.setDocument(new UIServices(35)); mCityTextField = new JTextField(); mCityTextField.setBounds(589, 163, 153, 20); panel.add(mCityTextField); mCityTextField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { mContactController.progressbarStatus(); } }); mCityTextField.setColumns(10); mCityTextField.setDocument(new UIServices(25)); mStateTextField = new JTextField(); mStateTextField.setBounds(589, 188, 56, 20); panel.add(mStateTextField); mStateTextField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { mContactController.progressbarStatus(); } }); mStateTextField.setColumns(10); mStateTextField.setDocument(new UIServices(2)); mZipCodeTextField = new JTextField(); mZipCodeTextField.setBounds(589, 213, 153, 20); panel.add(mZipCodeTextField); mZipCodeTextField.setDocument(new UIServices(9)); mZipCodeTextField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { mContactController.progressbarStatus(); char c = e.getKeyChar(); if (!Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)) e.consume(); } }); mZipCodeTextField.setColumns(10); mCountryTextField = new JTextField(); mCountryTextField.setBounds(589, 238, 153, 20); panel.add(mCountryTextField); mCountryTextField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { mContactController.progressbarStatus(); char c = e.getKeyChar(); if (Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)) e.consume(); } }); mCountryTextField.setColumns(10); mCountryTextField.setDocument(new UIServices(30)); mPhoneNumberTextField = new JTextField(); mPhoneNumberTextField.setBounds(589, 282, 153, 20); panel.add(mPhoneNumberTextField); mPhoneNumberTextField.setDocument(new UIServices(10)); mPhoneNumberTextField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { mContactController.progressbarStatus(); char c = e.getKeyChar(); if (!Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)) e.consume(); } }); mPhoneNumberTextField.setColumns(10); mEmailAddressTextField = new JTextField(); mEmailAddressTextField.setBounds(589, 310, 176, 20); panel.add(mEmailAddressTextField); mEmailAddressTextField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { mContactController.progressbarStatus(); } }); mEmailAddressTextField.setColumns(10); mEmailAddressTextField.setDocument(new UIServices1(100)); }
9
public static void drawObjects(Graphics g){ if (left) xs -= 1; else if (right) xs += 1; if (up) ys -= 1; else if (down) ys += 1; if (drag){ checkMouse(); } g.setColor(PlatformManager.floorColor); // draw dynamic objects for (Rectangle p : platforms) g.fillRect(p.x - xs, p.y - ys, p.width, p.height); for (Entity e : entities) g.drawImage(LivingEntityManager.enemySprites.get(e.getType()).get(e.aniFrame), e.getX() - xs, e.getY() - ys, null); g.drawImage(CharacterManager.boyStandFront, character.x - xs, character.y - ys, null); // draw static objects (spawns) g.fillRect(platformSpawn.x, platformSpawn.y, platformSpawn.width, platformSpawn.height); for (EntitySpawn es : EntitySpawn.spawns) g.drawImage(LivingEntityManager.enemySprites.get(es.getEntity().getType()).get(0), es.getX(), es.getY(), null); g.setColor(Color.WHITE); g.drawRect(hotbar.x, hotbar.y, hotbar.width, hotbar.height); }
8
@Override protected void decode( ChannelHandlerContext ctx, ByteBuf in, List<Object> out ) throws Exception { int byteSize = in.readableBytes(); if(byteSize == 0 || !ctx.channel().isOpen()) return; int id = Utils.readVarInt(in); int conState = ctx.channel().attr(Utils.connectionState).get(); switch(conState) { case 1: // Status switch(id) { case 0: // Status MCListener.logger.info(String.format("%s pinged the server using MC 1.7", Utils.getAddressString(ctx.channel().remoteAddress()))); send(ctx, writeStatusPacket()); break; case 1: // Ping send(ctx, writePongPacket(in.readLong())); break; } break; case 2: // Login MCListener.logger.info(String.format("%s connected using MC 1.7", Utils.getAddressString(ctx.channel().remoteAddress()))); disconnect(ctx, MCListener.kickMessage); break; } }
6
public static void CDC_pairwise(CDCRelation p, boolean connected) { int count=0; //int[] c = new int[511]; //counters int i,j; //first we calculate all the valid CDC relations, stored in valid_rel[] List<CDCRelation> valid_rel = new ArrayList<CDCRelation>(); CDCRelation r = new CDCRelation(0); r.connected=connected; for (i=1;i<=511;i++) { r = new CDCRelation(i); //TODO compare this with r.set(i); if (!connected || r.valid()) valid_rel.add(r); } //now we check the consistency of each pair of basic CDC relations CDCNetwork n = new CDCNetwork(); n.resize(2); n.connected=connected; n.setConstraint(0,0,new CDCRelation("O".toCharArray())); n.setConstraint(1,1,new CDCRelation("O".toCharArray())); n.setConstraint(0,1,p); for (j=0;j<valid_rel.size();j++) { n.setConstraint(1,0,valid_rel.get(j)); if (n.consistent()) { count++; System.out.println(j); } } if (connected) System.out.print("for connected case, "); else System.out.print("for possibly disconnected case, "); System.out.format("there are total %d consistent pairwise relation.\n", count); }
6
public static boolean export2FormatedJsonFiles(final String date, final String[] labels, final String[] labelsStat, final String text){ //Check if skip creating file if( labels.length == 0 && (text == null || text.trim().length() == 0) ){ return true; } final String checked = recursosTexto.getString("txtFileChecked"); final String missed = recursosTexto.getString("txtFileMissed"); final java.io.BufferedWriter bfw; final java.io.FileWriter fw; try{ fw = new java.io.FileWriter(date+".txt"); bfw = new java.io.BufferedWriter( fw ); String jsonStr = ""; String id = ""; String activities = ""; String notes = ""; id = date; activities = "[ "; if( labels.length == labelsStat.length ){ for (int i = 0; i < labels.length; i++) { if( labels[i] != null ){ //bfw.write(labels[i] + ": " + ( Integer.valueOf(labelsStat[i]) > 0 ? checked : missed) ); activities += " { \"type\" : \"checkbox\", \"name\" : \"" + labels[i] + "\", \"value\" : \"" + ( Integer.valueOf(labelsStat[i]) > 0 ? "true" : "false") + "\" },"; } } } activities = activities.substring( 0, activities.length()-1); //remove las ',' activities += " ]"; //bfw.write(text); notes = text; jsonStr = "{ \"_id\" : \"" + id + "\", \"activities\" : " + activities + ", \"notes\" : \"" + text + "\" }"; System.out.println(jsonStr); bfw.write(jsonStr); bfw.close(); }catch(IOException ioe){ System.out.println("IOException message when closing file: " + ioe.getMessage() ); javax.swing.JOptionPane.showMessageDialog(null, ioe.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE); return false; } System.out.println(""); return true; }
8
public static long convertToLong(String addr) throws Exception { String[] octs = addr.split("\\."); if( octs.length != 4 ){ throw new Exception("Invalid address format."); } long octA = Long.parseLong(octs[0]); long octB = Long.parseLong(octs[1]); long octC = Long.parseLong(octs[2]); long octD = Long.parseLong(octs[3]); if( octA < 0 || 255 < octA ){ throw new Exception("Invalid octet on 1st section."); } if( octB < 0 || 255 < octB ){ throw new Exception("Invalid octet on 2nd section."); } if( octC < 0 || 255 < octC ){ throw new Exception("Invalid octet on 3rd section."); } if( octD < 0 || 255 < octD ){ throw new Exception("Invalid octet on 4th section."); } return (octA<<24) | (octB<<16) | (octC<<8) | octD; }
9
public void expand() { computedIntervals++; Interval interval = q.poll(); double a = interval.a; double b = interval.b; double mid = (a + b) / 2; Interval interval1 = new Interval( a, mid, p, usedFormula ); Interval interval2 = new Interval( mid, b, p, usedFormula ); if ( (!interval1.singularityCase() || !interval2.singularityCase()) && Double.isInfinite(globalError)) globalError = 0.; if (!interval1.singularityCase() ){ integral += interval1.integral; globalError += interval1.error; } if (!interval2.singularityCase()){ integral += interval2.integral; globalError += interval2.error; } if (!interval.singularityCase()){ integral -= interval.integral; globalError -= interval.error; } this.q.add(interval1); this.q.add(interval2); }
6
public int getEnemiesLasersOnField(){ int enemyLaserCount = 0; for(Enemy enemy : munchkins){ if(enemy != null){ for(int i = 0; i < enemy.lasers.length; i++){ if(enemy.lasers[i] != null){ enemyLaserCount++; } } } } for(Enemy enemy : ufos){ if(enemy != null){ for(int i = 0; i < enemy.lasers.length; i++){ if(enemy.lasers[i] != null){ enemyLaserCount++; } } } } return enemyLaserCount; }
8
public void limpiarBD() { Query personas = actualizador.verificarConexion().createQuery("Select persona from Persona persona"); List<Persona> idsPersona = personas.getResultList(); for (Persona persona : idsPersona) { actualizador.bajaDePersona(persona.getCi()); } Query vehiculos = actualizador.verificarConexion().createQuery("Select vehiculo from Vehiculo vehiculo"); List<Vehiculo> idsVehiculo = vehiculos.getResultList(); for (Vehiculo vehiculo : idsVehiculo) { actualizador.bajaDeVehiculo(vehiculo.getMatricula()); } Query tipomoto = actualizador.verificarConexion().createQuery("Select tipomoto from TipoMoto tipomoto"); List<TipoMoto> idsTipoMoto = tipomoto.getResultList(); for (TipoMoto tipoMoto : idsTipoMoto) { actualizador.eliminarTipoMoto(tipoMoto.getId()); } Query departamentosID = actualizador.verificarConexion().createQuery("Select departamento from Departamento departamento"); List<Departamento> ids = departamentosID.getResultList(); for (Departamento departamento : ids) { actualizador.eliminarDepartamento(departamento.getId()); } }
4
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ParkBoy other = (ParkBoy) obj; if (code == null) { if (other.code != null) return false; } else if (!code.equals(other.code)) return false; return true; }
6
private int jjMoveStringLiteralDfa1_0(long active0) { try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(0, active0); return 1; } switch(curChar) { case 32: return jjMoveStringLiteralDfa2_0(active0, 0x40L); case 104: return jjMoveStringLiteralDfa2_0(active0, 0x500L); case 115: if ((active0 & 0x200L) != 0L) return jjStartNfaWithStates_0(1, 9, 4); break; case 118: return jjMoveStringLiteralDfa2_0(active0, 0x80L); default : break; } return jjStartNfa_0(0, active0); }
6
public static void fillIslands() { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { Index index = new Index(i, j); stack.push(index); String tempPath = ""; int tempWeight = 0; while (!stack.isEmpty()) { index = stack.pop(); if (islands[index.getRow()][index.getCol()] > 0) { tempPath = tempPath + "[" + index.getRow() + "][" + index.getCol() + "]"; tempWeight = tempWeight + islands[index.getRow()][index.getCol()]; if (index.getRow() + 1 < 4) { stack.push(new Index(index.getRow() + 1, index .getCol())); } if (index.getCol() + 1 < 4) { stack.push(new Index(index.getRow(), index.getCol() + 1)); } } } System.out.println("Path : " + tempPath + " Temp Wight :" + tempWeight); if (weight == 0 || tempWeight > weight) { path = tempPath; weight = tempWeight; } } } }
8
private void populateCyrillicComboBoxes() { DefaultComboBoxModel cyrillicCapitalLetterComboBoxModel = new DefaultComboBoxModel(); // Add the standard Cyrillic (Russian) characters to the combo for (int i = 0x0410; i < 0x042F; i++ ) { char a = (char) i; cyrillicCapitalLetterComboBoxModel.addElement(a); } // Build a list of less used characters (Ukrainian etc) char [] otherCyrillicCaps = { 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, 0x0409, 0x040A, 0x040B, 0x040C, 0x040E, 0x040F, 0x0490 }; // Add these to the combo for (char c : otherCyrillicCaps) { cyrillicCapitalLetterComboBoxModel.addElement(c); } // Set the model for the capital letters cyrillicCapitalLetterComboBox.setModel(cyrillicCapitalLetterComboBoxModel); DefaultComboBoxModel cyrillicSmallLetterComboBoxModel = new DefaultComboBoxModel(); for (int i = 0; i < cyrillicCapitalLetterComboBoxModel.getSize(); i++) { char a = (char) cyrillicCapitalLetterComboBoxModel.getElementAt(i); cyrillicSmallLetterComboBoxModel.addElement(Character.toLowerCase(a)); } cyrillicSmallLetterComboBox.setModel(cyrillicSmallLetterComboBoxModel); }
3
TranslationFinder(Elements subSectionTitles, Document document) { Elements transArray = document.getElementsByAttributeValueContaining("data-destinationLanguage", "אנגלית"); this.JSONTransArray = new JSONArray(); for (Element translation : transArray) { this.JSONTransArray.put(translation.text().toLowerCase()); } if (this.JSONTransArray.length() != 0) { return; } for (Element h3 : subSectionTitles) { if (h3.text().equals("תרגום") == true) { Element translation = h3.nextElementSibling(); Element englishEntry = null; if (translation == null) { // System.out.println("No translation for " + article.getTitle()); return; } for (Element li : translation.getElementsByTag("li")) { if (li.text().contains("אנגלית") == true) { englishEntry = li; break; } } if (englishEntry == null) { return; } String englishEntryText = englishEntry.text(); englishEntryText = englishEntryText.replaceAll("אנגלית:", ""); englishEntryText = englishEntryText.replaceAll(" ", ""); String[] strTransArray = englishEntryText.split("\\|"); for (String s : strTransArray) { s = s.toLowerCase(); } JSONTransArray = new JSONArray(strTransArray); } } // Uncomment to find problems //if (document.toString().contains("אנגלית") && !found()) { // System.out.println("This may be a problem"); //} }
9
public float setBand(int band, float neweq) { float eq = 0.0f; if ((band>=0) && (band<BANDS)) { eq = settings[band]; settings[band] = limit(neweq); } return eq; }
2
private void init() { JPanel content = new JPanel(); content.setLayout(new BorderLayout()); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BorderLayout()); JPanel spacerPanel = new JPanel(); spacerPanel.setLayout(new GridLayout()); if (m_allowAdd) { JButton addButton = new JButton("Add Key"); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String inputValue = JOptionPane .showInputDialog("What is the key you want to add?"); if (inputValue != null) { if (inputValue.trim().length() > 0) { m_props.setProperty(inputValue, ""); // redraw the table if (m_model != null) { m_model.fireTableDataChanged(); } } } } }); spacerPanel.add(addButton); } JButton closeButton = new JButton("Close"); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doExit(); } }); spacerPanel.add(closeButton); buttonPanel.add(spacerPanel, BorderLayout.EAST); content.add(buttonPanel, BorderLayout.SOUTH); m_model = new PairTableModel(); JTable tbl = new JTable(m_model); content.add(new JScrollPane(tbl), BorderLayout.CENTER); tbl.getColumnModel().getColumn(1).setPreferredWidth(5); setContentPane(content); // Dispose of the main app window when it gets closed. addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { doExit(); } }); }
4
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Map other = (Map) obj; if (this.noOfRows != other.noOfRows) { return false; } if (this.noOfColumns != other.noOfColumns) { return false; } return true; }
4
@Override public QuadTree getQuadTree(){ if (QT == null) { initDataStructure(); } return QT; }
1
private void randomizeBackground(Background background) { int j = 256; for(int k = 0; k < anIntArray1190.length; k++) anIntArray1190[k] = 0; for(int l = 0; l < 5000; l++) { int i1 = (int)(Math.random() * 128D * (double)j); anIntArray1190[i1] = (int)(Math.random() * 256D); } for(int j1 = 0; j1 < 20; j1++) { for(int k1 = 1; k1 < j - 1; k1++) { for(int i2 = 1; i2 < 127; i2++) { int k2 = i2 + (k1 << 7); anIntArray1191[k2] = (anIntArray1190[k2 - 1] + anIntArray1190[k2 + 1] + anIntArray1190[k2 - 128] + anIntArray1190[k2 + 128]) / 4; } } int ai[] = anIntArray1190; anIntArray1190 = anIntArray1191; anIntArray1191 = ai; } if(background != null) { int l1 = 0; for(int j2 = 0; j2 < background.anInt1453; j2++) { for(int l2 = 0; l2 < background.anInt1452; l2++) if(background.aByteArray1450[l1++] != 0) { int i3 = l2 + 16 + background.anInt1454; int j3 = j2 + 16 + background.anInt1455; int k3 = i3 + (j3 << 7); anIntArray1190[k3] = 0; } } } }
9
protected static Ptg calcCount( Ptg[] operands ) { int count = 0; for( Ptg operand : operands ) { Ptg[] pref = operand.getComponents(); // optimized -- do it once!! -jm if( pref != null ) { // it is some sort of range for( Ptg aPref : pref ) { Object o = aPref.getValue(); if( o != null ) { try { Double n = new Double( String.valueOf( o ) ); count++; } catch( NumberFormatException e ) { } } } } else { // it's a single ptgref Object o = operand.getValue(); if( o != null ) { try { Double n = new Double( String.valueOf( o ) ); count++; } catch( NumberFormatException e ) { } ; } } } PtgInt pint = new PtgInt( count ); return pint; }
7
public void testFilteredDocIdSet() throws Exception { final int maxdoc=10; final DocIdSet innerSet = new DocIdSet() { @Override public DocIdSetIterator iterator() { return new DocIdSetIterator() { int docid = -1; @Override public int docID() { return docid; } @Override public int nextDoc() throws IOException { docid++; return docid < maxdoc ? docid : (docid = NO_MORE_DOCS); } @Override public int advance(int target) throws IOException { while (nextDoc() < target) {} return docid; } }; } }; DocIdSet filteredSet = new FilteredDocIdSet(innerSet){ @Override protected boolean match(int docid) { return docid%2 == 0; //validate only even docids } }; DocIdSetIterator iter = filteredSet.iterator(); ArrayList/*<Integer>*/ list = new ArrayList/*<Integer>*/(); int doc = iter.advance(3); if (doc != DocIdSetIterator.NO_MORE_DOCS) { list.add(Integer.valueOf(doc)); while((doc = iter.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { list.add(Integer.valueOf(doc)); } } int[] docs = new int[list.size()]; int c=0; Iterator/*<Integer>*/ intIter = list.iterator(); while(intIter.hasNext()) { docs[c++] = ((Integer) intIter.next()).intValue(); } int[] answer = new int[]{4,6,8}; boolean same = Arrays.equals(answer, docs); if (!same) { System.out.println("answer: "+_TestUtil.arrayToString(answer)); System.out.println("gotten: "+_TestUtil.arrayToString(docs)); fail(); } }
6
public static Homework_database read(int value) { Homework_database homeworkreturn = null; { try { RandomAccessFile raf = new RandomAccessFile(login_area.setURL.getUrl(), "rw"); raf.seek(raf.length()); raf.seek(538*value); Timetable_main_EDIT.delete = raf.read(); raf.seek(raf.length()); raf.seek(538*value); raflength = (((int) raf.length())/538); Timetable_main_EDIT.ID = raf.readInt(); Timetable_main_EDIT.subject = raf.readUTF(); Timetable_main_EDIT.desc = raf.readUTF(); Timetable_main_EDIT.diff = raf.readUTF(); Timetable_main_EDIT.time = raf.read(); Timetable_main_EDIT.delete = raf.read(); removespaces(); raflength = (((int) raf.length())/538); } catch (EOFException ex) { //This exception will be caught when EOF is reached // JOptionPane.showMessageDialog(null,"No more homeworks left! :)", "Timetable Management Program", JOptionPane.INFORMATION_MESSAGE); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return homeworkreturn; }
3
private static String getArrayTableName(String tableName, String field) { return tableName + "_" + field; }
0
public void testPropertyPlusNoWrapHour() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.hourOfDay().addNoWrapToCopy(9); check(test, 10, 20, 30, 40); check(copy, 19, 20, 30, 40); copy = test.hourOfDay().addNoWrapToCopy(0); check(copy, 10, 20, 30, 40); copy = test.hourOfDay().addNoWrapToCopy(13); check(copy, 23, 20, 30, 40); try { test.hourOfDay().addNoWrapToCopy(14); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); copy = test.hourOfDay().addNoWrapToCopy(-10); check(copy, 0, 20, 30, 40); try { test.hourOfDay().addNoWrapToCopy(-11); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20, 30, 40); }
2
@Override public <T extends Comparable<? super T>> int search(T[] array, T key) { if (array == null) throw new NullPointerException("argument array is null"); if (key == null) throw new NullPointerException("argument key is null"); // Make sure every element is not null. for (T elem: array) { if (elem == null) throw new NullPointerException("All elements must not be null"); } // Make sure the array is sorted. if (!Util.isSorted(array)) throw new IllegalArgumentException(getClass().getSimpleName() + " argument array is not sorted"); int lo = 0; int hi = array.length - 1; while (lo <= hi) { // Key is in a[lo..hi] or not present. int mid = lo + (hi - lo) / 2; if (key.compareTo(array[mid]) < 0) hi = mid - 1; else if (key.compareTo(array[mid]) > 0) // NOTE adds lo = mid + 1; instead of lo = mid + 2. lo = mid + 2; else return mid; } return -1; }
9
public void resize() { int image[] = new int[trimWidth * trimHeight]; for (int offY = 0; offY < height; offY++) { for (int offX = 0; offX < width; offX++) { image[(offY + offsetY) * trimWidth + (offX + offsetX)] = pixels[offY * width + offX]; } } pixels = image; width = trimWidth; height = trimHeight; offsetX = 0; offsetY = 0; }
2
public void save(String filename) { File file = new File(filename); String suffix = filename.substring(filename.lastIndexOf('.') + 1); // png files if (suffix.toLowerCase().equals("png")) { try { ImageIO.write(offscreenImage, suffix, file); } catch (IOException e) { e.printStackTrace(); } } // need to change from ARGB to RGB for jpeg // reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727 else if (suffix.toLowerCase().equals("jpg")) { WritableRaster raster = offscreenImage.getRaster(); WritableRaster newRaster; newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2}); DirectColorModel cm = (DirectColorModel) offscreenImage.getColorModel(); DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(), cm.getBlueMask()); BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null); try { ImageIO.write(rgbBuffer, suffix, file); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Invalid image file type: " + suffix); } }
4
@Override protected void process(List<RegistrationState> l) { for (RegistrationState ls : l) { if (ls.isSuccess) { this.cp.setVisible(false); JOptionPane.showMessageDialog(cp, "Username successfully registered", "Success", JOptionPane.INFORMATION_MESSAGE, null); this.cp.mf.cancelRegistration(); return; } this.cp.loadCaptchaImage(ls.p); } }
2
public SwingWorker() { final Runnable doFinished = new Runnable() { public void run() { finished(); } }; Runnable doConstruct = new Runnable() { public void run() { try { setValue(construct()); } catch (Exception e) { setException(e); } finally { threadVar.clear(); } SwingUtilities.invokeLater(doFinished); } }; Thread t = new Thread(doConstruct); threadVar = new ThreadVar(t); }
1
public void setFloors(int value) { if (value <= 0) { throw new IllegalArgumentException( "Illegal number of floors, must be positive"); } else { floors = value; weight = calculateTotalWeight(); } }
1
public void update(double delta) { frameCount++; if(frameCount >= program.framerate) { secondFlash = !secondFlash; frameCount = 0; } //Camera Zoom canvas.camera.zoom(Input.getMouseScroll() / 10.0); if(canvas.camera.getScale() < maxZoom) canvas.camera.setScale(maxZoom); if(canvas.camera.getScale() > minZoom) canvas.camera.setScale(minZoom); //Camera movement if(Input.getMouse(Input.MOUSE_MIDDLE)) { Point p = Input.getMousePosition(); int x = p.x - mouseLastPosition.x; int y = p.y - mouseLastPosition.y; canvas.camera.translate(x, y); } //Cycle between people if(Input.getKeyDown(KeyEvent.VK_C)) { cameraCyclePeople(); } //Debug Mode program.stats.setEnabled(Input.getKey(KeyEvent.VK_F3)); for(Person person : people) person.update(delta); village.update(delta); if(System.nanoTime() - tickStart >= tickRate * 1e9) { tickStart = System.nanoTime(); tick(); } mouseLastPosition = Input.getMousePosition(); }
7
public static void main(String[] args) { // Exercício 03 Scanner entrada = new Scanner(System.in); // Esse é o Sacanner que captura dados do teclado. Para utilizá-lo é preciso importar a classe java.util.Scanner System.out.println("Digite um número: "); // Perguntamos um número...o programa vai esperar até o usuário digitar alguma coisa. int dia_da_semana = entrada.nextInt(); // Aqui que o Scanner que criamos acima efetua a captura do teclado e atribui seu valor a variavel dia_da_semana. switch(dia_da_semana){ case 1: System.out.println("Domingo"); break; case 2: System.out.println("Segunda"); break; case 3: System.out.println("Terça"); break; case 4: System.out.println("Quarta"); break; case 5: System.out.println("Quinta"); break; case 6: System.out.println("Sexta"); break; case 7: System.out.println("Sábado"); break; default: System.out.println("É necessário digitar um número."); entrada.close(); } }
7
public boolean canUpdate(long isbn, Book b, Statement st, ResultSet rs) throws SQLException { //Check if any authors will be left without a book. ArrayList<Author> leftAuth = getAuthors(isbn, st, rs); if(b.getAuthor() != null) leftAuth.removeAll(b.getAuthor()); //Test if any authors that are left out are only related to this book for(Author a: leftAuth) { rs = st.executeQuery("SELECT * FROM HasAuthor WHERE name = '" + a.getName() + "'"); rs.next(); if(!rs.next()) return false; } //Check if any publishers will be left without a book. ArrayList<Publisher> leftPub = getPublishers(isbn, st, rs); if(b.getPublisher() != null) leftPub.removeAll(b.getPublisher()); //Test if any publishers that are left out are only related to this book for(Publisher p: leftPub) { rs = st.executeQuery("SELECT * FROM HasPublisher WHERE name = '" + p.getName() + "'"); rs.next(); if(!rs.next()) return false; } return true; }
6
public boolean remove_special(String s,String p,String o,String s_type,String o_type) { String ret; deb_print("<remove_special>\n"); deb_print("Perform the QUERY\n"); ret = queryRDF( s.equals("*")?null:s ,p.equals("*")?null:p ,o.equals("*")?null:o ,s_type ,o_type); deb_print("KP-CORE MESSAGE:"+getErrMess()+"("+getErrID()+")\n"); deb_print("RDFQuery confirmed:"+(this.xmlTools.isQueryConfirmed(ret)?"YES":"NO")+"\n"); deb_print("*** SSAP message status:"+xmlTools.getSSAPmsgStatus(ret)+"\n"); if(!this.xmlTools.isQueryConfirmed(ret))return false; //"*** QUERY NOT CONFIRMED"; Vector<Vector<String>> triples = null; if(ret!=null) triples = this.xmlTools.getQueryTriple(ret); if(triples!=null) { deb_print("Triple to remove:\n"); for(int i=0; i<triples.size() ; i++ ) { Vector<String> t=triples.get(i); String st= " S:["+t.get(0) +"] P:["+t.get(1) +"] O:["+t.get(2) +"] Otype:["+t.get(3)+"]"; deb_print(st+"\n"); /*-----------------------------------------------------------------------------*/ /*------REMOVE-----------------------------------------------------------*/ ret = remove( t.get(0) ,t.get(1) ,t.get(2) ,"uri" ,t.get(3) ); deb_print("KP-CORE MESSAGE:"+getErrMess()+"("+getErrID()+")\n"); deb_print("*** SSAP message status:"+xmlTools.getSSAPmsgStatus(ret)+"\n"); /*-----------------------------------------------------------------------------*/ }//for(int j=0; i<triple.size() ; i++ ) } deb_print("</remove_special>\n"); return true; //"ALL DONE"; }//public String remove(String s,String p,String o,String s_type,String o_type)
8
public static LinkedList<File[]> recursiveConfigs(File folder, boolean rec) { LinkedList<File[]> files = new LinkedList<File[]>(); if(folder.exists() && folder.isDirectory()) { for(File f : folder.listFiles()){ if(f.isFile()){ if(f.getName().endsWith(".pc")) { files.add(new File[]{f}); } } else if(f.isDirectory() && !f.getName().equals(".") && !f.getName().equals("..") && rec) { files.addAll(recursiveConfigs(f, true)); } } } return files; }
9
private static int[] getNeighbours(ImageData imageData, int mx, int my, int y, int x) { int x0 = x - 1; int y0 = y - 1; int x2 = x + 1; int y2 = y + 1; x0 = x0 < 0 ? 0 : x0; x2 = x2 > mx ? mx : x2; y0 = y0 < 0 ? 0 : y0; y2 = y2 > my ? my : y2; int[] pixels = new int[9]; pixels[0] = imageData.getPixel(x0, y0); pixels[1] = imageData.getPixel(x, y0); pixels[2] = imageData.getPixel(x2, y0); pixels[3] = imageData.getPixel(x0, y); pixels[4] = imageData.getPixel(x, y); pixels[5] = imageData.getPixel(x2, y); pixels[6] = imageData.getPixel(x0, y2); pixels[7] = imageData.getPixel(x, y2); pixels[8] = imageData.getPixel(x0, y2); return pixels; }
4
public void simulate() throws IOException{ System.out.format("### %s ###\n",heuristic.type.toString()); boolean moreLinesToRead = true; if (debug_f) print_debug_header(); while (true) { commit(); issue(); moreLinesToRead = fetch_and_rename(); currCycle = currCycle + 1; decrementScoreboard(); if (totalUops >= uopLimit) { System.out.format("Reached insn limit of %d @ cycle %d. Ending Simulation...\n", uopLimit, currCycle); break; } else if (!moreLinesToRead && ROB.isEmpty()) { System.out.format("Reached to the end of trace totalUops %d @ cycle %d. Ending Simulation...\n", totalUops, currCycle); break; } } endStats(); if (printStats_f) printProgramStats();//print the program stats to help debugging System.out.format("##############################\n"); }
6
protected Color getNodeColor(TreeNode node) { return isSelected(node) ? selectedColor : deselectedColor; // Color color = super.getNodeColor(node); // return isSelected(node) ? color.darker() : color; }
1
@RequestMapping(value = "/sign_in") public String custVerification(Model m,HttpServletRequest request, HttpServletResponse response,HttpSession session) { String username = request.getParameter("custID"); System.out.println("Customer user name : "+username); String password = request.getParameter("password"); //verify if customer exists already in database String result = custDao.verifyCust(username,password); if(result.equals("user does not exist")) { System.out.println("Prompt customer to sign up"); return "home"; }else if(result.equals("user exist")) { System.out.println("Sign In succsessful"); session.setAttribute("cust_signedin", username); return "home"; } else if(result.equals("invalid password")) { System.out.println("password invalid"); } return "home"; }
3
public boolean isSolid(float x, float y) { if (x < 0 || x / tileSize >= width || y < 0 || y / tileSize >= height) return false; return getTileSolid(tiles[(int) (x / tileSize) + (int) (y / tileSize) * width]); }
4
boolean anyResultMatches(String transcriptId, Variant seqChange, ChangeEffects changeEffects, boolean useShort) { for (ChangeEffect chEff : changeEffects) { String resStr = chEff.toStringSimple(useShort); Transcript tr = chEff.getTranscript(); if (tr != null) { if ((transcriptId == null) || (transcriptId.equals(tr.getId()))) { if (resStr.indexOf(seqChange.getId()) >= 0) return true; // Matches one result in this transcript } } else if (resStr.indexOf(seqChange.getId()) >= 0) return true; // Matches any result (out of a transcript) } return false; }
6
public static void main (String args[]) { Map<String, String> map = new HashMap(); fillData(map); String[] strings = keysAsArray(map); for (String string : strings) { System.out.println(string); } System.out.println(""); List<String> list = keysAsList(map); for (String string : list) { System.out.println(string); } }
2
public void render(Graphics2D g2d) { g2d.drawImage(image, (int) x, (int) y, null); if (x < 0) g2d.drawImage(image, (int) x + Game.WIDTH, (int) y, null); else if (x > 0) g2d.drawImage(image, (int) x - Game.WIDTH, (int) y, null); }
2
@Override public void doAction(String value) { char choice = value.toUpperCase().charAt(0); do { switch (choice) { case 'M': return; case 'D': System.out.println("You are not carrying any logs"); break; case 'B': System.out.println("This function needs to check if \nthey have enough logs and build a fire\n if not, they need to go get more logs."); break; case 'I': System.out.println("This function needs to display inventory"); break; default: System.out.println("Invalid selection"); } //display(); choice = getInput().toUpperCase().charAt(0); } while (true); }
5
public int run(){ sort(array); return 0; }
0
public static void makeCompactGrid(Container parent, int rows, int cols, int initialX, int initialY, int xPad, int yPad) { SpringLayout layout; try { layout = (SpringLayout)parent.getLayout(); } catch (ClassCastException exc) { System.err.println("The first argument to makeCompactGrid must use SpringLayout."); return; } //Align all cells in each column and make them the same width. Spring x = Spring.constant(initialX); for (int c = 0; c < cols; c++) { Spring width = Spring.constant(0); for (int r = 0; r < rows; r++) { width = Spring.max(width, getConstraintsForCell(r, c, parent, cols). getWidth()); } for (int r = 0; r < rows; r++) { SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); constraints.setX(x); constraints.setWidth(width); } x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad))); } //Align all cells in each row and make them the same height. Spring y = Spring.constant(initialY); for (int r = 0; r < rows; r++) { Spring height = Spring.constant(0); for (int c = 0; c < cols; c++) { height = Spring.max(height, getConstraintsForCell(r, c, parent, cols). getHeight()); } for (int c = 0; c < cols; c++) { SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); constraints.setY(y); constraints.setHeight(height); } y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad))); } //Set the parent's size. SpringLayout.Constraints pCons = layout.getConstraints(parent); pCons.setConstraint(SpringLayout.SOUTH, y); pCons.setConstraint(SpringLayout.EAST, x); }
7
public static void main(String[] args) { if(args.length >= 1) { try { int servers = Integer.parseInt(args[0]); String mIP = (args.length >= 2) ? args[1] : "239.23.12.11"; InetAddress address = InetAddress.getByName(mIP); int basePort = (args.length >= 3) ? Integer.parseInt(args[2]) : 4049; int serverPort = 10000; for(int i = 0; i < servers; i++) { try { BasicServer server = new StatisticsServer(address, basePort, serverPort + i); Thread serverRunner = new Thread(server); serverRunner.start(); System.out.println("Started server " + server.getId()); } catch(IOException ioe) { System.err.println("Failed to start server " + (serverPort+i) + ". " + ioe.getMessage()); } } } catch(IOException ioe) { System.err.println("Invalid multicast IP"); } catch(NumberFormatException nfe) { System.err.println("Invalid port number"); } } else { System.out.println("Usage: java -cp build\\classes agent.rps.ServerRunner <numservers> [<multicast ip> <multicast port>]"); } }
7
public ArrayList<Integer> checkCollisions() { ArrayList<Integer> ints = new ArrayList<Integer>(); for (Rectangle r : getGame().getCollisionRecs()) { if (new Rectangle((int) (getBounds().x + 10 - getVeloX()), getBounds().y + 14, getBounds().width - 20, getBounds().height - 14).intersects(r)) ints.add(1); if (new Rectangle(getBounds().x + 10, (int) (getBounds().y + 10 - getVeloY()), getBounds().width - 20, getBounds().height - 14).intersects(r)) ints.add(3); if (new Rectangle(getBounds().x + 10, (int) (getBounds().y + 14 - getVeloY()), getBounds().width - 20, getBounds().height - 14).intersects(r)) { ints.add(4); } } return ints; }
4
public void setVar(PVar node) { if(this._var_ != null) { this._var_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._var_ = node; }
3
public static long[] calculatePalette(long[] colors, int numBuckets) { ArrayList<Bucket> buckets = new ArrayList<>(); Bucket initialBucket = new Bucket(); for (long color : colors) initialBucket.add(color); buckets.add(initialBucket); while (buckets.size() < numBuckets) { int maxI = -1; int maxDiff = Integer.MIN_VALUE; for (int i = 0; i < buckets.size(); i++) { int diff = buckets.get(i).getMaxDiff(); if (diff > maxDiff) { maxDiff = diff; maxI = i; } } if (maxDiff <= 0) break; buckets.add(buckets.get(maxI).split()); } long[] palette = new long[buckets.size()]; for (int i = 0; i < buckets.size(); i++) palette[i] = buckets.get(i).getAvgColor(); return palette; }
6
public void showCards() { playercards = GameData.CURRENT_PLAYER.getPlayerCards(); for (int i = 0; i < playercards.size(); i++) { if (i == 0) { cardone.setBounds(10, 10, 125, 195); cardone.setIcon(playercards.get(i).getCardIcon()); } else if (i == 1) { cardtwo.setBounds(135, 10, 125, 195); cardtwo.setIcon(playercards.get(i).getCardIcon()); } else if (i == 2) { cardthree.setBounds(255, 10, 125, 195); cardthree.setIcon(playercards.get(i).getCardIcon()); } else if (i == 3) { cardfour.setBounds(380, 10, 125, 195); cardfour.setIcon(playercards.get(i).getCardIcon()); } else if (i == 4) { cardfive.setBounds(505, 10, 125, 195); cardfive.setIcon(playercards.get(i).getCardIcon()); } else if (i == 5) { System.out .println("You have too many cards, please trade some in for armies!"); } } }
7
public void testGetCars() { TimeServer ts = new TimeServerLinked(); VehicleAcceptor r = new VehicleAcceptorObj(); Vehicle c = VehicleFactory.newCar(ts, r); r.accept(c); Assert.assertTrue(r.getCars().size() == 1); Assert.assertTrue(c.equals(r.getCars().get(0))); for (int i=0;i<10;i++) { r.accept(VehicleFactory.newCar(ts, r)); } Assert.assertTrue(r.getCars().size() == 11); Assert.assertTrue(c.equals(r.getCars().get(0))); Assert.assertTrue(c == r.getCars().get(0)); for (int i=0;i<10;i++) { //TODO rewtite TEST!!!! Assert.assertTrue(r.getCars().get(0) != null); } }
2
public int getFileCount(int idx) throws Exception{ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs =null; int result = 0; try{ conn = getConnection(); pstmt = conn.prepareStatement("select count(*) from board where idx=?"); pstmt.setInt(1, idx); rs = pstmt.executeQuery(); if(rs.next()){ result = rs.getInt(1); } }catch(Exception ex){ ex.printStackTrace(); }finally{ if(rs != null){ try{rs.close();} catch(SQLException e){e.printStackTrace();} } if(pstmt != null){ try{pstmt.close();} catch(SQLException e){e.printStackTrace();} } if(conn != null){ try{conn.close();} catch(SQLException e){e.printStackTrace();} } } return result; }
8
@Override public void unInvoke() { if(canBeUninvoked()) { if(affected instanceof MOB) { final MOB mob=(MOB)affected; final Room room = CMLib.map().getRoom(fromRoom); final int direction=this.direction; if((messedUp)||(direction<0)||(fromRoom==null)) { commonTell(mob,L("You've ruined the smuggler's hold!")); } else { synchronized(("SYNC"+room.roomID()).intern()) { final Room R=CMClass.getLocale("WoodRoom"); R.setRoomID(room.getArea().getNewRoomID(room,direction)); if(R.roomID().length()==0) { commonTell(mob,L("You've ruined the smuggler's hold!")); } else { R.setArea(room.getArea()); if(invoker==null) R.setDisplayText(L("The Smuggler's Hold")); else R.setDisplayText(L(invoker.name()+"'s Smuggler's Hold")); R.setDescription(""); Exit newExit=CMClass.getExit("GenDoor"); newExit.setName(L("a false wall")); newExit.setExitParams("wall","close","open","a false wall"); Thief_SmugglersHold holder=(Thief_SmugglersHold)this.copyOf(); holder.setMiscText(mob.Name()); holder.fullMode=false; newExit.addNonUninvokableEffect(holder); newExit.recoverPhyStats(); newExit.text(); room.rawDoors()[direction]=R; room.setRawExit(direction, newExit); Exit opExit=CMClass.getExit("Open"); R.rawDoors()[Directions.getOpDirectionCode(direction)]=room; R.setRawExit(Directions.getOpDirectionCode(direction), opExit); commonEmote(mob,L("<S-NAME> finish(es) the smuggler's hold!")); } } } } } super.unInvoke(); }
7
public void doCommand(String messageData, String nick) { String[] str = messageData.split(" "); for (int i = 0; i < commands.size(); i++) { if (str[0].startsWith(commands.get(i).getName())) { if (commands.get(i).userNeedsToBeOp() && ServerMain.uh.isOp(nick)) { try { ServerMain.EVENT_BUS.post(new CommandEvent(commands .get(i), nick, messageData, ServerMain.uh .getAddress(nick))); commands.get(i).performAction(messageData, nick); return; } catch (Exception e) { e.printStackTrace(); ServerMain.sh .sendMessageToAllUsers( "[Server]", "Command '" + str[0] + "' has generated an exception while running."); return; } } else if (commands.get(i).userNeedsToBeOp() && !ServerMain.uh.isOp(nick)) { ServerMain.sh.sendMessageToUser(nick, "You are not op :P", false); return; } else if (!commands.get(i).userNeedsToBeOp()) { try { commands.get(i).performAction(messageData, nick); return; } catch (Exception e) { e.printStackTrace(); ServerMain.sh .sendMessageToAllUsers( "[Server]", "Command '" + str[0] + "' has generated an exception while running."); return; } } } } ServerMain.sh.sendMessageToUser(nick, "Command does not exist!", false); }
9
protected double[][] calculateAssociationMatrix() { if( this.associationMatrix != null) return this.associationMatrix; if( this.clusterizedTrajectories == null) throw new RuntimeException("Error: impossible calculates the association matrix after the final calculation call"); NodeIndexing nodeIndexing = this.clusterizedTrajectories.get(0).getNodeIndexing(); // Association matrix initialization this.associationMatrix = new double[2][2]; this.associationMatrix[0][0] = 0; this.associationMatrix[0][1] = 0; this.associationMatrix[1][0] = 0; this.associationMatrix[1][1] = 0; // Matrix calculation for(int iTrj1 = 0; iTrj1 < this.clusterizedTrajectories.size(); ++iTrj1) { IClassificationResult<TimeType> trj1 = this.clusterizedTrajectories.get( iTrj1); String cluster1 = trj1.getClassification(); String tState1 = trj1.getNodeValue(0, nodeIndexing.getClassIndex()); for(int iTrj2 = iTrj1 + 1; iTrj2 < this.clusterizedTrajectories.size(); ++iTrj2) { IClassificationResult<TimeType> trj2 = this.clusterizedTrajectories.get( iTrj2); boolean clEqual = cluster1.equals( trj2.getClassification()); boolean tStateEqual = tState1.equals( trj2.getNodeValue(0, nodeIndexing.getClassIndex())); if( clEqual) { if( tStateEqual) ++this.associationMatrix[0][0]; // SS else ++this.associationMatrix[0][1]; // SD }else { if( tStateEqual) ++this.associationMatrix[1][0]; // DS else ++this.associationMatrix[1][1]; // DD } } } return this.associationMatrix; }
7
@Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof TransformedIterator<?, ?>)) { return false; } TransformedIterator<?, ?> that = (TransformedIterator<?, ?>) obj; return function.equals(that.function) && iterator.equals(that.iterator); }
9
private void updateGate(String A, String B, String C, String D, String E, String Y) throws InvalidPinException { if (this.isLow(A) && this.isLow(B) && this.isLow(C) && this.isLow(D) && this.isLow(E)) { this.setPin(Y, Pin.PinState.HIGH); } else { this.setPin(Y, Pin.PinState.LOW); } }
5
@Override public void onMouseMove(MouseMoveEvent event) { if (supportsTouchEvents) { return; } Widget sender = (Widget) event.getSource(); Element elem = sender.getElement(); // TODO optimize for the fact that elem is at (0,0) int x = event.getRelativeX(elem); int y = event.getRelativeY(elem); if (dragging == ACTIVELY_DRAGGING || dragging == DRAGGING_NO_MOVEMENT_YET) { // TODO remove Safari workaround after GWT issue 1807 fixed if (sender != capturingWidget) { // In Safari 1.3.2 MAC, other mouse events continue to arrive even when capturing return; } dragging = ACTIVELY_DRAGGING; } else { if (mouseDownWidget != null) { if (Math.max(Math.abs(x - mouseDownPageOffsetX), Math.abs(y - mouseDownPageOffsetY)) >= context.dragController.getBehaviorDragStartSensitivity()) { if (context.dragController.getBehaviorCancelDocumentSelections()) { DOMUtil.cancelAllDocumentSelections(); } if (!context.selectedWidgets.contains(context.draggable)) { context.dragController.toggleSelection(context.draggable); } // set context.mouseX/Y before startDragging() is called Location location = new WidgetLocation(mouseDownWidget, null); context.mouseX = mouseDownOffsetX + location.getLeft(); context.mouseY = mouseDownOffsetY + location.getTop(); startDragging(); } else { // prevent IE image drag when drag sensitivity > 5 event.preventDefault(); } } if (dragging == NOT_DRAGGING) { return; } } // proceed with the actual drag event.preventDefault(); actualMove(x, y); }
9
private static Location newLocation(Player player, Location loc, BorderData border, boolean notify) { if (Config.Debug()) { Config.LogWarn((notify ? "Border crossing" : "Check was run") + " in \"" + loc.getWorld().getName() + "\". Border " + border.toString()); Config.LogWarn("Player position X: " + Config.coord.format(loc.getX()) + " Y: " + Config.coord.format(loc.getY()) + " Z: " + Config.coord.format(loc.getZ())); } Location newLoc = border.correctedPosition(loc, Config.ShapeRound(), player.isFlying()); // it's remotely possible (such as in the Nether) a suitable location // isn't available, in which case... if (newLoc == null) { if (Config.Debug()) Config.LogWarn("Target new location unviable, using spawn."); newLoc = player.getWorld().getSpawnLocation(); } if (Config.Debug()) Config.LogWarn("New position in world \"" + newLoc.getWorld().getName() + "\" at X: " + Config.coord.format(newLoc.getX()) + " Y: " + Config.coord.format(newLoc.getY()) + " Z: " + Config.coord.format(newLoc.getZ())); if (notify) player.sendMessage(ChatColor.RED + Config.Message()); return newLoc; }
6
public void setTempo(int hora, int minuto, int segundo) { setHora(hora); setMinuto(minuto); setSegundo(segundo); }
0
public int getArticleCount(int area) throws Exception{ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs =null; int result = 0; try{ conn = getConnection(); pstmt = conn.prepareStatement("select count(*) from travel where area=?"); pstmt.setInt(1, area); rs = pstmt.executeQuery(); if(rs.next()){ result = rs.getInt(1); } }catch(Exception ex){ ex.printStackTrace(); }finally{ if(rs != null){ try{rs.close();} catch(SQLException e){e.printStackTrace();} } if(pstmt != null){ try{pstmt.close();} catch(SQLException e){e.printStackTrace();} } if(conn != null){ try{conn.close();} catch(SQLException e){e.printStackTrace();} } } return result; }
8
private void findUser(SessionRequestContent request) throws ServletLogicException { Criteria criteria = new Criteria(); criteria.addParam(DAO_ID_USER, request.getParameter(JSP_SELECT_ID)); User user = (User) request.getSessionAttribute(JSP_USER); if (user != null) { ClientType type = ClientTypeManager.clientTypeOf(user.getRole().getRoleName()); criteria.addParam(DAO_ROLE_NAME, type); } else { criteria.addParam(DAO_ROLE_NAME, request.getSessionAttribute(JSP_ROLE_TYPE)); } try { AbstractLogic userLogic = LogicFactory.getInctance(LogicType.USERLOGIC); List<User> users = userLogic.doGetEntity(criteria); if (users != null && !users.isEmpty()) { request.setSessionAttribute(JSP_CURRENT_USER, users.get(0)); } } catch (TechnicalException ex) { throw new ServletLogicException(ex.getMessage(), ex); } }
4
public void setStatus(SeanceStatus status) { if (status == null) { throw new IllegalArgumentException("Status shouldn't be NULL"); } this.status = status; }
1
private String lireFichier(String chemin_ficher) throws FileNotFoundException, IOException { contenu_fichier = new StringBuilder() ; f = new File(chemin_ficher) ; if(!f.getName().endsWith(".plic")) throw new ArrayIndexOutOfBoundsException() ; BufferedReader b = new BufferedReader(new FileReader(f)) ; String line = null ; while((line= b.readLine()) != null) contenu_fichier.append(line+"\n") ; return contenu_fichier.toString() ; }
2
public RaiseTilter() { requires(Robot.tilter); }
0
private void checkScoutValidity(StrategyBoard gameBoard, PlayerColor currentTurn, PieceType movePiece, Location moveFromLocation, Location moveToLocation) throws StrategyException { final int distance = moveFromLocation.distanceTo(moveToLocation); if (gameBoard.getPieceAt(moveToLocation) != null && distance > 1) { throw new StrategyException("Scout cannot move and strike on the same turn"); } final boolean verticalMove = moveFromLocation.getCoordinate(Coordinate.X_COORDINATE) == moveToLocation.getCoordinate(Coordinate.X_COORDINATE); final boolean forward = verticalMove ? moveFromLocation.getCoordinate(Coordinate.Y_COORDINATE) < moveToLocation.getCoordinate(Coordinate.Y_COORDINATE) : moveFromLocation.getCoordinate(Coordinate.X_COORDINATE) < moveToLocation.getCoordinate(Coordinate.X_COORDINATE); //Check every spot to the to location. Location2D nextCoordinate; final int startX = moveFromLocation.getCoordinate(Coordinate.X_COORDINATE); final int startY = moveFromLocation.getCoordinate(Coordinate.Y_COORDINATE); final int step = forward ? 1 : -1; final int start = verticalMove ? startY : startX; //start at the next spot final int stop = verticalMove ? startY + step * distance : startX + step * distance; for(int i = start + step; i != stop ; i += step) { nextCoordinate = verticalMove ? new Location2D(startX, i) : new Location2D(i, startY); if (gameBoard.getPieceAt(nextCoordinate) != null) { throw new StrategyException("Cannot move scout through another piece"); } } }
9
private void calculateLineHeight() { lineHeight = maxAscent = 0; // Each token style. for (int i=0; i<syntaxScheme.getStyleCount(); i++) { Style ss = syntaxScheme.getStyle(i); if (ss!=null && ss.font!=null) { FontMetrics fm = getFontMetrics(ss.font); int height = fm.getHeight(); if (height>lineHeight) lineHeight = height; int ascent = fm.getMaxAscent(); if (ascent>maxAscent) maxAscent = ascent; } } // The text area's (default) font). Font temp = getFont(); FontMetrics fm = getFontMetrics(temp); int height = fm.getHeight(); if (height>lineHeight) { lineHeight = height; } int ascent = fm.getMaxAscent(); if (ascent>maxAscent) { maxAscent = ascent; } }
7
public static void main(String[] args) throws Exception { BufferedWriter writer = new BufferedWriter(new FileWriter(new File( "c:\\temp\\SimulatedSpuriousCorrelationsAllGaussian.txt"))); writer.write("category\tabundant1\tlow1\tlow2\tresampledAbundnat1\tresampledLow1\tresampledLow2\tresampledRatio1\tresampledRatio2\n"); List<Double> abundant1 = populateGaussian(HIGH_ABUNDANCE_MEAN, HIGH_ABUNDNACE_SD, 2*SAMPLE_SIZE); List<String> categories= new ArrayList<String>(); for( int x=0 ; x < SAMPLE_SIZE * 2;x++) { if( RANDOM.nextFloat() <= 0.5f) { categories.add("A"); abundant1.set(x, abundant1.get(x) * 5 ); } else { categories.add("B"); } } List<Double> low1 = populateGaussian(LOW_ABUNDANCE_MEAN, LOW_ABUNDNACE_SF, 2*SAMPLE_SIZE); List<Double> low2 = populateGaussian(LOW_ABUNDANCE_MEAN, LOW_ABUNDNACE_SF, 2*SAMPLE_SIZE); for( int x=0; x < SAMPLE_SIZE * 2; x++) { writer.write(categories.get(x) + "\t"); writer.write( abundant1.get(x)+ "\t" ); writer.write( low1.get(x) + "\t" ); writer.write( low2.get(x) + "\t" ); List<String> sample = resample(abundant1.get(x), low1.get(x), low2.get(x)); int highCount =0; int lowCount1=0; int lowCount2=0; for(String s : sample) { if( s == HIGH) highCount++; else if (s == LOW1) lowCount1++; else if ( s== LOW2) lowCount2++; else throw new Exception("Logic error"); } writer.write(highCount + "\t"); writer.write(lowCount1 + "\t"); writer.write(lowCount2 + "\t"); double geoMean = geoMean(lowCount1, lowCount2, highCount); writer.write( (lowCount1 / geoMean) + "\t" ); writer.write( (lowCount2 / geoMean) + "\n" ); } writer.flush(); writer.close(); }
7
public void buffmsg(Message msg) { String name = msg.string().intern(); synchronized (buffs) { if (name == "clear") { buffs.clear(); } else if (name == "set") { int id = msg.int32(); Indir<Resource> res = sess.getres(msg.uint16()); String tt = msg.string(); int ameter = msg.int32(); int nmeter = msg.int32(); int cmeter = msg.int32(); int cticks = msg.int32(); boolean major = msg.uint8() != 0; Buff buff; if ((buff = buffs.get(id)) == null) { buff = new Buff(id, res); } else { buff.res = res; } if (tt.equals("")) buff.tt = null; else buff.tt = tt; buff.ameter = ameter; buff.nmeter = nmeter; buff.ntext = null; buff.cmeter = cmeter; buff.cticks = cticks; buff.major = major; buff.gettime = System.currentTimeMillis(); buffs.put(id, buff); } else if (name == "rm") { int id = msg.int32(); buffs.remove(id); } } }
5
public void run() { if (player!=null) { try { player.play(); } catch (JavaLayerException ex) { System.err.println("Problem playing audio: "+ex); } } }
2
protected void addOutsidersAndTimers(Faction F, Vector<Faction.FactionChangeEvent> outSiders, Vector<Faction.FactionChangeEvent> timers) { Faction.FactionChangeEvent[] CEs=null; CEs=F.getChangeEvents("ADDOUTSIDER"); if(CEs!=null) { for (final FactionChangeEvent ce : CEs) outSiders.addElement(ce); } CEs=F.getChangeEvents("TIME"); if(CEs!=null) { for (final FactionChangeEvent ce : CEs) { if(ce.triggerParameters().length()==0) timers.addElement(ce); else { int[] ctr=(int[])ce.stateVariable(0); if(ctr==null) { ctr=new int[]{CMath.s_int(ce.getTriggerParm("ROUNDS"))}; ce.setStateVariable(0,ctr); } if((--ctr[0])<=0) { ctr[0]=CMath.s_int(ce.getTriggerParm("ROUNDS")); timers.addElement(ce); } } } } }
7
@Override public void caseAMethodCallExp(AMethodCallExp node) { for(int i=0;i<indent;i++) System.out.print(" "); indent++; System.out.print("(Call [ "); System.out.print(node.getIdentifier()); System.out.println(" ]"); inAMethodCallExp(node); if(node.getHexp() != null) { node.getHexp().apply(this); } if(node.getDot() != null) { node.getDot().apply(this); } if(node.getIdentifier() != null) { node.getIdentifier().apply(this); } if(node.getLPar() != null) { node.getLPar().apply(this); } if(node.getExplist() != null) { node.getExplist().apply(this); } if(node.getRPar() != null) { node.getRPar().apply(this); } outAMethodCallExp(node); indent--; for(int i=0;i<indent;i++) System.out.print(" "); System.out.println(")"); }
8
private void nextGeneration() { boolean someSelected = false; for (int i = 0; i < generators.size(); i++) if (generators.get(i).isSelected()) { gaPop.setIndividualFitness(i, 1); generators.get(i).deselect(); someSelected = true; } if (someSelected) { if (!goBackButton.isEnabled()) goBackButton.setEnabled(true); Population<GeneratorIndividual<T>> oldPop = new Population<GeneratorIndividual<T>>(noGenerators, new GeneratorCreator<T>(front.getConverter())); oldPop.setIndividuals(gaPop.getIndividuals()); oldPops.push(oldPop); gaPop.nextGeneration(); setGeneratorsToPopulation(); } else { System.out.println("Select at least one parent"); } }
4
public static SampleSet generateSamples(final int length) { SampleSet set = new SampleSet(); // int size = 1 << length; boolean[] data = new boolean[length]; // for (int i = 0; i < size; i++) { Sample s = new Sample(1, length, 1, 1); // for (int j = 0; j < data.length; j++) { s.getInput()[j] = (data[j]?(1.0):(0.0)); } // s.getTarget()[0] = (xor(data)?(1.0):(0.0)); incrBit(data, 0); set.add(s); } // return set; }
4
@Override public void restoreCurrentToDefault() {cur = new Color(def.getRGB());}
0
public MainFrame() { super("Hello World"); setLayout(new BorderLayout()); lista = new ArrayList<FormEvent>(); btn = new JButton("Click me"); textPanel = new TextPanel(); formPanel = new FormPanel(); toolbar = new Toolbar(); dbl = new DatabaseLayer(); toolbar.setArrayList(lista); toolbar.setStringListener(new StringListener(){ @Override public void textEmitted(String text) { // TODO Auto-generated method stub textPanel.appendText(text); }}); toolbar.setArrayListener(new ArrayListener(){ @Override public void ArrayEmitted(ArrayList<FormEvent> lista) { // TODO Auto-generated method stub if(dbl.isConnected()){ ArrayList<FormEvent> list = dbl.resultQuery("select * from trabajador"); for(FormEvent f:list){ textPanel.appendText("ID: "+f.getId()+"\n"+ "Nombre: "+f.getName()+"\n"+ "ocupacion_Id: "+f.getOccupation()+"\n"+ "tipoEmpleado_Id: "+f.getEmpTipo()+"\n"+ "Genero: "+f.getGender()+"\n"+ "nacionalidad_Id: "+f.getNacionId()+"\n"+ "----------------------"+"\n"); } } } }); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { textPanel.appendText("Hello\n"); } }); formPanel.setFormListener(new FormListener(){ public void formEventOcurred(FormEvent e){ lista.add(e); if(dbl.isConnected()){ String sql = "INSERT INTO trabajador"+ "(tipoEmpleado_Id,nombre,ocupacion_Id,edad,genero,nacionalidad_Id)"+ "VALUES ("+e.getEmpTipo()+",'"+e.getName()+"',"+e.getOccupation()+","+30+ ",'"+e.getGender()+"',"+e.getNacionId()+")"; System.out.println(sql); dbl.queryExec(sql); } else{ System.out.println("Conexion no establecida"); } } }); add(toolbar, BorderLayout.NORTH); add(textPanel, BorderLayout.CENTER); add(btn, BorderLayout.SOUTH); add(formPanel,BorderLayout.WEST); setSize(700, 800); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); }
3
public boolean start() { synchronized (optOutLock) { // Did we opt out? if (isOptOut()) { return false; } // Is metrics already running? if (task != null) { return true; } // Begin hitting the server with glorious data task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { private boolean firstPost = true; public void run() { try { // This has to be synchronized or it can collide with the disable method. synchronized (optOutLock) { // Disable Task, if it is running and the server owner decided to opt-out if (isOptOut() && task != null) { task.cancel(); task = null; } } // We use the inverse of firstPost because if it is the first time we are posting, // it is not a interval ping, so it evaluates to FALSE // Each time thereafter it will evaluate to TRUE, i.e PING! postPlugin(!firstPost); // After the first post we set firstPost to false // Each post thereafter will be a ping firstPost = false; } catch (IOException e) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); } } } }, 0, PING_INTERVAL * 1200); return true; } }
6
public void update() { removeAll(); HighSeas highSeas = getMyPlayer().getHighSeas(); if (highSeas != null) { for (Unit unit : highSeas.getUnitList()) { boolean belongs; if (destination instanceof Europe) { belongs = unit.getDestination() == destination; } else if (destination instanceof Map) { belongs = unit.getDestination() == destination || (unit.getDestination() != null && unit.getDestination().getTile() != null && unit.getDestination().getTile().getMap() == destination); } else { logger.warning("Bogus DestinationPanel location: " + ((FreeColGameObject) destination) + " for unit: " + unit); belongs = false; } if (belongs) { UnitLabel unitLabel = new UnitLabel(getFreeColClient(), unit, getGUI()); unitLabel.setTransferHandler(defaultTransferHandler); unitLabel.addMouseListener(pressListener); add(unitLabel); } } } StringTemplate t = StringTemplate.template("goingTo") .addName("%type%", "ship") .addStringTemplate("%location%", destination.getLocationNameFor(getMyPlayer())); ((TitledBorder) getBorder()).setTitle(Messages.message(t)); revalidate(); }
8
public boolean Salvar(Venda obj) { try { if (obj.getId() == 0) { PreparedStatement comando = bd.getConexao().prepareStatement("insert into vendas(funcionario,cliente,pagamento,data_venda,total,status) values(?,?,?,?,?,?)"); comando.setInt(1, obj.getAtendente().getId()); comando.setInt(2,obj.getConsumidor().getId()); comando.setInt(3, obj.getTipo_paga().getId()); java.sql.Date data = new java.sql.Date(obj.getData_venda().getTime()); comando.setDate(4, data); comando.setDouble(5, obj.getTotal_final()); comando.setInt(6, 1); comando.executeUpdate(); } else { PreparedStatement comando = bd.getConexao().prepareStatement("update vendas set valorTotal = ?,data = ? where id = ?"); comando.setDouble(1, obj.getTotal()); java.sql.Date dt = new java.sql.Date(obj.getData_venda().getTime()); comando.setDate(2, dt); comando.setDouble(2, obj.getId()); comando.executeUpdate(); } for (Item_venda iv : obj.getItens()) { if (iv.getId() == 0) { PreparedStatement comando = bd.getConexao().prepareStatement("insert into item_venda(venda,produto,valor_item,qtd) values(?,?,?,?)"); comando.setInt(1, obj.getId()); comando.setInt(2, iv.getProduto().getId()); comando.setDouble(3, iv.getV_produto()); comando.setInt(4, iv.getQtd()); comando.executeUpdate(); } else { PreparedStatement comando = bd.getConexao().prepareStatement("update item_venda set produto=?, qtd=? where id=?"); comando.setInt(1, iv.getProduto().getId()); comando.setInt(2, iv.getQtd()); comando.setInt(3, obj.getId()); comando.executeUpdate(); } } return true; } catch (SQLException ex) { Logger.getLogger(VendaDao.class.getName()).log(Level.SEVERE, null, ex); return false; } }
4
private Move getMinMove(StateTree tree) throws Exception { if (tree.isLeaf()) { return new Move( tree.getMove(), tree.getScore()); } Move minMove = null; for (StateTree successor : tree.getSuccessors()) { Move move = this.getMaxMove(successor); if (minMove == null || move.getScore() < minMove.getScore()) { minMove = new Move(successor.getMove(), move.getScore()); } } return minMove; }
4
@EventHandler public void PigZombiePoison(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getPigZombieConfig().getDouble("PigZombie.Poison.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getPigZombieConfig().getBoolean("PigZombie.Poison.Enabled", true) && damager instanceof PigZombie && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, plugin.getPigZombieConfig().getInt("PigZombie.Poison.Time"), plugin.getPigZombieConfig().getInt("PigZombie.Poison.Power"))); } }
6
private double f(double b) { double PrB=1, p=probLessThan(b); for (int i = 0; i < futureBowls; i++) { PrB*=p; } double PrA=1-PrB; double ExA=exptGreaterThan(b); double ExB=exptLessThan(b); double Ex2=PrA*ExA+PrB*ExB; return Ex2; }
1
static String getPlatformFont() { if(SWT.getPlatform() == "win32") { return "Arial"; } else if (SWT.getPlatform() == "motif") { return "Helvetica"; } else if (SWT.getPlatform() == "gtk") { return "Baekmuk Batang"; } else if (SWT.getPlatform() == "carbon") { return "Arial"; } else { // photon, etc ... return "Verdana"; } }
4
int insertKeyRehash(short val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
9
public void updateLabels(){ //sets all the new labels depending on the board configuration int value; int index = 0; switch (gameMode) { //set labels differently depending on the game mode case "normal" : for (int r = 0; r < 4; r++) //labels will be counted left to right, up to down for (int c = 0; c < 4; c++) { value = board.BOARD[r][c]; labels[index].setLabel(value); index ++; } break; case "cupcake": index = 0; for (int r = 0; r < 4; r++) for (int c = 0; c < 4; c++) { value = board.BOARD[r][c]; labels[index].setLabelCupcake(value); index++; } break; case "randomColor": index = 0; for (int r = 0; r < 4; r++) for (int c = 0; c < 4; c++) { value = board.BOARD[r][c]; labels[index].setLabelRandom(value); index ++; } break; } }
9
@Override public String execute() throws Exception { try { session = ActionContext.getContext().getSession(); User u1 = (User) session.get("User"); if (existpass.isEmpty()) { addActionError("Please Enter existing password"); return "error"; } else { Criteria ucri = getMyDao().getDbsession().createCriteria(User.class); ucri.add(Restrictions.eq("emailId", u1.getEmailId())); ucri.add(Restrictions.eq("password", existpass)); ucri.setMaxResults(1); if (ucri.list().isEmpty()) { addActionError("Current password doesn't match please try again"); return "error"; } else { user = (User) myDao.getDbsession().get(User.class, u1.getEmailId()); user.setPassword(newpass); myDao.getDbsession().update(user); session.put("User", user); addActionMessage("New Password Successfully Changed"); return "success"; } } } catch (HibernateException e) { addActionError("Server Error Please Try Again Later "); e.printStackTrace(); return "error"; } catch (NullPointerException ne) { addActionError("Server Error Please Try Again Later "); ne.printStackTrace(); return "error"; } catch (Exception e) { addActionError("Server Error Please Try Again Later "); e.printStackTrace(); return "error"; } }
5
public String toQString() { StringBuffer str = new StringBuffer(); for (int i = 0; i < FIELD_NAME.length; ++i) { if (get(FIELD_NAME[i]) == null || get(FIELD_NAME[i]).equals("")) continue; if (i != 0) str.append("&"); try { str.append(FIELD_NAME[i] + "=" + URLEncoder.encode(get(FIELD_NAME[i]), "UTF-8")); } catch (UnsupportedEncodingException e) { // Shouldn't happen throw new Error(e); } } return str.toString(); }
5
public static CitationRecord read(InputStream is) throws IOException { CitationRecord rec=new CitationRecord(); String file=LabnoteUtil.readStreamToString(is); String[] lines=file.split("\\r\\n"); LinkedList<String> nlines=new LinkedList<String>(); for(String s:lines) nlines.add(s); while(!nlines.isEmpty()) { String line=nlines.removeFirst(); String linetype=line.substring(0, 2); if(!line.substring(2,2+4).equals(" - ")) throw new IOException("Bad separator - not a RIS file"); String therest=line.substring(2+4); if(linetype.equals("ER")) break; else if(linetype.equals("TY")) { if(therest.equals("ABST") || therest.equals("INPR") || therest.equals("JFULL") || therest.equals("JOUR")) { parseJournalArticle(rec, nlines); //Set type rec.setType(CitationRecord.TYPE_ARTICLE); } } } return rec; }
9
public ClusterNode getParent() { return this.parent; }
0
public static Document readResourceDocument(Class<?> c, String name) { Document doc = null; InputStream is = null; try { is = c.getResourceAsStream(name); DocumentBuilder db = XMLUtils.newDocumentBuilder(false); doc = db.parse(is); } catch (SAXException e) { doc = null; e.printStackTrace(); } catch (IOException e) { doc = null; e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException consumed) { } } } return doc; }
5
private static int loadTexture(String fileName) { String[] splitArray = fileName.split("\\."); @SuppressWarnings("unused") String ext = splitArray[splitArray.length - 1]; try { BufferedImage image = ImageIO.read(new File("./res/textures/" + fileName)); boolean hasAlpha = image.getColorModel().hasAlpha(); int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth()); ByteBuffer buffer = Util.createByteBuffer(image.getWidth() * image.getHeight() * 4); for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { int pixel = pixels[y * image.getWidth() + x]; buffer.put((byte) ((pixel >> 16) & 0xFF)); buffer.put((byte) ((pixel >> 8) & 0xFF)); buffer.put((byte) ((pixel >> 0) & 0xFF)); if (hasAlpha) buffer.put((byte) ((pixel >> 24) & 0xFF)); else buffer.put((byte) (0xFF)); } } buffer.flip(); // this.width = image.getWidth(); // this.height = image.getHeight(); // this.id = Engine.getRenderer().createTexture(width, height, buffer, true, true); // this.frameBuffer = 0; // this.pixels = null; int texture = glGenTextures(); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); return texture; } catch(Exception e) { e.printStackTrace(); System.exit(1); } return 0; }
4
public List<String> getValidationErrors() { List<String> errors = new ArrayList<String>(); if (customerId == null || customerId.length() == 0) errors.add("Customer ID is required"); if (username == null || username.length() == 0) errors.add("Customer username is required"); if (errors.size() > 0) return errors; if (!customerId.matches("\\d*")) errors.add("Customer ID should be a number"); if (username.matches(".*[<>\"&].*")) errors.add("Username may not contain angle brackets, quotes, greater, less or ampersan"); return errors; }
7