text
stringlengths
14
410k
label
int32
0
9
protected int partition(double[] array, int[] index, int l, int r, final int indexStart) { double pivot = array[(l + r) / 2]; int help; while (l < r) { while ((array[l] < pivot) && (l < r)) { l++; } while ((array[r] > pivot) && (l < r)) { r--; } if (l < r) { help = index[indexStart+l]; index[indexStart+l] = index[indexStart+r]; index[indexStart+r] = help; l++; r--; } } if ((l == r) && (array[r] > pivot)) { r--; } return r; }
8
public String getGeraGMP() throws SQLException, ClassNotFoundException { String sts = new String(); Connection conPol = conMgr.getConnection("PD"); if (conPol == null) { throw new SQLException("Numero Maximo de Conexoes Atingida!"); } try { Statement stmt = conPol.createStatement(); String strQl = "SELECT * FROM tb_gmp; "; ResultSet rs = stmt.executeQuery(strQl); while (rs.next()) { sts = sts + "<option value= " + rs.getInt("cod_gmp") + "> GMP-" + rs.getString("str_gmp") + "</option>"; } } finally { if (conPol != null) { conMgr.freeConnection("PD", conPol); } } return sts; }
3
public ArrayList<String> getRoomId() { return this.roomId; }
0
public synchronized static void newBorn(List<Ant> ants, Ant father, Ant mather) { int randomNumX = rand.nextInt(terrainWidth); int randomNumY = rand.nextInt(terrainHeight); if (father.getInteligence() && mather.getInteligence()) { Inteligence ant = new Inteligence(getMaxId(ants) + 1, father.getId(), mather.getId(), randomNumX, randomNumY, Color.RED); ant.setInteligence(true); ants.add(ant); } else if (father.getInteligence()) { Inteligence ant = new Inteligence(getMaxId(ants) + 1, father.getId(), mather.getId(), randomNumX, randomNumY, Color.RED); ant.setInteligence(true); ants.add(ant); }else if (mather.getInteligence()) { Inteligence ant = new Inteligence(getMaxId(ants) + 1, father.getId(), mather.getId(), randomNumX, randomNumY, Color.BLACK); if (getRandomBoolean()) { ant.setColor(Color.RED); ant.setInteligence(true); } ants.add(ant); } else { Ant ant = new Ant(getMaxId(ants) + 1, father.getId(), mather.getId(), randomNumX, randomNumY, Color.BLACK); ants.add(ant); } }
5
public void gen_opt_sim_negate(SemanticRec opSign, SemanticRec term) { if (opSign != null && term != null) { Type termType = getTypeFromSR(term); String op = opSign.getDatum(0); switch (termType) { case INTEGER: switch (op) { case "MP_MINUS": negateStackI(); break; case "MP_PLUS": break; default: Parser.semanticError(opSign + " is not a negation operator for type " + termType); } break; case FLOAT: switch (op) { case "MP_MINUS": negateStackF(); break; case "MP_PLUS": break; default: Parser.semanticError(opSign + " is not a negation operator for type " + termType); } break; default: Parser.semanticError(termType + "does not have a negation operation"); } } }
8
private void addLinks(ObjectStack oStack, Node rep, Node linker) { if(!rep.equals(linker)) { addLinkStatement(rep.getRepresentation(), linker.getRepresentation()); } List<Node> supers = oStack.getSupers(rep); for (Node sup : supers) { // recurse addLinks(oStack, sup,linker); } }
2
@EventHandler public void onPlayerQuit(PlayerQuitEvent event) { KaramPlayer player = m_plugin.playerManager.addOrGetPlayer(event.getPlayer()); if (player != null) { if (!player.isAllowedToLeave()) { m_plugin.log(Level.INFO, "All hope is lost for %s", player.player.getName()); if (m_plugin.settings.isIllegalQuitFineActivated()) { player.substractKarma(m_plugin.settings.getIllegalQuitFine()); } else { } } else { } m_plugin.playerManager.savePlayerData(player); m_plugin.playerManager.removePlayer(player); } else { } }
3
@Override public void deserialize(Buffer buf) { barType = buf.readByte(); if (barType < 0) throw new RuntimeException("Forbidden value on barType = " + barType + ", it doesn't respect the following condition : barType < 0"); slot = buf.readInt(); if (slot < 0 || slot > 99) throw new RuntimeException("Forbidden value on slot = " + slot + ", it doesn't respect the following condition : slot < 0 || slot > 99"); }
3
public void render(Graphics2D g) { g.translate(c.getXOffset(), c.getYOffset()); w.render(g); for (int i = 0; i < particles.size(); i++) { if (new Rectangle(particles.get(i).x, particles.get(i).y, 5, 5).intersects(new Rectangle((int) (-c.getXOffset() - 64), (int) (-c.getYOffset() - 64), 448 * 2 + 128, 360 * 2 + 64))) { particles.get(i).render(g); } } p.render(g); for (int i = 0; i < missiles.size(); i++) { if (missiles.get(i).intersects(new Rectangle((int) (-c.getXOffset() - 64), (int) (-c.getYOffset() - 64), 448 * 2 + 128, 360 * 2 + 64))) { missiles.get(i).render(g); } } for (int i = 0; i < ent.size(); i++) { if (ent.get(i).intersects(new Rectangle((int) (-c.getXOffset() - 64), (int) (-c.getYOffset() - 64), 448 * 2 + 128, 360 * 2 + 64))) { ent.get(i).render(g); } } w.preRender(g); g.translate(-c.getXOffset(), -c.getYOffset()); p.renderAfter(g); }
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(Renomear.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Renomear.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Renomear.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Renomear.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { Renomear dialog = new Renomear(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
static boolean esPosible(int inicio[],int cantInicio,long jugado,int cantJug) { boolean[][] tab=new boolean[100][100]; int x=50,y=50; tab[x][y]=true; for(int i=0;i<cantInicio;i++) { int p=inicio[i]; x+=jug[p][0]; y+=jug[p][1]; tab[x][y]=true; } for(int i=0;i<cantJug;i++) { int p=abs((int)(jugado&((1<<2)-1))); jugado=jugado>>>2; x+=jug[p][0]; y+=jug[p][1]; tab[x][y]=true; } int c=0,p=0; cola1[c][0]=x; cola1[c++][1]=y; for(;p<c;){ x=cola1[p][0]; y=cola1[p++][1]; for(int i=0;i<jug.length;i++) { if(x+jug[i][0]<0||x+jug[i][0]>=tab.length||y+jug[i][1]<0||y+jug[i][1]>=tab.length) return true; if(!tab[x+jug[i][0]][y+jug[i][1]]) { cola1[c][0]=x+jug[i][0]; cola1[c++][1]=y+jug[i][1]; tab[x+jug[i][0]][y+jug[i][1]]=true; } } } return false; }
9
@Override public void prepareInternal(int skips, boolean assumeOnSkip) { if(moves.length == 0) return; if(!assumeOnSkip) { for(int i=0;i<moves.length-1;i++) if(!moves[i].execute()) throw new RuntimeException("execution of move "+i+" failed"); } moves[moves.length-1].prepareInternal(skips, assumeOnSkip); }
4
public String reverse(String s) { String reversed = ""; String[] parsed = s.split(" "); if(parsed.length == 0) { return ""; } for(int i = parsed.length-1 ; i> -1; i--) { if(parsed[i].compareTo("") != 0) //if not null { reversed = reversed.concat(parsed[i]); if(i!= 0) { reversed = reversed.concat(" "); } } } // trim reversed from space at the beginning and at the end if(reversed.length() !=0) { if(reversed.charAt(reversed.length()-1) == ' ') { reversed = reversed.substring(0, reversed.length()-1); } if(reversed.charAt(0) == ' ') { reversed = reversed.substring(1, reversed.length()-1); } } return reversed; }
7
private void openMenuItem_actionPerformed(ActionEvent event) { JFileChooser fileChooser = createFileChooser(); fileChooser.showOpenDialog(this); File file = fileChooser.getSelectedFile(); if (file.exists()) { defaultDirectory = fileChooser.getCurrentDirectory(); try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) { String text; while ((text = randomAccessFile.readLine()) != null) { transmitText(text); } } catch (IOException ex) { Logger.getLogger(MonitorConsole.class.getName()).log(Level.SEVERE, "openMenuItem_ActionPerformed", ex); } } }
3
public String qualifier() { Assert.isTrue(desc.charAt(0) == Type.CLASS_CHAR, "No qualifier for " + desc); final int index = desc.lastIndexOf('/'); if (index >= 0) { return desc.substring(1, index); } return desc.substring(1, desc.lastIndexOf(';')); }
1
@Override public String getDesc() { return "ThrowVenomKnife"; }
0
void addPage(int pageIndex) { int size = pages.size(); if(size == 0) { pages.add(new Integer(pageIndex)); } // Even, so last entry is end of range else if((size % 2) == 0) { Integer end = (Integer) pages.get(size-1); // Continuing the existing sequential page range if(end.intValue() == (pageIndex-1)) { pages.set(size-1, new Integer(pageIndex)); } // Starting a new page range else if(end.intValue() < (pageIndex-1)) { pages.add(new Integer(pageIndex)); } } // Odd, so last entry is start of range else { Integer begin = (Integer) pages.get(size-1); // Continuing the existing sequential page range if(begin.intValue() == (pageIndex-1)) { pages.add(new Integer(pageIndex)); } // Starting a new page range, end the previous one first else if(begin.intValue() < (pageIndex-1)) { pages.add(begin); pages.add(new Integer(pageIndex)); } } }
6
public static void main(String[] args) { final Cv cvUtilisateur = objectFactory.createCv(); final IdentiteType identiteTypeUtilisateur = objectFactory.createIdentiteType(); final AdresseType adresseTypeUtilisateur = objectFactory.createAdresseType(); final FonctionType fonctionTypeUtilisateur = objectFactory.createFonctionType(); final CompetenceType competenceTypeTechniqueUtilisateur = objectFactory.createCompetenceType(); final CompetenceDetailType competenceDetailTypeTechniqueDeveloppementUtilisateur = objectFactory.createCompetenceDetailType(); final CompetenceDetailType competenceDetailTypeTechniqueServeurAppliUtilisateur = objectFactory.createCompetenceDetailType(); final CompetenceType competenceTypeFonctionnelleUtilisateur = objectFactory.createCompetenceType(); final CompetenceDetailType competenceDetailTypeFonctionnelleUtilisateur = objectFactory.createCompetenceDetailType(); final ExperienceType experienceTypeUtilisateurASP = objectFactory.createExperienceType(); final ExperienceType experienceTypeUtilisateurCarsat = objectFactory.createExperienceType(); initAdresseUtilisateur(adresseTypeUtilisateur); initIdentiteUtilisateur(identiteTypeUtilisateur, adresseTypeUtilisateur); initFonctionUtilisateur(fonctionTypeUtilisateur); initCompetenceDetailTechniqueDeveloppementUtilisateur(competenceDetailTypeTechniqueDeveloppementUtilisateur); initCompetenceDetailTechniqueServeurAppliUtilisateur(competenceDetailTypeTechniqueServeurAppliUtilisateur); initCompetenceDetailFonctionnelleUtilisateur(competenceDetailTypeFonctionnelleUtilisateur); competenceTypeTechniqueUtilisateur.getCompetence().add(competenceDetailTypeTechniqueDeveloppementUtilisateur); competenceTypeTechniqueUtilisateur.getCompetence().add(competenceDetailTypeTechniqueServeurAppliUtilisateur); competenceTypeFonctionnelleUtilisateur.getCompetence().add(competenceDetailTypeFonctionnelleUtilisateur); initPremiererExperienceCV(experienceTypeUtilisateurASP); initDeuxiemeExperienceCV(experienceTypeUtilisateurCarsat); cvUtilisateur.setIdentite(identiteTypeUtilisateur); cvUtilisateur.setFonction(fonctionTypeUtilisateur); cvUtilisateur.setCompetenceTechnique(competenceTypeTechniqueUtilisateur); cvUtilisateur.setCompetenceFonctionnelle(competenceTypeFonctionnelleUtilisateur); cvUtilisateur.getExperience().add(experienceTypeUtilisateurCarsat); cvUtilisateur.getExperience().add(experienceTypeUtilisateurASP); final JAXBContext jaxbContext; try { jaxbContext = JAXBContext.newInstance(Cv.class); final Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); final FileWriter writer = new FileWriter(CHEMIN_FICHIER_GENERE); writer.write("<?xml-stylesheet type=\"text/xsl\" href=\"xsl\\CV.xsl\">"); writer.write("\n"); final File fileSchema = new File(CHEMIN_SCHEMA); final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema = schemaFactory.newSchema(fileSchema); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.setSchema(schema); jaxbMarshaller.marshal(cvUtilisateur, writer); } catch (JAXBException e) { System.out.println("erreur lors de la génération du fichier XML."); e.printStackTrace(); } catch (IOException e) { System.out.println("erreur sur ke flux de fichier."); e.printStackTrace(); } catch (SAXException e) { System.out.println("erreur sur le schema."); e.printStackTrace(); } }
3
private void parseTimeControls(String key, int value) { // Java seriously needs to support Strings in switch statements (Java 1.7!) if (key.equals("movetime")) { timeControls |= TC_MOVETIME; moveTime = value; } else if (key.equals("depth")) { timeControls |= TC_FIXEDDEPTH; fixedDepth = value; } else if (key.equals("nodes")) { timeControls |= TC_NODES; fixedNoOfNodes = value; } else if (key.equals("mate")) { timeControls |= TC_INFINITE; System.out.println("Mate: NOT Supported!"); } else if (key.equals("movestogo")) { timeControls |= TC_MOVESTOGO; movesToGo = value; } else if (key.equals("wtime")) { timeControls |= TC_TIMELEFT; timeLeft[WHITE] = value; } else if (key.equals("winc")) { timeControls |= TC_INC; inc[WHITE] = value; } else if (key.equals("btime")) { timeControls |= TC_TIMELEFT; timeLeft[BLACK] = value; } else if (key.equals("binc")) { timeControls |= TC_INC; inc[BLACK] = value; } else { assert false : "No time control goes by the name " + key; } }
9
@Override public void handle(HttpExchange exchange) throws IOException { System.out.println("In Save Game handler."); String responseMessage = ""; if(exchange.getRequestMethod().toLowerCase().equals("post")) { exchange.getResponseHeaders().set("Content-Type", "appliction/json"); BufferedReader in = new BufferedReader(new InputStreamReader(exchange.getRequestBody())); String inputLine; StringBuffer requestJson = new StringBuffer(); while ((inputLine = in.readLine()) != null) { requestJson.append(inputLine); } in.close(); System.out.println(requestJson); SaveGameRequest request = (SaveGameRequest) translator.translateFrom(requestJson.toString(), SaveGameRequest.class); exchange.getRequestBody().close(); if(gamesFacade.validateGameID(request.getId())){ try{ gamesFacade.saveGame(request.getId(), request.getName()); responseMessage = "Successfully wrote game to file: " + request.getId(); exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); }catch(IOException e){ System.out.println("Error writing to file."); responseMessage = e.getMessage(); exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0); } } else{ System.out.println("Bad game id."); responseMessage = "Error: Bad game id"; exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0); } } else { // unsupported request method responseMessage = "Error: \"" + exchange.getRequestMethod() + "\" is not supported!"; exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0); } if (!responseMessage.isEmpty()) { //send failure response message OutputStreamWriter writer = new OutputStreamWriter( exchange.getResponseBody()); writer.write(responseMessage); writer.flush(); writer.close(); } exchange.getResponseBody().close(); }
5
public float[] computeOutput(float[] input) { // проверки if (input == null || input.length != size) throw new IllegalArgumentException(); // найдем победителя int winner = 0; for (int i = 1; i < size; i++) if (input[i] > input[winner]) winner = i; // готовим ответ float[] output = new float[size]; // проверим на минимальный уровень расхождения if (minLevel > 0) { float level = Float.MAX_VALUE; for (int i = 0; i < size; i++) if (i != winner && Math.abs(input[i] - input[winner]) < level) level = Math.abs(input[i] - input[winner]); if (level < minLevel) return output; } // говорим кто победитель output[winner] = 1; // вернем отклик return output; }
9
void addGuiComponent(String fieldname) { String fieldguiname = (String)fieldguinames.get(fieldname)+" "; String fieldtype = (String)fieldtypes.get(fieldname); Object fieldval = fieldvalues.get(fieldname); JPanel subpanel = new JPanel(new GridLayout(1,2)); subpanel.setBackground(bgcolor); mainpanel.add(subpanel); JLabel namelabel = new JLabel(fieldguiname,JLabel.RIGHT); namelabel.setBackground(bgcolor); namelabel.setForeground(textcolor); namelabel.setFont(mainfont); if (fieldtype.equals("int") || fieldtype.equals("double") ) { JTextField numfield = new JTextField(""+fieldval, 8); numfield.addCaretListener(new FieldChangeHandler(fieldname) { public void caretUpdate(CaretEvent e) { JTextField tf = (JTextField) fieldcomponents.get(this.fieldname); processAction(this.fieldname,tf.getText()); } }); if (fieldtype.equals("int")) { numfield.setToolTipText("Enter an integer."); } else { numfield.setToolTipText("Enter a real number."); } numfield.setFont(mainfont); numfield.setForeground(textcolor); numfield.setBackground(hltcolor); fieldcomponents.put(fieldname,numfield); subpanel.add(namelabel); subpanel.add(numfield); } else if (fieldtype.equals("String")) { JTextField strfield = new JTextField(""+fieldval, 8); strfield.addCaretListener(new FieldChangeHandler(fieldname) { public void caretUpdate(CaretEvent e) { JTextField tf = (JTextField) fieldcomponents.get(this.fieldname); processAction(this.fieldname,tf.getText()); } }); //strfield.addActionListener(new FieldChangeHandler(fieldname) { // public void actionPerformed(ActionEvent e) { // processAction(this.fieldname,e.getActionCommand()); // } //}); strfield.setToolTipText("Enter a text."); strfield.setFont(mainfont); strfield.setForeground(textcolor); strfield.setBackground(hltcolor); fieldcomponents.put(fieldname,strfield); subpanel.add(namelabel); subpanel.add(strfield); } else if (fieldtype.equals("boolean")) { JCheckBox boolfield = new JCheckBox("yes"); boolfield.addItemListener(new FieldChangeHandler(fieldname) { public void itemStateChanged(ItemEvent e) { Boolean val = new Boolean( e.getStateChange()==ItemEvent.SELECTED ); processAction(this.fieldname,val); } }); boolfield.setFont(mainfont); boolfield.setForeground(textcolor); boolfield.setBackground(bgcolor); fieldcomponents.put(fieldname,boolfield); subpanel.add(namelabel); subpanel.add(boolfield); } else if (fieldtype.equals("key")) { KeyField keyfield = new KeyField(fieldname,bgcolor,hltcolor); fieldcomponents.put(fieldname,keyfield); keyfield.setToolTipText( "Click then press a key to define keystroke." ); keyfield.setFont(mainfont); keyfield.setForeground(textcolor); subpanel.add(namelabel); subpanel.add(keyfield); /* This is "work in progress" } else if (fieldtype.equals("int2")) { CoordPanel copanel = new CoordPanel( fieldname+".",(Point)fieldval); copanel.setCoordListener(new FieldChangeHandler(fieldname) { public void coordChanged(CoordPanel src) { processAction(this.fieldname,src.getValue()); } }); fieldcomponents.put(fieldname,copanel); subpanel.add(copanel); } else if (fieldtype.equals("int4")) { CoordPanel copanel = new CoordPanel( fieldname+".",(Rectangle)fieldval); copanel.setCoordListener(new FieldChangeHandler(fieldname) { public void coordChanged(CoordPanel src) { processAction(this.fieldname,src.getValue()); } }); fieldcomponents.put(fieldname,copanel); subpanel.add(copanel); } else if (fieldtype.equals("File")) { // create filechooser, put it in a separate frame JFileChooser filechooser = new JFileChooser(); JFrame filechframe = new JFrame("Select filename"); filechframe.getContentPane().add(filechooser); filechframe.pack(); filechooser.addActionListener( new FieldChangeHandler(fieldname,filechframe) { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("ApproveSelection")) { ((JFrame)component).setVisible(false); processAction(this.fieldname, ((JFileChooser)e.getSource()).getSelectedFile()); } } }); fieldcomponents.put(fieldname,filechooser); // add button to open file chooser frame JButton filechbut = new JButton("Select file"); filechbut.addActionListener(new FieldChangeHandler(filechframe) { public void actionPerformed(ActionEvent e) { ((JFrame)component).setVisible(true); } }); subpanel.add(new JLabel(fieldguiname,JLabel.RIGHT)); subpanel.add(filechbut); } else if (fieldtype.equals("Color")) { // create color chooser, put it in a separate frame JColorChooser colchooser = new JColorChooser((Color)fieldval); JFrame colchframe = new JFrame("Select colour"); colchframe.getContentPane().add(colchooser); colchframe.pack(); colchooser.getSelectionModel().addChangeListener( new FieldChangeHandler(fieldname,colchframe) { public void stateChanged(ChangeEvent e) { processAction( this.fieldname, ((ColorSelectionModel)e.getSource()) .getSelectedColor() ); //((JFrame)component).setVisible(false); //System.out.println(e); //if (e.getActionCommand().equals("ApproveSelection")) { // ((JFrame)component).setVisible(false); // processAction(fieldname, // ((JFileChooser)e.getSource()).getSelectedFile()); //} } }); fieldcomponents.put(fieldname,colchooser); // add button to open color chooser frame JButton colchbut = new JButton("Select colour"); colchbut.addActionListener(new FieldChangeHandler(colchframe) { public void actionPerformed(ActionEvent e) { JFrame comp_frame = (JFrame) component; comp_frame.setVisible(!comp_frame.isVisible()); //((JFrame)component).setVisible(true); } }); subpanel.add(new JLabel(fieldguiname,JLabel.RIGHT)); subpanel.add(colchbut); */ } }
6
public static List<ShoppingCartInfo> getEventOrders(int eventId) throws HibernateException { List<ShoppingCartInfo> shoppingCartInfoList = null; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); try { // Begin unit of work session.beginTransaction(); Calendar calendar = new GregorianCalendar(); String hql = "select o,o.orderFood from OrderInfo as o where o.orderStatus>0" + " and DAYOFMONTH(o.createDate)=" + calendar.get(Calendar.DAY_OF_MONTH) + " and MONTH(o.createDate)=" + (calendar.get(Calendar.MONTH) + 1) + " and YEAR(o.createDate)=" + calendar.get(Calendar.YEAR) + " and o.eventId=" + eventId; Query query = session.createQuery(hql); @SuppressWarnings("unchecked") List<Object[]> orders = query.list(); if (orders.size() > 0) { shoppingCartInfoList = new ArrayList<ShoppingCartInfo>(); for (int i = 0; i < orders.size(); i++) { Object[] orderInfo = orders.get(i); OrderInfo orderEntity = (OrderInfo) orderInfo[0]; FoodInfo foodEntity = (FoodInfo) orderInfo[1]; ShoppingCartInfo cartInfo = new ShoppingCartInfo(); cartInfo.setOrderInfo(new OrderInfo( orderEntity.getUserId(), orderEntity.getFoodId(), orderEntity.getFoodCount(), orderEntity .getEventId(), orderEntity.getOrderStatus(), orderEntity .getCreateDate())); cartInfo.setFoodInfo(foodEntity); cartInfo.setOrderTotalPrice(); shoppingCartInfoList.add(cartInfo); } } // End of task work session.getTransaction().commit(); } catch (HibernateException hex) { logger.error(hex.toString()); HibernateUtil.getSessionFactory().getCurrentSession() .getTransaction().rollback(); } catch (Exception ex) { logger.error(ex.toString()); HibernateUtil.getSessionFactory().getCurrentSession() .getTransaction().rollback(); } return shoppingCartInfoList; }
4
public void increment(int by) { // if given value is negative, we have to decrement if (by < 0) { decrement(Math.abs(by)); return; } // cut off full overflows by %= (range + 1); // check if we would still overflow int space_up = max - value; if (by > space_up) { // we check how big overflow is and add that to min by -= space_up + 1; value = min + by; } else { // no overflowing, this is easy value += by; } }
2
public String matt2browser(){ /*[["Vasya"],["Mon","Tue","Wen","Thu"],["20.09","21.09","22.09","23.09"] ,["10:00","10:30","11:00","11:30","12:00"] ,[[0,1,0,0],[1,0,0,1],[0,0,1,1],[0,0,0,1] ,[1,1,0,1]]]*/ //getting this view for browser. StringBuffer daysStr=null; String name=data.getName(); Date startDate=data.getStartDate(); int nDays=data.getnDays(); int startHour=data.getStartHour(); int endHour=data.getEndHour(); int timeSlot=data.getTimeSlot(); int timeSlots; int hours=0; if (!(startHour==endHour)) { if (startHour < endHour) { hours = (endHour - startHour) * 60; } else { hours = (24 - startHour + endHour) * 60; } timeSlots=hours/timeSlot; } else{ hours = (24 - startHour + endHour) * 60; timeSlots=(hours/timeSlot)-1; } Calendar cal = new GregorianCalendar(Locale.US); cal.setTime(startDate); SimpleDateFormat dfDays=new SimpleDateFormat("EEE",Locale.US); daysStr = new StringBuffer(); daysStr.append("[["); daysStr.append('"'); daysStr.append(name); daysStr.append('"'); daysStr.append("],["); daysStr.append('"'); daysStr.append(dfDays.format(cal.getTime())); daysStr.append('"'); for(int i=1;i<nDays;i++){ daysStr.append(delimiter); cal.add(Calendar.DAY_OF_WEEK, 1); daysStr.append('"'); daysStr.append(dfDays.format(cal.getTime())); daysStr.append('"'); } daysStr.append("],"); cal.setTime(startDate); dfDays.applyPattern("dd.MMM"); daysStr.append("["); daysStr.append('"'); daysStr.append(dfDays.format(cal.getTime())); daysStr.append('"'); for(int i=1;i<nDays;i++){ daysStr.append(delimiter); cal.add(Calendar.DAY_OF_WEEK, 1); daysStr.append('"'); daysStr.append(dfDays.format(cal.getTime())); daysStr.append('"'); } daysStr.append("],"); cal.setTime(startDate); cal.set(Calendar.HOUR_OF_DAY,startHour); cal.set(Calendar.MINUTE,0); dfDays.applyPattern("HH:mm"); daysStr.append("["); daysStr.append('"'); daysStr.append(dfDays.format(cal.getTime())); daysStr.append('"'); for(int i=1;i<timeSlots;i++){ daysStr.append(delimiter); cal.add(Calendar.MINUTE, timeSlot); daysStr.append('"'); daysStr.append(dfDays.format(cal.getTime())); daysStr.append('"'); } daysStr.append("],"); if(slots!=null){ Object[] tmpArr=slots.toArray(); daysStr.append("["); int count=0; for(int i=0;i<timeSlots;i++){ daysStr.append("["); count=i; for(int j=0;j<nDays;j++){ if((boolean) tmpArr[count].equals(true)){ daysStr.append(1);} else{ daysStr.append(0);} daysStr.append(','); count=count+timeSlots; } daysStr.insert(daysStr.length()-1, "]"); } int t=daysStr.length(); daysStr.setLength(t-1); daysStr.append("]]"); } return daysStr.toString(); }
9
public int solution(int X, int Y, int K, int A[], int B[]) { n = A.length+1; a = new Integer[n]; b = new Integer[n]; for(int i=0; i<n; i++){ a[i] = i<n-1 ? A[i] : X; a[i] -= i>0 ? A[i-1] : 0; b[i] = i<n-1 ? B[i] : Y; b[i] -= i>0 ? B[i-1] : 0; } Arrays.sort(a); Arrays.sort(b); int l=a[0]*b[0], r=a[n-1]*b[n-1]; while(l<r){ int mid = l+(r-l)/2; int greaterCount = count(mid); if(greaterCount<K) r=mid; else l=mid+1; } return l; }
7
@Override public boolean deleteChild(Expression<?> n) { if (!(n instanceof BinaryArithmeticOperator)) { return false; } if (children.get(0).equals(n))//left { children.set(0, ((Expression<?>) (n.randomChild()))); } else if (children.get(1).equals(n))//right { children.set(1, ((Expression<?>) (n.randomChild()))); } else { return false; } return true; }
6
private static boolean getMouseUp(int mouseButton) { return !getMouse(mouseButton) && lastMouse[mouseButton]; }
1
private void initPanelGameLayout() { GroupLayout PGL = new GroupLayout(zPanelGame); zPanelGame.setLayout(PGL); int PrefSize = GroupLayout.PREFERRED_SIZE, DefaSize = -1; ComponentPlacement RelaComp = LayoutStyle.ComponentPlacement.RELATED; SequentialGroup [] PGLHQ = new SequentialGroup[10]; ParallelGroup [] PGLVQ = new ParallelGroup[10]; ParallelGroup PGLHVG = PGL.createParallelGroup(GroupLayout.Alignment.LEADING); SequentialGroup PGLSVG = PGL.createSequentialGroup().addContainerGap(); for (int i=0;i<10;i++){ PGLHQ[i] = PGL.createSequentialGroup(); PGLVQ[i] = PGL.createParallelGroup(GroupLayout.Alignment.LEADING); for (int j=0;j<10;j++){ if (j!=0) PGLHQ[i].addPreferredGap(RelaComp); PGLHQ[i].addComponent(jPxy[i][j], PrefSize, (j==9||j==0)?25:65, PrefSize); PGLVQ[i].addComponent(jPxy[i][j], PrefSize, (i==9||i==0)?25:65, PrefSize);} if (i!=0) PGLSVG.addPreferredGap(RelaComp); PGLSVG.addGroup(PGLVQ[i]); PGLHVG.addGroup(PGLHQ[i]);} PGLSVG.addContainerGap(); PGL.setVerticalGroup(PGL.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup(PGLSVG)); PGL.setHorizontalGroup(PGL.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup(PGL.createSequentialGroup() .addContainerGap().addGroup(PGLHVG).addContainerGap()));}
8
public void statusUpdate(int updateMessageType, String extraInfo) { String message = "Parsing status update: "; switch (updateMessageType) { case ParserStatusMessage.PARSING_STARTED: message += "Parsing has started. Parsing library file \"" + extraInfo + "\"."; break; case ParserStatusMessage.PARSING_LIBRARY: message += "Now parsing library properties."; break; case ParserStatusMessage.PARSING_TRACKS: message += "Now parsing tracks (" + extraInfo + " tracks parsed)."; break; case ParserStatusMessage.PARSING_PLAYLISTS: message += "Now parsing playlists (" + extraInfo + " playlists parsed)."; break; case ParserStatusMessage.PARSING_FINISHED: message += "Parsing has finished. " + extraInfo; break; case ParserStatusMessage.PARSE_TIME_MESSAGE: message += extraInfo; break; } //only print the message out if it's something we care about.. if (!message.equals("Parsing status update: ")) { printStream.println(message); } }
7
@Test public void branchInstrInvalidOpcodeTest() { //To test instruction is not created with illegal opcode for format try { instr = new BranchInstr(Opcode.ADD, 0); } catch (IllegalStateException e) { System.out.println(e.getMessage()); } assertNull(instr); //instr should still be null if creation has failed, which it should because of invalid opcode }
1
private static void newTopscore() throws FileNotFoundException { String initials = ""; while(initials.equals("")) // Re-show the window until the user types something initials = dialogInput(); int rank = 0; for (int i=0; i<topscore_length;i++) { if (topScores[i] > moves) { rank = i; break; } } for (int j=topscore_length-1; j>rank; j--){ topScores[j]=topScores[j-1]; topNames[j]=topNames[j-1]; } if (moves <= 999) topScores[rank] = moves; else topScores[rank] = 999; topNames[rank] = initials; writeFile(); }
5
@Override public void mouseDragged(MouseEvent me) { this.drag = true; hp.mx = me.getX(); hp.my = me.getY(); int x = me.getX() / scale; int y = me.getY() / scale; hp.setDrag(new Vector3f(x, y, 0)); Color c = null; if(SwingUtilities.isRightMouseButton(me)) { c = bg; } else if(SwingUtilities.isLeftMouseButton(me)) { c = fg; } if(curTool == TOOL_PENCIL) { hp.color(c.getRGB(), x, y); } else if(curTool == TOOL_FILLER) { hp.fill(c.getRGB(), x, y); } else if(curTool == TOOL_CHOOSER) { if(SwingUtilities.isRightMouseButton(me)) { bg = hp.getColorAt(x, y); } else if(SwingUtilities.isLeftMouseButton(me)) { fg = hp.getColorAt(x, y); } hp.setColor(fg.getRGB()); this.setTool(lastTool); } this.repaint(); view.updateHeightmap(hp.getTexture()); }
7
public static void UpperType(){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ conn.setAutoCommit(false); PreparedStatement stmnt = conn.prepareStatement("UPDATE Media set type = UPPER(type)"); stmnt.execute(); conn.commit(); conn.setAutoCommit(true); }catch(SQLException e){ e.printStackTrace(); } }
4
public int findNearestABondIndex(int x, int y) { ABonds abonds = ((ExtendedFrameRenderer) repaintManager.frameRenderer).abonds; if (abonds == null) return -1; int n = 0; synchronized (abonds.getLock()) { n = abonds.count(); } if (n <= 0) return -1; initHighlightTriangle(); Triangles triangles = ((ExtendedFrameRenderer) repaintManager.frameRenderer).triangles; triangles.removeTriangle(highlightTriangle); int zmin = Integer.MAX_VALUE; ABond abond; int zDepth; int foundIndex = -1; Atom[] atom = modelManager.frame.atoms; if (polygon == null) polygon = new Polygon(); Atom a1, a2, a3; synchronized (abonds.getLock()) { for (int i = 0; i < n; i++) { abond = abonds.getABond(i); a1 = atom[abond.atom1]; a2 = atom[abond.atom2]; a3 = atom[abond.atom3]; polygon.reset(); polygon.addPoint(a1.screenX, a1.screenY); polygon.addPoint(a2.screenX, a2.screenY); polygon.addPoint(a3.screenX, a3.screenY); if (polygon.contains(x, y)) { zDepth = a1.screenZ + a2.screenZ + a3.screenZ; if (zDepth < zmin) { zmin = zDepth; foundIndex = i; } } } } if (foundIndex >= 0) { triangles.addTriangle(highlightTriangle); abond = abonds.getABond(foundIndex); highlightTriangle.setVertices(atom[abond.atom1], atom[abond.atom2], atom[abond.atom3]); } return foundIndex; }
7
public void calcSequences(BigLong2ShortHashMap hm, String fastaFP) throws FileNotFoundException { int freqThreshold = supergraphFreq.get(); int lenThreshold = sequenceLen.get(); int kValue = k.get(); banKmers(hm, freqThreshold, kValue); int sequenceId = 0; ArrayList<Integer> sequenceLen = new ArrayList<Integer>(); ArrayList<Long> sequenceWeight = new ArrayList<Long>(); long kmersInSeq = 0; long totalKmersInSequences = 0; PrintWriter fastaPW = new PrintWriter(fastaFP); Iterator<MutableLongShortEntry> it = hm.entryIterator(); while (it.hasNext()) { MutableLongShortEntry entry = it.next(); long key = entry.getKey(); int value = entry.getValue(); if (value <= freqThreshold) { continue; } ShortKmer kmer = new ShortKmer(key, kValue); if (getLeftNucleotide(kmer, hm, freqThreshold) >= 0) { continue; } StringBuilder sequenceSB = new StringBuilder(kmer.toString()); long seqWeight = 0, minWeight = value, maxWeight = value; while (true) { long kmerRepr = kmer.toLong(); value = hm.getWithZero(kmerRepr); seqWeight += value; minWeight = Math.min(minWeight, value); maxWeight = Math.max(maxWeight, value); hm.put(kmerRepr, BAN_VALUE); byte rightNuc = getRightNucleotide(kmer, hm, freqThreshold); if (rightNuc < 0) { break; } sequenceSB.append(DnaTools.toChar(rightNuc)); kmer.shiftRight(rightNuc); } if (sequenceSB.length() >= lenThreshold) { sequenceId++; String sequenceStr = sequenceSB.toString(); sequenceLen.add(sequenceStr.length()); sequenceWeight.add(seqWeight); totalKmersInSequences += seqWeight; kmersInSeq += sequenceStr.length() - kValue + 1; String seqInfo = String.format(">%d length=%d sum_weight=%d min_weight=%d max_weight=%d", sequenceId, sequenceStr.length(), seqWeight, minWeight, maxWeight); fastaPW.println(seqInfo); fastaPW.println(sequenceStr); if (sequenceId % 10000 == 0) { debug("sequenceId = " + sequenceId + ", last len = " + sequenceStr.length()); } } } info(sequenceId + " sequences found"); info(kmersInSeq + " unique k-mers out of " + hm.size() + " in sequences"); info("Total k-mers in sequences = " + totalKmersInSequences); info("N50 value of sequences = " + getN50(sequenceLen)); dumpSeqInfo(sequenceLen, sequenceWeight, workDir + File.separator + "seq-info"); fastaPW.close(); }
7
public void addOreSpawn(Block block, World world, Random random, int blockXPos, int blockZPos, int maxX, int maxZ, int maxVeinSize, int chancesToSpawn, int minY, int maxY) { // int maxPossY = minY + (maxY - 1); assert maxY > minY : "The maximum Y must be greater than the Minimum Y"; assert maxX > 0 && maxX <= 16 : "addOreSpawn: The Maximum X must be greater than 0 and less than 16"; assert minY > 0 : "addOreSpawn: The Minimum Y must be greater than 0"; assert maxY < 256 && maxY > 0 : "addOreSpawn: The Maximum Y must be less than 256 but greater than 0"; assert maxZ > 0 && maxZ <= 16 : "addOreSpawn: The Maximum Z must be greater than 0 and less than 16"; int diffBtwnMinMaxY = maxY - minY; for (int x = 0; x < chancesToSpawn; x++) { int posX = blockXPos + random.nextInt(maxX); int posY = minY + random.nextInt(diffBtwnMinMaxY); int posZ = blockZPos + random.nextInt(maxZ); (new WorldGenMinable(block, maxVeinSize)).generate(world, random, posX, posY, posZ); } }
4
public static void main(String[] args) throws IOException { int portNo = 9090; try { if (args.length == 1) { portNo = Integer.parseInt(args[0]); } } catch (Exception e) { System.err.println("Invalid port number!"); System.exit(1); } ServerSocket listener = new ServerSocket(9090); StockControl.startUpdater(120000); try { while (true) { Socket socket = listener.accept(); Thread t = new Thread(new ConnectionHandler(socket)); t.start(); } } finally { listener.close(); } }
3
public UserVO getStudent(UserVO userVO) throws LibraryManagementException { ConnectionFactory connectionFactory = new ConnectionFactory(); Connection connection; try { connection = connectionFactory.getConnection(); } catch (LibraryManagementException e) { throw e; } ResultSet resultSet = null; PreparedStatement preparedStatement = null; try { if (userVO != null) { preparedStatement = connection .prepareStatement("select * from STUDENT where EMAIL = ?"); preparedStatement.setString(1, userVO.getUserId()); resultSet = preparedStatement.executeQuery(); if(resultSet.next()) { userVO = new UserVO(); userVO.setId(resultSet.getInt("ID")); userVO.setUserId(resultSet.getString("EMAIL")); userVO.setPassword(resultSet.getString("PASSWORD")); userVO.setUserType("student"); } else { userVO = null; } } } catch (SQLException e) { throw new LibraryManagementException(ExceptionCategory.SYSTEM); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { throw new LibraryManagementException( ExceptionCategory.SYSTEM); } } connectionFactory.closeConnection(connection); } return userVO; }
6
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
public static synchronized ValidatedHandshakeResponse validate(HandshakeRequestEvent handshakeRequestEvent, Channel c) { ValidatedHandshakeResponse vhr = null; short errCode = matchVersionAndKey(handshakeRequestEvent.getVersion(), handshakeRequestEvent.getAccessKey()); if(errCode != ValidatedHandshakeResponse.NO_ERROR) { return handshakeFailedMessage(errCode); } DBQueryUserResult dbQuery = Database.getUser(handshakeRequestEvent.getUsername(), handshakeRequestEvent.getPassword()); if(dbQuery == null) { return handshakeFailedMessage(ValidatedHandshakeResponse.CAUSE_USERNAME_PASSWORD_NOMATCH); } else if(dbQuery.getIsBanned()) { return handshakeFailedMessage(ValidatedHandshakeResponse.CAUSE_USER_BANNED); } // TODO: Add the user to the Sessions. Sessions.addSession(new Session(dbQuery.getAsUser(), c)); vhr = new ValidatedHandshakeResponse(dbQuery.getId()); return vhr; }
3
public void actionPerformed(ActionEvent ae) { if(ae.getSource() == loginPanel.getLoginButton()) { String szUsername = loginPanel.getUsernameField(); String szPasscode = loginPanel.getPasscodeField(); if(!(szUsername.isEmpty() || szPasscode.isEmpty())) { try { if(ub.authenticate(szUsername,szPasscode)) { setVisible(false); new FileSelectorWindow(); dispose(); } else JOptionPane.showMessageDialog(null,"Incorrect Username or Passcode.", "Case Sensitive", JOptionPane.ERROR_MESSAGE); } catch(IOException ioe) { //JOptionPane.showMessageDialog(null,ioe.getMessage()); JOptionPane.showMessageDialog(null,"Incorrect Username or Passcode.", "Case Sensitive", JOptionPane.ERROR_MESSAGE); } } else JOptionPane.showMessageDialog(null,"Username or Passcode fields can not be empty."); } else if (ae.getSource() == loginPanel.getRegisterButton()) { setVisible(false); new RegisterFrame(thisFrame,ub); } else if (ae.getSource() == loginPanel.getRecoveryButton()) { setVisible(false); new RecoverFrame(thisFrame,ub); } }
7
private static List<Exprent> extractParameters(List<PooledConstant> bootstrapArguments, InvocationExprent expr) { List<Exprent> parameters = expr.getLstParameters(); if (bootstrapArguments != null) { PooledConstant constant = bootstrapArguments.get(0); if (constant.type == CodeConstants.CONSTANT_String) { String recipe = ((PrimitiveConstant)constant).getString(); List<Exprent> res = new ArrayList<>(); StringBuilder acc = new StringBuilder(); int parameterId = 0; for (int i = 0; i < recipe.length(); i++) { char c = recipe.charAt(i); if (c == TAG_CONST || c == TAG_ARG) { // Detected a special tag, flush all accumulated characters // as a constant first: if (acc.length() > 0) { res.add(new ConstExprent(VarType.VARTYPE_STRING, acc.toString(), expr.bytecode)); acc.setLength(0); } if (c == TAG_CONST) { // skip for now } if (c == TAG_ARG) { res.add(parameters.get(parameterId++)); } } else { // Not a special characters, this is a constant embedded into // the recipe itself. acc.append(c); } } // Flush the remaining characters as constant: if (acc.length() > 0) { res.add(new ConstExprent(VarType.VARTYPE_STRING, acc.toString(), expr.bytecode)); } return res; } } return new ArrayList<>(parameters); }
9
private void reactOnNextButton() { _nextButtonWasClicked++; // nextButton will be enabled after something was dropped, so this will // be called after something was dropped if (_nextButtonWasClicked == 1) { setCoverArtDropMode(); } else if (_nextButtonWasClicked >= 2) { // now finally we have gotten the files which belong to this medium // AND we got the coverart! // lets go save this and ask for further medium specific // questions (e.g. music album, interpret or game name...) in new windows Type droppedMediumType; try { droppedMediumType = _dropboxTool.getDroppedMediumType(); if(droppedMediumType != null){ if (droppedMediumType.equals(Type.MUSIC)) { AddMusicTool addMusicTool = new AddMusicTool(_dropboxTool.getFiles(), _dropboxTool.getCoverArt()); _mediumspecquesttool = addMusicTool; informAllObserversAboutChanges(); } else if (droppedMediumType.equals(Type.VIDEO)) { System.out.println("Video hinzufügen"); AddVideoTool addVideoTool = new AddVideoTool(_dropboxTool.getFiles(), _dropboxTool.getCoverArt()); _mediumspecquesttool = addVideoTool; informAllObserversAboutChanges(); } else if (droppedMediumType.equals(Type.PICTURES)) { System.out.println("Bilder hinzufügen"); } else if (droppedMediumType.equals(Type.PROGRAM)) { System.out.println("Program/Spiel hinzufügen"); }else{ //cant recognize filetype JOptionPane.showMessageDialog(null,"Woops...magicBook can't recognize this filetype."); } }else{ //URL was entered, otherwise we wouldnt be here //String title = JOptionPane.showInputDialog(null, "What's the title for this URL?"); //URL url = new URL } } catch (Exception e) { /* TODO: maybe present the exception to the user 16.06.2012 */ e.printStackTrace(); } // _ui.closeWindow(); } }
8
@Override public ArrayList<Position> getPossibleMoves() { possibleMoves = new ArrayList<Position>(); for (Move move : moves) { int newX = getPosition().getX() + move.getX(); int newY = getPosition().getY() + move.getY(); newX = newX + move.getX(); if (newX < 0 || 7 < newX) continue; if (newY < 0 || 7 < newY) continue; possibleMoves.add(new Position(newX, newY)); newY = newY + move.getY(); if (newX < 0 || 7 < newX) continue; if (newY < 0 || 7 < newY) continue; possibleMoves.add(new Position(newX, newY)); } return possibleMoves; }
9
static protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; }
6
@Override public void saveTrace(String filename) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); for (AgentState s : state){ if (s instanceof DirtBasedAgentState){ DirtBasedAgentState b = (DirtBasedAgentState)s; int dist [] = b.getDistances(); int type[] = b.getTypes(); String output = ""; for (Direction d : Direction.values()){ output += dist[d.ordinal()] + "|" + type[d.ordinal()] + "|"; } output += s.getAction().name(); writer.write(output + "\n"); } } writer.close(); } catch (IOException e) { e.printStackTrace(); } }
4
@XmlElementDecl(namespace = "http://www.w3.org/2001/04/xmlenc#", name = "EncryptionProperty") public JAXBElement<EncryptionPropertyType> createEncryptionProperty(EncryptionPropertyType value) { return new JAXBElement<EncryptionPropertyType>(_EncryptionProperty_QNAME, EncryptionPropertyType.class, null, value); }
0
final void delete(int index) { if (!isNominal() && !isString() && !isRelationValued()) throw new IllegalArgumentException("Can only remove value of " + "nominal, string or relation-" + " valued attribute!"); else { m_Values = Utils.cast(m_Values.clone()); m_Values.remove(index); if (!isRelationValued()) { Hashtable<Object,Integer> hash = new Hashtable<Object,Integer>(m_Hashtable.size()); Enumeration enu = m_Hashtable.keys(); while (enu.hasMoreElements()) { Object string = enu.nextElement(); Integer valIndexObject = (Integer)m_Hashtable.get(string); int valIndex = valIndexObject.intValue(); if (valIndex > index) { hash.put(string, new Integer(valIndex - 1)); } else if (valIndex < index) { hash.put(string, valIndexObject); } } m_Hashtable = hash; } } }
7
public boolean delete(Word t){ Node temp; Node ptr = findNode(t); if(ptr == null) return false; if(ptr.left() == null){ ptr.setData(ptr.right().data()); ptr.setRight(ptr.right().right()); ptr.setLeft(ptr.right().left()); return true; } else if(ptr.right() == null){ ptr.setData(ptr.left().data()); ptr.setLeft(ptr.left().left()); ptr.setRight(ptr.left().right()); return true; } else{ temp = ptr.right(); while(temp.left() != null){ temp = temp.left(); } ptr.setData(temp.data()); ptr.setRight(temp.right()); return true; } }
4
protected void processPath() { while (activeNode.getxCoord() != endX || activeNode.getyCoord() != endY && !openNodes.isEmpty()) { checkOpenNodes(); activeNode.mapPiece.togglePath(); pathNodes.add(activeNode); if (activeNode.getxCoord() == endX && activeNode.getyCoord() == endY) { } else { openNodes.remove(activeNode); closedNodes.add(activeNode); addNodesNeighbours(); for (AStarNode neighbourNode : neighbourNodes) { if (closedNodes.contains(neighbourNode)) { calculateG(neighbourNode); neighbourNode.setParent(activeNode); } else if (openNodes.contains(neighbourNode)) { calculateG(neighbourNode); neighbourNode.setParent(activeNode); } else { openNodes.add(neighbourNode); calculateG(neighbourNode); } } } } }
8
public static void createDelFile(String genomeName, String outFile, double prob) throws IOException { Config config = new Config(genomeName, Gpr.HOME + "/snpEff/" + Config.DEFAULT_CONFIG_FILE); config.loadSnpEffectPredictor(); Random rand = new Random(20140129); StringBuilder out = new StringBuilder(); int count = 0; for (Gene g : config.getGenome().getGenes()) { for (Transcript tr : g) { for (Exon e : tr) { for (int i = e.getStart(); i < e.getEnd(); i++) { if (rand.nextDouble() < prob) { // Deletion length int delLen = rand.nextInt(10) + 2; if (i + delLen > e.getEnd()) delLen = e.getEnd() - i; if (delLen >= 2) { int idx = i - e.getStart(); String ref = e.basesAt(idx, delLen); String alt = ref.substring(0, 1); int pos = i + 1; String line = e.getChromosomeName() + "\t" + pos + "\t.\t" + ref + "\t" + alt + "\t.\t.\tAC=1\tGT\t0/1"; System.out.println(line); out.append(line + "\n"); count++; } } } } } } System.err.println("Count:" + count); System.out.println("Output file: " + outFile); Gpr.toFile(outFile, out); }
7
public static void modify(ConcordiaMembers concordiaMember){ boolean correctInput = false; Scanner myKey = new Scanner(System.in); do{ System.out.println("Press 1 to modify Name\nPress 2 to modify Concordia ID\nPress 3 to modify Status and other Attributes"); int option = myKey.nextInt(); switch(option){ case 1:{ System.out.print("What is the first name of this individual? "); String firstName=myKey.next(); System.out.print("What is the last name of " + firstName + "? "); String lastName=myKey.next(); concordiaMember.setFirstName(firstName); concordiaMember.setLastName(lastName); System.out.println("Changes updated!"); correctInput =true; break; } case 2:{ System.out.print("What is the Concordia ID? :"); String concordiaID=myKey.next(); concordiaMember.setConcordiaID(concordiaID); System.out.println("Changes updated!"); correctInput =true; break; } case 3:{ if(concordiaMember instanceof StaffMembers){ modifyStaff(concordiaMember); } else if(concordiaMember instanceof Students){ modifyStudent(concordiaMember); } else if(concordiaMember instanceof FacultyMembers){ modifyFaculty(concordiaMember); } System.out.println("Changes updated!"); correctInput = true; break; } default:{ System.out.println("Invalid Entry. Try again!"); break; } } } while(correctInput==false); }
7
private int[] getColumnStartingPositions(String line) { int[] columns = new int[34]; boolean skipBlanks = true; int j = 0; for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); if (ch == ' ') { if (!skipBlanks) { columns[j++] = i; skipBlanks = true; } } else { skipBlanks = false; } } columns[j] = line.length(); return columns; }
3
public void init(int mode, byte[] key, byte[] iv) throws Exception{ byte[] tmp; if(key.length>bsize){ tmp=new byte[bsize]; System.arraycopy(key, 0, tmp, 0, tmp.length); key=tmp; } try{ cipher=javax.crypto.Cipher.getInstance("RC4"); SecretKeySpec _key = new SecretKeySpec(key, "RC4"); cipher.init((mode==ENCRYPT_MODE? javax.crypto.Cipher.ENCRYPT_MODE: javax.crypto.Cipher.DECRYPT_MODE), _key); byte[] foo=new byte[1]; for(int i=0; i<skip; i++){ cipher.update(foo, 0, 1, foo, 0); } } catch(Exception e){ cipher=null; throw e; } }
4
@Override public void paint(Graphics g) { String romText = "Rom: Punkte: "; String karText = "Karthago: Punkte: "; lblNewLabel.setText("Aktueller Spieler: " + spiel.getAktuellerSpieler().toString()); brett.repaint(); super.paint(g); /*rom.setText(romText + brett.getGraph().getScore(Owner.Rom)); karthago.setText(karText + brett.getGraph().getScore(Owner.Cathargo)); PlayerAbs curPlayer = spiel.getCurrentPlayer(); amZug.setText("Am Zug ist: " + curPlayer.toString()); brett.repaint(); super.paint(g); if (spiel.isGameOver()) { if (brett.getGraph().getScore(Owner.Cathargo) < brett .getGraph().getScore(Owner.Rom)) rom.setText(romText + brett.getGraph().getScore(Owner.Rom) + " \t Gewinner"); else if (brett.getGraph().getScore(Owner.Cathargo) > brett .getGraph().getScore(Owner.Rom)) karthago.setText(karText + brett.getGraph().getScore(Owner.Cathargo) + " \t Gewinner"); lblGameOver.setVisible(true); }*/ }
0
@SuppressWarnings("static-access") @Override public String execute(String[] arg)throws ClassNotFoundException, IOException{ long pid = System.currentTimeMillis() % 100000; if(runList != null){ process = new Process(arg, process.IDLE, pid); runList.enQueue(process); }else return "ERROR: Batch not created!\n"; return "process " + process.getName() + " added to batch.\n"; }
1
private void handleGetConstants(TACMessage msg) { // The status code will be NOT_SUPPORTED and the message will contain // no other fields if the server did not support this command // => does not need to check it while (msg.nextTag()) { if (msg.isTag("gameLength")) { int len = msg.getValueAsInt(-1); if (len > 0) { this.gameLength = len * 1000; } } else if (msg.isTag("gameType")) { this.playingGameType = msg.getValue(); } } }
4
public String getWorkPosition() { return WorkPosition; }
0
public static final FileWatcherService getInstance(List<String> watchedFiles, EventBus eventBus) { if(INSTANCE==null) { INSTANCE = new FileWatcherService(watchedFiles,eventBus); } return INSTANCE; }
1
public void generateGameGraph(Game g){ if (isGameOver(g)){ return; } for (Node n : g.getNodes()){ for (Node m : g.getNodes()){ List<Face> common = getCommonFaces(n, m, g); if (!(common.isEmpty())){ for (Face f : common){ for (List<Boundary> b : getBoundaryPowerSet(f.getBoundaries())){ if (b.contains(n.getBoundaries()) || b.contains(m.getBoundaries())) continue; Game child = makeMove(n,m,b,g); if(child == null) continue; g.addChild(child); generateGameGraph(child); } } } } } }
9
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(GUI_ListaLectura.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUI_ListaLectura.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUI_ListaLectura.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUI_ListaLectura.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 GUI_ListaLectura().setVisible(true); } }); }
6
@Override protected void controlUpdate(float tpf) { if(((Node)spatial).getChild("Ninja") != null){ CharAnimationControl cac = ((Node)spatial).getChild("Ninja").getControl(CharAnimationControl.class); MeleeControl mc = spatial.getControl(MeleeControl.class); if(comboCommand == ComboName.COMBO1){ mc.setCommands(combo1_1); mc.setEnabled(enabled); cac.setCommand(combo1_1); }else if(comboCommand == ComboName.COMBO2){ mc.setCommands(combo2_1); mc.setEnabled(enabled); cac.setCommand(combo2_1); }else if(comboCommand == ComboName.COMBO3){ mc.setCommands(combo3_1); mc.setEnabled(enabled); cac.setCommand(combo3_1); }else if(comboCommand == ComboName.COMBO4){ mc.setCommands(combo4_1); mc.setEnabled(enabled); cac.setCommand(combo4_1); }else if(comboCommand == ComboName.COMBO5){ mc.setCommands(combo5_1); mc.setEnabled(enabled); cac.setCommand(combo5_1); }else if(comboCommand == ComboName.COMBO6){ mc.setCommands(combo6_1); mc.setEnabled(enabled); cac.setCommand(combo6_1); } comboCommand = ComboName.NONE; } checkComboChain(); }
7
public Member(String display, boolean isMethod, boolean manageModifier) { this.hasUrl = new UrlBuilder(null, ModeUrl.ANYWHERE).getUrl(display) != null; final Pattern pstart = MyPattern.cmpile("^(" + UrlBuilder.getRegexp() + ")([^\\[\\]]+)$"); final Matcher mstart = pstart.matcher(display); if (mstart.matches()) { if (mstart.groupCount() != 5) { throw new IllegalStateException(); } final UrlBuilder urlBuilder = new UrlBuilder(null, ModeUrl.AT_START); url = urlBuilder.getUrl(mstart.group(1)); url.setMember(true); display = /* mstart.group(1).trim() + */mstart.group(mstart.groupCount()).trim(); } else { final Pattern pend = MyPattern.cmpile("^([^\\[\\]]+)(" + UrlBuilder.getRegexp() + ")$"); final Matcher mend = pend.matcher(display); if (mend.matches()) { if (mend.groupCount() != 5) { throw new IllegalStateException(); } final UrlBuilder urlBuilder = new UrlBuilder(null, ModeUrl.AT_END); url = urlBuilder.getUrl(mend.group(2)); url.setMember(true); display = mend.group(1).trim(); } else { url = null; } } final String lower = display.toLowerCase(); if (manageModifier) { this.staticModifier = lower.contains("{static}") || lower.contains("{classifier}"); this.abstractModifier = lower.contains("{abstract}"); String displayClean = display.replaceAll("(?i)\\{(static|classifier|abstract)\\}", "").trim(); if (displayClean.length() == 0) { displayClean = " "; } if (VisibilityModifier.isVisibilityCharacter(displayClean.charAt(0))) { visibilityModifier = VisibilityModifier.getVisibilityModifier(display.charAt(0), isMethod == false); this.display = displayClean.substring(1).trim(); } else { this.display = displayClean; visibilityModifier = null; } } else { this.staticModifier = false; this.visibilityModifier = null; this.abstractModifier = false; display = display.trim(); this.display = display.length() == 0 ? " " : display.trim(); } }
9
public static BaseImage biCubicSmooth(BaseImage img, int width, int height) { if(width > img.getWidth() || height > img.getHeight()) { throw new IllegalStateException("Both width and height must be less then the current image!!"); } int scaleFactor = 7; BaseImage nimg = img; BaseImage resizedImg; while(true) { int runWidth = width; int runHeight = height; if(nimg.getWidth() > width) { runWidth = nimg.getWidth()-Math.max(1, (nimg.getWidth()/scaleFactor)); if(runWidth < width) { runWidth = width; } } if(nimg.getHeight() > height) { runHeight = nimg.getHeight()-Math.max(1, (nimg.getHeight()/scaleFactor)); if(runHeight < height) { runHeight = height; } } resizedImg = nimg.resize(runWidth, runHeight, false, BaseImage.ScaleType.CUBIC); nimg = resizedImg; if(nimg.getWidth() == width && nimg.getHeight() == height) { break; } } return resizedImg; }
9
public void cambiarPosicionJugado2(){ for(int x=0;x<8;x++){ for(int y=0;y<8;y++){ if(pd.mapa_jugador2[x][y].equals(codigo)) pd.mapa_jugador2[x][y]=""; } } int x=rd.nextInt(0)+7; int y=rd.nextInt(0)+7; cambiarPosicionJugado2(); }
3
private static void logHierarchy(String prefix, ClassLoader classLoader) { if (!isDiagnosticsEnabled()) { return; } ClassLoader systemClassLoader; if (classLoader != null) { final String classLoaderString = classLoader.toString(); logDiagnostic(prefix + objectId(classLoader) + " == '" + classLoaderString + "'"); } try { systemClassLoader = ClassLoader.getSystemClassLoader(); } catch(SecurityException ex) { logDiagnostic( prefix + "Security forbids determining the system classloader."); return; } if (classLoader != null) { StringBuffer buf = new StringBuffer(prefix + "ClassLoader tree:"); for(;;) { buf.append(objectId(classLoader)); if (classLoader == systemClassLoader) { buf.append(" (SYSTEM) "); } try { classLoader = classLoader.getParent(); } catch(SecurityException ex) { buf.append(" --> SECRET"); break; } buf.append(" --> "); if (classLoader == null) { buf.append("BOOT"); break; } } logDiagnostic(buf.toString()); } }
8
@Override public boolean isWebDriverType(String type) { return StringUtils.equalsIgnoreCase("firefox", type); }
0
public int handvalue(int hou, int han) { if (han == -2) { return 16000; } else if (han >= 15 || han == -1) { return 8000; } else if (han >= 13) { return 6000; } else if (han >= 10) { return 4000; } else if (han >= 8) { return 3000; } else if (han >= 7) return 2000; else if (han >= 3) { int value = hou * (int) Math.pow(2, han); if (value >= 2000) return 2000; else return value; } else { // error case // TODO print something useful? return 0; } }
9
@Override public Node streetQuery(String streetNameA, String streetNameB) throws IOException { // System.out.println("Calling streetQuery."); Node node = null; String input = null; try { StringBuilder sb = new StringBuilder("streetQuery\n"); sb.append(ProtocolParser.encodeString(streetNameA)); sb.append(ProtocolParser.encodeString(streetNameB)); String output = ProtocolParser.appendLineCount(sb.toString()); writer.print(output); writer.flush(); int lines = Integer.parseInt(reader.readLine().trim()); sb = new StringBuilder(); for (int i = 0; i < lines; i++) { String line = reader.readLine().trim(); sb.append(line); sb.append("\n"); } input = sb.toString(); } catch (IOException e){ System.err.println("ERROR: problem interacting with server."); System.err.println(e.getMessage()); } catch (NullPointerException e) { System.err.println("ERROR: not receiving server response."); e.printStackTrace(); } if (input != null) if (input.startsWith("Node")) { node = ProtocolParser.decodeNode(input); } else if (input.startsWith("IOException")) { throw ProtocolParser.decodeIOException(input); } return node; }
6
final int addVertex(int x, int y, int z) { for (int i1 = 0; i1 < vertexCount; i1++) { if (verticesX[i1] == x && y == verticesY[i1] && verticesZ[i1] == z) { return i1; } } verticesX[vertexCount] = x; verticesY[vertexCount] = y; verticesZ[vertexCount] = z; maxVertex = 1 + vertexCount; return vertexCount++; }
4
private void processAddMasterFile(Sim_event ev) { if (ev == null) { return; } Object[] pack = (Object[]) ev.get_data(); if (pack == null) { return; } File file = (File) pack[0]; // get the file file.setMasterCopy(true); // set the file into a master copy int sentFrom = ((Integer) pack[1]).intValue(); // get sender ID /****** // DEBUG System.out.println(super.get_name() + ".addMasterFile(): " + file.getName() + " from " + GridSim.getEntityName(sentFrom)); *******/ Object[] data = new Object[3]; data[0] = file.getName(); int msg = addFile(file); // add the file if (msg == DataGridTags.FILE_ADD_SUCCESSFUL) { registerMasterFile(file); data[1] = new Integer(sentFrom); masterFilesWaitingForAddACK_.add(data); } else { data[1] = new Integer(-1); // no sender id data[2] = new Integer(msg); // the result of adding a master file sim_schedule(outputPort_, 0, DataGridTags.FILE_ADD_MASTER_RESULT, new IO_data(data, DataGridTags.PKT_SIZE, sentFrom)); } }
3
@Override public void processChangeRoom() { System.out.println("Current Room:" + getCurrentRoom().getName()); int iNumMonsters = getCurrentRoom().getNumLivingBeings()-1; System.out.println("Number of monsters in current website: "+iNumMonsters+"."); if (iNumMonsters > 0) System.out.println("Monsters:"); for (int i = 0; i < iNumMonsters; i++) { System.out.println("\t"+getCurrentRoom().getLivingBeing(i).getName()); } int iNumDoors = getCurrentRoom().getNumDoors(); System.out.println("Number of hyperlinks leading out of this website:" + iNumDoors); System.out.println("Hyperlinks:"); for (int i = 0; i < iNumDoors; i++) { System.out.println("\tLeads To:"+getCurrentRoom().getDoor(i).getLeadsTo().getName()); } if (Math.random() > .5) { Potion p = new Potion(); bag.add(p); System.out.println("You found a "+p+"!"); } }
4
public static <T1, T2> List<TestCase<?, ?>> createByParams(String format, T1 expected, T2[] params) { List<TestCase<?, ?>> cases = new ArrayList<TestCase<?, ?>>(); for(T2 param : params) cases.add(new TestCase<T1, T2>(format, expected, param)); return cases; }
7
@EventHandler public void WitherWither(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.getZombieConfig().getDouble("Wither.Wither.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (damager instanceof WitherSkull) { WitherSkull a = (WitherSkull) event.getDamager(); LivingEntity shooter = a.getShooter(); if (plugin.getWitherConfig().getBoolean("Wither.Wither.Enabled", true) && shooter instanceof Wither && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, plugin.getWitherConfig().getInt("Wither.Wither.Time"), plugin.getWitherConfig().getInt("Wither.Wither.Power"))); } } }
7
@Override public void set(Object target, Object value) { if (staticBase != null) target = staticBase; if (type == int.class) unsafe.putInt(target, offset, (Integer) value); else if (type == short.class) unsafe.putShort(target, offset, (Short) value); else if (type == long.class) unsafe.putLong(target, offset, (Long) value); else if (type == byte.class) unsafe.putByte(target, offset, (Byte) value); else if (type == float.class) unsafe.putFloat(target, offset, (Float) value); else if (type == double.class) unsafe.putDouble(target, offset, (Double) value); else if (type == boolean.class) unsafe.putBoolean(target, offset, (Boolean) value); else if (type == char.class) unsafe.putChar(target, offset, (Character) value); else unsafe.putObject(target, offset, value); }
9
@EventHandler public void EnderDragonFireResistance(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.getEnderDragonConfig().getDouble("EnderDragon.FireResistance.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; }dodged = true; if (plugin.getEnderDragonConfig().getBoolean("EnderDragon.FireResistance.Enabled", true) && damager instanceof EnderDragon && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, plugin.getEnderDragonConfig().getInt("EnderDragon.FireResistance.Time"), plugin.getEnderDragonConfig().getInt("EnderDragon.FireResistance.Power"))); } }
6
public static boolean deletePerson(String userid) { ResultSet rs = null; Connection con = null; PreparedStatement ps = null; boolean result = true; try { String sql = "DELETE FROM PERSON WHERE userid=(?)"; con = ConnectionPool.getConnectionFromPool(); ps = con.prepareStatement(sql); ps.setString(1, userid); ps.executeUpdate(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { ConnectionPool.addConnectionBackToPool(con); } catch (Exception e) { e.printStackTrace(); } } } return result; }
7
@Override public boolean isSearched(String url) { return false; }
0
public String version() throws BITalinoException { try { socket.write(7); ByteBuffer buffer = ByteBuffer.allocate(30); // read until '\n' arrives byte b = 0; while ((char) (b = (byte) socket.getInputStream().read()) != '\n') buffer.put(b); // return a minified array buffer.flip(); return new String(buffer.array()); } catch (Exception e) { throw new BITalinoException(BITalinoErrorTypes.LOST_COMMUNICATION); } }
2
public void sincronizaArticulos(){ // TRAIGO EL ID POS PhpposAppConfigEntity appConfig = getAppConfig("id_pos"); // PREGUNTAR SI EL ID POS ESTA CONFIGURADO if (appConfig != null){ int idPos = Integer.parseInt(appConfig.getValue()); logger.info("****>>> idPos = " + idPos); // TRAIGO LA LISTA DE PRECIOS DE ORACLE List<PosListaPrecio> listaPrecios = facOracleDAO.getListaPrecios(idPos); logger.info("listaPrecios = " + listaPrecios.size()); for (PosListaPrecio itemOracle : listaPrecios) { try { char estadoItemOracle = itemOracle.getPcaEstado().toCharArray()[0]; logger.info("****>>> itemOracle.getPcaDescripcion() = " + itemOracle.getPcaDescripcion()+"\t****>>> estadoItemOracle = " + estadoItemOracle); switch (estadoItemOracle){ case 'N': saveNewItem(itemOracle, idPos); break; case 'U': updateItem(itemOracle, idPos); break; case 'I': inactivaItem(itemOracle, idPos); break; } } catch (DataAccessException e){ logger.info("e.getMessage() = " + e.getMessage()); } catch (Exception e){ e.printStackTrace(); logger.info("e.getMessage() = " + e.getMessage()); } } } }
7
public static void visitFilesRecursively(FileVisitor visitor, File directory, String filePattern, String directoryPattern, boolean recursively) { if (!directory.isDirectory()) directory = directory.getParentFile(); if (!directory.getName().matches(directoryPattern)) return; visitor.visitDirectory(directory); final ArrayList<File> childDirectories = new ArrayList<File>(); for (File file : directory.listFiles()) { if (file.isDirectory()) { childDirectories.add(file); } else if (file.isFile()) { if (!file.getName().matches(filePattern)) continue; visitor.visitFile(file); } } if (recursively) { for (File childDirectory : childDirectories) { visitFilesRecursively(visitor, childDirectory, filePattern, directoryPattern, recursively); } } }
8
private void saveBookingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBookingButtonActionPerformed boolean commitSuccess; if (!newBookingModel.isEmpty()) { int reply = jOptionPane.showConfirmDialog(this, "Are you sure you want to save?", "Save?", jOptionPane.YES_NO_OPTION); if (reply == jOptionPane.YES_OPTION) { commitSuccess = ctr.saveBooking(); ArrayList<Booking> bookingsNotSaved = ctr.getBookingsNotSaved(); if (bookingsNotSaved.size() > 0) { String stringShow = ""; for (Booking booking : bookingsNotSaved) { String str = "Room: " + booking.getRoomNo() + " is already occupied from " + booking.getCheckInDate() + " to " + booking.getCheckOutDate() + "\n"; stringShow = stringShow.concat(str); } jOptionPane.showMessageDialog(this, stringShow); } if (commitSuccess) { newBookingModel.clear(); newBookingStatusLabel.setText("Booking(s) were saved!"); refreshBookingTable(bookingTableModel); refreshRoomTable(roomTableModel, checkIn.getDate(), checkOut.getDate()); } else { jOptionPane.showMessageDialog(this, "Something went wrong with saving the booking!", "Booking Error! - rollback", jOptionPane.ERROR_MESSAGE); } } } else { newBookingStatusLabel.setText("There is no bookings to be saved."); } }//GEN-LAST:event_saveBookingButtonActionPerformed
5
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (active(request)) //if there is an active user { if (request.getRequestURI().equals(request.getContextPath() + "/blabs")) //if there is no string after blabs/ { //current user blab feed (following and own blabs) List<Blab> blabs = (List<Blab>)blabMain.getFeed(user.getEmail()); if (blabs.size() == 0) request.setAttribute("noMessages", "You have no blabs to display"); request.setAttribute("pageTitle", "Blab Feed"); request.getSession().setAttribute("blabs", blabs); request.setAttribute("list", true); request.getRequestDispatcher("/blabs.jsp").forward(request, response); return; } else //if there is a string after blabs/ { //find the last occurrence of / int last = request.getRequestURI().lastIndexOf('/'); String uri = request.getRequestURI().substring(last + 1); try //parse the uri string into an integer { int id = Integer.parseInt(uri); //single blab Blab blab = blabMain.getBlab(id); if (blab.getContent() == null) //if this blab does not exist { request.getRequestDispatcher("/404.jsp").forward(request, response); return; } request.getSession().setAttribute("blabs", blab); request.setAttribute("list", false); request.setAttribute("pageTitle", "Blab: #" + uri); request.getRequestDispatcher("/blabs.jsp").forward(request, response); } catch (NumberFormatException nfe) //the uri parsed is actually a string { //blabs for a specific user ProfileMain profileMain = new ProfileMain(); profileMain.setDataSource(dataSource); String email = profileMain.getEmail(uri); if ((profileMain.getUser(email)).getUsername() == null) //if the user does not exist { request.getRequestDispatcher("/404.jsp").forward(request, response); return; } List<Blab> blabs = blabMain.getBlabs(email); if (blabs.size() == 0) //if this user has not blabbed yet request.setAttribute("noMessages", "This user has not blabbed yet"); request.getSession().setAttribute("blabs", blabs); request.setAttribute("list", true); request.setAttribute("pageTitle", "Blabs by: @" + uri); request.getRequestDispatcher("/blabs.jsp").forward(request, response); } return; } } else { response.sendRedirect(request.getContextPath() + "/login"); //must be logged in to blab return; } }
7
boolean putPiece(int p, int row, int col) { // пробуем вставить паззл на доску, возвращает True если подходит if (board.getColor(row,col) != null) return false; for (int i = 1; i < 8; i += 2) { if (row+pieces[p][i] < 0 || row+pieces[p][i] >= rows || col+pieces[p][i+1] < 0 || col+pieces[p][i+1] >= cols) return false; else if (board.getColor(row+pieces[p][i],col+pieces[p][i+1]) != null) // один из нужных квадратов уже занят return false; } board.setColor(row,col,pieceColor[pieces[p][0]]); for (int i = 1; i < 8; i += 2) board.setColor(row + pieces[p][i], col + pieces[p][i+1], pieceColor[pieces[p][0]]); return true; }
8
public void setPrice(String price) { this.price = price; }
0
private TypeHolder _eraseTypeVariables(Map<String, TypeHolder> variable2Holder, Set<String> visitedVariables, TypeHolder typeHolder) { if (typeHolder.getRawClass() == null) { if (variable2Holder.containsKey(typeHolder.getName())) { TypeHolder th = variable2Holder.get(typeHolder.getName()); WildcardBound newWildcardBound = typeHolder.getWildcardBound() == WildcardBound.NO_WILDCARD ? th.getWildcardBound() : typeHolder.getWildcardBound(); visitedVariables.add(typeHolder.getName()); return th.changeWildcardBound(newWildcardBound); } else { if (visitedVariables.contains(typeHolder.getName())) { return TypeHolder.newInstance(Object.class).changeWildcardBound(WildcardBound.UPPER); } else { visitedVariables.add(typeHolder.getName()); for (TypeVariableHolder typeVariable : this.typeVariables) { if (typeVariable.getName().equals(typeHolder.getName())) { if (typeVariable.getTypeParams().size() > 0) { TypeHolder th = _eraseTypeVariables(variable2Holder, visitedVariables, typeVariable.getTypeParams().get(0)).changeWildcardBound(WildcardBound.UPPER); variable2Holder.put(typeHolder.getName(), th); return th; } else { TypeHolder th = TypeHolder.newInstance(Object.class).changeWildcardBound(WildcardBound.UPPER); variable2Holder.put(typeHolder.getName(), th); return th; } } } throw new IllegalStateException(); } } } else { List<TypeHolder> newTypeParams = new ArrayList<TypeHolder>(); for (TypeHolder typeParam : typeHolder.getTypeParams()) { TypeHolder newTypeParam = _eraseTypeVariables(variable2Holder, visitedVariables, typeParam); if (typeParam.getWildcardBound() != WildcardBound.NO_WILDCARD) { newTypeParam = newTypeParam.changeWildcardBound(typeParam.getWildcardBound()); } newTypeParams.add(newTypeParam); } return TypeHolder.newInstance(typeHolder.getRawClass(), newTypeParams ); } }
9
public void run() { rsSet=getResultSet(cur, limit); String insert="insert into idf(term,docnum,idf)values(?,?,?)"; int no=0; try { PreparedStatement statement=sqLconnection.conn.prepareStatement(insert); while(rsSet.next()) { String term=rsSet.getString("term"); int count=gettermCount(term); double idf=Math.log10((double)475748/count); statement.setString(1, term); statement.setInt(2, count); statement.setDouble(3, idf); statement.addBatch(); no++; if(no%1000==0) { statement.executeBatch(); statement.clearBatch(); System.out.println(name+":"+no); } } statement.executeBatch(); } catch (SQLException e) { e.printStackTrace(); } }
3
private void finaliseRelations() { if (tempRelations == null) return; PageLayout layout = page.getLayout(); Relations relations = layout.getRelations(); if (relations == null) return; for (int i=0; i<tempRelations.size(); i++) { List<String> rel = tempRelations.get(i); if (rel != null && rel.size() == 5) { RelationType type = "link".equals(rel.get(0)) ? RelationType.Link : RelationType.Join; String custom = rel.get(1); String comments = rel.get(2); String id1 = rel.get(3); String id2 = rel.get(4); ContentObject obj1 = contentObjects.get(id1); ContentObject obj2 = contentObjects.get(id2); if (obj1 != null && obj2 != null) { ContentObjectRelation relation = new ContentObjectRelation(obj1, obj2, type); relation.setCustomField(custom); relation.setComments(comments); relations.addRelation(relation); } } } }
8
public String convert(String s, int nRows) { if (s == null || "".equals(s) || nRows == 1) return s; StringBuffer sb = new StringBuffer(); for (int i = 0; i < nRows; i++) { int j = i; boolean odd = false; while (j < s.length()) { sb.append(s.charAt(j)); if (i == 0 || i == nRows - 1) { j += nRows * 2 - 2; } else { if (!odd) { j += (nRows - (i + 1)) * 2; } else { j += i + i; } odd = !(odd); } } } return sb.toString(); }
8
public final void modifyHealth(int toInflict) { health= health + toInflict; if(health > 100) { health = 100; } else if(health < 0) { health = 0; //uh oh } }
2
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Usage: java " + SSLJioClient.class.getName() + " URL [n] [delay]"); System.err.println("\tURL: The url of the service to test."); System.err.println("\tn: The number of clients. (default is " + NB_CLIENTS + ")"); System.err.println("\tdelay: The delay between writes. (default is " + DEFAULT_DELAY + "ms)"); System.exit(1); } URL strURL = new URL(args[0]); int delay = DEFAULT_DELAY; if (args.length > 1) { try { NB_CLIENTS = Integer.parseInt(args[1]); if (args.length > 2) { delay = Integer.parseInt(args[2]); if (delay < 1) { throw new IllegalArgumentException("Negative number: delay"); } } } catch (Exception exp) { System.err.println("Error: " + exp.getMessage()); System.exit(1); } } System.out.println("\nRunning test with parameters:"); System.out.println("\tURL: " + strURL); System.out.println("\tn: " + NB_CLIENTS); System.out.println("\tdelay: " + delay); String home = System.getProperty("user.home") + File.separatorChar; System.setProperty("javax.net.ssl.trustStore", home + "cacerts.jks"); System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); System.setProperty("javax.net.ssl.keyStore", home + ".keystore"); System.setProperty("javax.net.ssl.keyStorePassword", "bismillah"); Thread clients[] = new Thread[NB_CLIENTS]; for (int i = 0; i < clients.length; i++) { clients[i] = new SSLJioClient(strURL, delay); } for (int i = 0; i < clients.length; i++) { clients[i].start(); } for (int i = 0; i < clients.length; i++) { clients[i].join(); } }
8
public int zmq_sendiov (SocketBase s_, byte[][] a_, int count_, int flags_) { if (s_ == null || !s_.check_tag ()) { throw new IllegalStateException(); } int rc = 0; Msg msg; for (int i = 0; i < count_; ++i) { msg = new Msg(a_[i]); if (i == count_ - 1) flags_ = flags_ & ~ZMQ_SNDMORE; rc = s_sendmsg (s_, msg, flags_); if (rc < 0) { rc = -1; break; } } return rc; }
5
public BeerResponse(BeerReadOnly delegate) { this.delegate = delegate; }
0
@Override public ResultSet query(String query) { //Connection connection = null; Statement statement = null; ResultSet result = null/*new JdbcRowSetImpl()*/; try { //connection = open(); //if (checkConnection()) statement = this.connection.createStatement(); result = statement.executeQuery("SELECT CURTIME()"); switch (this.getStatement(query)) { case SELECT: result = statement.executeQuery(query); break; default: statement.executeUpdate(query); } //connection.close(); return result; } catch (SQLException e) { this.writeError("Error in SQL query: " + e.getMessage(), false); } return result; }
2
public void setShortMessageFontcolor(int[] fontcolor) { if ((fontcolor == null) || (fontcolor.length != 4)) { this.shortMessageFontColor = UIFontInits.SHORTMESSAGE.getColor(); } else { this.shortMessageFontColor = fontcolor; } somethingChanged(); }
2
private void waitForConnections() { while (true) { try { acceptConnection(); } catch (SocketTimeoutException e) { if (stopWaiting) { try { serverSocket.close(); } catch (IOException e1) { listener.onConnectionFailed(null, port, e1); } return; } } catch (IOException e) { listener.onConnectionFailed(null, port, e); } } }
5
public static boolean updateEventStatus(int eventId, int userId, int statusCode) throws HibernateException { boolean isUpdateEventStatusSuccessful = false; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); try { // Begin unit of work session.beginTransaction(); // update event status String hql = "select e from EventInfo as e where e.ownerId=" + userId + " and e.eventId=" + eventId; Query query = session.createQuery(hql); @SuppressWarnings("unchecked") List<EventInfo> list = query.list(); if (list.size() > 0) { // Is owner, then change the event status EventInfo eventEntity = list.get(0); if (eventEntity.getEventStatus() != statusCode) { eventEntity.setEventStatus(statusCode); session.save(eventEntity); } isUpdateEventStatusSuccessful = true; } // End unit of work session.getTransaction().commit(); } catch (HibernateException hex) { logger.error(hex.toString()); HibernateUtil.getSessionFactory().getCurrentSession() .getTransaction().rollback(); } catch (Exception ex) { logger.error(ex.toString()); HibernateUtil.getSessionFactory().getCurrentSession() .getTransaction().rollback(); } return isUpdateEventStatusSuccessful; }
4
public void stopall() { synchronized(clients) { for(TestClient c : clients) c.stop(); } }
1
public String toString() { return description(); }
0