method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
c45fe96f-3fb7-4e21-bcd7-d580d4b9c678
8
static String generateEquivalentJoinClause(List<ColumnNode> nodes) { if (nodes.isEmpty()) { return ""; } Set<String> tableNames = new LinkedHashSet<String>(); ListMap columnMap = new ListMap(); for (ColumnNode node : nodes) { final String tableName = node.getTableNode().getNodeFullName(); final String columnName = node.getName(); tableNames.add(tableName); columnMap.add(columnName, String.format("%s.%s", tableName, columnName)); } assert tableNames.size() >= 1; List<String> expressions = new ArrayList<String>(); if (tableNames.size() == 1) { for (ColumnNode node : nodes) { expressions.add(String.format("%s=?", node.getName())); } } else { // size >= 2 List<String> expressions2 = new ArrayList<String>(); for (Entry<String, List<String>> entry : columnMap.entrySet()) { List<String> a = entry.getValue(); final int n = a.size(); assert n >= 1; expressions2.add(String.format("%s=?", a.get(0))); if (n >= 2) { for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { expressions.add(String.format("%s=%s", a.get(i), a.get(j))); } } } } expressions.addAll(expressions2); } return String.format("%s", join(" AND ", expressions)); }
7cfc35ca-4225-4a70-a12d-a935c78e52b5
5
public void DisplayCluster() { System.out.printf("%s\n", CurrentCluster); for (int x = 0; x < GetCluster().getChild().length; x++) { System.out.printf("%s\n", SectorDetails(x)); for (int y = 0; y < GetSector(x).getChild().length; y++) { System.out.printf("%s\n", StarDetails(x,y)); for (int z = 0; z < GetStar(x,y).getChild().length; z++) { System.out.printf("%s\n", OrbitalDetails(x,y,z)); if (GetOrbital(x,y,z).getClass() == Planet.class) { for (int u = 0; u < ((Planet) GetOrbital(x,y,z)).GetMoon().length; u++) { System.out.printf("\t%s\n", MoonDetails(x, y, z, u)); } } System.out.println(); } } } }
3b99734b-2103-4152-80e7-43b27cf7b23c
6
private final void method3970(int i) { if (aBoolean9911) OpenGL.glPopMatrix(); anInt9840++; if (i != 1) method3950(69); if (!((NativeToolkit) this).aClass196_8184.method1450(-98)) { if (((NativeToolkit) this).aBoolean8069) { OpenGL.glLoadIdentity(); aBoolean9911 = false; } else { OpenGL.glLoadMatrixf (((NativeToolkit) this).aClass101_Sub2_8074 .method918(Class233.aFloatArray3015, 0), 0); aBoolean9911 = false; } } else { if (!aBoolean9914) { OpenGL.glLoadMatrixf (((NativeToolkit) this).aClass101_Sub2_8083 .method918(Class233.aFloatArray3015, 0), 0); aBoolean9914 = true; method3892(0); method3823((byte) -104); } if (!((NativeToolkit) this).aBoolean8069) { OpenGL.glPushMatrix(); OpenGL.glMultMatrixf (((NativeToolkit) this).aClass101_Sub2_8074 .method918(Class233.aFloatArray3015, i ^ 0x1), 0); aBoolean9911 = true; } else aBoolean9911 = false; } }
a33f1ea3-cdcd-4b0e-954f-3321f438dea9
9
private boolean enemyAttackCollision(AnimationCommands commands){ CollisionResults results = new CollisionResults(); BoundingVolume bv = ((Node)spatial).getChild("Ninja").getWorldBound(); getEnemyModels().collideWith(bv, results); if(results.size() > 0){ String parentName = results.getCollision(0).getGeometry().getParent().getName(); if(parentName.equals("AttackCollider")){ results.getCollision(0).getGeometry().getParent().getParent().getParent().getParent().getControl(controlnpc.BasicInfo.class).decreaseHP(damage); results.getCollision(0).getGeometry().getParent().getParent().getParent().getParent().getControl(AI1Control.class).pushSpatial(push_Force); }else if(parentName.equals("Enemy") || parentName.equals("Collider")){ results.getCollision(0).getGeometry().getParent().getParent().getControl(controlnpc.BasicInfo.class).decreaseHP(damage); results.getCollision(0).getGeometry().getParent().getParent().getControl(AI1Control.class).pushSpatial(push_Force); } for(int i = 1; i < results.size(); i++){ parentName = results.getCollision(i).getGeometry().getParent().getName(); if(!parentName.equals(results.getCollision(i-1).getGeometry().getParent().getName())){ if(parentName.equals("AttackCollider")){ results.getCollision(i).getGeometry().getParent().getParent().getParent().getParent().getControl(controlnpc.BasicInfo.class).decreaseHP(damage); results.getCollision(i).getGeometry().getParent().getParent().getParent().getParent().getControl(AI1Control.class).pushSpatial(push_Force); }else if(parentName.equals("Enemy") || parentName.equals("Collider")){ results.getCollision(i).getGeometry().getParent().getParent().getControl(controlnpc.BasicInfo.class).decreaseHP(damage); results.getCollision(i).getGeometry().getParent().getParent().getControl(AI1Control.class).pushSpatial(push_Force); } } } // String parentName = results.getClosestCollision().getGeometry().getParent().getName(); // // if(parentName.equals("AttackCollider")){ // results.getClosestCollision().getGeometry().getParent().getParent().getParent().getParent().getControl(controlnpc.BasicInfo.class).decreaseHP(damage); // results.getClosestCollision().getGeometry().getParent().getParent().getParent().getParent().getControl(AI1Control.class).pushSpatial(push_Force); // }else if(parentName.equals("Enemy") || parentName.equals("Collider")){ // results.getClosestCollision().getGeometry().getParent().getParent().getControl(controlnpc.BasicInfo.class).decreaseHP(damage); // results.getClosestCollision().getGeometry().getParent().getParent().getControl(AI1Control.class).pushSpatial(push_Force); // } } return false; }
1bc321b7-9f1e-4567-b540-a331e256422c
4
@Override public void valueUpdated(Setting s, Value v) { String setting = s.getName(); if (setting.equals(Mode)) { try { TimerMode m = (TimerMode) v.getEnum(); if (timerMode_ != m) { timerMode_ = m; if (m == TimerMode.INFINITE) { stopper_ = addInput(Stopper, ValueType.VOID); stopper_.addListener(this); getSetting(Delay).setMin(new Value(10)); } else { removeInput(stopper_); stopper_ = null; getSetting(Delay).setMin(new Value(1)); } } } catch (Exception e) { e.printStackTrace(); } } else { super.valueUpdated(s, v); } }
b3d06693-9985-48a2-a13a-6d323636dbc2
9
public SmallToken scan() throws IOException { // 去掉空字符 for ( ; ; readch()) { if (peek == ' ' || peek == '\t') continue; else if (peek == '\n') line = line + 1; else break; } // 特殊符号的情况 /* switch (peek) { case '&': if (readch('&')) return Word.And; else return new Token('&'); case '|': if (readch('|')) return Word.Or; else return new Token('|'); case '=': if (readch('=')) return Word.Eq; else return new Token('='); case '!': if (readch('=')) return Word.Ne; else return new Token('!'); case '<': if (readch('=')) return Word.Le; else return new Token('<'); case '>': if (readch('=')) return Word.Ge; else return new Token('>'); } */ // 数字 if (Character.isDigit(peek)) { int v = 0; do { v = 10*v + Character.digit(peek, 10); readch(); } while(Character.isDigit(peek)); if (peek != '.') return new SmallReal(v);// 整数 float x = v; float d = 10; for (;;) { readch(); if (!Character.isDigit(peek)) break; x = x + Character.digit(peek, 10) / d; d = d * 10; } return new SmallReal(x);// 浮点数 } // 单词 /* if (Character.isLetter(peek)) { StringBuffer b = new StringBuffer(); do { b.append(peek); readch(); } while (Character.isLetterOrDigit(peek)); String s = b.toString(); Word w = (Word)words.get(s); if (w != null) return w; w = new Word(s, Tag.ID); words.put(s, w); return w; } */ // 其它神奇的字符 SmallToken tok = new SmallToken(peek); peek = ' '; return tok; }
d22682e7-d7d5-4405-999f-52adbba0d908
4
private void initComponents() { this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); selectSectionLbl = new JLabel(); sectionScrollPane = new JScrollPane(); sectionListTable = new JTable(); enterMotherLangWordLbl = new JLabel(); enterTranslationLbl = new JLabel(); motherLangWordTextField = new JTextField(); translationWordTextField = new JTextField(); backBtn = new JButton(); addCardBtn = new JButton(); enterNewSectionName = new JLabel(); editCardsBtn = new JButton(); statusLbl = new JLabel(); addSectionBtn = new JButton(); newSectionTextField = new JTextField(); //======== this ======== setResizable(false); setTitle("Learning words - Add card"); Container contentPane = getContentPane(); contentPane.setLayout(null); //---- selectSectionLbl ---- selectSectionLbl.setText("Select section or add new one:"); selectSectionLbl.setFont(new Font("Segoe UI", Font.BOLD, 14)); contentPane.add(selectSectionLbl); selectSectionLbl.setBounds(new Rectangle(new Point(15, 15), selectSectionLbl.getPreferredSize())); //======== sectionScrollPane ======== { //---- sectionListTable ---- final SelectSectionTableModel model = new SelectSectionTableModel(); sectionListTable.setModel(model); sectionListTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); sectionListTable.setPreferredScrollableViewportSize(new Dimension(450, 300)); sectionListTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { int row = sectionListTable.getSelectedRow(); selectedSection = (model.getValueAt(row, 0)).toString(); selectedSectionId = (Integer)(model.getId(selectedSection)); if (!motherLangWordTextField.isEnabled() && !translationWordTextField.isEnabled() && !addCardBtn.isEnabled()) { motherLangWordTextField.setEnabled(true); translationWordTextField.setEnabled(true); addCardBtn.setEnabled(true); editCardsBtn.setEnabled(true); } } catch (Exception ex) { ex.printStackTrace(); } } }); sectionScrollPane.setViewportView(sectionListTable); } contentPane.add(sectionScrollPane); sectionScrollPane.setBounds(15, 40, 595, 110); //---- enterMotherLangWordLbl ---- enterMotherLangWordLbl.setText("Enter mother language word:"); enterMotherLangWordLbl.setFont(new Font("Segoe UI", Font.BOLD, 14)); contentPane.add(enterMotherLangWordLbl); enterMotherLangWordLbl.setBounds(new Rectangle(new Point(15, 230), enterMotherLangWordLbl.getPreferredSize())); //---- enterTranslationLbl ---- enterTranslationLbl.setText("Enter translation:"); enterTranslationLbl.setFont(new Font("Segoe UI", Font.BOLD, 14)); contentPane.add(enterTranslationLbl); enterTranslationLbl.setBounds(new Rectangle(new Point(15, 300), enterTranslationLbl.getPreferredSize())); contentPane.add(motherLangWordTextField); motherLangWordTextField.setBounds(15, 260, 290, 25); contentPane.add(translationWordTextField); translationWordTextField.setBounds(15, 325, 290, 25); motherLangWordTextField.setEnabled(false); translationWordTextField.setEnabled(false); //---- backBtn ---- backBtn.setText("Back"); contentPane.add(backBtn); backBtn.setBounds(505, 365, 78, 28); backBtn.addActionListener(new BackButtonListener(this, this.user)); //---- addCardBtn ---- addCardBtn.setText("Add card"); contentPane.add(addCardBtn); addCardBtn.setBounds(410, 365, 88, 28); addCardBtn.setEnabled(false); addCardBtn.addActionListener(new AddCardButtonListener(motherLangWordTextField, translationWordTextField, statusLbl)); //---- enterNewSectionName ---- enterNewSectionName.setText("Enter name of new section:"); enterNewSectionName.setFont(new Font("Segoe UI", Font.BOLD, 14)); contentPane.add(enterNewSectionName); enterNewSectionName.setBounds(new Rectangle(new Point(15, 160), enterNewSectionName.getPreferredSize())); //---- editCardsBtn ---- editCardsBtn.setText("Edit cards"); contentPane.add(editCardsBtn); editCardsBtn.setBounds(315, 365, 88, 28); editCardsBtn.setEnabled(false); editCardsBtn.addActionListener(new EditCardsButtonListener(user, this)); //---- statusLbl ---- statusLbl.setText("Status:"); statusLbl.setFont(statusLbl.getFont().deriveFont(statusLbl.getFont().getStyle() | Font.BOLD)); contentPane.add(statusLbl); statusLbl.setBounds(15, 410, 195, 16); //---- addSectionBtn ---- addSectionBtn.addActionListener(new AddSectionButtonListener(newSectionTextField, statusLbl, sectionListTable)); addSectionBtn.setText("Add section"); contentPane.add(addSectionBtn); addSectionBtn.setBounds(315, 180, 115, 28); contentPane.add(newSectionTextField); newSectionTextField.setBounds(15, 180, 290, 25); contentPane.setPreferredSize(new Dimension(635, 475)); pack(); setLocationRelativeTo(getOwner()); }
2e3dc3b0-ddde-4c91-8690-ab30b408502b
9
public String eventDescription(Event e){ //by Budhitama Subagdja String desc = ""; desc = desc + "At (" + e.x + "," + e.z +") "; desc = desc + "Health: " + e.curHealth + " "; if(e.emeDistance<1){ desc = desc + "Enemy Detected! Distance: " + e.emeDistance; } desc = desc + "\n"; if(!e.hasAmmo) desc = desc + "|Empty Ammo| "; if(e.reachableItem) desc = desc + "|Item detected|"; if(e.behave1) desc = desc + "|Doing A|"; if(e.behave2) desc = desc + "|Doing B|"; if(e.behave3) desc = desc + "|Doing C|"; if(e.behave4) desc = desc + "|Doing D|"; if(e.reward >=1){ desc = desc + "\n"; desc = desc + "FEELS GOOD!"; } if(e.reward <=0){ desc = desc + "\n"; desc = desc + "HURT!"; } return desc; }
10dded6b-216d-4274-8777-90a53680e330
0
public CategorizedAndroidSourceSinkParser(Set<CATEGORY> categories, String filename, boolean isSources, boolean isSinks){ this.categories = categories; this.fileName = filename; this.isSources = isSources; this.isSinks = isSinks; }
55288a49-03a8-464b-a062-86c7a0ccb5f7
2
@Override public void setValueAt(Object value, int rowIndex, int columnIndex) { switch (columnIndex) { case 0: isFileSelected.put(user.getFiles().get(rowIndex), (Boolean) value); break; case 5: user.getFiles().get(rowIndex).setAlgorithm((String) value); break; default: super.setValueAt(value, rowIndex, columnIndex); } }
361b6158-12d5-46c3-b375-ee1a314b7b54
5
protected void doPaethLine(byte[] curLine, byte[] prevLine) { // get the number of bytes per sample int sub = (int) Math.ceil((getBitsPerComponent() * getColors()) / 8.0); for (int i = 0; i < curLine.length; i++) { int left = 0; int up = 0; int upLeft = 0; // get the last value of this color int prevIdx = i - sub; if (prevIdx >= 0) { left = curLine[prevIdx] & 0xff; } // get the value on the previous line if (prevLine != null) { up = prevLine[i] & 0xff; } if (prevIdx > 0 && prevLine != null) { upLeft = prevLine[prevIdx] & 0xff; } // add the average curLine[i] += (byte) paeth(left, up, upLeft); } }
3b4a4553-5f3a-4099-acf1-363fb08f97f0
4
public void rescan() { rescanButton.setEnabled(false); // get the shared data structure WizardData data = this.getWizardData() ; if ( data != null ) { // get the Project TProject dummy = ( TProject ) data.getData() ; // project data TProjectData pdat = dummy.getProjectData() ; // base file specified ? String base = getBaseFileName() ; if ( base != null ) { if (base.length() > 0) { File workFile ; // !!! working directory and directory of basefile could be not equal !!!! if (baseFile != null) { workFile = baseFile ; } else { workFile = new File( dummy.getWorkingDirectory(), base ) ; } pdat.collect( workFile ) ; rescanButton.setEnabled( true ) ; } } /* else // no base file -> delete all files in table { TLanguageList lList = pdat.getAvailableLangs() ; lList.clear(); } */ // update the visible components updateProjectData(); } }
8de416cc-4ac8-461c-969d-d1eae168842f
7
public void insertarExtraccion() { ArrayList nom = new ArrayList(); nom.add(this.nombre_proyecto); extraccion.insertarRegistros("proyecto", nom); int ultimoReg = extraccion.extraerUltimoRegistro("proyecto", camposProyecto); this.id_proyecto=ultimoReg; ArrayList datos = new ArrayList(); for(int i = 0 ; i < this.enlaces_imagenes.size() ; i++) { datos.add(ultimoReg); datos.add(this.enlaces_imagenes.get(i).toString()); extraccion.insertarRegistros("enlaces_imagen", datos); datos.removeAll(datos); } for(int i = 0 ; i < this.enlaces_audios.size() ; i++) { datos.add(ultimoReg); datos.add(this.enlaces_audios.get(i)); extraccion.insertarRegistros("enlaces_audio", datos); datos.removeAll(datos); } for(int i = 0 ; i < this.enlaces_videos.size() ; i++) { datos.add(ultimoReg); datos.add(this.enlaces_videos.get(i)); extraccion.insertarRegistros("enlaces_video", datos); datos.removeAll(datos); } for(int i = 0 ; i < this.enlaces_documentos.size() ; i++) { datos.add(ultimoReg); datos.add(this.enlaces_documentos.get(i)); extraccion.insertarRegistros("enlaces_documento", datos); datos.removeAll(datos); } for(int i = 0 ; i < this.enlaces_otros.size() ; i++) { datos.add(ultimoReg); datos.add(this.enlaces_otros.get(i)); extraccion.insertarRegistros("enlaces_otro", datos); datos.removeAll(datos); } for(int i = 0 ; i < this.enlaces_recorridos.size() ; i++) { datos.add(ultimoReg); datos.add(this.enlaces_recorridos.get(i)); extraccion.insertarRegistros("enlaces_recorrido", datos); datos.removeAll(datos); } for(int i = 0 ; i < this.enlaces_sin_recorrer.size() ; i++) { datos.add(ultimoReg); datos.add(this.enlaces_sin_recorrer.get(i)); extraccion.insertarRegistros("enlaces_sin_recorrer", datos); datos.removeAll(datos); } }
eba4a9a6-4efc-4632-bad4-2160f352a0fd
7
public static RoomType randomRoom(int fullMapSize) { int x = 0; while (x == 0) { Iterator<RoomType> it = roomGenList.iterator(); while (it.hasNext()) { RoomType room = it.next(); if (room.getPercentageGen() == 0) { it.remove(); } else if (room.roomsGenned >= fullMapSize * fullMapSize * room.getPercentageGen()) { it.remove(); } } Double r = Math.random(); // Add up remaining % - if less than 100%, we'll refactor the percentages used when generating a room double remainingPercentage = 0; for (RoomType room: roomGenList) { remainingPercentage = room.getPercentageGen() + remainingPercentage; } double currentPercentage = 0; for (RoomType room : roomGenList) { room.percentage = (1 / remainingPercentage) * room.getPercentageGen(); currentPercentage = currentPercentage + room.percentage; if (r < currentPercentage) { room.roomsGenned = room.roomsGenned + 1; //System.out.println(room + " " + r + " " + room.roomsGenned + " " + room.percentage); return room; } } } return null; }
e24b18dc-86a6-476c-97dd-0261eed6fc91
9
void onDestroy() { String tableName; setSelectAll(false); queryBuilderPane.sqlDiagramViewPanel.removeAllRelation(this); queryBuilderPane.sqlBrowserViewPanel.removeFromClause(tableToken); QuerySpecification qs = queryBuilderPane.sqlBrowserViewPanel.getQuerySpecification(); if (tableToken.isAliasSet()) tableName = tableToken.getAlias(); else tableName = tableToken.getName(); Condition[] conditions = qs.getWhereClause(); for (int i = 0; i < conditions.length; i++) if (conditions[i].getLeft().toString().indexOf(tableName) != -1) queryBuilderPane.sqlBrowserViewPanel.removeWhereClause(conditions[i]); conditions = qs.getHavingClause(); for (int i = 0; i < conditions.length; i++) if (conditions[i].getLeft().toString().indexOf(tableName) != -1) queryBuilderPane.sqlBrowserViewPanel.removeHavingClause(conditions[i]); Group[] groups = qs.getGroupByClause(); for (int i = 0; i < groups.length; i++) if (groups[i].toString().indexOf(tableName) != -1) queryBuilderPane.sqlBrowserViewPanel.removeGroupByClause(groups[i]); Order[] orders = queryBuilderPane.getQueryModel().getOrderByClause(); for (int i = 0; i < orders.length; i++) if (orders[i].getExpression().toString().indexOf(tableName) != -1) queryBuilderPane.sqlBrowserViewPanel.removeOrderByClause(orders[i]); }
1fc64996-1b47-4e9c-b5d4-3c0ab82c9a26
5
public ViewController(GameController game, JFrame frame){ this.game2 = game; //pause game when frame looses focus frame.requestFocus(); frame.addFocusListener(new FocusListener(){ @Override public void focusGained(FocusEvent e) { for (Player p: game2.getPlayers()){ p.resetSpeed(); } game2.resume(); } @Override public void focusLost(FocusEvent e) { game2.pause(); } }); // setup grid layout int cols = 1; if (game.getPlayerCount()>4){ cols = 3; } else if (game.getPlayerCount()>2){ cols = 2; } frame.setLayout(new GridLayout(0, cols, 10, 10)); //add player views along with upcoming to the frame for (int i = 1; i<=game.getPlayerCount(); i+=2){ PlayerView playerView = new PlayerView(game.getPlayer(i), this, true); playerViews.add(playerView); JPanel pair = new JPanel(); pair.setLayout(new BorderLayout()); pair.add(playerView, BorderLayout.WEST); pair.add(new UpcomingView(this, game.getUpcoming()), BorderLayout.CENTER); if(i+1 <= game.getPlayerCount()){ playerView = new PlayerView(game.getPlayer(i+1), this, false); playerViews.add(playerView); pair.add(playerView, BorderLayout.EAST); } frame.add(pair); } //prepare frame frame.pack(); frame.repaint(); //setup listener to repaint when needed this.frame2 = frame; game.addStateListener(new GameEventListener(){ @Override public boolean handleEvent(GameEvent e) { frame2.repaint(); return false; } }); //register a custom powerup game.addPowerUp(2, new HideBoard(playerViews)); }
53af4cff-95ed-46a2-b8dc-a3444f3aaa78
2
public static int utf8EncodingSize(int ch) { if (ch <= 0x007f) return 1; else if (ch > 0x07ff) return 3; return 2; }
75772c15-6ef9-46ab-86c0-784e7bf770e0
1
public void addOptions(CmdLineOption... options) { for (CmdLineOption option : options) { addOption(option); } }
d698521b-8c9a-41e7-9e53-7a630ab13b96
4
public static void main(String args[]) { Logger log = Logger.getLogger("MAIN"); Properties pt = new Properties(); try { pt.load(new FileInputStream(args[0])); }catch (IOException ioe) { log.fatal("Couldn't load the config file!"); log.fatal("Usage: ConnectionTest configfile"); System.exit(1); } try { FTPConnection connection = FTPConnectionFactory.getInstance(pt); connection.connect(); connection.disconnect(); } catch (NotConnectedException nce) { log.error(nce); } catch (IOException ioe) { log.error(ioe); } catch (Exception e) { log.error(e); } }
12c57b9f-7536-49a9-ae40-77b228ddf2c2
2
private void setupTimer(int fps) { if (!(fpsTimer == null) && fpsTimer.isRunning()) fpsTimer.stop(); fpsTimer = new Timer(fps, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { repaint(); } }); fpsTimer.start(); }
5fb317db-6765-439b-9095-85351d09ee88
0
@Test public void test_numberOfPawns() { assertNotNull(board); assertEquals(numberOfPawns, board.numberOfPawns()); }
93a2ddb8-8cdf-45db-81fc-7e8fe93e5f7b
4
public static void setColor(String nom, int color) { Connection con = null; try { Class.forName("org.sqlite.JDBC"); con = DriverManager.getConnection("jdbc:sqlite:" + Parametre.workspace + "/bdd_models"); Statement stmt = con.createStatement(); String query = "select nom from modeles where nom=\"" + nom + "\""; ResultSet rs = stmt.executeQuery(query); if (rs.next() != false && rs.getString("nom").equals(nom)) { stmt.executeUpdate("update modeles set color='" + color + "' where nom='" + nom + "'"); } } catch (Exception e) { e.printStackTrace(); } finally { try { con.close(); } catch (Exception e) { e.printStackTrace(); } } }
f1c87144-c5ea-460b-964f-566d05ed7101
6
public String getLongDescription() { String longRoom = "You are " + description + ".\n" + getExitString(); String itemList = items.size() > 0 ? "\nItems: " + items.get(0) : ""; String charList = characters.size() > 0 ? "\nCharacters: " + characters.get(0) : ""; if(items.size() > 1) { for(int i = 1; i < items.size(); i++) { itemList += ", " + items.get(i); } } if(characters.size() > 1) { for(int i = 1; i < characters.size(); i++) { charList += ", " + characters.get(i); } } return longRoom + itemList + charList; }
141cb66e-0bd2-4334-bc36-1ca6fcdb85eb
8
public String[] loadAllBoardData() { if (pathLocation == null) { System.out.println("No loaded Path Location"); return new String[1]; } // Ensures the filename matches the sudoku format // String[] loadedData = null; String[] parseFiles = pathLocation.split("\\."); if (parseFiles.length == 2 && parseFiles[1].equals(new String("sudoku"))) { loadedData = new String[1]; parseFiles = new String[1]; parseFiles[0] = pathLocation.split("/")[pathLocation.split("/").length-1]; loadedData[0] = rawBoardData(); } // Checks if the pathLocation is a Folder and // loads all files that match the .sudoku format else { File[] files = file.listFiles(); parseFiles = new String[files.length]; int validFiles = 0; for (int i=0; i < files.length; i++) { String filename = files[i].getPath(); parseFiles[i] = (filename.split("\\.")[1].equals(new String("sudoku")) ? filename : null); validFiles+= (parseFiles[i] != null ? 1 : 0); } loadedData = new String[validFiles]; int j=0; for (int i=0; i < parseFiles.length; i++) { if (parseFiles[i] != null) { loadedData[j] = rawBoardData(parseFiles[i]); j++; } } } return loadedData; }
54a216b3-d9e2-4cc9-8025-de9d785f736f
6
private boolean prefers(Object x, Object y) throws Exception{ IPersistentSet xprefs = (IPersistentSet) getPreferTable().valAt(x); if(xprefs != null && xprefs.contains(y)) return true; for(ISeq ps = RT.seq(parents.invoke(y)); ps != null; ps = ps.next()) { if(prefers(x, ps.first())) return true; } for(ISeq ps = RT.seq(parents.invoke(x)); ps != null; ps = ps.next()) { if(prefers(ps.first(), y)) return true; } return false; }
b4d4c00b-f470-4424-b7f8-2d284eebfc16
9
public Pair<String,Node> rewriteExpression(String expr, XVariableContext varContext, XNamespaceContext nsContext) throws XPathException { this.varContext = varContext; this.nsContext = nsContext; String rewrittenExpression = expr; Node dominantNode = null; // Split into subexpressions first = null; last = null; int start = 0; for (int i = 0, n = expr.length(); i < n; i++) { char c = expr.charAt(i); if (c == '$') { if (i > start) addExpr(new Str(expr.substring(start, i))); // start of variable int j = start = i + 1; for (; j < n; j++) { char v = expr.charAt(j); if (endOfVar(v)) break; } addExpr(new Var(expr.substring(start, j))); start = j; i = j - 1; } } if (start < expr.length()) addExpr(new Str(expr.substring(start))); List<Node> nodes = new ArrayList<Node>(); first.collectNodes(nodes); if (nodes.size() > 0) { dominantNode = nodes.get(0); if (nodes.size() > 1) dominantNode = findDominantNode(nodes); first.replaceNodes(dominantNode); rewrittenExpression = first.toString(); } if (rewrittenExpression == null) throw new XPathException("Cannot rewrite expression to obtain a valid context node"); return new Pair(rewrittenExpression, dominantNode); }
a09675a8-11c3-4f75-9348-0b57858a946d
5
public void Control () { String mess; do { mess= receive(); if (mess.equals("1")){ LCD.drawString("it works!", 2, 2); //Location(); //set the return values //FlowOut.writeBytes("Message") }else if (in.equals("2")){ //getMap(); //set the return values //FlowOut.writeBytes("Message")) }else if (in.equals("3")){ RutineThree(); //set the return values //FlowOut.writeBytes("Message") }else if (in.equals("4")){ RutineFour(); //set the return values //FlowOut.writeBytes("Message") }else {LCD.drawString("no option available", 2, 2);} } while (mess.equals("0")); }
9b12c42a-619a-4480-a9ec-92561357f9c4
9
public void printDocumentTopics (File file, double threshold, int max) throws IOException { PrintWriter out = new PrintWriter(file); out.print ("#doc source topic proportion ...\n"); int docLen; int[] topicCounts = new int[ numTopics ]; IDSorter[] sortedTopics = new IDSorter[ numTopics ]; for (int topic = 0; topic < numTopics; topic++) { // Initialize the sorters with dummy values sortedTopics[topic] = new IDSorter(topic, topic); } if (max < 0 || max > numTopics) { max = numTopics; } for (int doc = 0; doc < data.size(); doc++) { LabelSequence topicSequence = (LabelSequence) data.get(doc).topicSequence; int[] currentDocTopics = topicSequence.getFeatures(); out.print (doc); out.print (' '); if (data.get(doc).instance.getSource() != null) { out.print (data.get(doc).instance.getSource()); } else { out.print ("null-source"); } out.print (' '); docLen = currentDocTopics.length; // Count up the tokens for (int token=0; token < docLen; token++) { topicCounts[ currentDocTopics[token] ]++; } // And normalize for (int topic = 0; topic < numTopics; topic++) { sortedTopics[topic].set(topic, (float) topicCounts[topic] / docLen); } Arrays.sort(sortedTopics); for (int i = 0; i < max; i++) { if (sortedTopics[i].getWeight() < threshold) { break; } out.print (sortedTopics[i].getID() + " " + sortedTopics[i].getWeight() + " "); } out.print (" \n"); Arrays.fill(topicCounts, 0); } }
82ceab65-1b04-44ca-be39-123336183b8b
1
public void testConstructor_ObjectStringEx2() throws Throwable { try { new TimeOfDay("1970-04-06T+14:00"); fail(); } catch (IllegalArgumentException ex) {} }
e2c2058b-0ea6-430a-a7f9-2be4ad800e05
1
private boolean onlyButtonOne( MouseEvent e ){ if( e.getButton() == MouseEvent.BUTTON1 ){ int modifiers = e.getModifiersEx(); int mask = MouseEvent.BUTTON2_DOWN_MASK | MouseEvent.BUTTON3_DOWN_MASK | MouseEvent.SHIFT_DOWN_MASK | MouseEvent.CTRL_DOWN_MASK | MouseEvent.ALT_DOWN_MASK | MouseEvent.ALT_GRAPH_DOWN_MASK | MouseEvent.META_DOWN_MASK; return (modifiers & mask) == 0; } else{ return false; } }
f89d13ed-fbcf-435c-9803-d832c3b1272e
3
public Value<?> readValue () throws IOException { final Value<?> val = readValueRec(); if (val == BVOID) { throw new IOException("Unexpected end value"); } return val; }
04305142-a68f-4a64-a5ce-925f81677e16
9
public static void main(String[] args) { Connection con = null; Statement st = null; ResultSet rs = null; String url = "jdbc:postgresql://localhost/postgres"; String user = "postgres"; String password = "super"; try { con = DriverManager.getConnection(url, user, password); st = con.createStatement(); rs = st.executeQuery("SELECT VERSION()"); if (rs.next()) { System.out.println("fr@ :"+rs.getString(1)); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Version.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { try { if (rs != null) { rs.close(); } if (st != null) { st.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(Version.class.getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } try{ SessionFactory sf = HibernateUtil.getSessionFactory(); } catch (Exception e){ System.out.println("HibernateUtil getSessionFactory failed!"); } for (int i=0;i<3;i++) { Task task = new Task(1, i + 2, i - 3, 4); BDCore.add(task); HistoryTask historyTask = new HistoryTask(new Task(10,i*10,i*10,40), 100); BDCore.add(historyTask); } int o=0; for (int i=0;i<7;i++){ Task t = BDCore.getNextTask(); int r=0; } int t=0; }
8a74f025-6115-4b5e-b7e2-440e7982586c
3
public GithubExploreMessage parse(String path) throws FileNotFoundException, IllegalArgumentException { // If we don't have a path to anything, no point in continuing. if (Strings.isEmpty(path)) { throw new IllegalArgumentException("Path is Null or Blank"); } File file = new File(path); // If we don't have a file or it doesn't exist no point in continuing. if (file == null || !file.exists()) { throw new FileNotFoundException("File Null or Not Found"); } return parseMessage(new FileReader(path)); }
461ba864-e855-4e6a-afa7-b1fede107058
7
public void putAll(Map<? extends String, ? extends V> m) { // TODO Auto-generated method stub if (m != null && !m.isEmpty()) { for (Entry<? extends String, ? extends V> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } } }
fade947a-80c7-453c-98ef-b8611ac82402
8
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { if(line.equals("0")) break; int n = Integer.parseInt(line); for (int i = 1234; i < 98765/n; i++) { int num = i*n; int k = i; int mask=0; if(num<10000) mask=1; while(num>=1){ mask|=1<<(num%10); num/=10; } while(k>=1){ mask|=1<<(k%10); k/=10; } if(mask == ((1<<10)-1)){ out.append(num+" / "+ i + " = " + n); } } } System.out.print(out); }
1ba0b64e-7e10-4489-83e1-bb35fd3863e2
8
static float lpc_from_data(float[] data, float[] lpc, int n, int m){ float[] aut=new float[m+1]; float error; int i, j; // autocorrelation, p+1 lag coefficients j=m+1; while(j--!=0){ float d=0; for(i=j; i<n; i++) d+=data[i]*data[i-j]; aut[j]=d; } // Generate lpc coefficients from autocorr values error=aut[0]; /* if(error==0){ for(int k=0; k<m; k++) lpc[k]=0.0f; return 0; } */ for(i=0; i<m; i++){ float r=-aut[i+1]; if(error==0){ for(int k=0; k<m; k++) lpc[k]=0.0f; return 0; } // Sum up this iteration's reflection coefficient; note that in // Vorbis we don't save it. If anyone wants to recycle this code // and needs reflection coefficients, save the results of 'r' from // each iteration. for(j=0; j<i; j++) r-=lpc[j]*aut[i-j]; r/=error; // Update LPC coefficients and total error lpc[i]=r; for(j=0; j<i/2; j++){ float tmp=lpc[j]; lpc[j]+=r*lpc[i-1-j]; lpc[i-1-j]+=r*tmp; } if(i%2!=0) lpc[j]+=lpc[j]*r; error*=1.0-r*r; } // we need the error value to know how big an impulse to hit the // filter with later return error; }
a179c3d9-fb6e-4b71-a210-c150ed4b56b5
9
private void validateRestrictions(String rql) { char chr = '-'; Stack<Integer> stack = new Stack<Integer>(); Integer integer = Integer.valueOf(0); boolean isString = false; for (int i = 0; i < rql.length(); i++) { chr = rql.charAt(i); switch(chr) { case '(': if(!isString) stack.add(integer); break; case ')': try { if(!isString) stack.pop(); } catch (EmptyStackException e) { throw new SyntaxException("Erro nas restrições"); } break; case '\'': isString = !isString; break; } } if(isString) throw new SyntaxException("String não fechada"); if(!stack.isEmpty()) throw new SyntaxException("Erro nas restrições"); }
d8325d3f-0b7a-4d34-9629-1937ac9dc24e
5
@Test(expected = ProcessRollbackException.class) public void testRollbackFail1() throws InvalidProcessStateException, ProcessExecutionException, InterruptedException, ExecutionException, ProcessRollbackException { // test executed component (execution completed) IProcessComponent<Void> decoratedComponent = TestUtil.rollbackFailComponent(); IProcessComponent<Void> busyComponent = new BusyComponent(decoratedComponent); AsyncComponent<Void> ac = new AsyncComponent<Void>(busyComponent); ac.execute().get(); // wait for completion Future<?> future = null; try { future = ac.rollback(); } catch (InvalidProcessStateException | ProcessRollbackException ex) { fail(ex.getMessage()); } try { future.get(); } catch (InterruptedException ex) { fail(ex.getMessage()); } catch (ExecutionException ex) { if (ex.getCause() instanceof ProcessRollbackException) { // expected, throw throw (ProcessRollbackException) ex.getCause(); } else { throw ex; } } finally { assertTrue(ac.getState() == ProcessState.ROLLBACK_FAILED); assertTrue(ac.getState() == decoratedComponent.getState()); } }
cddf9bd9-05b4-4312-bf9f-c74203194d70
7
private boolean processData(RdpPacket_Localised data, int[] ext_disc_reason) throws RdesktopException, OrderException { int data_type, ctype, clen, len, roff, rlen; data_type = 0; data.incrementPosition(6); // skip shareid, pad, streamid len = data.getLittleEndian16(); data_type = data.get8(); ctype = data.get8(); // compression type clen = data.getLittleEndian16(); // compression length clen -= 18; switch (data_type) { case (Rdp.RDP_DATA_PDU_UPDATE): logger.debug("Rdp.RDP_DATA_PDU_UPDATE"); this.processUpdate(data); break; case RDP_DATA_PDU_CONTROL: logger.debug(("Received Control PDU\n")); break; case RDP_DATA_PDU_SYNCHRONISE: logger.debug(("Received Sync PDU\n")); break; case (Rdp.RDP_DATA_PDU_POINTER): logger.debug("Received pointer PDU"); this.processPointer(data); break; case (Rdp.RDP_DATA_PDU_BELL): logger.debug("Received bell PDU"); // Toolkit tx = Toolkit.getDefaultToolkit(); // tx.beep(); System.err.println("beep"); break; case (Rdp.RDP_DATA_PDU_LOGON): logger.debug("User logged on"); break; case RDP_DATA_PDU_DISCONNECT: /* * Normally received when user logs out or disconnects from a * console session on Windows XP and 2003 Server */ ext_disc_reason[0] = processDisconnectPdu(data); logger.debug(("Received disconnect PDU\n")); break; default: logger.warn("Unimplemented Data PDU type " + data_type); } return false; }
721bf61f-31da-4e8c-abac-f7e3ab28bea8
2
public void dispatcherMessage(String message) { StringTokenizer stringTokenizer = new StringTokenizer(message, "@"); String source = stringTokenizer.nextToken(); String owner = stringTokenizer.nextToken(); String content = stringTokenizer.nextToken(); message = source + "說:" + content; contentArea.append(message + "\r\n"); if (owner.equals("ALL")) {// 群发 for (int i = clients.size() - 1; i >= 0; i--) { clients.get(i).getWriter().println(message); clients.get(i).getWriter().flush(); } } }
14ca3349-e472-48bd-aa34-faee4d0a1fbf
6
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof MyString)) { return false; } MyString other = (MyString) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; }
10c54a59-2d6f-4832-9a35-82d3b6716af7
7
public User addUser(boolean newDB) { String input = null; if (newDB) { input = JOptionPane.showInputDialog(new JFrame(), "Could not find any User, please add a new one. Username: ", "Add User", JOptionPane.PLAIN_MESSAGE); if(input == null) System.exit(0); while (input.equals("")) { JOptionPane.showMessageDialog(new JFrame(), "Cannot create LangDB without any user.", "Thats not how this works", JOptionPane.ERROR_MESSAGE); input = JOptionPane.showInputDialog(new JFrame(), "Username: ", "adding a new User", JOptionPane.PLAIN_MESSAGE); if(input == null) System.exit(0); } } else { input = JOptionPane.showInputDialog(new JFrame(), "Username: ", "Add User", JOptionPane.PLAIN_MESSAGE); if (input == null) return null; while(input.equals("")) { input = JOptionPane.showInputDialog(new JFrame(), "Username: ", "Add User", JOptionPane.PLAIN_MESSAGE); if (input == null) return null; } } return User.createNew(con, input); }
f708d69d-5075-4ec5-8f26-1bfbe622a565
9
public JSONObject processLoginTag(String email,String password) { try { Class.forName(JDBC_DRIVER); conn=DriverManager.getConnection(DB_URL,USER,PASS); stmt=conn.createStatement(); String sql="Select * from LOGIN_INFO where EMAIL='"+email+"'"; rs=stmt.executeQuery(sql); json=new JSONObject(); if(rs.isBeforeFirst()) { while(rs.next()) { String paswd=rs.getString("PASSWORD"); if(paswd.equals(password)) { json.put(SUCCESS, 1); json.put(MESSAGE, "Login Successful"); json.put("USER_ID", rs.getInt("USER_ID")); rs1=stmt.executeQuery("Select * from QUESTIONS"); if(rs1.isBeforeFirst()) { JSONArray questions=new JSONArray(); JSONObject object; while(rs1.next()) { object=new JSONObject(); object.put("QUESTION_ID", rs1.getInt("QUESTION_ID")); object.put("QUESTION_ASKED", rs1.getString("QUESTION_ASKED")); questions.add(object); } json.put("QUESTIONS", questions); }else { json.put(SUCCESS, 1); json.put(MESSAGE, "NoQuestions"); json.put("USER_ID", rs.getInt("USER_ID")); } return(json); } else { json.put(SUCCESS, 0); json.put(MESSAGE,"Invalid Password, Please try Again" ); return(json); } } } else { json.put(SUCCESS, 0); json.put(MESSAGE, "Invalid Email, Please try Again"); return(json); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try{ rs.close(); stmt.close(); if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } //json.put(SUCCESS, 0); //json.put(MESSAGE,"COULD NOT PROCESS REQUEST, PLEASE TRY AFTER SOMETIME" ); return(json); }
ea168df4-42fe-4083-a279-110ac772b508
8
public void move(){ if(getDirection() == Moveable.RIGHT && getX() + getWidth() < Board.WIDTH) setX(getX() + 2); else if(getDirection() == Moveable.LEFT && getX() > 0) setX(getX() - 2); else if(getDirection() == Moveable.UP && getY() > 0) setY(getY() - 2); else if(getDirection() == Moveable.DOWN && getY() + getHeight() < Board.HEIGHT) setY(getY() + 2); }
af3be21f-eb08-4065-a444-2d504d771176
5
static String extractVariableName(String variable) { if (variable == null || variable.startsWith(":") == false || variable.length() < 2) { throw new IllegalArgumentException("Argument is not a variable (starting with a colon)"); } String postColon = variable.substring(1); if (postColon.startsWith("{") && postColon.endsWith("}")) { return postColon.substring(1, postColon.length() - 1); } return postColon; }
9e7df43e-34d4-43fe-91cc-bc3ed27d439e
4
public boolean isLand() { switch(value) { case 12: case 13: case 14: case 15: return false; default: return true; } }
28f9797d-4731-4ea8-a880-9a28deab366b
7
public void finish() throws IOException { int err; do{ z.next_out=buf; z.next_out_index=0; z.avail_out=bufsize; if(compress){ err=z.deflate(JZlib.Z_FINISH); } else{ err=z.inflate(JZlib.Z_FINISH); } if(err!=JZlib.Z_STREAM_END && err != JZlib.Z_OK) throw new ZStreamException((compress?"de":"in")+"flating: "+z.msg); if(bufsize-z.avail_out>0){ out.write(buf, 0, bufsize-z.avail_out); } } while(z.avail_in>0 || z.avail_out==0); flush(); }
4bd3dfc2-d3c7-417a-9a5f-3b5976776826
4
public KDPoint vecinoMasCercano(KDNode node, KDPoint q) { KDNode farNode = null; if (node.isLeaf()) { updateIfBest(node.getPoint(), q); return mejorActual; } else if (node.greaterThanAxis(q)) { vecinoMasCercano(node.getRight(), q); farNode = node.getLeft(); } else { vecinoMasCercano(node.getLeft(), q); farNode = node.getRight(); } if (farNode.isLeaf()) updateIfBest(farNode.getPoint(), q); else if(farNode.isCloseEnough(q,distActual)) vecinoMasCercano(farNode, q); return mejorActual; }
69dcf65e-71b6-46ad-94c4-f01691bfe833
1
public int blockType(final Block block) { if (loopEdgeModCount != edgeModCount) { buildLoopTree(); } return block.blockType(); }
bbd4f043-8d73-4e0b-acf0-f1524d8691df
1
public void start(ServerHandler serverHandler){ if (!idleThreads.isEmpty()) { WorkerThread borrowedThread = this.borrowThread(); borrowedThread.setTask(serverHandler); } else { WorkerThread newThread = new WorkerThread(serverHandler); newThread.start(); } }
a7714186-e4de-4572-9e8b-a8ef70de42ce
1
protected final void addSchedulerListener( Class<? extends SchedulerListener> schedulerListenerType ) { doBind( schedulerListeners, schedulerListenerType ); }
162d8619-79ab-4445-b5a1-54b66f275510
1
public void setDirty(final boolean dirty) { this.isDirty = dirty; if (isDirty == true) { this.editor.setDirty(true); } }
2f8144e1-0393-4266-b3bd-a215804aec55
0
@BeforeClass public static void setUpClass() throws Exception { }
34921077-651e-48e3-9cda-f68fea9eb0a5
4
@Test public void saveLoadMatch(){ InputStream is = LoadGame.class.getResourceAsStream("standardMap.xml"); File targetFile = null; File saveFile = new File(System.getProperty("user.home"),"testSaveGame.xml"); byte[] buffer; try { buffer = new byte[is.available()]; is.read(buffer); targetFile = new File(System.getProperty("user.home"),"testLoadGame.xml"); OutputStream outStream = new FileOutputStream(targetFile); outStream.write(buffer); } catch (IOException e) { e.printStackTrace(); } game = loader.loadGame(targetFile); saver.save(game, saveFile); try { Scanner loadScan = new Scanner(targetFile); Scanner saveScan = new Scanner(saveFile); while(loadScan.hasNext() && saveScan.hasNext()){ String loadString = loadScan.next(); String saveString = saveScan.next(); assert(loadString.equals(saveString)); } } catch (FileNotFoundException e) { e.printStackTrace(); } }
87400dd3-6560-436d-a88c-9fa805198a77
0
public JLabel getjLabelVille() { return jLabelVille; }
83bcb709-75b5-488a-9f0c-fc03c22cbc57
5
public static void checkMethodTypeSig(String typesig) throws IllegalArgumentException { try { if (typesig.charAt(0) != '(') throw new IllegalArgumentException("No method signature: " + typesig); int i = 1; while (typesig.charAt(i) != ')') i = checkTypeSig(typesig, i); // skip closing parenthesis. i++; if (typesig.charAt(i) == 'V') // accept void return type. i++; else i = checkTypeSig(typesig, i); if (i != typesig.length()) throw new IllegalArgumentException("Type sig too long: " + typesig); } catch (StringIndexOutOfBoundsException ex) { throw new IllegalArgumentException("Incomplete type sig: " + typesig); } }
0b717f5c-68b4-4ced-8e96-2ec8c0b9db74
2
public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] A = new int[n]; for(int i=0;i<n;i++){ A[i]=in.nextInt(); } int[] results = mergeSort(A, 0, n-1); for(int i:results) System.out.println(i); }
f9e59225-cd05-47c3-8c3a-6a5bbc0a61f5
1
public static void swap() { if(isTwoPlayers) { readyToSwap = false; swappingNow = true; game.swapStates(); } }
e352d6dd-2119-4861-8928-3cb074c8d4d0
4
public void update(InputHandler input) { if(input.up)hero.y -= hero.speed; if(input.down)hero.y += hero.speed; if(input.left)hero.x -= hero.speed; if(input.right)hero.x += hero.speed; }
dd688d7e-63a1-4ef6-9e91-8587e1037d4a
5
public String alphabetizeYourName(String first, String middle, String last) { String nameInOrder = ""; if (first.compareTo(middle) < 0) { if (first.compareTo(last) < 0) { if (middle.compareTo(last) < 0) { nameInOrder = first = ", " + middle + ", " + last; } else { nameInOrder = first + ", " + last + ", " + middle; } } else { nameInOrder = last + ", " + first + "," + middle; } } else { if (middle.compareTo(last) < 0) { if (first.compareTo(last) < 0) { nameInOrder = middle + ", " + first + ", " + last; } else { nameInOrder = middle + ", " + last + ". " + first; } } else { nameInOrder = last + ", " + middle + ", " + first; } } return nameInOrder; }
908c1cfe-7d5f-40b8-ab90-7552b724ea6f
8
public Object getValueAt(int rowIndex, int columnIndex) { TableRow row = m_rows.get(rowIndex); switch (columnIndex) { case 0: return row.m_user1 + " v. " + row.m_user2; case 1: Generation gen = m_link.getGenerations()[row.m_generation]; return gen.getId(); case 2: if (row.m_ladder != -1) { Generation g = m_link.getGenerations()[row.m_generation]; Metagame metagame = g.getMetagames().get(row.m_ladder); return metagame.getName(); } return "(Custom)"; case 3: return row.m_rated ? "Yes" : "No"; case 4: return row.m_n; case 5: return row.m_pop; } assert false; return null; }
2d13c0e3-a731-4282-85fb-c53f4d08418c
1
private synchronized SSLSocketFactory sfac() { if(sfac == null) sfac = ctx().getSocketFactory(); return(sfac); }
550a6b62-b853-4144-a742-4f92aace3580
5
public EarthCreep(int id){ if (id > 0 && id < 4){ if (id == 1){ maxHp = 50; armor = 10; speed = 3f; }else if (id == 2){ maxHp = 500; armor = 15; speed = 3.2f; }else if (id == 3){ maxHp = 1500; armor = 25; speed = 4f; } bg = new GreenfootImage ("Enemy/earth"+id+".png"); type = 4; name = "Earth Creep " + id; stringType = "Earth"; currentHp = maxHp; targetHp = maxHp + maxHp/20; isBoss = false; flying = false; hpBar = new HealthBar (maxHp, currentHp); this.setImage (bg); } }
c877b2fe-ed2d-4a86-a35d-0f38cc06fc85
2
public Laser getLaser(Sprite laserParent){ for(int i = 0; i < lasers.size(); i++){ Sprite p = (Sprite) lasers.get(i).parent; if(p == laserParent){ return (Laser)lasers.get(i); } } return null; }
22af3f25-7442-464d-bbbc-a8e5ce304435
9
private boolean r_mark_suffix_with_optional_y_consonant() { int v_1; int v_2; int v_3; int v_4; int v_5; int v_6; int v_7; // (, line 153 // or, line 155 lab0: do { v_1 = limit - cursor; lab1: do { // (, line 154 // (, line 154 // test, line 154 v_2 = limit - cursor; // literal, line 154 if (!(eq_s_b(1, "y"))) { break lab1; } cursor = limit - v_2; // next, line 154 if (cursor <= limit_backward) { break lab1; } cursor--; // (, line 154 // test, line 154 v_3 = limit - cursor; if (!(in_grouping_b(g_vowel, 97, 305))) { break lab1; } cursor = limit - v_3; break lab0; } while (false); cursor = limit - v_1; // (, line 156 // (, line 156 // not, line 156 { v_4 = limit - cursor; lab2: do { // (, line 156 // test, line 156 v_5 = limit - cursor; // literal, line 156 if (!(eq_s_b(1, "y"))) { break lab2; } cursor = limit - v_5; return false; } while (false); cursor = limit - v_4; } // test, line 156 v_6 = limit - cursor; // (, line 156 // next, line 156 if (cursor <= limit_backward) { return false; } cursor--; // (, line 156 // test, line 156 v_7 = limit - cursor; if (!(in_grouping_b(g_vowel, 97, 305))) { return false; } cursor = limit - v_7; cursor = limit - v_6; } while (false); return true; }
c7c28598-326b-462e-9ff5-c9de734503d7
8
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if((affected==null)||(!(affected instanceof MOB))||(target==null)) return super.okMessage(myHost,msg); final MOB mob=(MOB)affected; if(msg.amISource(mob) &&(msg.amITarget(target)) &&(msg.targetMinor()==CMMsg.TYP_DAMAGE)) { int hurtAmount=msg.value(); final int reqDivisor=hpReq-getXLEVELLevel(invoker()); if(hurtAmount>=(target.baseState().getHitPoints()/reqDivisor)) { hurtAmount=(target.baseState().getHitPoints()/reqDivisor); msg.setValue(msg.value()+hurtAmount); if(injure()) mob.tell(mob,target,null,L("You score a DEEP cut into <T-YOUPOSS> '@x1'.",gone)); } else mob.tell(mob,target,null,L("You failed to injure <T-YOUPOSS> '@x1'.",gone)); unInvoke(); } return super.okMessage(myHost,msg); }
4611de0b-3f12-4eac-9396-6bce784c4dcb
8
public boolean dfs(int k){ if(k > 325) return true; int s = Integer.MAX_VALUE, c = 0; for(int t = R[Head]; t != Head; t = R[t]){ if(S[t] < s){ s = S[t]; c = t; } } if(c == 0) return true; remove(c); for(int i = D[c]; i != c; i = D[i]){ int t = (i - 325) / 4; oridata[t / 9] = (char)(t % 9 + '1'); for(int j = R[i]; j != i; j = R[j]){ remove(C[j]); } if(dfs(k + 1)) return true; for(int j = L[i]; j != i; j = L[j]){ resume(C[j]); } } resume(c); return false; }
3f30b2d5-43b7-4978-8d4d-e4d13953a324
3
public boolean validPixel(int x, int y) { return y >= 0 && y < height && x >= 0 && x < width; }
2732fe79-1637-4b5d-99bc-48417a06dd27
8
public void deParse(AlterFuzzyDomain alterFuzzyDomain) { buffer.append("CREATE FUZZY DOMAIN ") .append(alterFuzzyDomain.getName()); ExpressionDeParser expressionDeParser = new ExpressionDeParser(null, buffer); if (null != alterFuzzyDomain.getAddValues()) { buffer.append(" ADD VALUES "); try{ alterFuzzyDomain.getAddValues().accept(expressionDeParser); }catch(Exception e) {}; } else if (null != alterFuzzyDomain.getAddSimilarity()) { buffer.append(" ADD SIMILARITY {"); expressionDeParser.setUseBracketsInExprList(false); try{ alterFuzzyDomain.getAddSimilarity().accept(expressionDeParser); }catch(Exception e) {}; expressionDeParser.setUseBracketsInExprList(true); buffer.append("}"); } else if (null != alterFuzzyDomain.getDropValues()) { buffer.append(" DROP VALUES "); try{ alterFuzzyDomain.getDropValues().accept(expressionDeParser); }catch(Exception e) {}; } else if (null != alterFuzzyDomain.getDropSimilarity()) { buffer.append(" DROP SIMILARITY {"); expressionDeParser.setUseBracketsInExprList(false); try{ alterFuzzyDomain.getDropSimilarity().accept(expressionDeParser); }catch(Exception e) {}; expressionDeParser.setUseBracketsInExprList(true); buffer.append("}"); } }
38f4bdbe-3c4e-46b1-84af-e3245ba760ea
2
public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source.equals(input)) { String line = input.getText().trim(); if (line.length() > 0) { mainFrame.parseCmd(line); resetLine(); addCmdToHistory(line); } } }
0ecf3e96-8378-4351-b129-3e1be598a197
3
public void Agility(String message, int newX, int newY, int lvlReq, int XPgained, int delay, int emote) { if(AgilityTimer == 0) { if(playerLevel[16] >= lvlReq) { sendMessage(message); addSkillXP(XPgained, 16); teleportToX = newX; teleportToY = newY; AgilityTimer = delay; setAnimation(emote); updateRequired = true; appearanceUpdateRequired = true; } else if(playerLevel[16] < lvlReq) { sendMessage("You need an agility level of "+lvlReq+" to use this obstacle."); } } }
c15c0db4-d7e7-4836-82f9-5ff02de776d4
8
final public void Parameter() throws ParseException { /*@bgen(jjtree) Parameter */ SimpleNode jjtn000 = new SimpleNode(JJTPARAMETER); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { Identifier(); } catch (Throwable jjte000) { if (jjtc000) { jjtree.clearNodeScope(jjtn000); jjtc000 = false; } else { jjtree.popNode(); } if (jjte000 instanceof RuntimeException) { {if (true) throw (RuntimeException)jjte000;} } if (jjte000 instanceof ParseException) { {if (true) throw (ParseException)jjte000;} } {if (true) throw (Error)jjte000;} } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } }
7009df2e-e0c9-48cf-af70-5777be318b05
4
@Override protected ManifestEntry parseManifestEntryLine(String pLine, int lHighestSequencePosition) throws ExParser, ExManifest { ManifestEntry lManifestEntry = ManifestEntry.parseManifestFileLine(pLine, true); //Validate that sequence values are properly sequential if(lManifestEntry.getSequencePosition() <= lHighestSequencePosition){ throw new ExManifest("Manifest entry for file " + lManifestEntry.getSequencePosition() + ": " + lManifestEntry.getFilePath() + " is not in a valid order - an entry for position " + lHighestSequencePosition + " has already been processed."); } //Validate that file was not already implicated (note: utility scripts are allowed to be implicated multiple times) if(mFinalProcessedFilePathSet.contains(lManifestEntry.getFilePath()) && !lManifestEntry.isForcedDuplicate() && !BuiltInLoader.LOADER_NAME_SCRIPTRUNNER_UTIL.equals(lManifestEntry.getLoaderName()) ) { throw new ExManifest("Manifest entry for file " + lManifestEntry.getFilePath() + " already implicated and not marked as an explicit duplicate"); } return lManifestEntry; }
f03a7f9f-5684-4a50-a5e5-dbbbff018d23
3
private Connection getConnection() throws LoginException { final String dsJndi = this.getProperty(PARAM_DATASOURCE_JNDI); final String dbUser = this.getProperty(PARAM_DB_USER); final String dbPassword = this.getProperty(PARAM_DB_PASSWORD); try { /*String nonTxJndiName = dsJndi +"__nontx"; InitialContext ic = new InitialContext(); final DataSource dataSource = //V3 Commented (DataSource)ConnectorRuntime.getRuntime().lookupNonTxResource(dsJndi,false); //replacement code suggested by jagadish (DataSource)ic.lookup(nonTxJndiName);*/ ConnectorRuntime connectorRuntime = Util.getDefaultHabitat().getServiceHandle(cr).getService(); final DataSource dataSource = (DataSource) connectorRuntime.lookupNonTxResource(dsJndi, false); //(DataSource)ConnectorRuntime.getRuntime().lookupNonTxResource(dsJndi,false); Connection connection = null; if (dbUser != null && dbPassword != null) { connection = dataSource.getConnection(dbUser, dbPassword); } else { connection = dataSource.getConnection(); } return connection; } catch (Exception ex) { String msg = sm.getString("jdbcrealm.cantconnect", dsJndi, dbUser); LoginException loginEx = new LoginException(msg); loginEx.initCause(ex); throw loginEx; } }
a1ff653d-41a6-4393-a09e-c74f4d4231f7
1
public static void loadBill(String path){ tableData=xmlHandler.XMLHandler.readXML(path); total=0; for (int i=0;i<tableData.length;i++){ total+=(Integer)(tableData[i][2])*(Integer)(tableData[i][3]); } }
9d1285c2-329a-4062-bfa9-cb2bbf0e0f4c
5
@Override public void createSymbolicLink(String source, String destination) throws PathNotFoundException, SourceAlreadyExistsException, AccessDeniedException, UnsupportedFeatureException { if (symlinks) { try { if (pathExists(source)) throw new SourceAlreadyExistsException(); innerFs.createFile(source); FileSystemUtils.writeWholeText(attributeFs, getSymLinkPath(source), destination); } catch (NotAFileException e) { e.printStackTrace(); } catch (DriveFullException e) { e.printStackTrace(); } catch (DestinationAlreadyExistsException e) { throw new SourceAlreadyExistsException(); } } else innerFs.createSymbolicLink(source, destination); }
7099ffac-1ada-4aa4-9562-05336c264786
7
public double getSTDofDuration(RequestType type) { long temp = 0; int cnt = 0; double mean = getMeanofDuration(type); switch (type) { case ONDEMAND: for (OndemandRequest on : getOndemand()) { long duration = on.getDuration(); temp += (mean - duration) * (mean - duration); cnt++; } break; case SPOT: for (SpotRequest sp : getSpot()) { long duration = sp.getDuration(); temp += (mean - duration) * (mean - duration); cnt++; } break; case RESERVED: for (ReservedRequest re : getReserved()) { long duration = re.getDuration(); temp += (mean - duration) * (mean - duration); cnt++; } break; } if (cnt > 0) return Math.sqrt(temp / (double) cnt); return -1; }
be46bdb0-2ba9-46ed-9734-fcbdb48cb67a
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(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(login.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 login().setVisible(true); } }); }
9b2b456d-de13-4130-9dc0-224e824e5b6e
5
public static int login(String username, String password) { DBHelper db = DBHelperFactory.createDBHelper(); Account temp = db.retrieveAccount(username); if (temp == null) { return -1; } String passHash = ""; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(password.getBytes("UTF-8")); passHash = db.toHexString(hash); } catch(NoSuchAlgorithmException e){ e.printStackTrace(); } catch(UnsupportedEncodingException e){ e.printStackTrace(); } String pass = temp.getPassword(); if (pass.equals(passHash)) { if (temp.getManager()) { db.close(); return 1; } else { db.close(); return 0; } } else { db.close(); return -1; } }
963a5194-4ea4-4aeb-a592-8b448684b266
7
public void setValue(Keyword key, String value) { if (key.equals(Keyword.CONTENT)) { content = value; } else if (key.equals(Keyword.START)) { start = value; } else if (key.equals(Keyword.END)) { end = value; } else if (key.equals(Keyword.TYPE)) { type = Keyword.getMeaning(value); } else if (key.equals(Keyword.COMPLETED)) { isCompleted = Boolean.parseBoolean(value); } else if (key.equals(Keyword.ARCHIVED)) { isArchived = Boolean.parseBoolean(value); } else if (key.equals(Keyword.ALLDAY)) { isAllDayTask = Boolean.parseBoolean(value); } }
daf82a5b-1711-4fa1-a485-f0b14c63ea75
4
private static boolean isDataCorrect(ParticleEffect effect, ParticleData data) { return ((effect == BLOCK_CRACK || effect == BLOCK_DUST) && data instanceof BlockData) || (effect == ITEM_CRACK && data instanceof ItemData); }
eeba7e14-0565-416e-8ef9-cc5f12774d8d
3
public Integer getEnd() { if (end != null) if (end < 0 || end > 100) throw new RuntimeException("end取值范围0~100!"); return end; }
1eb7bb51-9ff4-4e96-8f8f-b1772350932e
0
@Override public void setMobile(String mobile) { super.setMobile(mobile); }
bd7ea048-b6ab-4764-a45b-aa0a58e3da10
3
private static ArrayList findModeAverage(int[] array, int size, int highestNumber) { ArrayList positionsOfModeValues = new ArrayList(); int highestFrequency = 0; int[] frequencyOf = new int[highestNumber+1]; for (int i=0; i<size; i++) { int currentNumber = array[i]; frequencyOf[currentNumber]++; if (frequencyOf[currentNumber] >= highestFrequency) { if (frequencyOf[currentNumber] > highestFrequency) { highestFrequency = frequencyOf[currentNumber]; positionsOfModeValues.clear(); } String newMode = Integer.toString(currentNumber); positionsOfModeValues.add(newMode); } /* if (frequencyOf[currentNumber] == highestFrequency) { String newMode = Integer.toString(currentNumber); positionsOfModeValues.add(newMode); } if (frequencyOf[currentNumber] > highestFrequency) { highestFrequency = frequencyOf[currentNumber]; positionsOfModeValues.clear(); String newMode = Integer.toString(currentNumber); positionsOfModeValues.add(newMode); } */ } return positionsOfModeValues; }
4931c1bf-12be-4ed9-ab4f-6ce692f776ab
7
public int createExchangeUsersBatch(List<VaultUser> users) { int recAdded = 0; Connection con = null; java.sql.PreparedStatement psExchangeUser = null; java.sql.PreparedStatement psLoginData = null; String psVaultUserSql = "INSERT INTO Users (" + "UserID,"+ "Email,"+ "ForeName,"+ "LastName,"+ "Password) " + "Values (?,?,?,?,?)"; String psAddLoginDataSql = "INSERT INTO LoginData (" + "UserID," + "LoginSuccess," + "LoginAttempts ) " + "Values (?,?,?)"; try { Class.forName("org.sqlite.JDBC"); try { con = DriverManager.getConnection(MxConnectionString); con.setAutoCommit(false); psExchangeUser = con.prepareStatement(psVaultUserSql); psLoginData = con.prepareStatement(psAddLoginDataSql); for(VaultUser vaultUser : users) { psExchangeUser.setString(1,vaultUser.getUserID()); psExchangeUser.setString(2,vaultUser.geteMail()); psExchangeUser.setString(3,vaultUser.getForeName()); psExchangeUser.setString(4,vaultUser.getLastName()); psExchangeUser.setString(5,vaultUser.getPassword()); psExchangeUser.addBatch(); psLoginData.setString(1,vaultUser.getUserID()); psLoginData.setBoolean(2,true); psLoginData.setInt(3,0); psLoginData.addBatch(); } int [] usersAdded = psExchangeUser.executeBatch(); int[] loginsAdded = psLoginData.executeBatch(); for(int i= 0; i < usersAdded.length ; i++) if(usersAdded[i] == 1) recAdded++; con.commit(); } catch (SQLException sqlExc) { System.out.println("Sql exception" + sqlExc.getMessage()); try { con.rollback(); } catch (SQLException e) { System.out.println("Sql exception on Rollback" + e.getMessage()); } } finally { try { con.close(); } catch (SQLException e) { System.out.println("Sql exception on Close" + e.getMessage()); } } } catch (ClassNotFoundException e) { System.out.println("SClass NOt Found Exception" + e.getMessage()); } return recAdded; }
56d22ee0-34d4-4209-8687-7cce6d6ea494
8
public void sortLabs(){ ArrayList<Timeslot>overfilledLabs; for(Student s: students){ if(!s.getFlaggedForLabs()){ s.setAssignedLab(s.getCombinedLabs().get(0)); s.getCombinedLabs().get(0).addStudent(s); } } Student currentStudent; overfilledLabs=overFilledLabs(); while(!overfilledLabs.isEmpty()){ for(Timeslot t: overfilledLabs){ for(int i=t.getPreferredMax();i<t.getAssigned().size();i++){ currentStudent=t.getAssigned().get(i); if(currentStudent.getCurrentIndexLabs()+1<currentStudent.getCombinedLabs().size()){ currentStudent.getCurrentLab().removeStudent(currentStudent); currentStudent.incrementIndexLabs(); currentStudent.getCurrentLab().addStudent(currentStudent); currentStudent.setAssignedLab(currentStudent.getCurrentLab()); } else{ if(currentStudent.getAssignedLab()!=null){ currentStudent.getAssignedLab().removeStudent(currentStudent); currentStudent.setAssignedLab(null); } currentStudent.setFlaggedForLabs(true); if(!flagged.contains(currentStudent)){ flagged.add(currentStudent); } } } overfilledLabs=overFilledLabs(); } } }
aaeb7765-8051-45b1-9806-0ff8c7587910
1
public final void run() throws FatalError, RestartLater, JSONException { BefehlFile file = new BefehlFile(); JSONObject now = file.getBefehl(); while (now != null) { printJump("(hole einen)"); PlanObject doit = PlanObject.get(now); doit.run(); now = file.getBefehl(); } printJump("(nichts)"); }
ab76ac83-b29e-4344-b23f-d989d433c4a9
3
public boolean isAvailableAt(Date targetDay) { RosterAvailability ra = checkAvailability (targetDay); if (ra == null) return false; if ((ra.getAvailabilityCode().equals(RosterAvailability.ROSTER_AVAILABLE)) || (ra.getAvailabilityCode().equals(RosterAvailability.ROSTER_OFFICE))) return true; return false; }
7bdd31fc-92bd-469b-b46f-0b4a34aa0d8e
3
public boolean validAttack(int myXCoor, int myYCoor, int targXCoor, int targYCoor, Board board){ int offset = -1; //Can only move forward if (COLOR.equals("B")) offset = 1; if (myYCoor + offset == targYCoor && Math.abs(myXCoor - targXCoor) == 1) return true; else{ return false; } }
bd26c5ff-4bab-4168-a944-3ddde8ed48ed
6
public int getRawValue() { switch (this.type) { case GPR: return this.register.ordinal(); case GPR_DEREF: return 0x08 + this.register.ordinal(); case GPR_RELATIVE_DEREF: return 0x10 + this.register.ordinal(); case SPR: return this.value; case CONST_DEREF: return 0x1e; case CONST: return 0x1f; default: // Shouldn't be reachable, but javac doesn't know that. throw new IllegalStateException(); } }
f43b3d45-d7cb-4831-b3dd-d2a0e722eb24
0
private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed setVisible(false); }//GEN-LAST:event_btnCerrarActionPerformed
ff8cb51d-8e76-44d3-818f-e62c3211ed04
4
private static WebDriver createLocalDriver(Capabilities capabilities) { String browserType = capabilities.getBrowserName(); if (browserType.equals("firefox")) return new FirefoxDriver(capabilities); if (browserType.startsWith("internet explorer")) return new InternetExplorerDriver(capabilities); if (browserType.equals("chrome")) return new ChromeDriver(capabilities); if (browserType.equals("opera")) return new OperaDriver(capabilities); throw new Error("Unrecognized browser type: " + browserType); }
e737b499-53da-4303-bce5-9daa5bd8a4be
5
private void deleteZIP(String fileName) { File f = new File(getCacheDir() + fileName); if (!f.exists()) throw new IllegalArgumentException( "Delete: no such file or directory: " + fileName); if (!f.canWrite()) throw new IllegalArgumentException("Delete: write protected: " + fileName); if (f.isDirectory()) { String[] files = f.list(); if (files.length > 0) throw new IllegalArgumentException( "Delete: directory not empty: " + fileName); } boolean success = f.delete(); if (!success) throw new IllegalArgumentException("Delete: deletion failed"); }
334650c5-ac24-4622-8a07-1d8f408b9936
2
public void save(File file) throws IOException { boolean jar = file.getName().endsWith(".jar") || file.getName().endsWith(".zip"); if(jar) { File temp = new File("./temp" + System.currentTimeMillis() + "/").getCanonicalFile(); loader.setOutputDir(temp); commit(); JarOutputStream jos = new JarOutputStream(new FileOutputStream(file)); saveDir(temp, jos, temp); jos.close(); FileUtilities.deleteDir(temp); } else { loader.setOutputDir(file); commit(); } }
4b2812b1-36e6-4641-8e4b-68eb0310ac20
5
public static L2PcInstance getRandomPlayer(L2Npc npc) { List<L2PcInstance> result = new ArrayList<>(); for (L2PcInstance player : npc.getKnownList().getKnownType(L2PcInstance.class)) { if (player.isDead()) continue; if (player.isGM() && player.getAppearance().getInvisible()) continue; result.add(player); } return (result.isEmpty()) ? null : result.get(Rnd.get(result.size())); }
11e5dbf9-850c-4535-90d5-81b85a7e011b
5
public static BuildContoursFlags swigToEnum(int swigValue) { if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue) { return swigValues[swigValue]; } for (int i = 0; i < swigValues.length; i++) { if (swigValues[i].swigValue == swigValue) { return swigValues[i]; } } throw new IllegalArgumentException("No enum " + BuildContoursFlags.class + " with value " + swigValue); }
10d9ee7b-2f86-493a-aace-a9b9a191df62
2
public void broadcast(Event event) { for(IModule listener : registeredObjects) { if(event.getOrigin() == listener) continue; listener.recieveEvent(event); } }
dde48d59-e678-459a-ac5c-ea9fd146556f
1
@Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; }
316eed34-7be0-4176-97c9-65c93728e9ea
1
public int compare(Object o1, Object o2) { String str1=(String) o1; String str2=(String) o2; int index1=str1.indexOf("/"); String loc1=str1.substring(index1+1); int index1_1=loc1.indexOf(","); int lc1_1=Integer.parseInt(loc1.substring(0,index1_1)); int lc1_2=Integer.parseInt(loc1.substring(index1_1+1)); int index2=str2.indexOf("/"); String loc2=str2.substring(index2+1); int index2_1=loc2.indexOf(","); int lc2_1=Integer.parseInt(loc2.substring(0,index2_1)); int lc2_2=Integer.parseInt(loc2.substring(index2_1+1)); if (lc1_1==lc2_1) { return lc1_2-lc2_2; } return lc1_1-lc2_1; }
06fd739f-01a6-4234-93f6-8e15dadbdba5
6
public void drawBackgroundStars(Graphics g) { int numStarsToFar = 0; Object[] bgStars = bgStarMap.keySet().toArray(); //count the number of bg stars out of range for (int i = 0; i < bgStars.length; i++) { Pair key = (Pair) bgStars[i]; int x = (int) key.getFirst(); int y = (int) key.getSecond(); if (distanceToShip(x, y) > Game.RESOLUTION_HEIGHT + 200) { numStarsToFar++; } } //player probably teleported from one side to the other //since most of the previous background stars are out of range if (numStarsToFar > bgStarCount / 2) { bgStarMap.clear(); loadBackground(); //load a fresh batch of bg stars around the ship bgStars = bgStarMap.keySet().toArray(); } //draw all the bg stars in range for (int i = 0; i < bgStars.length; i++) { Pair key = (Pair) bgStars[i]; int x = (int) key.getFirst(); int y = (int) key.getSecond(); if (distanceToShip(x, y) > Game.RESOLUTION_HEIGHT + 200) { //remove and replace the bg star since it is out of range bgStarMap.remove(key); addBGStar(Game.RESOLUTION_HEIGHT, Game.RESOLUTION_HEIGHT + 200); } else { Color starColor = bgStarMap.get(key); g.setColor(starColor); //use stars blue color intensity to determine the size int size = starColor.getBlue() < 50 ? 2 : 1; g.fillRect(x - cameraOffsetX, y - cameraOffsetY, size, size); } } }