text
stringlengths
14
410k
label
int32
0
9
public void acquireFocus() { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner(); Component content = getCurrentDockable(); while (focusOwner != null && focusOwner != content) { focusOwner = focusOwner.getParent(); } if (focusOwner == null) { EventQueue.invokeLater(() -> transferFocus()); } }
3
public static void printMap(Map<? extends Object, ? extends Object> m) { for (Object o : m.keySet()) { System.out.println(o.toString() + ": " + m.get(o).toString()); } }
3
public String preCreateTopic() { objectives = objModel.getAll(); boolean check = true; if (objectives.isEmpty()) { addFieldError("topic.objId", "Objective List is empty"); check = false; } if (check) { for (ObjectiveObj objectiveObj : objectives) { mObjective.put(objectiveObj.getObjId(), objectiveObj.getObjName()); } } return SUCCESS; }
3
public void updatePosition() { if (xPos < xDestination) xPos+= 2; else if (xPos > xDestination) xPos-= 2; if (yPos < yDestination) yPos+= 2; else if (yPos > yDestination) yPos-= 2; if (xPos == xDestination && yPos == yDestination) { if (command==Command.GoToSeat) agent.msgAnimationFinishedGoToSeat(); else if (command==Command.LeaveRestaurant) { agent.msgAnimationFinishedLeaveRestaurant(); isHungry = false; gui.setCustomerEnabled(agent); } if (moving == true) { moving = false; agent.msgAnimationDone(); } command=Command.noCommand; } }
9
public Game(Playmode playmode){ this.playmode = playmode; this.upcomingMatches = new PriorityQueue<>(); this.finishedMatches = new PriorityQueue<>(); this.runningMatch = null; this.alstLeftUser = new ArrayList<>(); ArrayList<User> alstUsers = new ArrayList<>(); for (Team team : playmode.getTeams()) { for (User user : team.getUser()) { alstUsers.add(user); } } this.alstNewMatchRequests = new ArrayList<>(); this.scoreList = new ScoreList(alstUsers.toArray(new User[0])); }
2
public void Faz_Tudo(String arq, int max) { Leitor le; Celula[][] mapa_lido; int[][] mundo_int = null; int t = 0; le = new Leitor(); try { mundo_int = le.LerArquivo(arq); } catch(Exception e) { e.printStackTrace(); } l = le.Getl(); c = le.Getc(); mapa_lido = mIntTomCelula(mundo_int, l, c); mapa_atual = mapa_lido; while(t < max) { mapa_prox = new Celula[l][c]; for(int k1 = 0; k1 < l; k1 ++) for(int k2 = 0; k2 < c; k2 ++) mapa_prox[k1][k2] = new Celula(NADA, 0); processaDefunto(); processaNada(); processaPredador(); processaPresa(); processaReciclador(); ContaTudo(); for(int i = 0; i < l; i++) { for(int j = 0; j < c; j++) { System.out.print(mapa_atual[i][j].tipo + " "); } System.out.printf("\n"); } System.out.printf("\n%d\n", t++); try { Thread.sleep(10); } catch(Exception e) { e.printStackTrace(); } mapa_atual = mapa_prox; } }
7
public boolean getBoolean(String key) throws JSONException { Object object = this.get(key); 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("JSONObject[" + quote(key) + "] is not a Boolean."); }
6
public boolean waitForMenuSelection(User user) { int menuOptionSelected = -1; Scanner reader = new Scanner(System.in); if(!TESTRUN){ menuOptionSelected = reader.nextInt(); menuOptionSelected --; } else{ Random random = new Random(); menuOptionSelected = random.nextInt() % NO_OF_MENU_OPTIONS; } switch (menuOptionSelected){ case 0: this.displayBooksInLibrary(user); break; case 1: if(true == this.reserveBookInLibrary(user)){ this.showMessage("Thank You! Enjoy the book"); } else{ this.showMessage("Sorry we don't have that book"); } break; case 2: this.viewMovieList(user); break; case 3: this.viewUsersProfile(user); break; case 4: this.quitProgram(); break; default: this.showMessage("Please Select A Valid Menu Option") ; this.showMenu(); return this.waitForMenuSelection(user); } return true; }
7
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(ClientAPP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ClientAPP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ClientAPP.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ClientAPP.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 ClientAPP().setVisible(true); } }); }
6
public long parseLong( long bitMask, boolean signed ) throws IOException { int sign = 1; int c = nextNonWhitespace(); position(-1); if( c == '+' ) { // Unclear if whitespace is allowed here or not c = read(); } else if( c == '-' ) { sign = -1; // Unclear if whitespace is allowed here or not c = read(); } Long result = null; if( c == '0' ) { int d = read(); if( d == 'x' || d == 'X' ) { result = parseIntString(16, "hexidecimal"); result = signExtend(result, bitMask, signed) * sign; } else if( d == 'b' || d == 'B' ) { result = parseIntString(2, "binary"); result = signExtend(result, bitMask, signed) * sign; } else { pushBack(d); } } else if( c == '\'' ) { result = parseCharLiteral() * sign; } if( result == null ) { // If we got here then we didn't use the original // char we read at the top of the method. pushBack(c); // Else read the number while we have digits result = parseIntString(10, "decimal") * sign; } // Verify that it fits the requirements checkBits(result, bitMask, signed); return result; }
9
public void flatTire() { for (Police p : data.getLevel().getPolices()) { if (p.containsPoint(x + INTERSECTION_RADIUS, y + INTERSECTION_RADIUS)) { float oldVelocityX = p.getVx(); float oldVelocityY = p.getVy(); p.setVx(0); p.setVy(0); pause(10000); p.setVx(oldVelocityX); p.setVy(oldVelocityY); } } for (Zombie z : data.getLevel().getZombies()) { if (z.containsPoint(x + INTERSECTION_RADIUS, y + INTERSECTION_RADIUS)) { float oldVelocityX = z.getVx(); float oldVelocityY = z.getVy(); z.setVx(0); z.setVy(0); pause(10000); z.setVx(oldVelocityX); z.setVy(oldVelocityY); } } for (Bandit b : data.getLevel().getBandits()) { if (b.containsPoint(x + INTERSECTION_RADIUS, y + INTERSECTION_RADIUS)) { float oldVelocityX = b.getVx(); float oldVelocityY = b.getVy(); b.setVx(0); b.setVy(0); pause(10000); b.setVx(oldVelocityX); b.setVy(oldVelocityY); } } }
6
@Override public void decreaseStock(int id, int amount) { int stock = findProductStock(id) - amount; String sql = "UPDATE product SET stock='" + stock + "' WHERE productid='" + id + "';"; Connection con = null; try { con = getConnection(); PreparedStatement statement = con.prepareStatement(sql); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { if (con != null) closeConnection(con); } }
2
public void setSeqID(String seqID) { this.seqID = seqID; }
0
private void AlarmSet(int prevmode) { if (prevmode != MODE_ASET) { inputval = alarmtime; } if (bl && cursor < 5) { cursor++; } else if (br && cursor > 0) { cursor--; } else if (bu) { inputval = IncTime(inputval, cursor); } else if (bd) { if (GetDigit(inputval, cursor) > 0) { inputval = DecDigit(inputval, cursor); } } alarmtime = inputval; }
8
public Tempo diferencaEmTempo(Tempo t) { int dif = diferencaEmSegundos(t); int s = dif % 60; dif = dif / 60; int m = dif % 60; int h = dif / 60; return new Tempo(h, m, s); }
0
public int getValue(int place) { ListElement current = head; if (place <= count) { for (int i = 1; i < place; i++) { current = current.next; } return current.value; } else { return error; } }
2
public Tile getTileLayer(Layer layer, int x, int y) { int[] SelectedLayer = layer.tiles; if(x < 0 || y < 0 || x >= width || y >= height) return VoidTile; if(SelectedLayer[x + y * width] < TileIDS.size()) { return TileIDS.get(SelectedLayer[x + y * width]); } else { return EmptyTile; } }
5
private void hold() { if (holdUsed) { // TODO: Alert the user they can't switch again with perhaps a sound return; } game.fallTimer.stop(); if (holdBlock != null) { Block temp = gameBlock; gameBlock = holdBlock; holdBlock = temp; gameBlock.freeGrid(); holdBlock.insert(holdGrid); if (!insertBlock(gameBlock)) { gameOver(false); return; } } else { holdBlock = gameBlock; holdBlock.insert(holdGrid); if (!getNext()) { gameOver(false); return; } } holdUsed = true; fallTimer.start(); }
4
@Override public void deserialize(Buffer buf) { messageId = buf.readShort(); if (messageId < 0) throw new RuntimeException("Forbidden value on messageId = " + messageId + ", it doesn't respect the following condition : messageId < 0"); int limit = buf.readUShort(); dialogParams = new String[limit]; for (int i = 0; i < limit; i++) { dialogParams[i] = buf.readString(); } limit = buf.readUShort(); visibleReplies = new short[limit]; for (int i = 0; i < limit; i++) { visibleReplies[i] = buf.readShort(); } }
3
public Object clone() { final Expr[] p = new Expr[params.length]; for (int i = 0; i < params.length; i++) { p[i] = (Expr) params[i].clone(); } return copyInto(new CallMethodExpr(kind, (Expr) receiver.clone(), p, method, type)); }
1
private void printBufferState() { for (int i = 0; i < buffer.length; ++i) { System.out.print(buffer[i] + " "); } System.out.println(); }
1
public static double longestCommonSubsequence(ArrayList<Node> pageNodes1,ArrayList<Node> pageNodes2){ int[][] num=new int[pageNodes1.size()+1][pageNodes2.size()+1]; //Iterator it1=pageNodes1.iterator(); //Iterator it2=pageNodes2.iterator(); for(int i=1;i<=pageNodes1.size();i++){ for(int j=1;j<=pageNodes2.size();j++){ if(pageNodes1.get(i-1).toPlainTextString().equals(pageNodes2.get(j-1).toPlainTextString())){ num[i][j]=1+num[i-1][j-1]; } else{ num[i][j]=Math.max(num[i-1][j], num[i][j-1]); } } } System.out.println("length of LCS="+num[pageNodes1.size()][pageNodes2.size()]); int s1position=pageNodes1.size(),s2position=pageNodes2.size(); List<Node> result=new LinkedList<Node>(); while(s1position!=0 && s2position !=0){ if(pageNodes1.get(s1position-1).equals(pageNodes2.get(s2position-1))){ result.add(pageNodes1.get(s1position-1)); s1position--; s2position--; } else{ if(num[s1position][s2position-1]>num[s1position-1][s2position]){ s2position--; } else{ s1position--; } } } Collections.reverse(result); return num[pageNodes1.size()][pageNodes2.size()]; }
7
public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); 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(); } }
9
public String readLine(){ if (lines.size() > 0){ return lines.remove(0); } return null; }
1
public void reset()throws TableException{ String createString; java.sql.Statement stmt; try{ createString = "drop table " + CUSTOMER_TABLE_NAME + ";"; stmt = sqlConn.createStatement(); stmt.executeUpdate(createString); } catch (java.sql.SQLException e) { if (!(e.getMessage().contains("Unknown"))) System.err.println(e); } try{ //Create the CUSTOMER Table createString = "create table " + CUSTOMER_TABLE_NAME + " " + "(CustomerID integer identity (1,1) NOT NULL, " + "FirstName varchar(50) NOT NULL, " + "LastName varchar(50) NOT NULL, " + "BillAddress integer NOT NULL, " + "ShipAddress integer NOT NULL, " + "EmailAddress varchar(50) NOT NULL, " + "PhoneNumber varchar(13) NULL, " + "OrderIDs integer NULL, " + "PRIMARY KEY (CustomerID))"; /* "FOREIGN KEY (BillAddress) REFERENCES FEARSOME_ADDRESS (AddressID), " + "FOREIGN KEY (ShipAddress) REFERENCES FEARSOME_ADDRESS (AddressID), " + "FOREIGN KEY (OrderIDs) REFERENCES FEARSOME_ORDERS (OrderID)) "; * */ stmt = sqlConn.createStatement(); stmt.executeUpdate(createString); } catch (java.sql.SQLException e) { throw new TableException("Unable to create " + CUSTOMER_TABLE_NAME + "\nDetaill: " + e); } }
3
@EventHandler public void serverInit(FMLServerStartedEvent event) { MCUtil.checkVersion(Side.SERVER); }
0
public JobSchedulerBuilder withJobGroup( String jobGroup ) { this.jobGroup = jobGroup; return this; }
0
public static void main(String[] args) { //start loc if (args.length > 0) { try { int startLocation = Integer.parseInt(args[0]); //check for loc if ( startLocation >= 0 && startLocation <= MAX_LOCALES) { currentLocale = startLocation; } } catch(NumberFormatException ex) { // catch(Exception ex) System.out.println("" + args[0] + " is not a location."); if (DEBUGGING) { System.out.println(ex.toString()); } } } init(); //this block only adds the first location, other locations are added through navigate. try{BackPath.push(locations[currentLocale]);} catch(Exception ex){System.out.println("Caught exception: " + ex.getMessage());} try{FrontPath.enqueue(locations[currentLocale]);} catch(Exception ex){System.out.println("Caught exception: " + ex.getMessage());} updateDisplay(); //loop while (stillPlaying) { getCommand(); navigate(); updateDisplay(); if(score<0){ System.out.println("You've spent more than you have. There're no free lunches in this world, pal. But:"); quit(); } } System.out.println("Thanks for playing!"); }
9
public static void main(String[] args) { try { ObjectMapper objectMapper = new ObjectMapper(); Map<String,String> map = new HashMap<String,String>(); map.put("name", "sergii"); String json = objectMapper.writeValueAsString(map); System.out.println(json); } catch (Exception e) { e.printStackTrace(); } }
1
private Meeting getSelectedData(){ selectedData = null; int[] selectedRow = table.getSelectedRows(); int[] selectedColumns = table.getSelectedColumns(); System.out.println(table.getSelectedColumn()); //Fix for exeption når man trykker på kollonne 0 if(table.getSelectedColumn() != 0) { for (int i = 0; i < selectedRow.length; i++) { for (int j = 0; j < selectedColumns.length; j++) { selectedData = (Meeting) table.getValueAt(selectedRow[i], selectedColumns[j]); } } System.out.println("Selected: " + selectedData); if(selectedData != null){ statusPane.setText(selectedData.toString()); }else{ statusPane.setText("No meeting selected"); } return selectedData; } return null; }
4
private String readUTF(int index, final int utfLen, final char[] buf) { int endIndex = index + utfLen; byte[] b = this.b; int strLen = 0; int c; int st = 0; char cc = 0; while (index < endIndex) { c = b[index++]; switch (st) { case 0: c = c & 0xFF; if (c < 0x80) { // 0xxxxxxx buf[strLen++] = (char) c; } else if (c < 0xE0 && c > 0xBF) { // 110x xxxx 10xx xxxx cc = (char) (c & 0x1F); st = 1; } else { // 1110 xxxx 10xx xxxx 10xx xxxx cc = (char) (c & 0x0F); st = 2; } break; case 1: // byte 2 of 2-byte char or byte 3 of 3-byte char buf[strLen++] = (char) ((cc << 6) | (c & 0x3F)); st = 0; break; case 2: // byte 2 of 3-byte char cc = (char) ((cc << 6) | (c & 0x3F)); st = 1; break; } } return new String(buf, 0, strLen); }
7
void addAlmostSet( int offset, BitSet bs, BitSet missing, String frag ) { this.versions.or(bs); if ( this.offset == -1 ) this.offset = offset; this.state = SectionState.almost; for (int i = bs.nextSetBit(1); i>= 0; i = bs.nextSetBit(i+1)) { if ( lists.containsKey((short)i) ) { FragList fl = lists.get( (short)i ); fl.add( FragKind.almost, frag, bs ); } else { FragList fl = new FragList(); fl.add( FragKind.almost, frag, bs ); lists.put( (short)i, fl ); } } // fill in the gaps with empty fraglists for (int i = missing.nextSetBit(1); i>= 0; i = missing.nextSetBit(i+1)) { if ( !lists.containsKey((short)i) ) { FragList fl = new FragList(); fl.add( FragKind.almost, "", missing ); lists.put( (short)i, fl ); } } }
5
private void push(JSONObject jo) throws JSONException { if (this.top >= maxdepth) { throw new JSONException("Nesting too deep."); } this.stack[this.top] = jo; this.mode = jo == null ? 'a' : 'k'; this.top += 1; }
2
public void startTargets(int square, int steps) { visitedMtx = new HashMap<Integer, Boolean>(); for(int i = 0; i < NUMBEROFSPACES; i++) { visitedMtx.put(i, false); } visitedMtx.put(square, true); calcTargets(square, steps); }
1
public synchronized double[][] getICVectors( ) { if ( icVectors == null ) { // calculate independent component vectors and readd the mean icVectors = Matrix.mult(separatingMatrix, inVectors); } return(icVectors); }
1
public boolean addUser(ClientDB client) { // TODO Auto-generated method stub if (checkSpace()) { if (checkDuplicate(client.getUserID())) { for (int i = 0; i < clientObj.length; i++) { if(clientObj[i]==null){ clientObj[i]=client; return true; } } } else{ return false; } } else{ return false; } return false; }
4
private Temperature(int conversionFactor, String name) { super(conversionFactor, name); }
0
public static void initializeFileInputStream(InputFileStream self) { if (!(self.filename != null)) { return; } { String filename = Stella.translateLogicalPathname(self.filename); { Keyword testValue000 = self.ifNotExistsAction; if ((testValue000 == Stella.KWD_ABORT) || (testValue000 == Stella.KWD_PROBE)) { if (!(Stella.probeFileP(filename))) { return; } } else if (testValue000 == Stella.KWD_ERROR) { Stella.ensureFileExists(filename, "initialize-file-input-stream"); } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("initialize-file-input-stream: illegal :if-not-exists action: `" + self.ifNotExistsAction + "'"); throw ((BadArgumentException)(BadArgumentException.newBadArgumentException(stream000.theStringReader()).fillInStackTrace())); } } } FileInputStream inputStream; try { inputStream = new FileInputStream(filename); self.nativeStream = new PushbackBufferedReader(inputStream, "utf8"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (self.nativeStream == null) { { OutputStringStream stream001 = OutputStringStream.newOutputStringStream(); stream001.nativeStream.print("initialize-file-input-stream: Could not open `" + self + "'"); throw ((InputOutputException)(InputOutputException.newInputOutputException(stream001.theStringReader()).fillInStackTrace())); } } self.state = Stella.KWD_OPEN; Stella.$OPEN_FILE_STREAMS$.push(self); } }
8
@Override public double evaluate(int[][] board) { int x = -1, y = -1; int max = -1; int n = board.length; int m = board[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (board[i][j] > max) { max = board[i][j]; x = i; y = j; } } } /*return Math.min( Math.min(x, n - 1 - x), Math.min(y, m - 1 - y) );/**/ return Math.min(x, n - 1 - x); //return distToNearestCorner(x, y, n, m); }
3
public static boolean parseBoolean(CharSequence chars) { return (chars.length() == 4) && (chars.charAt(0) == 't' || chars.charAt(0) == 'T') && (chars.charAt(1) == 'r' || chars.charAt(1) == 'R') && (chars.charAt(2) == 'u' || chars.charAt(2) == 'U') && (chars.charAt(3) == 'e' || chars.charAt(3) == 'E'); }
8
private Input sIB_ProcessInput() { double valSum = 0.0; for (int i = 0; i < m_numInstances; i++) { valSum = 0.0; for (int v = 0; v < m_data.instance(i).numValues(); v++) { valSum += m_data.instance(i).valueSparse(v); } if (valSum <= 0) { if(m_verbose){ System.out.format("Instance %s sum of value = %s <= 0, removed.\n", i, valSum); } m_data.delete(i); m_numInstances--; } } // get the term-document matrix Input input = new Input(); input.Py_x = getTransposedNormedMatrix(m_data); if (m_uniformPrior) { input.Pyx = input.Py_x.copy(); normalizePrior(m_data); } else { input.Pyx = getTransposedMatrix(m_data); } input.sumVals = getTotalSum(m_data); input.Pyx.timesEquals((double) 1 / input.sumVals); // prior probability of documents, ie. sum the columns from the Pyx matrix input.Px = new double[m_numInstances]; for (int i = 0; i < m_numInstances; i++) { for (int j = 0; j < m_numAttributes; j++) { input.Px[i] += input.Pyx.get(j, i); } } // prior probability of terms, ie. sum the rows from the Pyx matrix input.Py = new double[m_numAttributes]; for (int i = 0; i < input.Pyx.getRowDimension(); i++) { for (int j = 0; j < input.Pyx.getColumnDimension(); j++) { input.Py[i] += input.Pyx.get(i, j); } } MI(input.Pyx, input); return input; }
9
protected void syncSpi() throws BackingStoreException { if (isRemoved()) return; final File file = FilePreferencesFactory.getPreferencesFile(); if (!file.exists()) return; synchronized (file) { Properties p = new Properties(); try { p.load(new FileInputStream(file)); StringBuilder sb = new StringBuilder(); getPath(sb); String path = sb.toString(); final Enumeration<?> pnen = p.propertyNames(); while (pnen.hasMoreElements()) { String propKey = (String) pnen.nextElement(); if (propKey.startsWith(path)) { String subKey = propKey.substring(path.length()); // Only load immediate descendants if (subKey.indexOf('.') == -1) { root.put(subKey, p.getProperty(propKey)); } } } } catch (IOException e) { throw new BackingStoreException(e); } } }
7
private String getDescription() { String desc = "@MongoFind(value=[" + this.getParsedShell().getOriginalExpression() + "],batchSize=[" + batchSize + "]),@MongoMapper(" + beanMapper.getClass() + ")"; if (skipIndex != -1) { desc = ",@MongoSkip(" + skipIndex + ")"; } if (limitIndex != -1) { desc = ",@MongoLimit(" + limitIndex + ")"; } if (sortObject != null) { desc = ",@MongoSort(" + sortObject.toString() + ")"; } if (this.isUnique) { desc = desc + ",@Unique()"; } if (!StringUtils.isEmpty(globalCollectionName)) { desc = ",@MongoCollection(" + globalCollectionName + ")"; } return desc; }
5
public Long open() { Shell parent = getParent(); shell = new Shell(parent, SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL); shell.setText("Modeling time input"); shell.setLayout(new GridLayout(2, true)); Label label = new Label(shell, SWT.NULL); label.setText("Please enter new modeling time:"); final Text text = new Text(shell, SWT.SINGLE | SWT.BORDER); text.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.keyCode == 13){ try { value = Long.parseLong(text.getText()); close(); } catch (Exception ex) { } } } }); final Button buttonOK = new Button(shell, SWT.PUSH); buttonOK.setGrayed(true); buttonOK.setText("Ok"); buttonOK.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Button buttonCancel = new Button(shell, SWT.PUSH); buttonCancel.setText("Cancel"); text.addListener(SWT.Modify, new Listener() { public void handleEvent(Event event) { try { value = Long.parseLong(text.getText()); buttonOK.setEnabled(true); } catch (Exception e) { buttonOK.setEnabled(false); } } }); buttonOK.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { shell.dispose(); } }); buttonCancel.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { value = null; shell.dispose(); } }); shell.addListener(SWT.Traverse, new Listener() { public void handleEvent(Event event) { if(event.detail == SWT.TRAVERSE_ESCAPE) event.doit = false; } }); text.setText(""); shell.pack(); shell.open(); Display display = parent.getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return value; }
6
private String readChars ( int ln ) { byte[] b = new byte[ln]; try { fidx.read(b); } catch (IOException e) { e.printStackTrace(); } String s = ""; for(int i=0;i<ln;i++) s+=(char)b[i]; return s; }
2
public Map<Integer, Integer> getGeneSpans(String text) { Map<Integer, Integer> begin2end = new HashMap<Integer, Integer>(); Annotation document = new Annotation(text); pipeline.annotate(document); List<CoreMap> sentences = document.get(SentencesAnnotation.class); for (CoreMap sentence : sentences) { List<CoreLabel> candidate = new ArrayList<CoreLabel>(); for (CoreLabel token : sentence.get(TokensAnnotation.class)) { String pos = token.get(PartOfSpeechAnnotation.class); if (pos.startsWith("NN")) { candidate.add(token); } else if (candidate.size() > 0) { int begin = candidate.get(0).beginPosition(); int end = candidate.get(candidate.size() - 1).endPosition(); begin2end.put(begin, end); candidate.clear(); } } if (candidate.size() > 0) { int begin = candidate.get(0).beginPosition(); int end = candidate.get(candidate.size() - 1).endPosition(); begin2end.put(begin, end); candidate.clear(); } } return begin2end; }
5
public BodypartSummaryPanel(BodyPart bodypart) { super(); this.bodypart = bodypart; }
0
private Authentication parseAuthentication(XmlPullParser parser) throws Exception { Authentication authentication = new Authentication(); boolean done = false; while (!done) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { if (parser.getName().equals("username")) { authentication.setUsername(parser.nextText()); } else if (parser.getName().equals("password")) { authentication.setPassword(parser.nextText()); } else if (parser.getName().equals("digest")) { authentication.setDigest(parser.nextText()); } else if (parser.getName().equals("resource")) { authentication.setResource(parser.nextText()); } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getName().equals("query")) { done = true; } } } return authentication; }
8
static Tex makesh(Resource res) { BufferedImage img = res.layer(Resource.imgc).img; Coord sz = Utils.imgsz(img); BufferedImage sh = new BufferedImage(sz.x, sz.y, BufferedImage.TYPE_INT_ARGB); for (int y = 0; y < sz.y; y++) { for (int x = 0; x < sz.x; x++) { long c = img.getRGB(x, y) & 0x00000000ffffffffL; int a = (int) ((c & 0xff000000) >> 24); sh.setRGB(x, y, (a / 2) << 24); } } return (new TexI(sh)); }
2
public List<Entity> getEntities() { if (sim != null) return Collections.synchronizedList(Collections.unmodifiableList(sim.getWorld().getEntities())); else return new ArrayList<Entity>(); }
1
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Position other = (Position) obj; if (orientation != other.orientation) return false; if (point == null) { if (other.point != null) return false; } else if (!point.equals(other.point)) return false; return true; }
7
public ReferenceList getReferenceList() { return referenceList; }
0
public void close() throws IOException { reader.close(); }
0
protected void checkErrors(String line, String caller) throws IOException, LoginException { // System.out.writeln(line); // empty response from server if (line.isEmpty()) // UnknownError...?? changed to IOException throw new IOException("Received empty response from server!"); // successful if (line.contains("result=\"Success\"")) return; // rate limit (automatic retry), though might be a long one (e.g. email) if (line.contains("error code=\"ratelimited\"")) { log(Level.WARNING, "Server-side throttle hit.", caller); throw new HttpRetryException("Action throttled.", 503); } // blocked! if (line.contains("error code=\"blocked") || line.contains("error code=\"autoblocked\"")) { log(Level.SEVERE, "Cannot " + caller + " - user is blocked!.", caller); throw new AccountLockedException("Current user is blocked!"); } // cascade protected if (line.contains("error code=\"cascadeprotected\"")) { log(Level.WARNING, "Cannot " + caller + " - page is subject to cascading protection.", caller); throw new CredentialException("Page is cascade protected"); } // database lock (automatic retry) if (line.contains("error code=\"readonly\"")) { log(Level.WARNING, "Database locked!", caller); throw new HttpRetryException("Database locked!", 503); } // action error (no SMWAskAPI extension installed?) if (line.contains("error code=\"unknown_action\"")) { log(Level.WARNING, "Server does not understand action. Needed extension may be missing.", caller); throw new IOException("API does not understand action. Needed extension may be missing."); } // unknown error if (line.contains("error code=\"unknownerror\"")) // eclarke: this is unbelievable. don't throw Errors unless there's a problem with the virtual machine. // fixed to be reasonable // throw new UnknownError("Unknown MediaWiki API error, response was " + line); throw new IOException("Unknown MediaWiki API error, response was "+ line); // generic (automatic retry) throw new IOException("MediaWiki error, response was " + line); }
9
@Override public boolean onCommand(CommandSender sender, Command command, String sabel, String[] args) { if (Utils.commandCheck(sender, command, "anima")) { Player player = (Player) sender; if (args.length == 0) { int animaBarSize = 130; int maxanima = MPlayer.getLevel(player) * 100; int maxsubanima = MPlayer.getSubLevel(player) * 100; int anima = MPlayer.getAnima(player); int subanima = MPlayer.getSubAnima(player); if (anima > maxanima) { anima = maxanima; } if (subanima > maxsubanima) { subanima = maxsubanima; } int indicator_anima = 0; int indicator_subanima = 0; try { indicator_anima = (anima * animaBarSize) / maxanima; indicator_subanima = (subanima * animaBarSize) / maxsubanima; } catch (ArithmeticException e) { // Do nothing because anima/subanima is already 0 } int empty_anima = animaBarSize - indicator_anima; int empty_subanima = animaBarSize - indicator_subanima; String fullanima = ""; for (int i = 0; i < indicator_anima; i++) { fullanima = fullanima + "|"; } String fullsubanima = ""; for (int i = 0; i < indicator_subanima; i++) { fullsubanima = fullsubanima + "|"; } String emptyanima = ""; for (int i = 0; i < empty_anima; i++) { emptyanima = emptyanima + "|"; } String emptysubanima = ""; for (int i = 0; i < empty_subanima; i++) { emptysubanima = emptysubanima + "|"; } player.sendMessage(Utils.center("--- §6[§fAnima - " + anima + " §6|§f SubAnima - " + subanima + "§6]§f ---")); player.sendMessage(Utils.center(" §6{§a" + fullanima + ChatColor.GRAY + emptyanima + "§6} §flvl " + MPlayer.getLevel(player))); player.sendMessage(Utils.center(" §6{§a" + fullsubanima + ChatColor.GRAY + emptysubanima + "§6} §flvl " + MPlayer.getSubLevel(player))); } return true; } return false; }
9
@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 Agenda)) { return false; } Agenda other = (Agenda) object; if ((this.agendaPK == null && other.agendaPK != null) || (this.agendaPK != null && !this.agendaPK.equals(other.agendaPK))) { return false; } return true; }
5
private static void mergeMessageSetExtensionFromBytes( ByteString rawBytes, ExtensionRegistry.ExtensionInfo extension, ExtensionRegistryLite extensionRegistry, Message.Builder builder, FieldSet<FieldDescriptor> extensions) throws IOException { FieldDescriptor field = extension.descriptor; boolean hasOriginalValue = hasOriginalMessage(builder, extensions, field); if (hasOriginalValue || ExtensionRegistryLite.isEagerlyParseMessageSets()) { // If the field already exists, we just parse the field. Message value = null; if (hasOriginalValue) { Message originalMessage = getOriginalMessage(builder, extensions, field); Message.Builder subBuilder= originalMessage.toBuilder(); subBuilder.mergeFrom(rawBytes, extensionRegistry); value = subBuilder.buildPartial(); } else { value = extension.defaultInstance.getParserForType() .parsePartialFrom(rawBytes, extensionRegistry); } setField(builder, extensions, field, value); } else { // Use LazyField to load MessageSet lazily. LazyField lazyField = new LazyField( extension.defaultInstance, extensionRegistry, rawBytes); if (builder != null) { // TODO(xiangl): it looks like this method can only be invoked by // ExtendableBuilder, but I'm not sure. So I double check the type of // builder here. It may be useless and need more investigation. if (builder instanceof ExtendableBuilder) { builder.setField(field, lazyField); } else { builder.setField(field, lazyField.getValue()); } } else { extensions.setField(field, lazyField); } } }
5
@Override public void processCas(CAS aCas) throws ResourceProcessException { // TODO Auto-generated method stub JCas jcas; try { jcas = aCas.getJCas(); } catch (CASException e) { throw new ResourceProcessException(e); } FSIterator<org.apache.uima.jcas.tcas.Annotation> it = jcas.getAnnotationIndex(geneTag.type) .iterator(); System.out.println("Consuming CAS"); String geneId = null; String geneContent = null; String myoutput = null; int start = -1; int end = -1; while (it.hasNext()) { geneTag geneAnnotation = (geneTag) it.next(); geneId = geneAnnotation.getId(); geneContent = geneAnnotation.getContent(); start = geneAnnotation.getBegin(); end = geneAnnotation.getEnd(); myoutput = geneId + "|" + start + " " + end + "|" + geneContent; // Get sentence from my // output file if (hash.containsKey(myoutput)) { // Detect whether my output CAS matches the sample correct++; } else { wrong++; } // Write out file try { writeIntoFile(geneId, geneContent, start, end); } catch (IOException e) { throw new ResourceProcessException(e); } catch (SAXException e) { throw new ResourceProcessException(e); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Calculate precision, recall and F by provided equations double precision = 1.0 * correct / (correct + wrong); double recall = 1.0 * correct / numbers; System.out.println("Precision: " + precision + "\n" + "Recall: " + recall + "\n" + "F = " + 2.0 * precision * recall / (precision + recall)); }
6
private int playerPieceTypeRemaining(HantoPlayerColor player, HantoPieceType pieceType) { if (player == HantoPlayerColor.BLUE) { return bluePiecesLeft.get(pieceType); } else { return redPiecesLeft.get(pieceType); } }
1
public static void main(String[] args) { int N = 12; for (int i = 1; i <= N; i++) System.out.println(i + ": " + fib(i)); }
1
public double executaTorno() { double menorTempo = getTempoUniversal()+1; ordenaPeloTempoDeSaidaT(maquinaTorno); for(int i=maquinaTorno.size()-1 ; i>=0 && maquinaTorno.size()>0 && verificaMaquinaTorno(maquinaTorno) ; i--) //percorre a lista de maquina e verifica os status dos rolamentos { if(maquinaTorno.get(i).getStatus()==1)//verifica se ela esta ocupada { if(maquinaTorno.get(i).getInstante() -maquinaTorno.get(i).getRolamento().getInstante()>0)//adiciona o tmepo parado { maquinaTorno.get(i).getRolamento().addTempoParado(maquinaTorno.get(i).getInstante() -maquinaTorno.get(i).getRolamento().getInstante()); } else { maquinaTorno.get(i).getRolamento().addTempoParado(0); maquinaTorno.get(i).setInstante(maquinaTorno.get(i).getRolamento().getInstante()); } /*se seu tempo parado+ tempo que ira ficar na maquina + instante de chegada for menor que o tempo atual ele executa */ /*vale lembrar que o instante para mim é o instante que o rolamento solicita a entrada em uma maquina(ou que vai pra fila ou que sai da maquina)*/ if( (maquinaTorno.get(i).getRolamento().getInstante()+maquinaTorno.get(i).getRolamento().getTempoTorno() + maquinaTorno.get(i).getRolamento().getTempoParado() <= getTempoUniversal())) { maquinaTorno.get(i).getRolamento().setInstante(maquinaTorno.get(i).getRolamento().getTempoParado()+maquinaTorno.get(i).getRolamento().getInstante() +maquinaTorno.get(i).getRolamento().getTempoTorno()); maquinaTorno.get(i).setInstante(maquinaTorno.get(i).getRolamento().getInstante()); System.out.println(maquinaTorno.get(i).getRolamento().getTipo() + " Pronto na maquina Torno"); if(listaTorno.size()==0) { maquinaTorno.get(i).setInstante(0); } addLista(maquinaTorno.get(i).getRolamento(), maquinaTorno.get(i).getRolamento().getProxMaquina()); /*retorna o menor tempo, no caso o instante que o rolamento sai da maquina*/ if(menorTempo > maquinaTorno.get(i).getRolamento().getInstante()) { menorTempo=maquinaTorno.get(i).getRolamento().getInstante(); } maquinaTorno.get(i).removeRolamento(); disponibilidadeTorno++; break; } } } return menorTempo; }
8
public void update() { growVillages(); chunksLock.readLock().lock(); try { for (Chunk c : chunks) { if (c.update() && !toDraw.contains(c)) { toDraw.add(c); } } } finally { chunksLock.readLock().unlock(); } ArrayList<Village> villages = getVillages(); for (Village v : villages) { v.update(); } }
4
private boolean findEntry() { Cursor waitCursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT); shell.setCursor(waitCursor); boolean matchCase = searchDialog.getMatchCase(); boolean matchWord = searchDialog.getMatchWord(); String searchString = searchDialog.getSearchString(); int column = searchDialog.getSelectedSearchArea(); searchString = matchCase ? searchString : searchString.toLowerCase(); boolean found = false; if (searchDialog.getSearchDown()) { for(int i = table.getSelectionIndex() + 1; i < table.getItemCount(); i++) { if (found = findMatch(searchString, table.getItem(i), column, matchWord, matchCase)){ table.setSelection(i); break; } } } else { for(int i = table.getSelectionIndex() - 1; i > -1; i--) { if (found = findMatch(searchString, table.getItem(i), column, matchWord, matchCase)){ table.setSelection(i); break; } } } shell.setCursor(null); return found; }
6
public boolean isAutarkic(IGroup g) { if (g.zgetGroupType() == GroupType.PACKAGE) { return false; } if (g.zgetGroupType() == GroupType.INNER_ACTIVITY) { return true; } if (g.zgetGroupType() == GroupType.CONCURRENT_ACTIVITY) { return true; } if (g.zgetGroupType() == GroupType.CONCURRENT_STATE) { return true; } if (getChildrenGroups(g).size() > 0) { return false; } for (Link link : getLinks()) { if (EntityUtils.isPureInnerLink3(g, link) == false) { return false; } } for (ILeaf leaf : g.getLeafsDirect()) { if (leaf.getEntityPosition() != EntityPosition.NORMAL) { return false; } } return true; }
9
@EventHandler(priority=EventPriority.LOW, ignoreCancelled = true) final void onStructureGrow(StructureGrowEvent event){ if (panic){ event.setCancelled(true); return; } if (!monitorStructureGrowth) return; final List<Location> affected = new LinkedList<Location>(); for ( BlockState state : event.getBlocks()){ affected.add(state.getLocation()); } Location loc = event.getLocation(); if ( loc == null){ // compatibility check (i do not know what else might be grown later on and how). if ( affected.isEmpty()) return; else loc = affected.remove(0); if ( affected.isEmpty()) return; } if (!sameOwners(loc, affected)) event.setCancelled(true); }
7
public String toString() { // only ZeroR model? if (m_ZeroR != null) { StringBuffer buf = new StringBuffer(); buf.append(this.getClass().getName().replaceAll(".*\\.", "") + "\n"); buf.append(this.getClass().getName().replaceAll(".*\\.", "").replaceAll(".", "=") + "\n\n"); buf.append("Warning: No model could be built, hence ZeroR model is used:\n\n"); buf.append(m_ZeroR.toString()); return buf.toString(); } StringBuffer model = new StringBuffer(m_neuralNodes.length * 100); //just a rough size guess NeuralNode con; double[] weights; NeuralConnection[] inputs; for (int noa = 0; noa < m_neuralNodes.length; noa++) { con = (NeuralNode) m_neuralNodes[noa]; //this would need a change //for items other than nodes!!! weights = con.getWeights(); inputs = con.getInputs(); if (con.getMethod() instanceof SigmoidUnit) { model.append("Sigmoid "); } else if (con.getMethod() instanceof LinearUnit) { model.append("Linear "); } model.append("Node " + con.getId() + "\n Inputs Weights\n"); model.append(" Threshold " + weights[0] + "\n"); for (int nob = 1; nob < con.getNumInputs() + 1; nob++) { if ((inputs[nob - 1].getType() & NeuralConnection.PURE_INPUT) == NeuralConnection.PURE_INPUT) { model.append(" Attrib " + m_instances.attribute(((NeuralEnd)inputs[nob-1]). getLink()).name() + " " + weights[nob] + "\n"); } else { model.append(" Node " + inputs[nob-1].getId() + " " + weights[nob] + "\n"); } } } //now put in the ends for (int noa = 0; noa < m_outputs.length; noa++) { inputs = m_outputs[noa].getInputs(); model.append("Class " + m_instances.classAttribute(). value(m_outputs[noa].getLink()) + "\n Input\n"); for (int nob = 0; nob < m_outputs[noa].getNumInputs(); nob++) { if ((inputs[nob].getType() & NeuralConnection.PURE_INPUT) == NeuralConnection.PURE_INPUT) { model.append(" Attrib " + m_instances.attribute(((NeuralEnd)inputs[nob]). getLink()).name() + "\n"); } else { model.append(" Node " + inputs[nob].getId() + "\n"); } } } return model.toString(); }
9
@Override public IAttemptClientConnect getAttemptClientConnect() { return attemptClientConnect; }
0
@Override public Date deserialize (JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { if (!(json instanceof JsonPrimitive)) { throw new JsonParseException("Date was not string: " + json); } if (type != Date.class) { throw new IllegalArgumentException(getClass() + " cannot deserialize to " + type); } String value = json.getAsString(); synchronized (enUsFormat) { try { return enUsFormat.parse(value); } catch (ParseException e) { try { return iso8601Format.parse(value); } catch (ParseException e2) { try { String tmp = value.replace("Z", "+00:00"); return iso8601Format.parse(tmp.substring(0, 22) + tmp.substring(23)); } catch (ParseException e3) { throw new JsonSyntaxException("Invalid date: " + value, e3); } } } } }
5
public static String base64Encode(byte[] src) { int unpadded = (src.length * 8 + 5) / 6; int padding = 4 - (unpadded % 4); int d = 0; int e = 3; long buffer = 0; if (padding == 4) padding = 0; char[] encoded = new char[unpadded + padding]; while (d < src.length) { // Push into buffer in 8-bit chunks for (int i = 0; i < 3; i++) { buffer <<= 8; buffer |= ((d < src.length ? src[d++] & 0x00ff : 0)); } // Pop from buffer in 6-bit chunks for (int i = 0; i < 4; i++) { encoded[e--] = e64[(int) (buffer & 0x3f)]; buffer >>>= 6; } e += 8; } while (padding > 0) { encoded[unpadded + --padding] = '='; } return new String(encoded); }
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."); }
6
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = ""; response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); String dbDriver = "org.postgresql.Driver"; try { URI dbUri = new URI(System.getenv("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = dbUri.getUserInfo().split(":")[1]; String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath(); Class.forName(dbDriver); con = DriverManager.getConnection(dbUrl, username, password); Statement st = con.createStatement(); String väljund = "select nimi,tüüp,kohad,algus,asula,aadress,looja from sundmused where tüüp = 'Arvutimäng'"; ResultSet rs = st.executeQuery(väljund); ResultSetMetaData rsmd = rs.getMetaData(); //Stringid tulpade väärtuste jaoks, et muus järjekorras datasse pressida koos htmliga String nimi = ""; String tuup = ""; String kohad = ""; String algus = ""; String asula = ""; String aadress = ""; String looja = ""; while (rs.next()) { /* for (int i = 1; i <= columnsNumber; i++) { data += rs.getString(i) + " "; } data += "<br>";*/ nimi = rs.getString(1); tuup = rs.getString(2); kohad = rs.getString(3); algus = rs.getString(4); asula = rs.getString(5); aadress = rs.getString(6); looja = rs.getString(7); /* data += nimi + " "+ tuup + " "+ "<br>"+ kohad + " "+ algus + " "+ asula + " "+ aadress + " "+ looja + "<br>";*/ data += "<p>"; if (tuup.equals("Lauamäng")){ data += "<img class=\"event_type\" src=\"icons/cards.png\" alt=\"type_logo\"/>"; } else { data += "<img class=\"event_type\" src=\"icons/pc.png\" alt=\"type_logo\"/>"; } data += tuup + ": " + nimi + " - " + looja + "<br>"; data += "Aadress: "+ aadress +", "+ asula + "; algus: " + algus +"<br>"; data += "Lisainfo: " +"<br>"; data += "Kohtade arv: "+ kohad +"<br>"; data += "</p>"; nimi = tuup = kohad = algus = asula = aadress = looja = ""; } writer.write(data); con.close(); } catch (SQLException e) { writer.println(e.toString()); } catch (ClassNotFoundException e) { writer.println("ClassNotFoundException"); } catch (URISyntaxException e) { e.printStackTrace(); } }
5
private boolean getModinfoStringFromJAR(File jarfile) { StringBuilder builder = new StringBuilder(); String inputFile = "jar:file:/" + jarfile.getAbsolutePath() + "!/mcmod.info"; InputStream in = null; try { URL inputURL = new URL(inputFile); JarURLConnection conn = (JarURLConnection) inputURL.openConnection(); in = conn.getInputStream(); int ch; while ((ch = in.read()) != -1) { builder.append((char) ch); } } catch (Exception e) { } finally { if(in!=null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } String jsontext = builder.toString(); if (!jsontext.equals("")) { return readModinfo(jsontext); } return false; }
5
public boolean[][] createWallMap(TiledMap map) { if (map == null) return null; int layer = map.getLayerIndex("Tile Layer 3"); boolean[][] wallMap = new boolean[32][24]; for (int j=0; j<wallMap[0].length; ++j) for (int i=0; i<wallMap.length; ++i) if (map.getTileId(i, j, layer) != 0) wallMap[i][j] = true; return wallMap; }
4
public synchronized boolean setMaster(final CloudNode cloudNode) { Objects.requireNonNull(cloudNode, "The given cloud node must not be null."); final Lock lock = Holder.INSTANCE.getInstance().getLock("my-distributed-lock"); lock.lock(); try { final NodeRecord masterRecord = HazelcastHelper.<NodeRecord>getAtomicReference(MASTER_NODE).get(); if (masterRecord != null) { final long count = Holder.INSTANCE.getInstance().getCluster().getMembers() .stream() .filter(member -> StringUtils.equals(masterRecord.getMemberId(), member.getUuid())) .count(); if (count != 0) { logger.warn("The master node has already existed: {}", masterRecord); return false; } this.unregisterNode(masterRecord.getNodeName()); } final NodeRecord newMasterRecord = HazelcastHelper.<String, NodeRecord>getMap(ACTIVE_NODES).get(cloudNode.getName()); HazelcastHelper.getAtomicReference(MASTER_NODE).set(newMasterRecord); logger.info("This node has already become the new master node: {}", newMasterRecord); if (WORKING_MODE) { final Thread thread = new Thread(this.createProducer(cloudNode)); thread.start(); } } finally { lock.unlock(); } return true; }
3
public void movement(VectorShape v) { v.setX(v.getX() + v.getVelX()); v.setY(v.getY() + v.getVelY()); if (v.getX() > this.width) { v.setX(0); } if (v.getX() < 0) { v.setX(width); } if (v.getY() > this.height) { v.setY(0); } if (v.getY() < 0) { v.setY(this.height); } if (v.getClass() == new Laser(0, 0, 0).getClass()) { v.setCounter(v.getCounter() + 1); if (v.getCounter() > 20) { v.setAlive(false); } } }
6
private void printGridletList(GridletList list, String name, boolean detail, double gridletLatencyTime[]) { int size = list.size(); Gridlet gridlet = null; String indent = " "; System.out.println(); System.out.println("============= OUTPUT for " + name + " =========="); System.out.println("Gridlet ID" + indent + "STATUS" + indent + "Resource ID" + indent + "Cost" + indent + "CPU Time"+ indent + "Latency"); // a loop to print the overall result int i = 0; for (i = 0; i < size; i++) { gridlet = (Gridlet) list.get(i); System.out.print(indent + gridlet.getGridletID() + indent + indent); System.out.print(gridlet.getGridletStatusString()); System.out.println(indent + indent + gridlet.getResourceID() + indent + indent + gridlet.getProcessingCost() + indent + indent + gridlet.getActualCPUTime()+ indent + indent + gridletLatencyTime[gridlet.getGridletID()]); writeFin(name, gridlet.getGridletID(), GridSim.getEntityName(gridlet.getResourceID()), gridlet.getProcessingCost(), gridlet.getActualCPUTime(), GridSim.clock()); } if (detail == true) { // a loop to print each Gridlet's history for (i = 0; i < size; i++) { gridlet = (Gridlet) list.get(i); System.out.println(gridlet.getGridletHistory()); System.out.print("Gridlet #" + gridlet.getGridletID()); System.out.println(", length = " + gridlet.getGridletLength() + ", finished so far = " + gridlet.getGridletFinishedSoFar()); System.out.println("======================================\n"); } } System.out.println("================================================="); }
3
static void Algoritmo(MatingPool Pool, int Repeticiones) { while(Repeticiones > 0) { ArrayList<Lista> NuevaPoblacion = new ArrayList<>(); NuevosCandidatos.clear(); System.out.println("\nNUEVOS CANDIDATOS BASADOS EN EL PORCENTAJE DE FITNESS Y UN RANDOM:\n"); for(int i = 0; i < Pool.getListas().size(); i++) { NuevosCandidatos.add(Pool.getCandidato(RandomDecimal(0, 1))); System.out.print("Nuevo candidato: "); //Si es nulo significa que no se encontro un intervalo para el resultado del random en la ruleta y esto es solo //posible si todos los porcentajes son 0%, es decir ningun candidato es valido para tomarse en cuenta. if(NuevosCandidatos.get(i) != null) { System.out.println(NuevosCandidatos.get(i).getList().toString()); System.out.println(); System.out.println(); } else { System.out.println(); System.out.println("ERROR: TODOS LOS PORCENTAJES SON 0%"); TieneSolucion = false; break; } } if(!TieneSolucion) { break; } System.out.println("\nCRUCES DE LOS CANDIDATOS\n"); for(int i = 0; i < NuevosCandidatos.size(); i++) { Lista Candidato = NuevosCandidatos.get(i); System.out.println("Candidato:"); System.out.println(Candidato.getList().toString()); System.out.println(); Candidato.CruceOrden(RandomEntero(0,(Candidato.getList().size()/2)), RandomEntero((Candidato.getList().size()/2),Candidato.getList().size()-1)); NuevaPoblacion.add(Candidato); System.out.println("Permutacion:"); System.out.println(Candidato.getList().toString()); System.out.println(); } System.out.println("\nNUEVA POBLACION GENERADA DE LOS CRUCES\n"); for(int i = 0; i < NuevaPoblacion.size(); i++) { System.out.println(NuevaPoblacion.get(i).getList().toString()); System.out.println(); } System.out.println("\nNUEVA MATING POOL\n"); Pool.setListas(NuevaPoblacion); Pool.Calcular(); Pool.Show(); Repeticiones--; } }
6
public static <TElement, TCollection extends Collection<TElement>> TCollection addAllFlat(final TCollection target, final Iterable<? extends Iterable<? extends TElement>> sources) { if (target != null && sources != null) { for (Iterable<? extends TElement> source : sources) { for (TElement element : source) { target.add(element); } } } return target; }
7
@Override public double getExpectation() throws ExpectationException { if (nu > 2) { return (double) 1 / (nu - 2); } else { throw new ExpectationException("InverseChiSquared expectation nu > 2."); } }
1
public Network() throws Exception { port=6740; while(!portChosen){ if(checkPort(port))portChosen=true; else if(port<6750){port+=1;} } localAddress = (Inet4Address)Inet4Address.getLocalHost(); sender = new Sender(); receiver = new Receiver(port); receiver.addObserver(this); }
3
private boolean validate_otps(List<String> otps, NameCallback nameCb) throws LoginException { boolean validated = false; for (String otp : otps) { log.trace("Checking OTP {}", otp); VerificationResponse ykr; try { ykr = this.yc.verify(otp); } catch (YubicoVerificationException e) { log.warn("Errors during validation: ", e); throw new LoginException("Errors during validation: " + e.getMessage()); } catch (YubicoValidationFailure e) { log.warn("Something went very wrong during authentication: ", e); throw new LoginException("Something went very wrong during authentication: " + e.getMessage()); } if (ykr != null) { log.trace("OTP {} verify result : {}", otp, ykr.getStatus().toString()); if (ykr.getStatus() == ResponseStatus.OK) { String publicId = YubicoClient.getPublicId(otp); log.info("OTP verified successfully (YubiKey id {})", publicId); if (is_right_user(nameCb.getName(), publicId)) { this.principals.add(new YubikeyPrincipal(publicId, this.idRealm)); /* Don't just return here, we want to "consume" all OTPs if * more than one is provided. */ validated = true; } } else { log.debug("OTP validation returned {}", ykr.getStatus().toString()); } } } return validated; }
6
@Override public int append(final NodeLike<Node<N, E>, E>[] out, final int pos) { if(pos == 0) { out[0] = this; return 1; } @SuppressWarnings("unchecked") final NodeLike<N, E>[] buffer = (NodeLike<N, E>[]) out; final NodeLike<Node<N, E>, E> left = out[pos - 1]; if(left instanceof PartialInnerNode) { buffer[pos - 1] = ((PartialInnerNode<N, E>) left).sub; if(sub.append(buffer, pos) == pos) { out[pos - 1] = new PartialInnerNode<>(buffer[pos - 1]); } else { @SuppressWarnings("unchecked") final Node<N, E>[] ch = new Node[2]; ch[0] = (Node<N, E>) buffer[pos - 1]; ch[1] = (Node<N, E>) buffer[pos]; out[pos - 1] = new InnerNode<>(ch); out[pos] = null; } return pos; } final Node<N, E>[] children = ((InnerNode<N, E>) left).children; final int n = children.length; final Node<N, E> a, b; if(sub instanceof Node) { a = children[n - 1]; b = (Node<N, E>) sub; } else { buffer[pos - 1] = children[n - 1]; if(sub.append(buffer, pos) == pos) { final Node<N, E>[] ch = children.clone(); ch[n - 1] = (Node<N, E>) buffer[pos - 1]; out[pos - 1] = new InnerNode<>(ch); return pos; } a = (Node<N, E>) buffer[pos - 1]; b = (Node<N, E>) buffer[pos]; } if(n < FingerTree.MAX_ARITY) { @SuppressWarnings("unchecked") final Node<N, E>[] ch = new Node[n + 1]; System.arraycopy(children, 0, ch, 0, n - 1); ch[n - 1] = a; ch[n] = b; out[pos - 1] = new InnerNode<>(ch); out[pos] = null; return pos; } final int ll = (n + 1) / 2, rl = n + 1 - ll; @SuppressWarnings("unchecked") final Node<N, E>[] ls = new Node[ll], rs = new Node[rl]; System.arraycopy(children, 0, ls, 0, ll); System.arraycopy(children, ll, rs, 0, rl - 2); rs[rl - 2] = a; rs[rl - 1] = b; out[pos - 1] = new InnerNode<>(ls); out[pos] = new InnerNode<>(rs); return pos + 1; }
6
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=getTargetAnywhere(mob,commands,givenTarget,false,true,true); if(target==null) return false; if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MASK_MOVE|CMMsg.TYP_JUSTICE|(auto?CMMsg.MASK_ALWAYS:0),auto?L("A stink cloud surrounds <T-NAME>!"):L("^F<S-NAME> stinkif(ys) <T-NAMESELF>.^?")); CMLib.color().fixSourceFightColor(msg); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); if(target.playerStats()!=null) { mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> <S-IS-ARE> stinkier!")); target.playerStats().adjHygiene(PlayerStats.HYGIENE_DELIMIT+1); Log.sysOut("Stinkify",mob.Name()+" stinkied "+target.name()+"."); } else mob.tell(mob,target,null,L("<T-NAME> is a mob. Try a player.")); } } else return beneficialVisualFizzle(mob,target,L("<S-NAME> attempt(s) to stinkify <T-NAMESELF>, but fail(s).")); return success; }
7
public Carte(){ map = new Element[LARGEUR_CARTE][HAUTEUR_CARTE]; // Génération de la map for(int x = 0; x < LARGEUR_CARTE; x++){ for(int y = 0; y < HAUTEUR_CARTE; y++){ map[x][y] = new Element(new Position(x, y),BackgroundEnum.plain); } } }
2
protected void showPopup(MouseEvent event) { // Should we show a popup menu? if (event.isPopupTrigger()) { Point p = getView().transformFromAutomatonToView(event.getPoint()); if (lastClickedState != null && shouldShowStatePopup()) { stateMenu.show(lastClickedState, getView(), p); } else { emptyMenu.show(getView(), p); } } lastClickedState = null; lastClickedTransition = null; }
3
public static final boolean isAngleWallParallel(double angle) { return Utils.isNear(angle, 0) || Utils.isNear(angle, HALF_PI) || Utils.isNear(angle, PI) || Utils.isNear(angle, ONE_HALF_PI) || Utils.isNear(angle, TWO_PI); }
4
public void update(){ if(!ctrl.isRunning()){ start(); } checkEndConditions(); if(ctrl.isRunning()){ timer.addMillis((lastCount-ctrl.getEnemyShipCount())*500); lastCount=ctrl.getEnemyShipCount(); if(ctrl.getEnemyShipCount()==0){ for (int i = 0; i < nextSpawnAmount; i++) { spawnShipRandomly(); } lastCount=nextSpawnAmount; nextSpawnAmount=nextSpawnAmount*2; } timer.update(); } ctrl.update(); }
4
public static Node getOtherNode(Edge edge, Node node) { for (Node n : edge.getAdjacent()) { if (!n.equals(node)) { return n; } } return null; }
2
private void removePoints(int id) throws SQLException { /* * Gets the number of group matches where the team id is playing or has played. * The -1 is because the arraylist is not starting on 1 but 0, so 1 lower. */ int matches = matchmgr.showCountTeamGroup(id) - 1; /* * The i in the for loop symbolises the place in the arraylist. */ for (int i = 0; i <= matches; i++) { int guestTeamId = matchmgr.getGroupMatchesByTeamId(id).get(i).getGuestTeamId(); int homeTeamId = matchmgr.getGroupMatchesByTeamId(id).get(i).getHomeTeamId(); /* * Checking whether the selected match is played, if 1 continue */ if (matchmgr.getGroupMatchesByTeamId(id).get(i).getIsPlayed() == 1) { /* * Checks if the given team id is the same the hometeams id in the match. */ if (id == homeTeamId) { /* * Checks if the chosen team has lost or were tied * if they lost, the winning team looses 3 points * if tied the other team looses 1 point. * if they wont we wont remove any points, since the team is getting deleted. */ if (matchmgr.getGroupMatchesByTeamId(id).get(i).getHomeGoals() < matchmgr.getGroupMatchesByTeamId(id).get(i).getGuestGoals()) { int currentPoints = teammgr.getById(guestTeamId).getPoints(); teammgr.setPoints(currentPoints - 3, teammgr.getById(guestTeamId)); } else if (matchmgr.getGroupMatchesByTeamId(id).get(i).getHomeGoals() == matchmgr.getGroupMatchesByTeamId(id).get(i).getGuestGoals()) { int currentPoints = teammgr.getById(guestTeamId).getPoints(); teammgr.setPoints(currentPoints - 1, teammgr.getById(guestTeamId)); } } /* * Checks if the given team id is the same the guestteams id in the match. */ else if (id == guestTeamId) { /* * Checks if the chosen team has lost or were tied * if they lost, the winning team looses 3 points * if tied the other team looses 1 point. * if they wont we wont remove any points, since the team is getting deleted. */ if (matchmgr.getGroupMatchesByTeamId(id).get(i).getHomeGoals() > matchmgr.getGroupMatchesByTeamId(id).get(i).getGuestGoals()) { int currentPoints = teammgr.getById(homeTeamId).getPoints(); teammgr.setPoints(currentPoints - 3, teammgr.getById(homeTeamId)); } else if (matchmgr.getGroupMatchesByTeamId(id).get(i).getHomeGoals() == matchmgr.getGroupMatchesByTeamId(id).get(i).getGuestGoals()) { int currentPoints = teammgr.getById(homeTeamId).getPoints(); teammgr.setPoints(currentPoints - 1, teammgr.getById(homeTeamId)); } } } } }
8
public void decrement(int by) { // if given value is negative, we have to increment if (by < 0) { decrement(Math.abs(by)); return; } // check if we would overflow int space_down = value - min; if (by > space_down) { // we simply use min value = min; } else { // no overflowing, this is easy value -= by; } }
2
public double centerControl() { if (getKingLocation(getPlayerToMove().toLowerCase())==null) return -10000000; if (getKingLocation(getPlayerToMove() == "W"? KrakenColor.BLACK_ITEM:KrakenColor.WHITE_ITEM)==null) return 10000000; int myPuntuation=0; String itemColor = playerToMove == W ? KrakenColor.WHITE_ITEM:KrakenColor.BLACK_ITEM; for(int i = 2;i<4;i++) for(int j = 0;j<colBoard;j++) if (board[i][j] != null && board[i][j].getColor().equals(itemColor)){ myPuntuation+=100; } return myPuntuation; }
8
public String getEmployeeName() { return employeeName; }
0
private Random getInstanceOfRandom(long seed) throws InitializationError { String randomClass = System.getProperty("jcheck.random"); if (randomClass != null) { try { Class<?> random = Class.forName(randomClass); Constructor<?> randConst = random.getConstructor(long.class); return (Random) randConst.newInstance(seed); } catch (Exception ex) { throw new InitializationError("Unable to create instance of random"); } } return new Random(seed); }
4
Template loadTemplate(String name, int[] array) { return new Template(name, loadArray(array)); }
0
@Override public Object getValueAt(int row, int col) { switch (col) { case COL_FULL_ACCT : return fullAccounts.get(row); case COL_TANK_NUM : return tankNums.get(row); case COL_SVC_NUM : return svcNums.get(row); case COL_NAME : return names.get(row); case COL_REF_NUM : return refNums.get(row); case COL_DOC_TYPE : return docTypes.get(row); case COL_DATE : return dates.get(row); case COL_MAINT_DT : return maintDates.get(row); case COL_MAINT_USER : return maintUsers.get(row); default: return null; } }
9
public void put(Object o) { stackList.add(o); }
0
private static HashMap<String, String> listTests(String dirPath, int level) { HashMap<String, String> listoffiles = new HashMap<String,String>(); try{ File dir = new File(dirPath); File[] firstLevelFiles = dir.listFiles(); if (firstLevelFiles != null && firstLevelFiles.length > 0) { for (File aFile : firstLevelFiles) { if (!aFile.isDirectory()) { listoffiles.put(aFile.getName().toLowerCase().trim(), aFile.getAbsolutePath().toLowerCase().trim()); } } } } catch(Exception ex){ System.out.println("Error at GetProgramFiles.listTests " + ex.getMessage()); listoffiles = null; } return listoffiles; }
5
public void train(Pattern p) { // propagate; set activation Values this.propagate(p, false); // run over all Layers from the bottom to the top; Except the Input // Layer // Backpropagation for (int i = neurons.size() - 1; i > 0; i--) { for (int s = 0; s < neurons.get(i).size(); s++) { Neuron neuron = neurons.get(i).get(s); if (neuron.getNeuronType() == ENeuronType.Output) { neuron.calculateDeltaFunctionValuesForOutputNeuron(p .getOutputNeuronsSet()[s]); } if (neuron.getNeuronType() == ENeuronType.Hidden) { neuron.calculateDeltaFunctionValuesForHiddenNeuron(); } if (neuron.getNeuronType() == ENeuronType.Input) { throw new IllegalStateException( "Error: Input Neuron in Layer " + i + " found!"); } } } // Calculate new weights for (int i = 1; i < neurons.size(); i++) { for (Neuron neuron : neurons.get(i)) { neuron.calculateNewWeightsForMyDendrites(learningRate); } } }
7
public void showLine(int lineNumber) { for (int i = 0; i < fieldSize; i++) { showCell(i,lineNumber); } }
1
public void mapTileDeckClicked() { if (((Window) getTopLevelAncestor()).getPlayer().isPlayersTurn()) { if (GameHandler.instance.getCurrentState() == GameState.tilePlacement) { if (GameHandler.instance.getMap().getTempTile() == null) { MapTile tile = GameHandler.instance.getTileDeck().getNextCard(); if (tile != null) { boolean possible = false; for (int x = 0; x < 11; x += 1) { for (int y = 0; y < 11; y += 1) { for (int r = 0; r < 4; r += 1) { if (GameHandler.instance.getMap().checkValidPosition(tile, x, y)) { possible = true; } tile.rotateTile(); } } } if (possible) { GameHandler.instance.getMap().addTempTile(tile); } else { DialogHandler.showMessage(null, RB.get("MapTileDeckButton.no_available_places_message"), RB.get("MapTileDeckButton.map_tile"), //$NON-NLS-1$ //$NON-NLS-2$ JOptionPane.INFORMATION_MESSAGE); GameHandler.instance.nextGameState(); GameHandler.instance.nextGameState(); } } else { DialogHandler .showMessage( null, RB.get("MapTileDeckButton.no_more_cards_message"), RB.get("MapTileDeckButton.map_tile"), JOptionPane.INFORMATION_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ GameHandler.instance.nextGameState(); GameHandler.instance.nextGameState(); } } } } }
9