method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
2145e377-2996-4fb2-acd6-c7e8ba9e5f7d
4
public void add(String word) { if (word == null || word.isEmpty()) return; Node localRoot = root; for (int i = 0; i < word.length(); i ++) { Character c = word.charAt(i); if (localRoot.children.containsKey(c)) { localRoot = localRoot.children.get(c); } else { Node node = new Node(c); localRoot.children.put(c, node); localRoot = node; } } localRoot.isLeaf = true; }
0efc2ad1-b6e6-4927-bfb2-72ba48c9be93
3
public static void main(String[] args) { Random random = new Random(); for(int i=1;i<=100;i++){ if(i%10 == 0){ try { Thread.sleep(random.nextInt(5)*1000); System.out.println(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(i + "\t"); } }
d553a6fe-ab5d-435f-8660-dd2ef2bb7c8d
6
EditDialog(Editable ce, CircuitSimulator f) { super((Frame)null, "Edit Component", false); cframe = f; elm = ce; setLayout(new EditDialogLayout()); einfos = new EditInfo[10]; noCommaFormat = DecimalFormat.getInstance(); noCommaFormat.setMaximumFractionDigits(10); noCommaFormat.setGroupingUsed(false); int i; for (i = 0;; i++) { einfos[i] = elm.getEditInfo(i); if (einfos[i] == null) { break; } EditInfo ei = einfos[i]; add(new Label(ei.name)); if (ei.choice != null) { add(ei.choice); ei.choice.addItemListener(this); } else if (ei.checkbox != null) { add(ei.checkbox); ei.checkbox.addItemListener(this); } else { add(ei.textf = new TextField(unitString(ei), 10)); if (ei.text != null) { ei.textf.setText(ei.text); } ei.textf.addActionListener(this); if (ei.text == null) { add(ei.bar = new Scrollbar(Scrollbar.HORIZONTAL, 50, 10, 0, barmax + 2)); setBar(ei); ei.bar.addAdjustmentListener(this); } } } einfocount = i; add(applyButton = new Button("Apply")); applyButton.addActionListener(this); add(okButton = new Button("OK")); okButton.addActionListener(this); Point x = cframe.main.getLocationOnScreen(); Dimension d = getSize(); setLocation(x.x + (cframe.winSize.width - d.width) / 2, x.y + (cframe.winSize.height - d.height) / 2); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { closeDialog(); } } ); }
c8e49bee-4db0-47d2-8ee1-127a8438c483
2
void makeEquiv(final Node node1, final Node node2) { final Set s1 = equivalent(node1); final Set s2 = equivalent(node2); if (s1 != s2) { s1.addAll(s2); final Iterator iter = s2.iterator(); while (iter.hasNext()) { final Node n = (Node) iter.next(); equiv.put(n, s1); } } }
69cc5c48-1e18-44db-816a-69688fd12153
4
public Dispatcher () throws InterruptedException { workers = new ArrayList<Worker>(); for (int x=0;x<10;x++){ JobImpl1 j = new JobImpl1(); j.id="Job-"+x; qManager.push("Queue1",j); } for (int x=0;x<10;x++){ Worker w1 = new Worker1(qManager,x); workers.add(w1); w1.start(); } for (int x=0;x<10;x++){ Worker w2 = new Worker2(qManager,x); workers.add(w2); w2.start(); } //Thread.sleep(5000); /*for (int x=100;x<200;x++){ JobImpl1 j = new JobImpl1(); j.id="Job-"+x; qManager.push("Queue1",j); }*/ Thread.sleep(2000); for (Worker ww:workers) { ww.interrupt(); ((Thread)ww).join(); } System.out.println("Queue1: "+qManager.getCount("Queue1")); System.out.println("Queue2: "+qManager.getCount("Queue2")); }
683d735d-d252-4047-b86f-5b0cf707e677
9
public final GalaxyXDefinitionParser.expression_return expression() throws RecognitionException { GalaxyXDefinitionParser.expression_return retval = new GalaxyXDefinitionParser.expression_return(); retval.start = input.LT(1); int expression_StartIndex = input.index(); CommonTree root_0 = null; GalaxyXDefinitionParser.logical_or_expression_return logical_or_expression93 = null; RewriteRuleSubtreeStream stream_logical_or_expression=new RewriteRuleSubtreeStream(adaptor,"rule logical_or_expression"); try { if ( state.backtracking>0 && alreadyParsedRule(input, 17) ) { return retval; } // C:\\Users\\Timo\\EclipseProjects\\GalaxyX\\build\\classes\\com\\galaxyx\\parser\\GalaxyXDefinitionParser.g:153:2: ( logical_or_expression ->) // C:\\Users\\Timo\\EclipseProjects\\GalaxyX\\build\\classes\\com\\galaxyx\\parser\\GalaxyXDefinitionParser.g:153:4: logical_or_expression { pushFollow(FOLLOW_logical_or_expression_in_expression712); logical_or_expression93=logical_or_expression(); state._fsp--; if (state.failed) return retval; if ( state.backtracking==0 ) stream_logical_or_expression.add(logical_or_expression93.getTree()); // AST REWRITE // elements: // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: if ( state.backtracking==0 ) { retval.tree = root_0; RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null); root_0 = (CommonTree)adaptor.nil(); // 153:26: -> { root_0 = null; } retval.tree = root_0;} } retval.stop = input.LT(-1); if ( state.backtracking==0 ) { retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { if ( state.backtracking>0 ) { memoize(input, 17, expression_StartIndex); } } return retval; }
18da18c5-e01c-4a35-9d3c-4642f5df186c
6
public Cabin getCabin(int cabin_id) { Cabin cabin = new Cabin(); ResultSet rs = null; try{ statement = connection.createStatement(); String sql = "select * from cabins where cabin_id = " + cabin_id + ";"; rs = statement.executeQuery(sql); while(rs.next()){ cabin.setName(rs.getString("cabin_name")); cabin.setWood(rs.getInt("cabin_wood")); cabin.setWood_updated(rs.getDate("wood_updated")); cabin.setLat(rs.getDouble("lat")); cabin.setLng(rs.getDouble("lng")); cabin.setLocation(rs.getString("location")); cabin.setCapacity(rs.getInt("beds")); cabin.setDifficulty(rs.getInt("difficulty")); } } catch(SQLException se) { se.printStackTrace(); } finally { try{ if(rs != null) rs.close(); } catch(Exception e) {}; try{ if(statement != null) statement.close(); } catch(Exception e) {}; } cabin.setId(cabin_id); return cabin; }
e42c90be-0bc4-4586-9186-34f0ea6ec5c6
3
@Override public EventCommentType getTypeByName(final String name) throws WrongTypeNameException { if (name == null) { throw new WrongTypeNameException("Type name is empty"); } switch (name) { case BEFORE_COMMENT_TYPE_NAME: case AFTER_COMMENT_TYPE_NAME: return new EventCommentType(name); default: throw new WrongTypeNameException("Type name is wrong"); } }
dab48841-8972-468d-a179-37ddeb491a7b
9
public boolean verificarMovimientoValido(Operador operador){ char direccion=operador.getDireccion(); int[] coordenada=matriz.retornarCoordenadaDe(matriz.getSortingRobot().getId()); if(coordenada!=null){ //Izquierda if(direccion=='l'){ if(matriz.estaDentroDeMatriz(coordenada[0],coordenada[1]-1)==false){ return false; } return true; } //Derecha if(direccion=='r'){ if(matriz.estaDentroDeMatriz(coordenada[0],coordenada[1]+1)==false){ return false; } return true; } //Arriba if(direccion=='u'){ if(matriz.estaDentroDeMatriz(coordenada[0]-1,coordenada[1])==false){ return false; } return true; } //Abajo if(direccion=='d'){ if(matriz.estaDentroDeMatriz(coordenada[0]+1,coordenada[1])==false){ return false; } return true; } } return false; }
dd7a0f69-b5ab-4e5d-a618-61eaf23f12c8
6
public static String tempban(String muter, String mutedPlayerName, double days){ // Initial message String regex = RPSystem.chatConfig.getString("format.ban"); int realDays = 0; // Token replacement regex = regex.replaceAll("%t", Timestamp.NOW()); regex = regex.replaceAll("%banner", muter); if(days >= 1) { regex.replaceAll("%y", "days"); realDays = (int) days; } else if(days >= 0.014666666666666667 && days < 1){ regex = regex.replaceAll("%y", "hours"); realDays = (int) (24 * days); } else if(days >= 0.00024444444444444445 && days < 0.014666666666666667){ regex = regex.replaceAll("%y", "minutes"); realDays = (int) (1440 * days); } else if(days < 0.00024444444444444445) { regex = regex.replaceAll("%y", "seconds"); realDays = (int) (186400 * days); } regex = regex.replaceAll("%banned", mutedPlayerName); regex = regex.replaceAll("%n", Integer.toString(realDays)); regex = build(regex.split(" ")); return regex; }
b7d83d06-867b-4bfc-8613-029d696d2210
7
public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuilder sb = new StringBuilder(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if ("".equals(string)) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); }
c9109c70-4b26-4264-a722-f687c85b8d2e
5
public static Colour lightValue(World world) { final float dayValue = dayValue(world) ; if (dayValue == 1) return DAY_LIGHT ; if (dayValue == 0) return NIGHT_LIGHT ; final Colour a, b ; final float w ; if (dayValue > 0.5f) { a = DAY_LIGHT ; b = isMorning(world) ? MORNING_LIGHT : EVENING_LIGHT ; w = (dayValue - 0.5f) * 2 ; } else { a = isMorning(world) ? MORNING_LIGHT : EVENING_LIGHT ; b = NIGHT_LIGHT ; w = dayValue * 2 ; } final Colour blend = new Colour().set( (a.r * w) + (b.r * (1 - w)), (a.g * w) + (b.g * (1 - w)), (a.b * w) + (b.b * (1 - w)), 1 ) ; return blend ; }
9b5f09b3-7d4a-479d-8b7a-89d039932c89
4
public synchronized int addPlayer(Player player) { if (game != null && playerCount < players.length) { player.setSeatNumber(game.addPlayer(player)); players[playerCount++] = player; addGameListener((GameListener) player.getUser().getGameSocket()); if (playerCount == 1) { for (GameLawEnforcer game : gameEnforcers) { game.start(); } } broadcast(PLAYER_HAS_JOINED + "@username=" + player.getUser().getUsername() + "," + NUMBER_OF_PLAYERS_KEY + playerCount, player); return playerCount; } return -1; }
d9d36e93-da0c-4259-a438-72981a65339b
5
public String buscarDocumentoPorTipoNumero(String tipo, String numero) { ArrayList<Venta> geResult= new ArrayList<Venta>(); ArrayList<Venta> dbVentas = tablaVentas(); String result=""; try{ for (int i = 0; i < dbVentas.size() ; i++){ if (dbVentas.get(i).getTipo().equalsIgnoreCase(tipo)){ if(dbVentas.get(i).getNumero().equals(numero)){ geResult.add(dbVentas.get(i)); } } else { result="\nNo existe el tipo de documento ingresado."; } } }catch (NullPointerException e) { result="No existe la venta de tipo "+tipo+" con el numero: "+numero; } if (geResult.size()>0){ result=imprimir(geResult); } else { result="\nNo se ha encontrado ningun registro"; } return result; }
fdaefd3f-3a18-43aa-bb4a-5c832c55bb4c
7
public void move(Box toBox) { if (!(this instanceof gameLogic.Movable)) { return; } if (!getBox().isAdjacentTo(toBox)) { return; } Box oldBox = getBox(); try { getBox().getChart().place(this, toBox); } catch (BoxBusyException e) { return; // TODO: handle exception } // Stream the event MoveEvent evt = new MoveEvent((Movable)this, oldBox, toBox); Object[] listeners = getListeners().getListenerList(); for (int i = 0; i < listeners.length; i += 2) { if (listeners[i] == EntityListener.class) { ((EntityListener)listeners[i+1]).EntityEventOccurred(evt); } } // If it has a turn, process it if (this instanceof PlayableEntity) { if (((PlayableEntity)this).isOnTurn()) { ((PlayableEntity)this).performTurnAction(Turn.Action.Move); } } }
c6ee22bf-e332-4cd3-ac44-95ee9239bc28
8
public void createUnits(int gridXlength, int gridZlength, Grid grid, float gridHeight){ if (side){ lines = 0; // the variable lines is added to check if it's player 1 or player 2 position, if it's player 2 it starts on the other edge of the grid } else { lines = gridXlength; lineStart = lines; // lineStart is always the same as line was before the loop started } units = new Units[gridZlength][gridXlength]; // creating the Units multiarray for the player class so we can find a specific unit in the class for(int i = 0; i < (unitsAmount > (gridXlength*gridZlength)?(gridXlength*gridZlength): unitsAmount); i++){ // the for loops never loops more than the amount of tile there is on the field int currentColumn = (int)(i/gridZlength); int direction = (side? 1:-1); units[i-currentColumn*gridZlength][currentColumn] = new Testunit(); units[i-currentColumn*gridZlength][currentColumn].create // placing the units on different locations depending on if it's player 1 or 2 (assetManager, rootNode, unitNode, grid, grid.getGrid((currentColumn*direction)+lineStart+(side?0:-1), i-currentColumn*gridZlength), gridHeight, side); grid.getGrid((currentColumn*direction)+lineStart+(side?0:-1), // adding the current unit to the tile so we can handle the tile as the unit later i-currentColumn*gridZlength).currentUnit = units[i-currentColumn*gridZlength][currentColumn]; units[i-currentColumn*gridZlength][(currentColumn*1)].currentTile = grid.getGrid((currentColumn*direction)+lineStart+(side?0:-1), // adding the current tile to the unit i-currentColumn*gridZlength); if (side == false){ lines = lineStart - currentColumn*2; // decreasing the lines depending on what column the unit is on (*2 because of currentColumn adds +1 column each "i" 1-2=-1 insead of 1-1=0 to make it decrease in columns each time it has looped each column) } //zLength = (int) Math.ceil(unitsAmount / gridZlength); //xLength = (int) Math.ceil(unitsAmount/zLength); } }
b0ef8da2-1971-4d35-a9f0-21be9dc71734
1
private void adjustVolume(boolean volumeOn, int volume) { Signlink.midivol = volume; if (volumeOn) { Signlink.midi = "voladjust"; } }
9f03f3c5-9e68-4392-8b62-ed5b2ebe940e
2
public ActivityManagementWindow(MainWindow mainWindow, Student stu) { setTitle("Modificar actividades de un alumno"); setResizable(false); this.mainWindow = mainWindow; this.student = stu; setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 457, 326); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); matriculateButton = new JButton("Matricular ->"); matriculateButton.addActionListener(this); unMatriculateButton = new JButton("<- Desmatricular"); unMatriculateButton.addActionListener(this); matriculated = new DefaultListModel(); notMatriculated = new DefaultListModel(); activityService = ActivityService.getInstance(); familyService = FamilyService.getInstance(); List<String> activitiesStr = new ArrayList<String>(); List<Activity> activities = activityService.getActivities(); Set<Activity> activitiesStudent = student.getActivities(); Iterator<Activity> iter; Activity aux; iter = activities.iterator(); while (iter.hasNext()) { aux = iter.next(); if (activitiesStudent.contains(aux)) { matriculated.addElement(aux.getName()); } else { notMatriculated.addElement(aux.getName()); } } list_1 = new JList(notMatriculated); list_2 = new JList(matriculated); JScrollPane scrollPane_2 = new JScrollPane(list_1); JScrollPane scrollPane_1 = new JScrollPane(list_2); acceptButton = new JButton("Aceptar"); acceptButton.addActionListener(this); cancelButton = new JButton("Cancelar"); cancelButton.addActionListener(this); JLabel lblNewLabel = new JLabel("Estudiante:"); lblNewLabel.setName("lblNewLabel"); lblNewLabel.setText("Estudiante: " + student.getName() + " " + student.getLastname()); GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane .setHorizontalGroup(gl_contentPane .createParallelGroup(Alignment.LEADING) .addGroup( gl_contentPane .createSequentialGroup() .addGap(26) .addGroup( gl_contentPane .createParallelGroup( Alignment.LEADING) .addComponent( lblNewLabel) .addGroup( gl_contentPane .createSequentialGroup() .addGroup( gl_contentPane .createParallelGroup( Alignment.LEADING, false) .addComponent( matriculateButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( scrollPane_2, GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)) .addGap(28) .addGroup( gl_contentPane .createParallelGroup( Alignment.LEADING, false) .addComponent( unMatriculateButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( scrollPane_1, GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)) .addPreferredGap( ComponentPlacement.RELATED) .addGroup( gl_contentPane .createParallelGroup( Alignment.TRAILING) .addComponent( acceptButton, GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE) .addComponent( cancelButton, GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)))) .addContainerGap())); gl_contentPane .setVerticalGroup(gl_contentPane .createParallelGroup(Alignment.LEADING) .addGroup( gl_contentPane .createSequentialGroup() .addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 32, GroupLayout.PREFERRED_SIZE) .addPreferredGap( ComponentPlacement.RELATED) .addGroup( gl_contentPane .createParallelGroup( Alignment.LEADING) .addGroup( gl_contentPane .createParallelGroup( Alignment.BASELINE) .addComponent( scrollPane_1, GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE) .addGroup( gl_contentPane .createSequentialGroup() .addComponent( acceptButton) .addGap(15) .addComponent( cancelButton))) .addComponent( scrollPane_2, GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)) .addPreferredGap( ComponentPlacement.RELATED) .addGroup( gl_contentPane .createParallelGroup( Alignment.BASELINE) .addComponent( unMatriculateButton) .addComponent( matriculateButton)) .addContainerGap())); contentPane.setLayout(gl_contentPane); }
9fdbe192-520c-4d04-97ea-0ba88a5c5ca2
8
@Override public void mousePressed(MouseEvent e) { try{ double childX =0; double childY =0; double parentX=0; double parentY=0; double childW=0; double childH=0; double parentW=0; double parentH=0; Object child = graphComponent.getGraph().getSelectionCell(); Object parent = graphComponent.getGraph().getModel().getParent(child); if(originalParent.isEmpty() || originalParent.get(child) == null){ originalParent.put(child, parent); }else parent = originalParent.get(child); mxRectangle rec = graphComponent.getGraph().getCellBounds(graphComponent.getGraph().getSelectionCell()); childX = rec.getX(); childY = rec.getY(); childW = rec.getWidth(); childH = rec.getHeight(); mxRectangle rec2 = graphComponent.getGraph().getCellBounds(originalParent.get(child)); if(rec2 != null){ parentX = rec2.getX(); parentY = rec2.getY(); parentH=rec2.getHeight(); parentW=rec2.getWidth(); } int cX = (int) childX; int cY = (int) childY; int pX= (int) parentX; int pY= (int) parentY; int cW = (int) childW; int cH= (int) childH; int pW= (int) parentW; int pH= (int) parentH; Rectangle cr = new Rectangle(cX,cY,cW,cH); Rectangle pr = new Rectangle(pX,pY,pW,pH); if (!pr.contains(cr)) { graphComponent.getGraph().insertEdge(null, null, null,originalParent.get(child),child); } else if (pr.contains(cr)) { Object[] edges = graphComponent.getGraph().getEdgesBetween(parent, child); for (Object edge : edges) { graphComponent.getGraph().getModel().remove(edge); } } }catch(NullPointerException nul){ }catch(Exception en){ en.printStackTrace(); } }
acb14fd7-19db-4bee-b05b-a74daf571979
5
public String addParameter(int position, String parameter){ String lastParameter = IVPValue.NULL; if(arguments.size() >= position && position != 0){ lastParameter = (String) arguments.get(position); } if(arguments.size() <= position && position != 0){ arguments.add(position, parameter); }else if(position == 0){ arguments.add(parameter); } return lastParameter; }
4b492cb0-6530-4c10-ae75-4c4a5a965a52
9
public Wave35CinnabarGym(){ super(); MobBuilder m = super.mobBuilder; for(int i = 0; i < 1700; i++){ if(i < 2000){ if(i % 17 == 0) add(m.buildMob(MobID.RAPIDASH)); else if(i % 11 == 0) add(m.buildMob(MobID.NINETALES)); else if(1 % 3 == 0) add(m.buildMob(MobID.VULPIX)); else if(i % 2 == 0) add(m.buildMob(MobID.PONYTA)); else add(m.buildMob(MobID.GROWLITHE)); } else{ if(i % 4 == 0) add(m.buildMob(MobID.GROWLITHE)); else if(i % 3 == 0) add(m.buildMob(MobID.PONYTA)); else if(i % 2 == 0) add(m.buildMob(MobID.RAPIDASH)); else add(m.buildMob(MobID.ARCANINE)); } } }
74029194-b455-42ee-bd80-a0372722c942
2
public static void main(String args[]){ ArrayList<String> lines=new ArrayList(); lines.add("First line"); lines.add("Second line"); lines.add("Third line"); Iterator iter=(Iterator) lines.iterator(); while(iter.hasNext()){ System.out.println(iter.next()); } Collections.reverse(lines); iter=(Iterator) lines.iterator(); while(iter.hasNext()){ System.out.println(iter.next()); } //reverse(lines); }
bc18229b-b6b8-41de-85de-a8c4e0aee0dc
5
private void doShowContextMenu(MouseEvent event) { // grab the item or category under the mouse events point if there is // there is an item or category under this point. Object itemOrCategory = getItemOrCategoryUnderPoint(event.getPoint()); // if there was no item under the click, then call the generic contribution method. // else if there was a SourceListItem under the click, call the corresponding contribution // method. // else if there was a SourceListCategory under the click, call the corresponding contribution // method. JPopupMenu popup = null; if (itemOrCategory == null) { popup = fContextMenuProvider.createContextMenu(); } else if (itemOrCategory instanceof SourceListItem) { popup = fContextMenuProvider.createContextMenu((SourceListItem) itemOrCategory); } else if (itemOrCategory instanceof SourceListCategory) { popup = fContextMenuProvider.createContextMenu((SourceListCategory) itemOrCategory); } // only show the context-menu if menu items have been added to it. if (popup != null && popup.getComponentCount() > 0) { popup.show(fTree, event.getX(), event.getY()); } }
1945d122-10f7-4eb9-bd04-8d812be895f6
7
private static int printSourceNumber(String source, int offset, StringBuffer sb) { double number = 0.0; char type = source.charAt(offset); ++offset; if (type == 'S') { if (sb != null) { int ival = source.charAt(offset); number = ival; } ++offset; } else if (type == 'J' || type == 'D') { if (sb != null) { long lbits; lbits = (long)source.charAt(offset) << 48; lbits |= (long)source.charAt(offset + 1) << 32; lbits |= (long)source.charAt(offset + 2) << 16; lbits |= source.charAt(offset + 3); if (type == 'J') { number = lbits; } else { number = Double.longBitsToDouble(lbits); } } offset += 4; } else { // Bad source throw new RuntimeException(); } if (sb != null) { sb.append(ScriptRuntime.numberToString(number, 10)); } return offset; }
9e4f7ebc-f681-41b8-aabb-4eef208c12dd
8
public void CaptureBlackPiece(int r1, int c1, int r2, int c2) { // Check Valid Capture assert(Math.abs(r2-r1)==2 && Math.abs(c2-c1)==2); // Obtain the capture direction MoveDir dir = r2>r1?(c2>c1?MoveDir.forwardRight:MoveDir.forwardLeft) :(c2>c1?MoveDir.backwardRight:MoveDir.backwardLeft); // Removing Black Piece from the board switch(dir){ case forwardLeft: this.cell[r1+1][c1-1] = CellEntry.empty; break; case forwardRight: this.cell[r1+1][c1+1] = CellEntry.empty; break; case backwardLeft: this.cell[r1-1][c1-1] = CellEntry.empty; break; case backwardRight: this.cell[r1-1][c1+1] = CellEntry.empty; break; } // Decreasing the count of black pieces this.blackPieces--; // Making move this.MakeMove(r1, c1, r2, c2); //return dir; }
d5d1b7dc-4c43-4a66-9ee4-82e72b1e1924
5
public void genEnergyType(){ rand = new Random(); energyRoll = (rand.nextInt(5)+1); if(energyRoll == 1){ energyType = "Acid"; } else if(energyRoll == 2){ energyType = "Cold"; } else if(energyRoll == 3){ energyType = "Fire"; } else if(energyRoll == 4){ energyType = "Electricity"; } else if(energyRoll == 5){ energyType = "Sonic"; } }
dbffb4cb-13da-4c39-8f67-51e7c571ad30
1
public static Singleton getInstancia() { if (singleton==null) { singleton= new Singleton(); } return singleton; }
b1cd84fc-85b1-42c7-be4d-6b4d01108952
0
public void update() { }
e72a099a-5164-44ca-b1e9-98d63e050e51
9
@Override public int compare(Invocation c1, Invocation c2) { MethodCall o1 = c1.getMethodCall(); MethodCall o2 = c2.getMethodCall(); // First compare on names { int value = comp(nameMatches(o1), nameMatches(o2)); if (value != 0) { return value; } } // Compare on method signature { int value = comp(methodMatches(o1), methodMatches(o2)); if (value != 0) { return value; } } // Compare on actual arguments and types { Class[] parameters = method.getParameters(); int i = 0; for (Matcher matcher : argumentMatchers) { int value = comp(matchNull(o1, i), matchNull(o2, i)); if (value != 0) { return value; } value = comp(matchArg(o1, i, matcher), matchArg(o2, i, matcher)); if (value != 0) { return value; } value = comp(matchType(o1, i, parameters), matchType(o1, i, parameters)); if (value != 0) { return value; } i++; } } // Compare number of arguments int value = comp(compareLength(o1), compareLength(o2)); if (value != 0) { return value; } // Compare number of arguments int len1 = getNumArgs(o1); int len2 = getNumArgs(o2); if (len1 < len2) { return -1; } if (len1 > len2) { return 1; } // Compare on argument hashcodes in order to put equal // argument lists next to each other return compareOrigin(c1, c2); }
5ac7e287-1248-4f72-bc21-06a5e902b80f
3
private static Long seatClassToLong(Ticket.seatClass sc) { if (sc == Ticket.seatClass.SEAT_CLASS_ECONOMIC) return 1L; else if (sc == Ticket.seatClass.SEAT_CLASS_BUSINESS) return 2L; else if (sc == Ticket.seatClass.SEAT_CLASS_FIRST) return 3L; else return 1L; }
052ca869-0607-4454-a171-b1b8badfe6ca
8
public static void pprintQuantifiedVariables(Vector variables, boolean includetypesP, org.powerloom.PrintableStringWriter stream) { if (variables == null) { return; } stream.print("("); Native.setIntSpecial(OntosaurusUtil.$PPRINT_INDENT$, ((Integer)(OntosaurusUtil.$PPRINT_INDENT$.get())).intValue() + 1); { Skolem vbl = null; Vector vector000 = variables; int index000 = 0; int length000 = vector000.length(); int i = Stella.NULL_INTEGER; int iter000 = 1; for (;index000 < length000; index000 = index000 + 1, iter000 = iter000 + 1) { vbl = ((Skolem)((vector000.theArray)[index000])); i = iter000; if (includetypesP) { stream.print("("); } { Surrogate testValue000 = Stella_Object.safePrimaryType(vbl); if (Surrogate.subtypeOfP(testValue000, OntosaurusUtil.SGT_LOGIC_PATTERN_VARIABLE)) { { PatternVariable vbl000 = ((PatternVariable)(vbl)); OntosaurusUtil.pprintObject(vbl000, stream); } } else if (Surrogate.subtypeOfP(testValue000, OntosaurusUtil.SGT_LOGIC_SKOLEM)) { { Skolem vbl000 = ((Skolem)(vbl)); OntosaurusUtil.pprintObject(vbl000, stream); } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } if (includetypesP) { OntosaurusUtil.pprintObject(Logic.logicalType(vbl), stream); stream.print(")"); } if (i < variables.length()) { if (includetypesP) { OntosaurusUtil.pprintNewline(stream); } else { stream.print(" "); } } } } Native.setIntSpecial(OntosaurusUtil.$PPRINT_INDENT$, ((Integer)(OntosaurusUtil.$PPRINT_INDENT$.get())).intValue() - 1); stream.print(")"); }
07f4ebf5-c98b-424c-a150-ac77614297ab
7
public boolean surLeSol(Body body) { if (world == null) { return false; } // collision avec le perso est apparu? CollisionEvent[] evenementCollision = world.getContacts(body); for (int i = 0; i < evenementCollision.length; i++) { // si le point de la collision est proche des pieds if (evenementCollision[i].getPoint().getY() > getY() + (tailleBlockPerso / 4)) { // regarde qu'elle corps est rentre en collision avec quelque // chose if (evenementCollision[i].getNormal().getY() < -0.5) { // corps B est rentre en collision, est ce notre perso? si // oui, retourne on est au sol if (evenementCollision[i].getBodyB() == body) return true; } // corps B est rentre en collision, est ce notre perso? si oui, // retourne on est au sol if (evenementCollision[i].getNormal().getY() > 0.5) if (evenementCollision[i].getBodyA() == body) return true; } } return false; }
fb336b71-1d9b-4d1c-9cc0-18065c4639c8
1
public JSONArray getJSONArray(String key) throws JSONException { Object o = get(key); if (o instanceof JSONArray) { return (JSONArray)o; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); }
9f5405c7-d0ed-44bc-8793-febded83836a
4
public boolean metaValid() { return !(this.title.isEmpty() || this.artist.isEmpty() || this.creator.isEmpty() || this.version.isEmpty() || this.source.isEmpty()); }
df7f47fb-1058-4229-9c8f-8b39e64b2d51
5
@Override public void run() { //System.out.println("Log thread started"); while (!terminated || (strings.size() != 0)) { if (strings.size() != 0) { try { out.write(strings.get(0)); out.newLine(); } catch (IOException e) { e.printStackTrace(); } strings.remove(0); } } try { String hours = new SimpleDateFormat("HH").format(Calendar.getInstance().getTime()); String minutes = new SimpleDateFormat("mm").format(Calendar.getInstance().getTime()); String seconds = new SimpleDateFormat("ss").format(Calendar.getInstance().getTime()); String millis = new SimpleDateFormat("SSS").format(Calendar.getInstance().getTime()); String startTimeLog = hours + ":" + minutes + ":" + seconds + ":" + millis; out.write("[Log ended at " + startTimeLog + "]"); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } //System.out.println("Log thread terminated"); }
07ae7d9b-83ab-4804-8acc-a24d1746ba8a
7
public void changeHairAllFemales() { createHairListsOutOfWhiteLists(); int counter = 0; int max = SkyProcStarter.merger.getNPCs().getRecords().size(); for (NPC_ n : SkyProcStarter.merger.getNPCs()) { counter++; SPProgressBarPlug.setStatusNumbered(counter, max, "deploying new hairstyles"); if (n.get(NPC_.NPCFlag.Female)) { m_raceName = (SkyProcStarter.merger.getRaces().get(n.getRace())).getEDID(); if (m_raceName.toLowerCase().contains("imperial") || m_raceName.toLowerCase().contains("breton") || m_raceName.toLowerCase().contains("nord") || m_raceName.toLowerCase().contains("redguard")) { if (!m_raceName.toLowerCase().contains("child")) { m_npc = n; changeHair(); n = m_npc; SkyProcStarter.patch.addRecord(n); m_npc = null; m_raceName = null; } } } } }
557178f4-8370-43b3-9499-2b22d2e50037
6
@EventHandler public void onInventoryClick(InventoryClickEvent e){ Player p = (Player) e.getWhoClicked(); // Player who clicked ItemStack clicked = e.getCurrentItem(); // Item clicked Inventory inventory = e.getInventory(); // Inventory clicked // Cosmetics Menu if (inventory.getName().equals(CosmeticMenu.getCosmeticMenu().getName())){ if (clicked.getType() == Material.PUMPKIN){ HatMenu.openMenu(p); e.setCancelled(true); } else if (clicked.getType() == Material.IRON_CHESTPLATE){ WardrobeMenu.openWardrobe(p); e.setCancelled(true); } } // Wardrobe Menu else if (inventory.getName().equals(WardrobeMenu.getWardrobeMenu().getName())){ p.getInventory().setHelmet(clicked); p.getInventory().setChestplate(clicked); p.getInventory().setLeggings(clicked); p.getInventory().setBoots(clicked); e.setCancelled(true); p.closeInventory(); } // Hat Menu else if (inventory.getName().equals(HatMenu.getHatMenu().getName())){ if (clicked.getType() == Material.ARROW){ CosmeticMenu.openMenu(p); } else { p.getInventory().setHelmet(clicked); e.setCancelled(true); p.closeInventory(); } } }
7af9aa4a-058a-4e59-87c8-f9fa48192eeb
8
@Override public void run() { int compteur = 0; FileReader fr; try { fr = new FileReader(new File(Common.DIRRSC + corpus)); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); while (line != null) { try { HashMap<String, Short> tf_doc; String[] doc = line.split("\t"); int hash_doc = Integer.parseInt((doc[0])); tf_doc = getTermFrequencies(doc[1], normalizer, stopwords); for (Map.Entry<String, Short> word : tf_doc.entrySet()) { String w = word.getKey(); if (!Common.isEmptyWord(w)) { TreeMap<Integer, Short> listDocs = index.get(w); if (listDocs != null) { // le mot existe dans l'index, on l'ajoute dans // la liste des documents listDocs.put(hash_doc, word.getValue()); index.put(w, listDocs); } else { TreeMap<Integer, Short> list_docs = new TreeMap<>(); list_docs.put(hash_doc, word.getValue()); index.put(w, list_docs); } } } } catch (IOException e) { e.printStackTrace(); } if (compteur == this.reached) { compteur = 0; saveTempIndex(); } line=br.readLine(); compteur++; } br.close(); fr.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } saveTempIndex(); fusionIndexes(this.tmp_idx, this.name_idx); System.gc(); }
51a120d1-2f8a-400c-8c4a-e53ec9f392ba
1
public Object get(Object key) { processQueue(); SoftReference ref = (SoftReference)hash.get(key); if (ref != null) return ref.get(); return null; }
f1dbb190-b755-44f4-9197-31c36f4fb7ca
2
private void initExistingBonus() { List<BonusQuestion> list = Bonus.getAllQuestions(); GameData g = GameData.getCurrentGame(); setWeekSpinner(Bonus.getMaxWeek(), g.getCurrentWeek()); if (list == null || list.size() == 0) { return; // nothing to load } setQuestionSpinner(1, Bonus.getNumQuestionsInWeek(1)); setQuestionView(Bonus.getQuestion(getCurrentWeek(), getCurrentQNum())); }
ed15388c-edf4-4431-b8dd-86dde68c2d8f
5
private void run() { long time = 0, lastTime = 0, currentFPSSample = 0, lastFPSTime = 0; isRunning = true; while(isRunning) { if(Window.isCloseRequested()) isRunning = false; // Input Stuff game.input(); if(Input.isKeyPressed(Input.KEY_F1)) screenshot(); Input.update(); // Timing Stuff time = Time.getTime(); Time.setDelta((time - lastTime)/1000000f); deltaSamples[(int) (currentFPSSample % deltaSamples.length)] = (float) Time.getDelta(); FPS = (int) (1f/avg(deltaSamples) * 1000); lastTime = time; if(time - lastFPSTime > Time.SECOND) { secondsFPS = FPS; lastFPSTime = time; } fpsSamples[(int) (currentFPSSample++ % fpsSamples.length)] = FPS; //game.update(); game.playerUpdate(); // Rendering Stuff render(); // This stops the aux thread from completely freezing try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } Display.sync(TARGET_FPS); } System.out.println(); shutDown(); }
0db481b3-8ce1-4a22-97f7-064d5bff7a92
9
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equalsIgnoreCase("node")) { inNode = true; CoastlineNode node = getNodeInformation(attributes); if (node != null) { // nodes.put(node.getID(), node); if (!outsideBorder(node.getY(), node.getX())) { nodes.put(node.getID(), node); } } } else if (localName.equalsIgnoreCase("way")) { inWay = true; String id = attributes.getValue("id"); if (id != null) { edgeID = Integer.parseInt(id); } } if (inWay) { if (localName.equalsIgnoreCase("nd")) { String ref = attributes.getValue("ref"); if (ref != null) { try { int parsedInt = Integer.parseInt(ref); nodeRefQueue.add(parsedInt); } catch (NumberFormatException ex) { Logger.getLogger(Coastline.CoastlineXMLHandler.class.getName()).log(Level.SEVERE, null, ex); } } } } }
17a0940b-8574-454d-a945-7de12c8567f1
8
public void renderProjectile(int xp, int yp, Projectile p) { xp -= xOffset; yp -= yOffset; for(int y = 0; y < p.getSpriteSize(); y++) { int ya = y + yp; for(int x = 0; x < p.getSpriteSize(); x++) { int xa = x + xp; if(xa < -p.getSpriteSize() || xa >= width || ya < 0 || ya >= height) { break; } if(xa < 0) { xa = 0; } int col = p.getSprite().pixels[x + y * p.getSpriteSize()]; if(col != ALPHA_COL) { pixels[xa + ya * width] = col; } } } }
1b18f37e-f0d7-4547-9463-be4f5d85481d
7
public boolean isValidPosition(Point p){ if (p.x < 0 || p.x >= width || p.y < 0 || p.y >= height) return false; if (map.get(p.y).get(p.x) == BLOCK || map.get(p.y).get(p.x) == START || map.get(p.y).get(p.x) == EXIT) return false; return true; }
ec933a47-7c29-4016-8812-40c7de95a3ea
3
private Raum waehleNeuenRaum(ServerKontext kontext, Raum raum) { // Normaler Weise zwei Felder weiter, es sei denn, im ersten Feld ist // der Spieler Raum neuerRaum1 = selectRaumOhneKatze(raum.getAusgaenge()); // Kann sich die Katze nicht bewegen? if(neuerRaum1 == null) return raum; // Katze auf Spieler getroffen? if(istEinSpielerImRaum(kontext, neuerRaum1)) return neuerRaum1; Raum neuerRaum2 = selectRaumOhneKatze(neuerRaum1.getAusgaenge()); // Hat neuerRaum1 keine Ausgänge? if(neuerRaum2 == null) return neuerRaum1; return neuerRaum2; }
04ac4131-382f-44af-bdea-5b5e7c6433d8
7
public void start() throws IOException { myServerSocket = new ServerSocket(); myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); myThread = new Thread(new Runnable() { @Override public void run() { do { try { final Socket finalAccept = myServerSocket.accept(); registerConnection(finalAccept); finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT); final InputStream inputStream = finalAccept.getInputStream(); asyncRunner.exec(new Runnable() { @Override public void run() { OutputStream outputStream = null; try { outputStream = finalAccept.getOutputStream(); TempFileManager tempFileManager = tempFileManagerFactory.create(); HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress()); while (!finalAccept.isClosed()) { session.execute(); } } catch (Exception e) { // When the socket is closed by the client, we throw our own SocketException // to break the "keep alive" loop above. if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { e.printStackTrace(); } } finally { safeClose(outputStream); safeClose(inputStream); safeClose(finalAccept); unRegisterConnection(finalAccept); } } }); } catch (IOException e) { } } while (!myServerSocket.isClosed()); } }); myThread.setDaemon(true); myThread.setName("NanoHttpd Main Listener"); myThread.start(); }
90fdfff6-e99c-4eb2-a823-df88c271c2c7
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ObjectFields)) { return false; } ObjectFields other = (ObjectFields) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
3c63f540-3623-4a18-9d5d-7b678b5569e6
3
public void updateSharkHealth(){ if(sharkCanTakeDamage) { for (int i = 0; i < sharks.size(); i++) { sharks.get(i).updateHealth(); if (sharks.get(i).getDead() == true) { killshark = true; updateScore('a'); buildSharkKillTimer(1); sharkTimer.start(); } } } else{ } }
567b8c8c-de5b-4c3e-b6de-41c60b72544a
8
public int run() { String indexValue = "0"; // Get the index value. if (register.equalsIgnoreCase("1")) indexValue = ASCView.getIndex1(); else if (register.equalsIgnoreCase("2")) indexValue = ASCView.getIndex2(); else if (register.equalsIgnoreCase("3")) indexValue = ASCView.getIndex3(); int value = 0; value = Integer.parseInt(indexValue, 16); // Increment it value += 1; if (value >= 65536) { ASCView.setCarBit(true); value = 0; } indexValue = Integer.toHexString(value); // Update the register with the new value. if (register.equalsIgnoreCase("1")) ASCView.setIndex1(formatText(indexValue)); else if (register.equalsIgnoreCase("2")) ASCView.setIndex2(formatText(indexValue)); else if (register.equalsIgnoreCase("3")) ASCView.setIndex3(formatText(indexValue)); if (value == 0) return 1; return -1; }
7d428b1c-a1f6-4096-9c4a-d3748690eb28
9
public String nextToken() throws JSONException { char c; char q; StringBuilder sb = new StringBuilder(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
5ecbe3ff-276b-4036-a91c-383cb3ad7dcb
7
public double calculate(Accession a1, Accession a2) { double value = getMemoizedValue(a1.getId(), a2.getId()); if (value != MISSING_VAL) { return value; } ListIterator<List<Double>> m1Itr = a1.getSSRValues().listIterator(); ListIterator<List<Double>> m2Itr = a2.getSSRValues().listIterator(); double markerCnt = 0; double sumMarkerSqDiff = 0; while (m1Itr.hasNext() && m2Itr.hasNext()) { ListIterator<Double> a1Itr = m1Itr.next().listIterator(); ListIterator<Double> a2Itr = m2Itr.next().listIterator(); double markerSqDiff = 0; while (a1Itr.hasNext() && a2Itr.hasNext()) { Double Pxla = a1Itr.next(); Double Pyla = a2Itr.next(); if( Pxla != null && Pyla != null ) { markerSqDiff += (Pxla - Pyla) * (Pxla - Pyla); } } sumMarkerSqDiff += markerSqDiff; markerCnt++; } value = 1.0/(Math.sqrt(2.0 * markerCnt))*Math.sqrt(sumMarkerSqDiff); setMemoizedValue(a1.getId(), a2.getId(), value); return value; }
0f7ebe3a-290f-4429-b6c3-8d5f189bb22c
9
void setStateFromLocalConnState(int localCallState) { switch (localCallState) { case 1: setConnectionState(84, null); setTermConnState(98, null); break; case 2: setConnectionState(83, null); setTermConnState(97, null); break; case 3: setConnectionState(88, null); setTermConnState(98, null); break; case 4: setConnectionState(88, null); setTermConnState(99, null); break; case 5: setConnectionState(82, null); break; case 6: setConnectionState(90, null); setTermConnState(102, null); break; case 0: if (this.provider.isLucent()) { log.info("NULL localCallState implies BRIDGED for " + this); setConnectionState(88, null); setTermConnState(100, null); } break; case -1: } setConnectionState(91, null); setTermConnState(103, null); }
f497994e-2ad6-489c-a9ff-48298ac65cb6
3
public AbstractInsnNode[][] findGroups(String regex) { try { Matcher regexMatcher = Pattern.compile(processRegex(regex), Pattern.MULTILINE).matcher(representation); if (regexMatcher.find()) { AbstractInsnNode[][] result = new AbstractInsnNode[regexMatcher .groupCount() + 1][0]; for (int i = 0; i <= regexMatcher.groupCount(); i++) result[i] = makeResult(regexMatcher.start(i), regexMatcher.end(i)); return result; } } catch (PatternSyntaxException ex) { ex.printStackTrace(); } return new AbstractInsnNode[0][0]; }
48d40101-20ed-4524-b094-7a469035a7f5
2
public int findMaximum(ArrayList <Employee> employee, int i) { int j, max = i; for(j = i + 1; j < employee.size(); j++) { if (employee.get(j).getGrossPay() > employee.get(max).getGrossPay()) max = j; } return max; }
73846e95-a42f-4a6f-b517-bed307243b18
6
public boolean method577(int i) { if (anIntArray776 == null) { if (anIntArray773 == null) return true; if (i != 10) return true; boolean flag1 = true; for (int k = 0; k < anIntArray773.length; k++) flag1 &= Model.method463(anIntArray773[k] & 0xffff); return flag1; } for (int j = 0; j < anIntArray776.length; j++) if (anIntArray776[j] == i) return Model.method463(anIntArray773[j] & 0xffff); return true; }
b05cbca0-eeb2-4ee5-abb5-3ecef4bc862e
7
public static List<Tile> loadMap(String filename) { ArrayList<String> lines = new ArrayList<String>(); int width = 0; InputStream is = MapLoader.class.getClassLoader().getResourceAsStream( filename); System.out.println(is.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); while (true) { String line; try { line = reader.readLine(); // no more lines to read if (line == null) { reader.close(); break; } if (!line.startsWith("!")) { lines.add(line); width = Math.max(width, line.length()); } } catch (IOException e) { System.out.println(e.getMessage()); System.out.println(e); } } List<Tile> tiles = new ArrayList<Tile>(); for (int j = 0; j < 12; j++) { String line = lines.get(j); for (int i = 0; i < width; i++) { if (i < line.length()) { char ch = line.charAt(i); Tile t = new Tile(i, j, Character.getNumericValue(ch)); tiles.add(t); } } } return tiles; }
7b847cae-bcb7-4cb8-a5a9-4aa305860982
8
private void createRivers() { for (int i = 0; i < bounds.width / 2; i++) { Corner c = corners.get(r.nextInt(corners.size())); if (c.ocean || c.elevation < 0.3 || c.elevation > 0.9) { continue; } // Bias rivers to go west: if (q.downslope.x > q.x) continue; while (!c.coast) { if (c == c.downslope) { break; } Edge edge = lookupEdgeFromCorner(c, c.downslope); if (!edge.v0.water || !edge.v1.water) { edge.river++; c.river++; c.downslope.river++; // TODO: fix double count } c = c.downslope; } } }
02defccc-d25a-4b57-9501-fbd1a447b7f0
8
public static void cleanAll() { for (Shit s: shitList) { s.remove(); } for (Vomit v: vomitList) { v.remove(); } for (ObjEX oex: Food.objEXList) { if (((Food)oex).isEmpty()) oex.remove(); } for (Body b: bodyList) { if (b.isDead()) b.remove(); } for (ObjEX oex: Stalk.objEXList) { Stalk st = (Stalk)oex; if (st.getPlantYukkuri() == null){ st.remove(); } } }
58ee31be-2ce5-41ac-9d5e-6ea1ef1f93fe
6
public int PosToInt(int x, int y, int z) { if (x < 0) { return -1; } if (x >= width) { return -1; } if (y < 0) { return -1; } if (y >= height) { return -1; } if (z < 0) { return -1; } if (z >= depth) { return -1; } return x + z * width + y * width * depth; }
c5901b52-44ad-4368-b958-0be9281509e2
8
private boolean execLoadFeatures(VectorMap queryParam, StringBuffer respBody, DBAccess dbAccess) throws Exception { boolean success = true; int clntIdx = queryParam.qpIndexOfKeyNoCase("clnt"); String clientName = (String) queryParam.getVal(clntIdx); //System.out.println( "clnt = " + clientName ); int filePathIdx = queryParam.qpIndexOfKeyNoCase("path"); if (filePathIdx == -1) { WebServer.win.log.error("Parameter path is missing"); return false; } String filePath = (String) queryParam.getVal(filePathIdx); //System.out.println( "filePath = " + filePath ); int csIdx = queryParam.qpIndexOfKeyNoCase("cs"); if (csIdx == -1) { WebServer.win.log.error("Parameter cs is missing"); return false; } String cs = (String) queryParam.getVal(csIdx); //System.out.println( "cs = " + cs ); int ftrColIdx = queryParam.qpIndexOfKeyNoCase("ftrcol"); int ftrCol; if (ftrColIdx == -1) { WebServer.win.log.debug("Parameter ftrcol is missing, assuming it is 0"); ftrCol = 0; } ftrCol = Integer.parseInt((String) queryParam.getVal(ftrColIdx)); //System.out.println( "ftrCol = " + ftrCol ); int defValueIdx = queryParam.qpIndexOfKeyNoCase("defvalue"); String defValue; if (ftrColIdx == -1) { WebServer.win.log.debug("Parameter defvalue is missing, assuming it is 0.0"); defValue = "0.0"; } else { defValue = (String) queryParam.getVal(defValueIdx); } int prefixIdx = queryParam.qpIndexOfKeyNoCase("pref"); String prefix; if (prefixIdx == -1) { WebServer.win.log.debug("Parameter prefixIdx is missing, assuming it is NULL"); prefix = ""; } else { prefix = (String) queryParam.getVal(prefixIdx); } //System.out.println( "defValue = " + defValue ); File csvFile = new File(filePath); if (csvFile.exists() == false || csvFile.isDirectory() == true) { WebServer.win.log.error("The specified file does not exists or it is a directory"); return false; } BufferedReader input = new BufferedReader(new FileReader(csvFile)); String line; int rows = 0; Connection con = dbAccess.getConnection(); Statement stmt = con.createStatement(); while ((line = input.readLine()) != null) { String tokens[] = line.split(cs); String ftr = prefix + tokens[ftrCol]; //PFeature feature = new PFeature( ftr, defValue, defValue ); String sql = "REPLACE INTO " + DBAccess.FEATURE_TABLE + " " + "(uf_feature, uf_defvalue, uf_numdefvalue, " + DBAccess.FIELD_PSCLIENT + " ) VALUES ('" + ftr + "', '" + defValue + "', " + defValue + ",'" + clientName + "')"; //rows += dbAccess.insertNewFeature( feature , clientName); rows += stmt.executeUpdate(sql); } input.close(); stmt.close(); respBody.append(DBAccess.xmlHeader("/resp_xsl/rows.xsl")); respBody.append("<result>\n"); respBody.append("<row><num_of_rows>").append(rows).append("</num_of_rows></row>\n"); respBody.append("</result>"); return success; }
c30e36b7-7329-4bcf-9870-353e30cb3b72
6
public static void write(String outFilePath, int start, int end, String inFilePath) throws Exception { HashSet<String> set = new HashSet<String>(); BufferedReader reader = new BufferedReader(new FileReader(new File(inFilePath))); BufferedWriter writer = new BufferedWriter(new FileWriter(new File( outFilePath))); writer.write(reader.readLine() + "\n"); for(String s = reader.readLine(); s != null; s = reader.readLine()) { String[] splits = s.split("\t"); if( Integer.parseInt(splits[2]) >= start && Integer.parseInt(splits[2]) <= end) { writer.write(s + "\n"); StringTokenizer sToken = new StringTokenizer(splits[4]); StringBuffer buff = new StringBuffer(); buff.append(sToken.nextToken()); while( sToken.hasMoreTokens() ) { String val = sToken.nextToken(); if( val.indexOf("ECNC") == -1) buff.append(" " + val); set.add(buff.toString()); } } } writer.flush(); writer.close(); List<String> list = new ArrayList<String>(set); Collections.sort(list); for(String s : list) { System.out.println(s); } }
cc24168a-0ebe-41a4-8651-eccf20fee853
8
public DwgObject getDwgSuperEntity(DwgObject entity) { if(entity.hasSubEntityHandle()){ int handleCode = entity.subEntityHandle.getCode(); int offset = entity.subEntityHandle.getOffset(); int handle = -1; DwgObject object; switch(handleCode){ // TODO: case 0x2: // TODO: case 0x3: case 0x4: case 0x5: handle = offset; break; // TODO: case 0x6: case 0x8: handle=entity.getHandle().getOffset() - 1; break; case 0xA: handle = entity.getHandle().getOffset() + offset; break; case 0xC: handle = entity.getHandle().getOffset() - offset; break; default: logger.warn ("DwgObject.getDwgSuperEntity: handleCode "+handleCode+" no implementado. offset = "+offset); } if(handle != -1){ object = getDwgObjectFromHandle(handle); if(object != null) return object; } } return null; }
2315a6fd-910c-4810-a906-577431576ae1
0
public void setExecute(boolean execute) { this.execute = execute; }
298617a5-acce-4829-982d-f766922eabb2
7
private static void connectOption() throws UnspecifiedErrorException, IOException, InvalidHeaderException { final Pattern pattern = Pattern.compile("(.+):(\\d+)"); System.out.println(String.format("\n%s > %s >\n" , SHELL_TITLE, Options.CONNECT.getTitle())); boolean validInput; Matcher input = null;; do { System.out.print("Server details as 'hostname:port': "); String readString = in.nextLine(); // Check if the input signifies a return to the main menu if (isReturnToMainMenu(readString)) { return; } input = pattern.matcher(readString); validInput = input.lookingAt(); if (!validInput) { System.out.println("Invalid entry, please re-enter the details."); } } while (!validInput); System.out.println(); boolean result = false; try { result = client.Connect(input.group(1), Integer.parseInt(input.group(2))); } catch (NumberFormatException e) { } catch (FullServerException e) { System.out.println( String.format("The client could not connect for the following reason:\n%s", e.getMessage())); } catch (AlreadyOnlineException e) { System.out.println( String.format("The client could not connect for the following reason:\n%s", e.getMessage())); } if (result) { System.out.println("The connection was successful."); menuOptions.clear(); menuOptions.add(Options.MESSAGES); menuOptions.add(Options.QUEUES); menuOptions.add(Options.DISCONNECT); } else System.out.println("The connection was not successful."); }
1f40ab8c-8304-400a-9e23-7a45e7264c9f
2
public DataProcessor(int option) { // polymorphism switch (option) { case 0: // initialize as a string processor cp = new StringCompressor(); ep = new StringEncryptor(); break; case 1: // initialze as a file processor cp = new FileCompressor(); ep = new FileEncryptor(); break; } }
62679d51-404e-4cce-935a-821fb81c323c
1
@Override public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { return orientation == SwingConstants.VERTICAL ? visibleRect.height : visibleRect.width; }
ed4c5719-61e5-488f-8e42-e713ec15ffc1
2
public PathManager() { if (System.getProperty("os.name").equals("Linux")) { standardPath = "/" + standardPath.substring(0, standardPath.length() - 1); } else if (System.getProperty("os.name").toLowerCase().equals("mac")) { standardPath = "/" + standardPath.substring(0, standardPath.length() - 1); } }
e95ab0f2-5702-417d-ad83-9087f8dc3548
2
public void testFactory_parseMinutes_String() { assertEquals(0, Minutes.parseMinutes((String) null).getMinutes()); assertEquals(0, Minutes.parseMinutes("PT0M").getMinutes()); assertEquals(1, Minutes.parseMinutes("PT1M").getMinutes()); assertEquals(-3, Minutes.parseMinutes("PT-3M").getMinutes()); assertEquals(2, Minutes.parseMinutes("P0Y0M0DT2M").getMinutes()); assertEquals(2, Minutes.parseMinutes("PT0H2M").getMinutes()); try { Minutes.parseMinutes("P1Y1D"); fail(); } catch (IllegalArgumentException ex) { // expeceted } try { Minutes.parseMinutes("P1DT1M"); fail(); } catch (IllegalArgumentException ex) { // expeceted } }
b9ca4692-91a2-41b9-abd4-0343bdac1266
4
public void setzeMaeuse(int anzahlMaeuse) { ArrayList<Raum> kannMausEnthaltenRaum = new ArrayList<Raum>(); for(Raum raum : _connections.keySet()) { if(raum.getRaumart() != RaumArt.Ende && raum.getRaumart() != RaumArt.Start) kannMausEnthaltenRaum.add(raum); } if(kannMausEnthaltenRaum.size() > 0) mausInRaumSetzen(kannMausEnthaltenRaum, anzahlMaeuse); }
cc0668c4-c340-4571-bee0-a70ae8974069
2
final protected boolean dropChild(PropertyTree childMatch) { boolean found=false; for(Iterator<PropertyTree> c=children.iterator();c.hasNext();) { if(c.next() == childMatch) { c.remove(); } } return found; }
7ac1d098-e643-415e-94c2-def74e6d9be2
4
public static void readFile(){ File file=new File("monsters.dat"); FileInputStream fin; ObjectInputStream in; try { fin = new FileInputStream(file); in=new ObjectInputStream(fin); int numMonsters=in.readInt(); current_id=numMonsters+2; for(int i=0; i<numMonsters; i++){ Monster m=(Monster)in.readObject(); monsters.add(m); } in.close(); fin.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ } }
a2e5ea55-d17b-493e-80f7-bd3c346e8ad8
2
public void damageTile(int hitpoints, AIConnection dealingPlayer){ Debug.highlight(coords.getCompactString(), 255, 0, 0); if(playerOnTile == null){ return; } else { if(tileType == TileType.SPAWN){ Debug.info("Hit spawn tile, no damage received."); } else { playerOnTile.damagePlayer(hitpoints, dealingPlayer); } } }
e2238e00-50ae-46af-aa55-40118ec7ceb8
5
public static boolean azionePossibile(ICard card, List<ICard> tableCards, List<ICard> presa) { //Butto una carta e non faccio prese if(presa.size() == 0) { boolean esistePresa = existPresa(card, tableCards); if(esistePresa){ log("Non puoi usare la carta " + card.getCardStr() + ", una presa e' possibile."); return false; } return true; } else{ //Butto una carta e faccio una presa boolean presaPossibile = presaPossibile(card, tableCards, presa); if(!presaPossibile){ log("Non puoi usare la carta " + card.getCardStr() + " con la presa specificata"); String takingStr = "Taking: ["; if(presa.size() != 0) for(ICard c : presa) takingStr += c.getCardStr() + " "; log(takingStr + "]"); return false; } else return true; } }
27ed1016-bb68-4523-b332-81cd621f111d
7
public static String getPhotoList(String date, String keyword) { DB db = _mongo.getDB(DATABASE_NAME); DBCollection coll = db.getCollection(COLLECTION_PHOTOSEARCH); BasicDBObject query = new BasicDBObject(); if (date != null && !date.equals("")) { query.put("startDate", "" + getYear(date)); } if (keyword != null && !keyword.equals("")) { query.put("title", java.util.regex.Pattern.compile("(?i)" + keyword)); } DBCursor cur = coll.find(query); if (cur.hasNext()) { boolean isFirst = true; StringBuffer sb = new StringBuffer(); sb.append("["); while (cur.hasNext()) { if (!isFirst) sb.append(", "); sb.append(cur.next().toString()); isFirst = false; } sb.append("]"); return sb.toString(); } return ""; }
c63fd326-4004-4e5a-8d2b-3f300b3f34f2
4
private void DFS(List<Integer>[] adjacentVertices, Integer vertex, List<Integer> currentComponent) { explored[vertex] = true; if(currentComponent != null) currentComponent.add(vertex); List<Integer> adjacentVertexList = adjacentVertices[vertex]; if(adjacentVertexList!=null){ for(int i=0; i< adjacentVertexList.size(); i++){ Integer adjacentVerex= adjacentVertexList.get(i); if(!explored[adjacentVerex]) DFS(adjacentVertices, adjacentVerex, currentComponent); } } finishingTime++; finishingTimes[vertex] = finishingTime; }
892509b7-4025-49ad-924b-ceda0ae31b3b
9
private void writeName(String uri, String localName, String qualifiedName) throws SAXException { try { if (uri == null || uri.length() == 0) { if (qualifiedName == null || qualifiedName.length() == 0) { output.write(localName.getBytes("UTF-8")); } else { output.write(qualifiedName.getBytes("UTF-8")); } } else if (localName == null || localName.length() == 0) { output.write(qualifiedName.getBytes("UTF-8")); } else { String prefix = stackedIndexPeek(prefixesByNamespaceURI, uri); if (prefix == null || prefix.length() == 0) { output.write(localName.getBytes("UTF-8")); } else { output.write(prefix.getBytes("UTF-8")); output.write(":".getBytes("UTF-8")); output.write(localName.getBytes("UTF-8")); } } } catch (Exception e) { throw new SAXException(e); } }
4bd2a4e2-b143-41bd-b0be-f0c84ad75039
6
public static void main(String[] args) { BufferedImage bi = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.getGraphics(); g.setColor(new Color(0, 0, 0)); g.fillRect(0, 0, 128, 128); try { ImageIO.write(bi, "PNG", new FileOutputStream(new File("terrain.png"))); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } new MapMaker().setVisible(true); }
2a37aca4-189d-4358-9f2c-3e309b1d4b10
6
public static void DividiFileR() { RegistraTempo rt = new RegistraTempo(); rt.Start(); try { Scanner scanner = new Scanner(System.in); System.out.println("Divisione file puliti da R"); System.out.println("Sicuro?"); String sel = "s"; //scanner.next(); if (!sel.equals("s")) { System.out.println("Annullato"); return; } byte[] encoded = Files.readAllBytes(Paths.get(Configuration.TxtDir + "data_to_split.txt")); //byte[] encoded = Files.readAllBytes(Paths.get(Configuration.TxtDir + "mancanti.txt")); String str = Charset.defaultCharset().decode(ByteBuffer.wrap(encoded)).toString(); String[] rows = str.split("\n"); String lastId = ""; PrintWriter writer = null; long rowCount = 0; long docCount = 0; long writeCount = 0; double perc = 0; for (String row : rows) { String[] fields = row.split("\t"); // id - type - value - term - creation - gran String doc_id = fields[0]; String doc_type = fields[1]; String doc_value = fields[2]; String doc_term = fields[3]; String doc_creation = fields[4]; String doc_gran = fields[5]; System.out.printf("\rRiga %d/%d", ++rowCount, rows.length); perc = 100 * (double)rowCount / (double)rows.length; System.out.printf(" %.1f%%", perc); String filename = Configuration.HeidelCollectionRoot + "R_puliti_divisi/" + doc_id + "_" + doc_creation + ".txt"; writer = new PrintWriter(new FileWriter(filename, true)); if (!doc_id.equals(lastId)) { //System.out.printf(" Documents: %d", ++docCount); if (!lastId.equals("")) { //writer.close(); } lastId = doc_id; docCount++; } writer.printf("%s\t%s\t%s\n", doc_type, doc_value, doc_gran); writeCount++; System.out.printf(" Documents: %d", docCount); System.out.printf(" Write: %d", writeCount); writer.close(); } if (!lastId.equals("")) { //writer.close(); } System.out.println(); } catch (IOException ex) { System.out.println(ex); } rt.Stop(true); }
e6b48956-3d77-4a68-9d36-93ceef87e37a
5
public CheckResultMessage checkJ03(int day) { int r1 = get(17, 2); int c1 = get(18, 2); int r2 = get(20, 2); int c2 = get(21, 2); BigDecimal b = new BigDecimal(0); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); b = getValue(r2 + day, c2 + 13, 4).add( getValue(r2 + day, c2 + 15, 4)).add( getValue(r2 + day, c2 + 17, 4)); if (0 != getValue(r1 + 2, c1 + 1 + day, 3).compareTo(b)) { return error("支付机构单个账户报表<" + fileName + ">系统未增加银行已增加未达账项余额 J03:" + day + "日错误"); } in.close(); } catch (Exception e) { } } else { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); b = getValue1(r2 + day, c2 + 13, 4).add( getValue1(r2 + day, c2 + 15, 4)).add( getValue1(r2 + day, c2 + 17, 4)); if (0 != getValue1(r1 + 2, c1 + 1 + day, 3).compareTo(b)) { return error("支付机构单个账户报表<" + fileName + ">系统未增加银行已增加未达账项余额 J03:" + day + "日错误"); } in.close(); } catch (Exception e) { } } return pass("支付机构单个账户报表<" + fileName + ">系统未增加银行已增加未达账项余额 J03:" + day + "日正确"); }
684c27af-eaef-4a63-bb0b-9f4c5e3aac60
8
private void writeObject(String name, Object obj, StringBuffer sb, String prepend) { if( name != null) { sb.append(prepend+_json_quote+name+_json_quote+":"); } if(obj instanceof JSONObject) { JSONObject o = (JSONObject)obj; o.pre_serialize(); if( name == null) { sb.append(prepend); } sb.append("{\n"); o.serialize(sb,prepend+_json_tab); sb.append(prepend+"},\n"); } else { if(obj instanceof Collection) { Collection<Object> v = (Collection<Object>)obj; sb.append("[\n"); for( Object o : v) { writeObject(null,o,sb,prepend+_json_tab); } sb.append(prepend+"],\n"); } else if(obj instanceof String) { String o = (String)obj; sb.append(_json_quote+o+_json_quote+",\n"); } else if(obj instanceof Integer) { Integer o = (Integer)obj; sb.append(o.intValue()+",\n"); } else if(obj instanceof Float) { Float o = (Float)obj; sb.append(o.doubleValue()+",\n"); } else sb.append(obj+",\n"); } }
6d4f9e3d-d51b-491f-a65e-dde87094a37d
4
public String getReadableName() { if ((firstname==null)||(firstname.isEmpty()) || (lastname==null)||(lastname.isEmpty())) { return username; } return MessageFormat.format("{0} {1}", firstname, lastname); }
925da642-e9db-4a9d-af27-15a58a111681
6
@Override public void innerRun() { while (true) { printShell(); String queryString = readQuery(); if (queryString == null || queryString.equals("")) { continue; } else if (queryString.equals(QUIT_COMMAND)) { return; } else if (queryString.startsWith(CONNECT_COMMAND)) { setDbFileName(queryString.replace(CONNECT_COMMAND, "").trim()); continue; } IQuery query = parseQuery(queryString); if (query != null) { executeAndPrintResult(query); } } }
95708d5b-b19b-45a0-8c51-903363ffad08
1
@Override public String toString() { String ret = String.format("%s - %s", id, name); if (error != null) ret += "error: " + error; return ret; }
70f43f15-cd3e-4d47-aa24-83cea54db99b
4
private FormData readFormData_wwwFormURLEncoded( String contentType, HeaderParams headerParams ) throws IOException, HeaderFormatException, DataFormatException, UnsupportedFormatException { // Retrieve the Content-Length header from the request to determine the number of bytes expected to read. Long contentLength = this.getRequestHeaders().getLongValue( HTTPHeaders.NAME_CONTENT_LENGTH ); if( contentLength == null ) throw new HeaderFormatException( "Cannot read form data. No (valid) 'Content-Length' header present." ); ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream(); this.getLogger().log( Level.FINE, getClass().getName() + ".readFormData_wwwFormURLEncoded()", "Going to read " + contentLength + " bytes from POST data input stream ..." ); long totalLength = CustomUtil.transfer( this.getInputStream(), byteArrayOutput, contentLength.longValue(), // maxReadLength Math.min(1024, contentLength.intValue()) // bufferSize ); String urlEncoded = new String( byteArrayOutput.toByteArray() ); this.getLogger().log( Level.FINE, getClass().getName() + ".readFormData_wwwFormURLEncoded()", "POST data read, url-encoded: " + urlEncoded ); String acceptEncoding = this.getRequestHeaders().getStringValue( HTTPHeaders.NAME_ACCEPT_CHARSET ); if( acceptEncoding == null ) { // Default charset is ISO-8859-1. // This is ugly. I want to use UTF-8 :(( //acceptEncoding = "ISO-8859-1"; acceptEncoding = java.nio.charset.StandardCharsets.ISO_8859_1.name(); this.getLogger().log( Level.INFO, getClass().getName() + ".readFormData_wwwFormURLEncoded()", "The header" + HTTPHeaders.NAME_ACCEPT_CHARSET + " is not present. Using default value '" + acceptEncoding + "'." ); } HeaderParams acceptParams = new HeaderParams( HTTPHeaders.NAME_ACCEPT_CHARSET, acceptEncoding ); String charset = acceptParams.getToken( 0, 0 ); try { this.getLogger().log( Level.INFO, getClass().getName() + ".readFormData_wwwFormURLEncoded()", "Processing POST data using charset '" + charset + "' ..." ); // Decode and parse the form data Query query = new Query( urlEncoded, charset, // The url's charset false // no case sensitive mapping ); // Build form data directly from query //FormData formData = new QueryFormDataDelegation( query ); FormData formData = new DefaultFormData(); HTTPHeaders queryHeaders = new HTTPHeaders(); Iterator<String> keyIter = query.keyIterator(); while( keyIter.hasNext() ) { String tmpKey = keyIter.next(); String tmpValue = query.getParam( tmpKey ); queryHeaders.add( new HTTPHeaderLine(tmpKey,tmpValue) ); } FormDataItem item = new FormDataItem( queryHeaders, this.getInputStream() ); formData.add( item ); this.getLogger().log( Level.FINE, getClass().getName() + ".readFormData_wwwFormURLEncoded()", "POST form data retrieved: " + formData ); return formData; } catch( UnsupportedEncodingException e ) { this.getLogger().log( Level.INFO, getClass().getName() + ".readFormData_wwwFormURLEncoded()", "Going to read " + contentLength + " bytes from POST data input stream ..." ); throw new UnsupportedFormatException( "Unsupported encoding for POST data '" + charset + "' (" + e.getMessage() + ")." ); } }
8dd146c7-6dcc-4255-879f-a2e1f718a600
1
@Test public void dequeueTest() { for (int i = 1; i < 8; i++) { System.out.println(""); printTime(testArrayDequeDequeue(100000 * (int) Math.pow(2, i))); printTime(testQueueDequeue(100000 * (int) Math.pow(2, i))); } }
90e1ea70-bcd8-4190-b5f7-73d2873e585e
8
private void writeJSON(Object value) throws JSONException { if (JSONObject.NULL.equals(value)) { write(zipNull, 3); } else if (Boolean.FALSE.equals(value)) { write(zipFalse, 3); } else if (Boolean.TRUE.equals(value)) { write(zipTrue, 3); } else { if (value instanceof Map) { value = new JSONObject((Map) value); } else if (value instanceof Collection) { value = new JSONArray((Collection) value); } else if (value.getClass().isArray()) { value = new JSONArray(value); } if (value instanceof JSONObject) { writeObject((JSONObject) value); } else if (value instanceof JSONArray) { writeArray((JSONArray) value); } else { throw new JSONException("Unrecognized object"); } } }
2cea35a8-edc1-4f93-98f0-3b39eb73e177
8
public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); // 生成公用的随机向量文件 RandomGeneration.randomVector(conf); FileSystem hdfs = FileSystem.get(conf); hdfs.delete(outputFolder, true); hdfs.delete(outputFolder2, true); // 获取分布式缓存文件路径 DistributedCache.addCacheFile(randomVectorPath.toUri(), conf); String[] otherArgs = new GenericOptionsParser(conf, args) .getRemainingArgs(); if (otherArgs.length != 0) { System.err.println("Usage: 神马都没有!"); System.exit(2); } Job job = new Job(conf, "HSEM" + "_" + String.valueOf(RANDOM_VECTORS) + "_" + String.valueOf(PERMUTATION) + "_" + String.valueOf(WINDOW)); job.setJarByClass(EntityDriver.class); job.setMapperClass(EntityMap.class); job.setReducerClass(EntityReduce.class); if (PERMUTATION >= 11) // 依据随机变换数量决定reduce数量 job.setNumReduceTasks(11); else job.setNumReduceTasks(PERMUTATION); job.setMapOutputKeyClass(IntWritable.class); job.setMapOutputValueClass(EntityData.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(EntityPairData.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); FileStatus stats[] = hdfs.listStatus(inputFolder); for (int i = 0; i < stats.length; i++) { if (!stats[i].isDir()) FileInputFormat.addInputPath(job, stats[i].getPath()); } SequenceFileOutputFormat.setOutputCompressionType(job, CompressionType.RECORD); SequenceFileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); SequenceFileOutputFormat.setOutputPath(job, outputFolder); // FileOutputFormat.setOutputPath(job, outputFolder); if (job.waitForCompletion(true)) { Job secondJob = new Job(conf, "Deduplication" + "_" + String.valueOf(RANDOM_VECTORS) + "_" + String.valueOf(PERMUTATION) + "_" + String.valueOf(WINDOW)); secondJob.setJarByClass(EntityDriver.class); secondJob.setInputFormatClass(SequenceFileInputFormat.class); secondJob.setMapperClass(DeduplicationMap.class); secondJob.setReducerClass(DeduplicationReduce.class); secondJob.setMapOutputKeyClass(Text.class); secondJob.setMapOutputValueClass(EntityPairData.class); secondJob.setNumReduceTasks(11); secondJob.setOutputKeyClass(Text.class); secondJob.setOutputValueClass(FloatWritable.class); FileStatus stats2[] = hdfs.listStatus(outputFolder); for (int i = 0; i < stats2.length; i++) { if (!stats2[i].isDir()) FileInputFormat .addInputPath(secondJob, stats2[i].getPath()); // SequenceFileInputFormat // .addInputPath(secondJob, stats2[i].getPath()); } FileOutputFormat.setOutputPath(secondJob, outputFolder2); System.exit(secondJob.waitForCompletion(true) ? 0 : 1); } // System.exit(job.waitForCompletion(true) ? 0 : 1); }
d73b528e-2d39-414b-af2d-edb6b9d33c02
4
private void writeLights(Document document) { for (int i = 0; i < lights.size(); i++) { Element lightNode = document.createElement("light"); Element color = document.createElement("color"); color.appendChild(document.createTextNode(write3Tuple(lights.get(i) .getColor()))); lightNode.appendChild(color); if (lights.get(i) instanceof AmbientLightObject) { lightNode.setAttribute("type", "ambient"); document.getFirstChild().appendChild(lightNode); } else if (lights.get(i) instanceof PointLightObject) { lightNode.setAttribute("type", "point"); PointLightObject pLight = (PointLightObject) lights.get(i); Element attenuation = document.createElement("attenuation"); attenuation.appendChild(document .createTextNode(write3Tuple(pLight.getAttenuation()))); lightNode.appendChild(attenuation); } else if (lights.get(i) instanceof DirectionalLightObject) { lightNode.setAttribute("type", "directional"); DirectionalLightObject dLight = (DirectionalLightObject) lights .get(i); Element direction = document.createElement("direction"); direction.appendChild(document .createTextNode(write3Tuple(dLight.getDirection()))); lightNode.appendChild(direction); } Element bounds = document.createElement("bounds"); Element position = document.createElement("position"); position.appendChild(document.createTextNode(write3Tuple(lights .get(i).getPosition()))); bounds.appendChild(position); Element radius = document.createElement("radius"); radius.appendChild(document.createTextNode(Double.toString(lights .get(i).getRadius()))); bounds.appendChild(radius); lightNode.appendChild(bounds); document.getFirstChild().appendChild(lightNode); } }
17822c1a-2f01-49d8-97a8-350f96711a43
0
@BeforeClass public static void setUpClass() { }
9853409a-7977-4a8c-902d-43bb3afcbe8e
1
public UnionFind(int N) { componentCount = N; // Initially assume that all nodes are in different // components, components containing just themselves id = new int[N]; // allocate memory height = new int[N]; sz = new int[N]; // Initialise for (int i = 0; i < N; i++) { id[i] = i; height[i] = 0; sz[i] = 1; } }
5a2cdcb7-e427-49e1-b1d8-f6a4e0d9e6d4
0
public String getLogin(){ return login; }
b900cd37-2a60-4188-b94a-b91174ffeca1
6
public boolean getBoolean(int index) throws JSONException { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object) .equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object) .equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); }
f4133976-6329-471d-9239-e368c96da9cb
3
@Override public void shoot(Point targetPoint) { if (actionMode != ActionMode.ATTACKING) { actionMode = ActionMode.ATTACKING; } if (canFire) { registry.getProjectileManager().createProjectile(this, "FireBall", 10, new Point( getMapX(), getMapY()), targetPoint, false, false, true, (int) ((float) touchDamage * 0.75f)); canFire = false; recastTotalTime = 0; } else { long p = registry.getImageLoader().getPeriod(); recastTotalTime = (recastTotalTime + registry.getImageLoader().getPeriod()) % (long) (1000 * RECAST_TIME * 2); if ((recastTotalTime / (RECAST_TIME * 1000)) > 1) { canFire = true; recastTotalTime = 0; } } }
d9b23288-ea14-4af9-9502-958c23a729a3
7
public List<Producto> getProductos() { Connection connection = null; Statement stmt = null; ResultSet rs = null; try { connection = pool.getConnection(); stmt = connection.createStatement(); rs = stmt.executeQuery("select id,descripcion,costo,existencias,precio,utilidad,codigo from omoikane.ramcachearticulos"); List<Producto> productos = new ArrayList<Producto>(); while(rs.next()) { try { final Producto p = new Producto(); p.setId(rs.getLong("id")); p.setDescripcion(rs.getString("descripcion")); p.setCosto(rs.getBigDecimal("costo")); p.setExistencias(rs.getBigDecimal("existencias")); p.setPrecio(rs.getBigDecimal("precio")); p.setUtilidad(rs.getBigDecimal("utilidad")); p.setCodigo(rs.getString("codigo")); productos.add(p); } catch (SQLException e) { e.printStackTrace(); } } return productos; } catch (Exception e) { Logger.getLogger(ExtractorOmoikane.class).error("Error extrayendo productos de omoikane", e); } finally { try { if(rs != null) rs.close(); if(stmt != null) stmt.close(); if(connection != null) connection.close(); } catch (SQLException e) { Logger.getLogger(ExtractorOmoikane.class).error("Error al cerrar conexiones", e); } } return null; }
f081b803-2f72-415a-a220-0157aebce3b0
9
private void adaptNewSetsMembership() throws ServerException { Connection conn = null; boolean startedTransaction = false; Iterator<SetInfo> newUserDefinedSetInfosIterator = this.newUserDefinedSetsMap.values().iterator(); while (newUserDefinedSetInfosIterator.hasNext()) { SetInfo curentSetInfo = newUserDefinedSetInfosIterator.next(); String curentSpec = curentSetInfo.getSetSpec(); Vector<String> resourceIds = _driver.retrieveIdsForSetQuery(curentSpec); if (resourceIds != null) { try { conn = RecordCache.getConnection(); conn.setAutoCommit(false); startedTransaction = true; String path = _disk.write(curentSetInfo); _db.addNewUserDefinedSet(conn, curentSpec, path); if (resourceIds.size() > 0) { _db.putSetMembership(conn, curentSpec, resourceIds); } conn.commit(); } catch (Throwable th) { _LOG.error("Adapt set membership for set spec " + curentSpec + " aborted."); if (startedTransaction) { _LOG.error("Start to roll back the transaction."); try { conn.rollback(); } catch (SQLException e) { _LOG.error( "Failed to roll back failed transaction", e); } } } finally { if (conn != null) { try { if (startedTransaction) conn.setAutoCommit(false); } catch (SQLException e) { _LOG.error("Failed to set autoCommit to false", e); } finally { RecordCache.releaseConnection(conn); } } } } else { _LOG.error("Missing result of search query for set spec " + curentSpec); throw new RepositoryException( "Missing result of search query for set spec " + curentSpec); } } }
b4d3d06e-56b7-483a-8f31-4033e6a5a115
2
@Override public int hashCode() { int hash = 5; hash = 79 * hash + ( this.left != null ? this.left.hashCode() : 0 ); hash = 79 * hash + ( this.right != null ? this.right.hashCode() : 0 ); return hash; }
069b3a26-dbb7-4fdb-b5d8-552ff4f5f5eb
2
private HashMap<Integer, String> LoadTimestampDiffsFromFile() { try ( InputStream file = new FileInputStream("timestamps.ser"); InputStream buffer = new BufferedInputStream(file); ObjectInput input = new ObjectInputStream(buffer);) { //deserialize the List HashMap<Integer, String> hashMap = (HashMap<Integer, String>) input.readObject(); return hashMap; } catch (ClassNotFoundException ex) { logger.error("Cannot deserialize object. Class not found." + ex.getMessage()); } catch (IOException ex) { logger.error("Cannot deserialize object: " + ex.getMessage()); } return new HashMap<>(); }
d4bafaac-33f4-4836-98cf-884462454ce9
1
public String toString() { return newObj != null ? newObj.toString() : "" + value; }
8b22cdb1-0b19-41c3-b950-01e3a7dc0296
3
public ByteBuffer loadIcon(String filename, int width, int height) throws IOException { BufferedImage image = ImageIO.read(new File("./res/icons/"+filename)); // load image // convert image to byte array byte[] imageBytes = new byte[width * height * 4]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int pixel = image.getRGB(j, i); for (int k = 0; k < 3; k++) // red, green, blue imageBytes[(i*16+j)*4 + k] = (byte)(((pixel>>(2-k)*8))&255); imageBytes[(i*16+j)*4 + 3] = (byte)(((pixel>>(3)*8))&255); // alpha } } return ByteBuffer.wrap(imageBytes); }
4e8049d4-87b5-4013-a08e-4079f3e07a52
8
public boolean execute(Closure closure){ // get the internal thread number int i = getInternalThreadId(); // ####################################################################### // guard stage // ####################################################################### // mark this thread as active active[i] = true; // check whether the other thread is active if (active[(i + 1) % 2]){ // if the other thread is active then mark this to wait wait[i] = true; // wait until the other thread is deactived or marks this thread to not wait while ( active[(i + 1) % 2] && wait[i] ){ // if this is waker wake up the other thread if (waker == i){ wait[(i + 1) % 2] = false; } // if waker change is in progress then acknowledge it if (waker_change){ waker_change = false; } Thread.yield(); } } // ####################################################################### // selection stage // ####################################################################### // mark this selected selected[i] = true; assert !selected[(i+1) % 2]; // execute the business method boolean result = closure.execute(); // mark this unselected selected[i] = false; // change waker if this is not the one if (waker != i){ // change waker to point to this thread waker = i; // tell the other thread about the change if (active[(i + 1) % 2]){ // yield the change waker_change = true; // wait until the other thread acknowledges the change while (waker_change){ Thread.yield(); } } } // mark this inactive active[i] = false; // return the result of the business execution return result; }