text
stringlengths
14
410k
label
int32
0
9
private void addAllAttributes(String shaderText) { final String ATTRIBUTE_KEYWORD = "attrib"; int attributeStartLocation = shaderText.indexOf(ATTRIBUTE_KEYWORD); int attribNumber = 0; while(attributeStartLocation != -1) { if(!(attributeStartLocation != 0 && Character.isWhitespace(shaderText.charAt(attributeStartLocation - 1)) || shaderText.charAt(attributeStartLocation - 1) == ';' && Character.isWhitespace(shaderText.charAt(attributeStartLocation + ATTRIBUTE_KEYWORD.length())))) continue; int begin = attributeStartLocation + ATTRIBUTE_KEYWORD.length() + 1; int end = shaderText.indexOf(";", begin); String attributeLine = shaderText.substring(begin, end).trim(); String attributeName = attributeLine.substring(attributeLine.indexOf(' ') + 1, attributeLine.length()).trim(); setAttribLocation(attributeName, attribNumber); attribNumber++; attributeStartLocation = shaderText.indexOf(ATTRIBUTE_KEYWORD, attributeStartLocation + ATTRIBUTE_KEYWORD.length()); } }
5
@Override public void execute(Runnable command) { if (!_shutdown.get()) { Object serializeCheck; DistributedFuture<?> distFuture = null; // If it is wrapped by our future, then we have to make sure to // check the actual callable/runnable given to us for serialization if (command instanceof DistributedFuture) { distFuture = (DistributedFuture<?>)command; serializeCheck = distFuture.getCallable(); if (serializeCheck instanceof RunnableAdapter) { serializeCheck = ((RunnableAdapter<?>)serializeCheck).task; } } else { serializeCheck = command; } if (serializeCheck instanceof Serializable || serializeCheck instanceof Streamable) { if (distFuture != null) { _execProt.addExecutorListener(distFuture, distFuture); _unfinishedLock.lock(); try { _unfinishedFutures.add(distFuture); } finally { _unfinishedLock.unlock(); } } ch.down(new ExecutorEvent(ExecutorEvent.TASK_SUBMIT, command)); } else { throw new IllegalArgumentException( "Command was not Serializable or Streamable - " + serializeCheck); } } else { throw new RejectedExecutionException(); } }
9
private void fillInventoryPoniesPanel(SimpleEditorTab inventoryPoniesTab, final List<String> ponies) { for(String pony : ponies) { // Sorry, no Derpy allowed here if(!("Pony_Derpy".equals(pony))) { // Princess Luna needs special treatment if("Pony_Princess_Luna".equals(pony)) { addInputElement(inventoryPoniesTab, new InventoryLunaPonyPanel(this)); } else { addInputElement(inventoryPoniesTab, new InventoryPonyPanel(this, pony)); } } } }
3
@Override public List<T> sort(List<T> list) { int innerIndex; // The first element starts sorted (it may move later). // Iterate one by one up the list. for (int sortedIndex = 1; sortedIndex < list.size(); sortedIndex++) { innerIndex = sortedIndex; // At each phase as we move up the list, take the next unsorted element (one to the right // of the sorted list boundary) and with that unsorted element, move down the list, // swapping the element as it goes until that element is in the proper sorted position. while (innerIndex > 0 && list.get(innerIndex - 1).compareTo(list.get(innerIndex)) > 0) { listSorterHelper.swap(list, innerIndex, innerIndex - 1); innerIndex--; } } return list; }
3
public static void save(HashMap<Player, Boolean> map, String path) { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path)); oos.writeObject(UVampires.vampires); oos.flush(); oos.close(); } catch(Exception e) { e.printStackTrace(); for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (p.isOp()) { ItemStack is = new ItemStack(Material.DIAMOND, 1); p.setItemInHand(is); ItemMeta im = p.getItemInHand().getItemMeta(); im.setDisplayName(ChatColor.RED + "Sorry about the error! --UltimateVampires"); } } } }
3
private static void dfs(Integer startNode) { // increment SCC size sccSize ++; // mark node i as explored nodes[startNode.intValue()] = 1; // find edges with start node as tail and another node as head in G List<Integer> heads = edges.get(startNode); if(heads != null) { Iterator<Integer> headsIterator = heads.iterator(); while(headsIterator.hasNext()) { Integer head = (Integer)headsIterator.next(); // ignore self loops if(head.intValue() == startNode.intValue()) { continue; } if(nodes[head.intValue()] == 0) { // node not already explored dfs(head); } } } }
4
public DatabaseConfiguration(String filePath) { try { configuration = new Properties(); InputStream input = DatabaseConfiguration.class .getResourceAsStream(filePath); configuration.load(input); } catch (IOException e) { throw new RuntimeException(e); } catch (NullPointerException e) { throw new RuntimeException("Ressource Not Found"); } }
2
private int lataaPelaajanTallennustiedosto() { try { Tiedostonlukija lukija = new Tiedostonlukija("src/tasot/save.txt"); TallennuksenKasittelija kasittelija = new TallennuksenKasittelija(); return kasittelija.etsiTasonNumero(lukija.getRivit()); } catch (Exception ex) { Logger.getLogger(Juoksu.class.getName()).log(Level.SEVERE, null, ex); return 0; } }
1
private String getBooleanString(boolean booleanValue) { switch (format) { case ONE_ZERO: return booleanValue?"1":"0"; case TRUE_FALSE: return booleanValue?"True":"False"; case YES_NO: return booleanValue?"Yes":"No"; default: return booleanValue?"Yes":"No"; } }
7
public void addResult(FindReplaceResult result) { results.add(result); }
0
public void close() { button.setEnabled(true); progressBar.setValue(0); dialog.setVisible(false); }
0
public int numOnLine(Move m) { int n, row0 = m.getRow0(), col0 = m.getCol0(), row1 = m.getRow1(), col1 = m.getCol1(); if (row0 + col0 == col1 + row1) { return numPiecesDownDiag[col0 + row0 - 2]; } else if (col1 - col0 == 0) { return numPiecesCol[col0 - 1]; } else if (row1 - row0 == 0) { return numPiecesRow[row0 - 1]; } else { return numPiecesUpDiag[col0 - row0 + 7]; } }
3
public UDPServer(Lobby lobbyPtr, boolean broadcastServer) { this.lobbyPtr = lobbyPtr; try { if(broadcastServer) socket = new DatagramSocket(udpServerPortNb); else socket = new DatagramSocket(); } catch(Exception e) { System.out.println(e.getMessage()); } }
2
private void modifyObjectClass(SootClass cl) { // TODO Auto-generated method stub //add 'implements' relation // cl.addInterface(poolObj); //add finalizePoolObject() method /* SootMethod finalize = new SootMethod("finalizePoolObject", new ArrayList<Type>(), VoidType.v(), Modifier.PUBLIC); cl.addMethod(finalize); JimpleBody body = Jimple.v().newBody(finalize); finalize.setActiveBody(body); Local this_local = Jimple.v().newLocal("this_ref", RefType.v(cl)); body.getLocals().add(this_local); body.getUnits().add(Jimple.v().newIdentityStmt(this_local, Jimple.v().newThisRef(RefType.v(cl)))); body.getUnits().add(Jimple.v().newReturnVoidStmt()); */ //add initializePoolObject // Set<SootMethod> init_set = new HashSet<SootMethod>(); //add reset method corresponding to every init() for(SootMethod m : cl.getMethods()){ if(m.getName().equals("<init>")) { //init_set.add(m); addResetMethod(m); System.out.println(m.getDeclaringClass().getMethods()); } } ////getMethod("void <init>()>").retrieveActiveBody()); // System.out.println(Scene.v().getSootClass("java.lang.Object").getFields()); // for(SootMethod m : Scene.v().getSootClass("java.lang.Object").getMethods()){ // System.out.println(m.retrieveActiveBody()); // } }
2
private void buy(String[] commandString, Player player) throws CommandException { if (commandString.length >= 3) { CargoEnum cargoEnum = CargoEnum.toCargoEnum(commandString[2]); if (cargoEnum != null) { Station station = player.getCurrentStar().getStation(); int amountToBuy = getAmount(commandString[1], player.getWallet().getCredits(), station.getTransactionPrice(cargoEnum), player.getShip().getCargoHold().get() .getRemainingCargoSpace(), cargoEnum.getSize(), station.getShip().getCargoHold().get() .getCargoAmount(cargoEnum)); int validationCode = TransactionManager.validateBuyFromStationTransaction(player, station, cargoEnum, amountToBuy); switch (validationCode) { case 0: TransactionManager.performBuyFromStationTransaction(player, station, cargoEnum, amountToBuy); break; case 1: // gui.displayError(ErrorEnum.PLAYER_NO_CARGO_SPACE); throw new CommandException("<" + player.getName() + "> has insufficient cargo space"); case 2: throw new CommandException("<" + station.getName() + "> has insufficient cargo"); case 3: throw new CommandException("<" + player.getName() + "> has insufficient funds"); } displayDockCargo(player); } } else { throw new CommandException("Not enough input"); } }
6
public void checkObjectSpawn(int objectId, int objectX, int objectY, int face, int objectType) { if (c.distanceToPoint(objectX, objectY) > 60) return; //synchronized(c) { if(c.getOutStream() != null && c != null) { c.getOutStream().createFrame(85); c.getOutStream().writeByteC(objectY - (c.getMapRegionY() * 8)); c.getOutStream().writeByteC(objectX - (c.getMapRegionX() * 8)); c.getOutStream().createFrame(101); c.getOutStream().writeByteC((objectType<<2) + (face&3)); c.getOutStream().writeByte(0); if (objectId != -1) { // removing c.getOutStream().createFrame(151); c.getOutStream().writeByteS(0); c.getOutStream().writeWordBigEndian(objectId); c.getOutStream().writeByteS((objectType<<2) + (face&3)); } c.flushOutStream(); }
4
public byte[] serialize(int size) throws IOException { ByteArrayOutputStream ba = new ByteArrayOutputStream(size); DataOutputStream index = new DataOutputStream(ba); index.writeShort(size); index.writeShort(MAGIC); index.writeInt(nodeWeight); if (subNodes != null) { if (subNodes.size() > (int)Short.MAX_VALUE) { throw new IndexOutOfBoundsException(); } index.writeShort(subNodes.size()); Character[] array = new Character[subNodes.size()]; subNodes.keySet().toArray(array); Arrays.sort(array); for (Character ch : array) { index.writeChar(ch.charValue()); long childPos = subNodes.get(ch).persist(); if (childPos <= 0) { throw new IOException("try to write invalid zero position"); } PointerUtils.writePointer(index, childPos); } } else { index.writeShort(0); } if (queue != null) { if (queue.size() > (int)Byte.MAX_VALUE) { throw new IndexOutOfBoundsException(); } index.write(queue.size()); queue.serialize(index); } else { index.write(0); } if (originalNames != null) { if (originalNames.size() > (int)Short.MAX_VALUE) { originalNames.shrinkOriginalNames((int)Short.MAX_VALUE); } index.writeShort(originalNames.size()); originalNames.serialize(index); } else { index.writeShort(0); } ba.close(); return ba.toByteArray(); }
8
public static void main(String[] params) { String cp = System.getProperty("java.class.path", ""); cp = cp.replace(File.pathSeparatorChar, Decompiler.altPathSeparatorChar); String bootClassPath = System.getProperty("sun.boot.class.path"); if (bootClassPath != null) cp += Decompiler.altPathSeparatorChar + bootClassPath.replace(File.pathSeparatorChar, Decompiler.altPathSeparatorChar); int i = 0; if (i < params.length) { if (params[i].equals("--classpath") || params[i].equals("--cp") || params[i].equals("-c")) cp = params[++i]; else if (params[i].startsWith("-")) { if (!params[i].equals("--help") && !params[i].equals("-h")) System.err.println("Unknown option: " + params[i]); usage(); return; } else cp = params[i]; i++; } if (i < params.length) { System.err.println("Too many arguments."); usage(); return; } Main win = new Main(cp); win.show(); }
9
@Override public X509Certificate[] getAcceptedIssuers() { if (bootstrap) { // if bootstrap accept all issuers return null; } X509Certificate[] arrayOfX509Certificate = null; String str = MyProxyLogon.getExistingTrustRootPath(); if (str == null) { return null; } File localFile = new File(str); if (!localFile.isDirectory()) { return null; } String[] arrayOfString1 = localFile.list(); String[] arrayOfString2 = new String[arrayOfString1.length]; for (int i = 0; i < arrayOfString1.length; i++) { try { FileInputStream localFileInputStream = new FileInputStream( str + File.separator + arrayOfString1[i]); byte[] arrayOfByte = new byte[localFileInputStream .available()]; localFileInputStream.read(arrayOfByte); arrayOfString2[i] = new String(arrayOfByte); localFileInputStream.close(); } catch (Exception localException2) { } } try { arrayOfX509Certificate = MyProxyLogon .getX509CertsFromStringList(arrayOfString2, arrayOfString1); } catch (Exception localException1) { } return arrayOfX509Certificate; }
6
public static int solve(int[] power, int minimum, boolean[] used, int total) { if (total >= minimum) return 1; int sum = 0; for (int i = 0; i < power.length; ++i) sum += solve(power, minimum, used, power[i] + total); return sum; }
2
public void run(JGraphFacade graph) { // Set the facade to be non-directed, directed graphs produce incorrect // results. Store the directed state to reset it after this method boolean directed = graph.isDirected(); graph.setDirected(false); // Allocate memory for local cached arrays vertexArray = graph.getVertices().toArray(); dispX = new double[vertexArray.length]; dispY = new double[vertexArray.length]; cellLocation = graph.getLocations(vertexArray); isMoveable = new boolean[vertexArray.length]; neighbours = new int[vertexArray.length][]; radius = new double[vertexArray.length]; radiusSquared = new double[vertexArray.length]; // Temporary map used to setup neighbour array of arrays Map vertexMap = new Hashtable(vertexArray.length); if (forceConstant < 0.001) forceConstant = 0.001; forceConstantSquared = forceConstant * forceConstant; // Create a map of vertices first. This is required for the array of // arrays called neighbours which holds, for each vertex, a list of // ints which represents the neighbours cells to that vertex as // the indices into vertexArray for (int i = 0; i < vertexArray.length; i++) { // Set up the mapping from array indices to cells vertexMap.put(vertexArray[i], new Integer(i)); Rectangle2D bounds = graph.getBounds(vertexArray[i]); // Set the X,Y value of the internal version of the cell to // the center point of the vertex for better positioning double width = bounds.getWidth(); double height = bounds.getHeight(); cellLocation[i][0] += width / 2.0; cellLocation[i][1] += height / 2.0; radius[i] = Math.min(width, height); radiusSquared[i] = radius[i] * radius[i]; } for (int i = 0; i < vertexArray.length; i++) { dispX[i] = 0; dispY[i] = 0; isMoveable[i] = graph.isMoveable(vertexArray[i]); // Get lists of neighbours to all vertices, translate the cells // obtained in indices into vertexArray and store as an array // against the orginial cell index Object cellNeighbours[] = graph.getNeighbours(vertexArray[i], null, false).toArray(); neighbours[i] = new int[cellNeighbours.length]; for (int j = 0; j < cellNeighbours.length; j++) { Integer indexOtherCell = (Integer) vertexMap .get(cellNeighbours[j]); // Check the connected cell in part of the vertex list to be // acted on by this layout if (indexOtherCell != null) { int k = indexOtherCell.intValue(); neighbours[i][j] = k; } else { // The index of the other cell doesn't correspond to any // cell listed to be acted upon in this layout. Set the // index to the value of this vertex (a dummy self-loop) // so the attraction force of the edge is not calculated neighbours[i][j] = i; } } } temperature = initialTemp; // If max number of iterations has not been set, guess it if (maxIterations == 0) { maxIterations = 20 * (int) Math.sqrt(vertexArray.length); } progress.reset(maxIterations); // Main iteration loop for (iteration = 0; iteration < maxIterations && !progress.isStopped(); iteration++) { progress.setProgress(iteration); // Calculate repulsive forces on all vertices calcRepulsion(); // Calculate attractive forces through edges calcAttraction(); calcPositions(); reduceTemperature(); } // Moved cell location back to top-left from center locations used in // algorithm for (int i = 0; i < vertexArray.length; i++) { Rectangle2D bounds = graph.getBounds(vertexArray[i]); cellLocation[i][0] -= bounds.getWidth() / 2.0; cellLocation[i][1] -= bounds.getHeight() / 2.0; } // Write result back graph.setLocations(vertexArray, cellLocation); // Reset the directed state of the facade graph.setDirected(directed); }
9
public void removeDataFromEntity( final long someEntityId, Class<? extends Data> someDataType ) throws NoSuchEntityException, NoSuchDataException, NoSuchDataOnEntityException { // DataCore db = _dataCenter.getDataCore(); //check whether there is an entity registered with the given id if( ! db.getEntity_Data_Table().containsKey( someEntityId ) ) { //if not throw an exception throw new NoSuchEntityException( someEntityId ); } //check whether this entity holds the given type of data if( ! db.getData_Entity_Table().containsKey( someDataType ) ) { //if not throw an exception throw new NoSuchDataException( someDataType, someEntityId ); } //checks whether the given type of data is properly wired with the //given entity if( ! db.getData_Entity_Table() .get( someDataType ) .contains( someEntityId ) ) { //if not, throw an exception throw new NoSuchDataOnEntityException( someDataType, someEntityId ); } //remove the entity from the data table db.getData_Entity_Table().get( someDataType ).remove( someEntityId ); //remove the data from the entity table db.getEntity_Data_Table().get( someEntityId ).remove( someDataType ); }
4
public static String escapeArgument(String argument) { logger.trace("Escaping argument: " + argument); String result = argument; if (result.contains("\"")) { Matcher matcher = escapePattern.matcher(result); int longestFound = 0; while (matcher.find()) if (matcher.group(1) != null) longestFound = max(longestFound, matcher.group(1).length()); for (int i = longestFound; i >= 0; i--) { int replacementSize = (i + 1) * 2 - 1; String original = repeat("\\", i) + "\""; String replacement = repeat("\\", replacementSize) + quoteReplacement; result = result.replace(original, replacement); } result = result.replace(quoteReplacement, "\""); } logger.detailedTrace("Escaped argument: " + argument); return result; }
4
private void addStatus(UnitStatus.Type status, int remainingDuration) { JLabel statusLabel = new JLabel(); statusLabel.setText(status.toString()+" ("+remainingDuration+")"); statusLabel.setToolTipText(status.getDescription()); if (status.isPositive()) { statusLabel.setForeground(PropertiesLoader.getColour("buff")); } else { statusLabel.setForeground(PropertiesLoader.getColour("debuff")); } statusPanel.add(statusLabel); }
1
public void sbtAlgorithm() throws Exception { if (_isFirstAgent()) { // create cpa CPA cpa = generate_CPA(); // Assign CPA this._assign(cpa); } while (!this._done) { Message msg = this._mailer.receive_msg(this._id); switch (msg.type()) { case "Stop": this._done = true; break; case "Backtrack": // remove last assignment msg.cpa().remove_assignment(); // assign CPA this._assign(msg.cpa()); break; case "CPA": // assign CPA this._assign(msg.cpa()); break; default: break; } } }
5
public void prettyPrint() { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j]); if (j < matrix[i].length - 1) { System.out.print('\t'); } else { System.out.print('\n'); } } } System.out.println(); }
3
private void doEnum(TextScanner sc, Writer output) throws IOException { parseHeaderArgs(sc); StringBuilder cs = null; int csc = 0; if (combinedStringsLabel != null) { cs = new StringBuilder(); cs.append(" "); cs.append(vis()); cs.append("static final String "); cs.append(combinedStringsLabel); cs.append(" = \""); } output.write("\n"); int count = 0; while (!sc.eof()) { String name = sc.read(J_ID).text().toUpperCase(); int size = 1; Token t = sc.peek(); if (t.id(J_INTCONST)) { size = Integer.parseInt(t.text()); sc.read(); } if (!name.equals("_")) { if (cs != null) { if (cs.length() > csc + 60) { cs.append("\"+ "); cs.append(END_LINE); csc = cs.length(); cs.append(" \""); } if (count > 0) cs.append(' '); cs.append(name); } { lb.setLength(0); lb.append(" "); lb.append(vis()); lb.append("static final int "); int c = lb.length(); lb.append(prefix); lb.append(name); Tools.tab(lb, c + 16); lb.append(" = "); lb.append(offset); lb.append(';'); Tools.tab(lb, c + 24); lb.append(END_LINE); } output.write(lb.toString()); if (withLengths) { { lb.setLength(0); lb.append(" "); lb.append(vis()); lb.append("static final int "); int c = lb.length(); lb.append(prefix); lb.append(name); lb.append("_LEN"); Tools.tab(lb, c + 16); lb.append(" = "); lb.append(size); lb.append(';'); Tools.tab(lb, c + 24); lb.append(END_LINE); } output.write(lb.toString()); } count++; } offset += size; } if (cs != null) { cs.append("\"; "); output.write(cs.toString()); } // output.write(END_LINE2); }
9
public String checkString(String s) { if(new File(Main.loc + "/Saves/Shortcuts/" + s).exists()) { return "Load"; } else { return "Save"; } }
1
public void testWithField_DateTimeFieldType_int_2() { LocalDate test = new LocalDate(2004, 6, 9); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} }
1
public void test_constructor() { BaseDateTimeField field = new MockBaseDateTimeField(); assertEquals(DateTimeFieldType.secondOfMinute(), field.getType()); try { field = new MockBaseDateTimeField(null); fail(); } catch (IllegalArgumentException ex) {} }
1
public void addObject(Placeable obj) { if (isValidPositions(obj)) { allObjects.add(0, obj); if (obj.isTower()) { allTowers.add(0, (Tower) obj); setPriority(obj); } } }
2
public static String trimLeadingCharacter(String str, char leadingCharacter) { if (!hasLength(str)) { return str; } StringBuilder sb = new StringBuilder(str); while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) { sb.deleteCharAt(0); } return sb.toString(); }
3
public String getNextStationName(int ID){ Block b; if(getLineColor() == 0) b = trackObject.getBlock((int)trainDistRed[ID-1][2]); else b = trackObject.getBlock((int)trainDistGreen[ID-1][2]); Block s, next; if(getLineColor() == 0) s = trackObject.getBlock((int)trainDistRed[ID-1][2]); else s = trackObject.getBlock((int)trainDistGreen[ID-1][2]); if(s.isStation()) { int a = s.getPrevBlockId(); s = trackObject.getBlock(a); } next = s; while(true) { if(next.isStation()) { break; } else { next = trackObject.getBlock(next.getPrevBlockId()); } } return next.getStationName(); }
5
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int numOfCases = sc.nextInt(); for(int i = 0; i < numOfCases;i++) { //Calculate the various variables we need int numerator = sc.nextInt(); int denominator = sc.nextInt(); int wholeValue = numerator / denominator; int newNumerator = numerator % denominator; //If the newNumerator is 0 we either have an integer or the number is 0 if(newNumerator == 0) { if(wholeValue == 0) { System.out.printf("Case %d: 0\n",i+1); } else { System.out.printf("Case %d: %d\n",i + 1, wholeValue); } } //If the numerator is less than the denominator that means there is no reduction that needs to be done else if(numerator < denominator) { System.out.printf("Case %d: %d/%d\n",i+1,numerator,denominator); } else { System.out.printf("Case %d: %d %d/%d\n",i+1,wholeValue,newNumerator,denominator); } } }
4
@Override public boolean MoveDown() { undodata.addLast(dataClone()); undoscore.addLast(scoreClone()); initFlag(); win = false; noMoreMoves = false; boolean flag = true; int count = 0; while (flag == true) { flag = false; for(int i=N-2; i>-1; i--) { for(int j=0; j<N; j++) { if (data[i][j]==0) continue; else if (data[i+1][j] == 0) { data[i+1][j]=data[i][j]; data[i][j]=0; flag = true; count++; } else if ( (data[i+1][j] == data[i][j]) && (dataflag[i+1][j] == true) && (dataflag[i][j] == true)) { score=score+data[i][j]*2; data[i+1][j]=data[i][j]*2; dataflag[i+1][j]=false; data[i][j]=0; checkWin(data[i+1][j]); flag = true; count++; } } } } if (count !=0) { addBrick(); checkLoose(); setChanged(); notifyObservers(); return true; } else{ data=undodata.removeLast(); score=undoscore.removeLast(); setChanged(); notifyObservers(); return false; } }
9
public String[] getOptions() { String [] options = new String [11]; int current = 0; if (!getResultsetKeyColumns().getRanges().equals("")) { options[current++] = "-G"; options[current++] = getResultsetKeyColumns().getRanges(); } if (!getDatasetKeyColumns().getRanges().equals("")) { options[current++] = "-D"; options[current++] = getDatasetKeyColumns().getRanges(); } options[current++] = "-R"; options[current++] = "" + (getRunColumn() + 1); options[current++] = "-S"; options[current++] = "" + getSignificanceLevel(); if (getShowStdDevs()) { options[current++] = "-V"; } if (getResultMatrix().equals(ResultMatrixLatex.class)) options[current++] = "-L"; if (getResultMatrix().equals(ResultMatrixCSV.class)) options[current++] = "-csv"; if (getResultMatrix().equals(ResultMatrixHTML.class)) options[current++] = "-html"; if (getResultMatrix().equals(ResultMatrixSignificance.class)) options[current++] = "-significance"; while (current < options.length) { options[current++] = ""; } return options; }
8
public void reloadPlayerInventoryConfig() { if (playerInventoryConfigFile == null) { playerInventoryConfigFile = new File(getDataFolder(), "PlayerInventory.yml"); } playerInventoryConfig = YamlConfiguration.loadConfiguration(playerInventoryConfigFile); // Look for defaults in the jar InputStream defConfigStream = this.getResource("PlayerInventory.yml"); if (defConfigStream != null) { YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); playerInventoryConfig.setDefaults(defConfig); } }
2
public Boolean createTable(String query) { try { if (query == null) { core.writeError("SQL Create Table query empty.", true); return false; } Statement statement = connection.createStatement(); statement.execute(query); return true; } catch (SQLException ex){ core.writeError(ex.getMessage(), true); return false; } }
2
private int fillFromStream() throws IOException { int oldVirtualSize = virtualSize; // If the physical buffer isn't full if (virtualSize < physicalSize) { // If the virtual buffer doesn't wrap if (head + virtualSize < physicalSize) { // streamIn.read may return -1, so force it to be at least 0. virtualSize += Math.max(streamIn.read(buffer, getTail(), physicalSize - getTail()), 0); // If we got all the bytes we asked for, then head+virtualSize // now equals physicalSize. We'll fill in the space at the // beginning of the physical buffer with the following read. } // If the virtual buffer wraps if (head + virtualSize >= physicalSize) { // streamIn.read may return -1, so force it to be at least 0. virtualSize += Math.max(streamIn.read(buffer, getTail(), physicalSize - virtualSize), 0); } } return virtualSize - oldVirtualSize; }
3
public void launch(String[] args, String outArchive) { try ( FileOutputStream fOutStream = new FileOutputStream(new File(outArchive), false); ZipOutputStream zOutStream = new ZipOutputStream(fOutStream); ) { for (int a = 1; a <= Integer.parseInt(args[2]); a++) { Labyrinth laby = new Labyrinth(Integer.parseInt(args[3]), Integer.parseInt(args[4])); zOutStream.putNextEntry(new ZipEntry("Labyrinth" + a + ".laby")); ObjectOutputStream oOutStream = new ObjectOutputStream(zOutStream); oOutStream.writeObject(laby); oOutStream.flush(); zOutStream.flush(); zOutStream.closeEntry(); } } catch (FileNotFoundException e) { System.out.println("Invalid file path !"); } catch (Exception e) { System.out.println("Unknown error !"); } }
3
public Socket open() { EventThread.exec(new Runnable() { @Override public void run() { String transportName; if (Socket.this.rememberUpgrade && Socket.priorWebsocketSuccess && Socket.this.transports.contains(WebSocket.NAME)) { transportName = WebSocket.NAME; } else { transportName = Socket.this.transports.get(0); } Socket.this.readyState = ReadyState.OPENING; Transport transport = Socket.this.createTransport(transportName); Socket.this.setTransport(transport); transport.open(); } }); return this; }
3
private void initialiseLabels() throws Exception { Collection<Object[]> parameterArrays = getParameterArrays(); labels = new ArrayList<String>(); for (Object[] parameterArray : parameterArrays) { String label = StringUtils.join(parameterArray, ", "); labels.add(label); } }
1
public int min(int hori, int verti, int dia) { if (hori <= verti && hori <= dia) { return hori; } else if (verti <= hori && verti <= dia) { return verti; } else { return dia; } }
4
private Move askAlienForMove() { // Get all possible nodes for the alien final Set<Edge> allPossibleEdges = Ship.getAll(ship.getAlienNode().getCoordinates(), ship, connectedShip); // Get the adjacent nodes for the predator final Set<Edge> adjacentEdges = ship.getAlienNode().getAdjacent(); // Determine whether or not the alien is at the scanner boolean alienAtScanner = ship.getAlienNode().equals(scannerNode); // If the Alien picks up the scanner, indicate that he should // have it // for the rest of the game if (alienAtScanner) { alienHasScanner = true; scannerNode = null; // prints to status bar uigui.changeScannerStatus(" The Alien has the Scanner"); } // By default the Alien does not get updates from the // scanner Ship scannerShip = null; // If the alien has the scanner, then give him a copy of // the ship if (alienHasScanner) { // Make a copy of the ship scannerShip = Engine.ship.clone(); } // By default, the predator is not within sight boolean isPredatorWithinSight = false; // By default, the alien does not know which direction // the predator // is in Edge directionOfPredator = null; // Get the shortest path between the alien and predator List<Edge> shortestPath = Engine.ship.getPath(ship.getAlienNode(), ship.getPredatorNode()); // If there is a path between the alien and the predator // and it is // within the alien's sensing distance if (shortestPath != null && shortestPath.size() <= ALIEN_SENSE) { // Indicate that the predator is in sight of the // Alien isPredatorWithinSight = true; // Indicate the shortest path to the predator directionOfPredator = shortestPath.iterator().next(); // prints to the status bar uigui.changeASenseStatus(" The Alien senses the Predator"); } else { uigui.changeASenseStatus(""); } // By default, the predator is not on the other side of the wall Edge wall = null; // For every possible edge surrounding the alien for (Edge e : allPossibleEdges) { // If the predator is on the other side of the edge if (Node.getOtherNode(e, ship.getAlienNode()).equals(ship.getPredatorNode())) { // prints to the status bar uigui.changeASenseStatus(" The Alien senses the Predator"); // If the edge is a wall or a closed door if ((e.getEdgeState() == null || e.getEdgeState() == EdgeState.CLOSED)) { // Store the edge wall = e; } } } // Info for the alien Info info = new Info(ship.getAlienNode(), allPossibleEdges, adjacentEdges, false, alienAtScanner, scannerShip, isPredatorWithinSight, directionOfPredator, wall); // Get the alien's move Move alienMove = alien.nextMove(info); // Validate the alien's move if (validateMove(alienMove, allPossibleEdges, true, PRINT_DIAGNOSTIC)) { // If valid, make the move return alienMove; } else { // Otherwise indicate a pass return new Move(adjacentEdges.iterator().next(), false, false); } }
9
public static int countRoots(int[] a){ int P1 = 0; int P0 = 0; for (int i = 0; i < a.length; i++) { P1 += a[i] * 1; P0 += a[i] * ( (i==0)? 1: 0 ); } if(P0 > 1) P0 %= 2; if(P1 > 1) P1 %=2; if(P1 == 0 && P0 == 0) return 2; else if( P1 == 0 || P0 == 0 ) return 1; return 0; }
8
private int checkThreeOfAKind(int player) { int[] hand = new int[players[player].cards.size()]; int i = 0; for (int card : players[player].cards) { hand[i++] = card % 13; } int matchCount = 0; for (int j = 0; j < hand.length; j++) { for (int k = 0; k < hand.length; k++) { if (j != k) { if (hand[j] == hand[k]) { matchCount++; if (matchCount == 2) return hand[j]; } } } matchCount = 0; } return -1; }
6
private long computeFileSize(File file) { if (file.isFile()) { return file.length(); } else if (file.isDirectory()) { File subs[] = file.listFiles(); long s = 0; for (int i = 0; i < subs.length; i++) { s += computeFileSize(subs[i]); } return s; } else { return 0; //links and things are not stored, so they are 0. } }
3
public void create(Lenguaje lenguaje) throws PreexistingEntityException, RollbackFailureException, Exception { if (lenguaje.getEmpleadoCollection() == null) { lenguaje.setEmpleadoCollection(new ArrayList<Empleado>()); } EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Collection<Empleado> attachedEmpleadoCollection = new ArrayList<Empleado>(); for (Empleado empleadoCollectionEmpleadoToAttach : lenguaje.getEmpleadoCollection()) { empleadoCollectionEmpleadoToAttach = em.getReference(empleadoCollectionEmpleadoToAttach.getClass(), empleadoCollectionEmpleadoToAttach.getEmpNoEmpleado()); attachedEmpleadoCollection.add(empleadoCollectionEmpleadoToAttach); } lenguaje.setEmpleadoCollection(attachedEmpleadoCollection); em.persist(lenguaje); for (Empleado empleadoCollectionEmpleado : lenguaje.getEmpleadoCollection()) { empleadoCollectionEmpleado.getLenguajeCollection().add(lenguaje); empleadoCollectionEmpleado = em.merge(empleadoCollectionEmpleado); } em.getTransaction().commit(); } catch (Exception ex) { try { em.getTransaction().rollback(); } catch (Exception re) { throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); } if (findLenguaje(lenguaje.getLenLenguaje()) != null) { throw new PreexistingEntityException("Lenguaje " + lenguaje + " already exists.", ex); } throw ex; } finally { if (em != null) { em.close(); } } }
7
public SymbolDigraph(String filename, String delimiter) { st = new ST<String, Integer>(); // First pass builds the index by reading strings to associate // distinct strings with an index In in = new In(filename); while (in.hasNextLine()) { String[] a = in.readLine().split(delimiter); for (int i = 0; i < a.length; i++) { if (!st.contains(a[i])) st.put(a[i], st.size()); } } // inverted index to get string keys in an aray keys = new String[st.size()]; for (String name : st.keys()) { keys[st.get(name)] = name; } // second pass builds the digraph by connecting first vertex on each // line to all others G = new Digraph(st.size()); in = new In(filename); while (in.hasNextLine()) { String[] a = in.readLine().split(delimiter); int v = st.get(a[0]); for (int i = 1; i < a.length; i++) { int w = st.get(a[i]); G.addEdge(v, w); } } }
6
private void setLookAndFeel(int theme) { switch (theme) { case 0: try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception exc) { System.err.println("ERROR - Themes: Metal (default) theme can't be set. " + exc.getMessage()); } break; case 1: try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception exc) { System.err.println("ERROR - Themes: Motif (system's look) theme can't be set. " + exc.getMessage()); } break; case 2: try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (Exception exc) { System.err.println("ERROR - Themes: Nimbus theme can't be set. " + exc.getMessage()); } break; } }
6
public static void javaOutputStartupUnitsToFile(StringHashTable startupht, Cons keylist) { { String classoutputfile = null; Cons startupfunctions = null; { Object old$CurrentStream$000 = Stella.$CURRENT_STREAM$.get(); try { Native.setSpecial(Stella.$CURRENT_STREAM$, null); { StringWrapper classname = null; Cons iter000 = keylist; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { classname = ((StringWrapper)(iter000.value)); startupfunctions = ((Cons)(startupht.lookup(classname.wrapperValue))); if ((startupfunctions != null) && (!(startupfunctions == null))) { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, ((TranslationUnit)(startupfunctions.value)).homeModule()); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); classoutputfile = Stella.string_javaMakeCodeOutputFileName(classname.wrapperValue, false); { OutputFileStream classoutputstream = null; try { classoutputstream = Stella.openOutputFile(classoutputfile, Stella.NIL); Native.setSpecial(Stella.$CURRENT_STREAM$, classoutputstream); if (((Integer)(Stella.$TRANSLATIONVERBOSITYLEVEL$.get())).intValue() >= 1) { System.out.println("Writing `" + classoutputfile + "'..."); } OutputStream.javaOutputFileHeader(classoutputstream, Stella.string_javaMakeCodeOutputFileName(classname.wrapperValue, true)); ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.println("public class " + classname.wrapperValue + " {"); Stella.javaBumpIndent(); { TranslationUnit function = null; Cons iter001 = startupfunctions; for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) { function = ((TranslationUnit)(iter001.value)); Cons.javaOutputMethod(TranslationUnit.javaTranslateUnit(function).rest); function.translation = null; function.codeRegister = null; } } Stella.javaUnbumpIndent(); ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.println("}"); } finally { if (classoutputstream != null) { classoutputstream.free(); } } } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } } } } } finally { Stella.$CURRENT_STREAM$.set(old$CurrentStream$000); } } } }
6
public int stringY(String str) { if (str == null || str.length() == 0) return 0; int y = 0; int length = str.length(); for (int i = 0; i != length; ++i) { int y0 = charY(str.charAt(i)); if (y > y0) y = y0; } return y; }
4
@Override public void setType(int id, String type) { try { connection = getConnection(); ptmt = connection.prepareStatement("UPDATE User_types SET type=? WHERE id_user=?;"); ptmt.setInt(2, id); ptmt.setString(1, type); ptmt.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(UserTypesDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ptmt != null) { ptmt.close(); } if (connection != null) { connection.close(); } if (resultSet != null) { resultSet.close(); } } catch (SQLException ex) { Logger.getLogger(UserTypesDAO.class.getName()).log(Level.SEVERE, null, ex); } } }
5
public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof TOObjectPropsId)) return false; TOObjectPropsId castOther = (TOObjectPropsId) other; return (this.getObjectPropsId() == castOther.getObjectPropsId()) && (this.getObjectId() == castOther.getObjectId()) && (this.getPropId() == castOther.getPropId()); }
5
public String bubbleSort(String a) { char[] arr = a.toCharArray(); for (int i = arr.length - 1; i > 0; i--) { for (int j = 1; j <= i; j++) { // notice if (arr[j - 1] > arr[j]) { swap(arr, j, j - 1); } } } return new String(arr); }
3
@Override public void run() { try { DataInputStream dis = new DataInputStream(connection.getInputStream()); DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); PacketInHandshake handshake = PacketInHandshake.read(dis); if (handshake == null) { return; } if (handshake.getState() == 1) { PacketInRequest request = PacketInRequest.read(dis); if (!request.getSuccess()) { return; } PacketOutResponse response = new PacketOutResponse(Config.versionName, Config.versionProtocol, Config.playersMax, Config.description); PacketOutResponse.write(dos, response); PacketInPing ping = PacketInPing.read(dis); PacketOutPing pingOut = new PacketOutPing(ping.getPing()); PacketOutPing.write(dos, pingOut); MaintenanceServer.println("Ping complete to " + connection.getInetAddress().getHostAddress() + ":" + connection.getPort() + "!"); } else if (handshake.getState() == 2) { PacketOutDisconnect disconnect = new PacketOutDisconnect(Config.disconnectMessage); PacketOutDisconnect.write(dos, disconnect); MaintenanceServer.println("Client attempted to connect from " + connection.getInetAddress().getHostAddress() + ":" + connection.getPort() + "." + System.lineSeparator() + "Sent disconnect message."); } else { MaintenanceServer.println("There was an unknown handshake form " + connection.getInetAddress().getHostAddress() + ":" + connection.getPort() + " (State " + handshake.getState() + ") ?!"); } } catch (Exception e) { MaintenanceServer.printException(e); MaintenanceServer.println("There was an error! Oh no!"); } finally { try { connection.close(); } catch (Exception e) { MaintenanceServer.printException(e); } } }
6
public void testKeySetAdds() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap<String> map = new TIntObjectHashMap<String>(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntSet keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); try { keyset.add( 1138 ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { Set<Integer> test = new HashSet<Integer>(); test.add( Integer.valueOf( 1138 ) ); keyset.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { TIntSet test = new TIntHashSet(); test.add( 1138 ); keyset.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { int[] test = { 1138 }; keyset.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } }
6
private static String generateNDigitStringNumber(Integer n) { StringBuilder sb = new StringBuilder(n); sb.append('1'); // 1 is already given so lets minus n by 1 n -= 1; for (int i = 0; i < n; i++) { sb.append('0'); } return sb.toString(); }
1
public static void onVillageChanged(String newVillage) { Coord coords = villageCoords.get(newVillage); if (coords == null) return; if (!newVillage.equals(lastVillage)) { if (newVillage.length() == 0) { lastVillage = null; // Leaving } else { lastVillage = newVillage; // Entering if (!JSBotUtils.inTheHouse()) { myLastGlobalCoord = coords; myLastGameCoord = JSBotUtils.MyCoord(); if (UI.instance.slenhud != null) UI.instance.slenhud.error("Global coords handled: " + newVillage + myLastGlobalCoord.div(100).toString()); } } } }
5
public CardEditorScreen(Card card) { this.card = card; this.setLayout(new BorderLayout()); // URL fontURL; try { // fontURL = new URL("http://www.webpagepublicity.com/free-fonts/a/Airacobra%20Condensed.ttf"); font = Font.createFont(Font.TRUETYPE_FONT, new File("Amigo.ttf")); titleFont = Font.createFont(Font.TRUETYPE_FONT, new File("MORPHEUS.TTF")); titleFont = titleFont.deriveFont(30.0f); // font = Font.createFont(Font.TRUETYPE_FONT, fontURL.openStream()); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(font); font = font.deriveFont(20.0f); name.addActionListener(this); save.addActionListener(this); } catch (Exception e) { e.printStackTrace(); } toolBar.setBackground(Color.WHITE); TitledBorder toolBarBorder = BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Toolbar"); toolBarBorder.setTitleJustification(TitledBorder.RIGHT); toolBar.setBorder(toolBarBorder); toolBar.setLayout(new GridLayout(2, 5)); switch(card.getType()) { case POWER: setUpPowerEditor(); break; case FEAT: break; case ITEM: break; } JPanel center = new JPanel(); canvas = new CardPanel(); center.add(canvas, BorderLayout.CENTER); this.add(toolBar, BorderLayout.NORTH); this.add(center, BorderLayout.CENTER); }
4
@Override public String stateStringSubject(Rider R) { switch(rideBasis) { case Rideable.RIDEABLE_AIR: case Rideable.RIDEABLE_LAND: case Rideable.RIDEABLE_WATER: case Rideable.RIDEABLE_WAGON: return "being ridden by"; case Rideable.RIDEABLE_TABLE: case Rideable.RIDEABLE_SIT: case Rideable.RIDEABLE_SLEEP: case Rideable.RIDEABLE_ENTERIN: case Rideable.RIDEABLE_LADDER: return "occupied by"; } return ""; }
9
public String getSongElementTypeAsString() { String result = "["; switch (type) { case BREAK: result += "BREAK"; break; case BRIDGE: result += "BRIDGE"; break; case CHORUS: result += "CHORUS"; break; case INTRO: result += "INTRO"; break; case OUTRO: result += "OUTRO"; break; case VERSE: result += "VERSE"; } result += "]"; return result; }
6
public int nthSuperUglyNumber(int n, int[] primes) { if(n==1) return 1; int[]ugly=new int[n]; ugly[0]=1; int[] index=new int[primes.length]; Arrays.fill(index,0); for (int pointer=1; pointer<n;pointer++){ int nextValue=Integer.MAX_VALUE,nextIndex=0; for(int i=0;i<index.length;++i){ while (ugly[index[i]]*primes[i]<=ugly[pointer-1]) index[i]++; if(ugly[index[i]]*primes[i] < nextValue){ nextValue=ugly[index[i]]*primes[i]; nextIndex=i; } } ugly[pointer]=nextValue; index[nextIndex]++; } return ugly[n-1]; }
5
public static ArrayList<UserAccount> readUserAccounts(String filename) { File file = new File(filename); if (file.exists()) { ObjectInputStream ois = null; try { // // Read the previously stored SecretKey. // SecretKey key = (SecretKey) readFromFile(KEY_FILE.toString()); ArrayList<UserAccount> userList = new ArrayList<UserAccount>(); ois = new ObjectInputStream(new FileInputStream(filename)); UserAccount tempUser = null; SealedObject tempSealed = null; boolean eof = false; while (!eof) { tempSealed = (SealedObject) ois.readObject(); // // Preparing Cipher object from decryption. // String algorithmName = tempSealed.getAlgorithm(); Cipher objCipher = Cipher.getInstance(algorithmName); objCipher.init(Cipher.DECRYPT_MODE, key); tempUser = (UserAccount) tempSealed.getObject(objCipher); if (tempUser == null) { eof = true; break; } userList.add(tempUser); } return userList; } catch (EOFException e) { } catch (Exception e) { e.printStackTrace(); } finally { try { if (ois != null) { ois.close(); } } catch (IOException e) { e.printStackTrace(); } } } return null; }
7
protected Field getField() { return field; }
0
public static Map<String, BufferedImage> getDataFromDirPath(String dirPath) { Map<String, BufferedImage> res = new HashMap<>(); File dir = new File(dirPath); if (dir.isDirectory()) { try { ImagesIterator imagesIterator = new ImagesIterator(dir); while (imagesIterator.hasNext()) { File imgFile = imagesIterator.next(); BufferedImage bufferedImage = ImageIO.read(imgFile); String filenameOfCurrentImage = imagesIterator.getFilenameOfCurrentImage(); StringTokenizer st = new StringTokenizer(filenameOfCurrentImage, "._"); res.put(st.nextToken(), bufferedImage); } } catch (IOException ex) { Logger.getLogger(ImagesLoader.class.getName()).log(Level.SEVERE, null, ex); } } return res; }
3
public static ArrayList<String> winner(ArrayList<String> playerOne, ArrayList<String> playerTwo) throws NoSuchStrategyError { if(verifyPlay(playerOne.get(1)) || verifyPlay(playerTwo.get(1))) throw new NoSuchStrategyError("Strategy must be one of R,P,S"); if(playerOne.get(1)==playerTwo.get(1)) return playerOne; if (playerOne.get(1)=="S"){ if (playerTwo.get(1)=="P") return playerOne; else return playerTwo; } else if (playerOne.get(1)=="P"){ if (playerTwo.get(1)=="R") return playerOne; else return playerTwo; } else{ if (playerTwo.get(1)=="S") return playerOne; else return playerTwo; } }
8
@Override public void stateChanged(ChangeEvent e) { switch(((JTabbedPane)e.getSource()).getSelectedIndex()){ case MY_HISTORY: if(!changed[MY_HISTORY]){ changed[MY_HISTORY] = true; } break; case MY_STEPS: if(!changed[MY_STEPS]){ changed[MY_STEPS] = true; steps.renewChart(); } break; case MY_ACHIEVEMENT: if(!changed[MY_ACHIEVEMENT]){ changed[MY_ACHIEVEMENT] = true; achievement.update(); } break; case OUR_DIFFERENCE: if(difference.getOppID() == null) difference.askForUserID(); break; case SUBONLINE: submit.askForProID(); break; default: break; } }
9
private void skipDeletedPredecessors(Node<E> x) { whileActive: do { Node<E> prev = x.prev; // assert prev != null; // assert x != NEXT_TERMINATOR; // assert x != PREV_TERMINATOR; Node<E> p = prev; findActive: for (;;) { if (p.item != null) break findActive; Node<E> q = p.prev; if (q == null) { if (p.next == p) continue whileActive; break findActive; } else if (p == q) continue whileActive; else p = q; } // found active CAS target if (prev == p || x.casPrev(prev, p)) return; } while (x.item != null || x.next == null); }
9
@Override public Descriptor compile(SymbolTable syms) { Descriptor descr = null; String identName = ((IdentNode)ident).getIdentName(); if (type instanceof IdentNode) { descr = syms.descriptorFor(identName); } else if (type instanceof ArrayTypeNode || type instanceof RecordTypeNode) { descr = type.compile(syms); } else { throw new CompilerException("unsupported type: " + type); } syms.declareType(identName, descr); return descr; }
3
public void setFesIdPos(Integer fesIdPos) { this.fesIdPos = fesIdPos; }
0
private boolean outsideBorder(double lat, double lon) { return (Double.compare(lat, MAX_LAT) > 0 || Double.compare(lat, MIN_LAT) < 0 || Double.compare(lon, MAX_LON) > 0 || Double.compare(lon, MIN_LON) < 0); }
3
public Role getRole() { return this.role; }
0
@Override public Double getElement(int row, int column) { int index = 0; boolean elementIsZero = true; if (row == column) { return diag.get(row); } else { ArrayList<String> rowInColIndexes = colIndexes.get(column); if (rowIndexes != null && colIndexes != null && rowInColIndexes != null) { for (String line : colIndexes.get(column)) { if (line.endsWith("|" + row)) { index = Integer.parseInt(line.split("\\|")[0]); elementIsZero = false; break; } } if (!elementIsZero) { return values.get(index); } else { return 0.0; } } else { return 0.0; } } }
7
public Lemonade() { this.setName("Lemonade"); this.setPrice(new BigDecimal(15)); }
0
public DnDTabbedPane() { super(); final DragSourceListener dsl = new DragSourceListener() { @Override public void dragEnter(DragSourceDragEvent e) { e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop); } @Override public void dragExit(DragSourceEvent e) { e.getDragSourceContext() .setCursor(DragSource.DefaultMoveNoDrop); lineRect.setRect(0, 0, 0, 0); glassPane.setPoint(new Point(-1000, -1000)); glassPane.repaint(); } @Override public void dragOver(DragSourceDragEvent e) { Point glassPt = e.getLocation(); SwingUtilities.convertPointFromScreen(glassPt, glassPane); int targetIdx = getTargetTabIndex(glassPt); // if(getTabAreaBounds().contains(tabPt) && targetIdx>=0 && if (getTabAreaBounds().contains(glassPt) && targetIdx >= 0 && targetIdx != dragTabIndex && targetIdx != dragTabIndex + 1) { e.getDragSourceContext().setCursor( DragSource.DefaultMoveDrop); glassPane.setCursor(DragSource.DefaultMoveDrop); } else { e.getDragSourceContext().setCursor( DragSource.DefaultMoveNoDrop); glassPane.setCursor(DragSource.DefaultMoveNoDrop); } } @Override public void dragDropEnd(DragSourceDropEvent e) { lineRect.setRect(0, 0, 0, 0); dragTabIndex = -1; glassPane.setVisible(false); if (hasGhost()) { glassPane.setVisible(false); glassPane.setImage(null); } } @Override public void dropActionChanged(DragSourceDragEvent e) { } }; final Transferable t = new Transferable() { private final DataFlavor FLAVOR = new DataFlavor( DataFlavor.javaJVMLocalObjectMimeType, NAME); @Override public Object getTransferData(DataFlavor flavor) { return DnDTabbedPane.this; } @Override public DataFlavor[] getTransferDataFlavors() { DataFlavor[] f = new DataFlavor[1]; f[0] = this.FLAVOR; return f; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor.getHumanPresentableName().equals(NAME); } }; final DragGestureListener dgl = new DragGestureListener() { @Override public void dragGestureRecognized(DragGestureEvent e) { if (getTabCount() <= 1) return; Point tabPt = e.getDragOrigin(); dragTabIndex = indexAtLocation(tabPt.x, tabPt.y); // "disabled tab problem". if (dragTabIndex < 0 || !isEnabledAt(dragTabIndex)) return; initGlassPane(e.getComponent(), e.getDragOrigin()); try { e.startDrag(DragSource.DefaultMoveDrop, t, dsl); } catch (InvalidDnDOperationException idoe) { idoe.printStackTrace(); } } }; new DropTarget(glassPane, DnDConstants.ACTION_COPY_OR_MOVE, new CDropTargetListener(), true); new DragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dgl); }
9
public List<List<Integer>> zigzagLevelOrderDeque(TreeNode root) { if (root == null) { return null; } List<List<Integer>> result = new ArrayList<List<Integer>>(); Deque<TreeNode> deque = new LinkedList<TreeNode>(); deque.add(null); deque.add(root); while (deque.size() > 1) { TreeNode node = deque.poll(); if (node == null && deque.getFirst() == null) { break; } else if (node == null) { result.add(new ArrayList<Integer>()); deque.add(null); continue; } result.get(result.size() - 1).add(node.val); if (node.left != null) { deque.add(node.left); } if (node.right != null) { deque.add(node.right); } } return result; }
7
public static boolean isStandardErrorParam(String accession) { return INTENSITY_STD_ERR_SUBSAMPLE1.getAccession().equals(accession) || INTENSITY_STD_ERR_SUBSAMPLE2.getAccession().equals(accession) || INTENSITY_STD_ERR_SUBSAMPLE3.getAccession().equals(accession) || INTENSITY_STD_ERR_SUBSAMPLE4.getAccession().equals(accession) || INTENSITY_STD_ERR_SUBSAMPLE5.getAccession().equals(accession) || INTENSITY_STD_ERR_SUBSAMPLE6.getAccession().equals(accession) || INTENSITY_STD_ERR_SUBSAMPLE7.getAccession().equals(accession) || INTENSITY_STD_ERR_SUBSAMPLE8.getAccession().equals(accession); }
7
FileVersion(final String version) { this.original = version; if (this.original == null) { this.major = null; this.minor = null; this.revision = null; this.type = null; this.build = null; return; } final String[] split = Pattern.compile("\\.|a|b|rc").split(this.original); this.major = Integer.parseInt(split[0]); this.minor = Integer.parseInt(split[1]); this.revision = Integer.parseInt(split[2]); final Matcher m = Pattern.compile("a|b|rc").matcher(this.original); this.type = (m.find() ? m.group(0) : null); this.build = (split.length >= 4 ? Integer.parseInt(split[3]) : null); }
3
public HBox getActionBox() { return actionBox; }
0
private static void copyFileFromFileSystem(String sourceFileName, File target) { try { File in = new File(sourceFileName); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(target).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, e); } catch (IOException e) { JOptionPane.showMessageDialog(null, e); } }
5
@Override public AUTOMATON initObj() { Class<AUTOMATON> classTypeDef = getClassTypeDef(); try { return classTypeDef.getConstructor(new Class[] { Class.forName("[C"), Integer.TYPE}).newInstance(new Object[] {alphabet, 2}); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
7
public static Node minimum(Node root){ while(root.left != null) root = root.left; return root; }
1
public TripDBPanel() { super (new BorderLayout ()); targetDay = Calendar.getInstance(); targetDay.setTime(new Date ()); targetDay.add(Calendar.DATE, 1); Calendar startDay = Calendar.getInstance(); startDay.setTime(MainWindow.setupData.getEventStartDate()); if (targetDay.before(startDay)) targetDay = startDay; // create table showing roster availability setBackground(Color.BLUE); headerPanel = new JPanel ( new BorderLayout ()); prevDayButton = new JButton (MainWindow.getImageIcon("toolbarButtonGraphics/navigation/Back16.gif")); nextDayButton = new JButton (MainWindow.getImageIcon("toolbarButtonGraphics/navigation/Forward16.gif")); prevDayButton.addActionListener(this); nextDayButton.addActionListener(this); JPanel datePickerPanel = new JPanel(); new JDateComponentFactory(); targetDayPicker = JDateComponentFactory.createJDatePicker(); targetDayPicker.setTextEditable(true); targetDayPicker.setShowYearButtons(true); targetDayPicker.getModel().addChangeListener(this); targetDayPicker.getModel().setDate( targetDay.get(Calendar.YEAR), targetDay.get(Calendar.MONTH), targetDay.get(Calendar.DATE)); targetDayPicker.getModel().setSelected(true); datePickerPanel.add(prevDayButton); datePickerPanel.add ((Component)targetDayPicker); datePickerPanel.add(nextDayButton); datePickerPanel.setBorder(BorderFactory.createLoweredBevelBorder()); headerPanel.add(datePickerPanel, BorderLayout.WEST); JPanel wwLevelPanel = new JPanel (); tfWW[0] = addStatisticsField(wwLevelPanel, "WW-I:"); tfWW[1] = addStatisticsField(wwLevelPanel, "WW-II:"); tfWW[2] = addStatisticsField(wwLevelPanel, "WW-III:"); tfWW[3] = addStatisticsField(wwLevelPanel, "WW-IV:"); tfWW[4] = addStatisticsField(wwLevelPanel, "WW-V:"); tfTotal = addStatisticsField(wwLevelPanel, "Total:"); headerPanel.add (wwLevelPanel, BorderLayout.CENTER); JPanel rosterPanel = new JPanel (); tfRoster = addStatisticsField(rosterPanel, "FL:"); headerPanel.add (rosterPanel, BorderLayout.EAST); headerPanel.setBackground(new Color (220, 220, 220)); tripListModel = new DefaultListModel<TripComponent>(); // create trip list in left panel tripList = new JList<TripComponent> (tripListModel); tripList.setCellRenderer(new TripListRenderer()); tripList.addListSelectionListener(this); tripList.setTransferHandler(new TripListTransferHandler(this)); // Create JTabbedPane object tabpanePlanningSteps = new JTabbedPane (JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT ); // create panel to select river information JPanel panelRivers = new JPanel ( new BorderLayout ()); panelRivers.setBackground(Color.BLUE); tabpanePlanningSteps.addTab("Fl\u00FCsse", panelRivers); riverListModel = new DefaultListModel<RiverComponent>(); // create trip list in left panel riverList = new JList<RiverComponent> (riverListModel); riverList.setCellRenderer(new RiverListRenderer()); panelRivers.add (new JScrollPane(riverList), BorderLayout.CENTER); riverList.setDragEnabled(true); riverList.setTransferHandler(new RiverListTransferHandler(this)); // create panel with trip details JPanel panelDetails = new JPanel ( new BorderLayout ()); panelDetails.setBackground(new Color (220, 220, 220)); tabpanePlanningSteps.addTab("Details", panelDetails); JPanel detailsGridPanel = new JPanel (new GridLayout (10,1)); detailsGroupNumber = new JLabel ("Gruppe "); detailsGridPanel.add (detailsGroupNumber); detailsRiverInfo = new JLabel ("Name km \u02AC"); detailsGridPanel.add (detailsRiverInfo); detailsTripFrom = new JLabel ("Von: "); detailsGridPanel.add (detailsTripFrom); detailsTripTo = new JLabel ("Nach: "); detailsGridPanel.add (detailsTripTo); detailsWwLevel = new JLabel ("WW Stufe: "); detailsGridPanel.add (detailsWwLevel); detailsDistanceToStart = new JLabel ("Anfahrt: 0km"); detailsGridPanel.add (detailsDistanceToStart); JPanel TripTypePanel = new JPanel (new FlowLayout (FlowLayout.LEADING)); detailsIsEducation = new JCheckBox ("Schulung"); detailsIsEducation.addActionListener(this); TripTypePanel.add (detailsIsEducation); detailsIsKidsTour = new JCheckBox ("Kids/Teenie-Tour"); detailsIsKidsTour.addActionListener(this); detailsIsKidsTour.setToolTipText("Autofahrer z�hlen nicht zur Gruppe dazu."); TripTypePanel.add(detailsIsKidsTour); detailsGridPanel.add(TripTypePanel); JPanel grPanel = new JPanel (new FlowLayout (FlowLayout.LEADING)); grPanel.add (new JLabel ("Gruppengr\u00f6\u00dfe:")); Integer groupSize[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}; detailsGroupSize = new JComboBox<Integer>(groupSize); grPanel.add (detailsGroupSize); detailsGroupSize.addActionListener(this); detailsGridPanel.add (grPanel); JPanel drPanel = new JPanel (new FlowLayout (FlowLayout.LEADING)); drPanel.add(new JLabel ("Fahrer:")); Integer drivers[] = {0, 1, 2, 3}; detailsDriverCount = new JComboBox<Integer>(drivers); detailsDriverCount.addActionListener(this); drPanel.add (detailsDriverCount); detailsGridPanel.add (drPanel); // create panel to select roster information JPanel panelRosters = new JPanel ( new BorderLayout ()); panelRosters.setBackground(Color.YELLOW); tabpanePlanningSteps.addTab("Fahrtenleiter", panelRosters); rosterListModel = new DefaultListModel<RosterComponent>(); // create trip list in left panel rosterList = new JList<RosterComponent> (rosterListModel); rosterList.setCellRenderer(new RosterListRenderer(targetDay)); updateRosterList (); panelRosters.add (new JScrollPane(rosterList), BorderLayout.CENTER); rosterList.setDragEnabled(true); rosterList.setTransferHandler(new RosterListTransferHandler(this)); //Add the start time spinner. JPanel timePanel = new JPanel (new FlowLayout(FlowLayout.LEADING)); timePanel.add(new JLabel ("Startzeit: ")); SimpleDateFormat sdfWithDefaultYear = new SimpleDateFormat("HH:mm"); Date initDate; try { initDate = sdfWithDefaultYear.parse("10:00"); } catch (ParseException e) { initDate = new Date(); } SpinnerModel dateModel = new SpinnerDateModel(initDate, null, null, Calendar.MINUTE);//ignored for user input detailsStartTimeSpinner = new JSpinner (dateModel); detailsStartTimeSpinner.setEditor(new JSpinner.DateEditor(detailsStartTimeSpinner, "HH:mm")); detailsStartTimeSpinner.addChangeListener(this); timePanel.add(detailsStartTimeSpinner); Calendar cal = Calendar.getInstance(); cal.set (Calendar.HOUR_OF_DAY, startTimeButtonStartHour); cal.set (Calendar.MINUTE, startTimeButtonStartMinute); for (int i = 0; i < startTimeButtonsCount; i++) { JButton tb = new JButton (new SimpleDateFormat("HH:mm").format(cal.getTime())); tb.addActionListener(this); tb.setActionCommand("SetTime"); timePanel.add (tb); cal.add(Calendar.MINUTE, 15); } detailsGridPanel.add (timePanel); panelDetails.add (detailsGridPanel, BorderLayout.NORTH); JPanel detailsBottomPanel = new JPanel (new BorderLayout()); JPanel detailsRosterPanel = new JPanel (new BorderLayout()); detailsRosterPanel.add(new JLabel ("Fahrtenleiter"), BorderLayout.NORTH); detailsRosterListModel = new DefaultListModel<RosterComponent> (); detailsRosterList = new JList<RosterComponent> (detailsRosterListModel); detailsRosterList.setPreferredSize(new Dimension (200, 20)); detailsRosterList.setVisibleRowCount(1); detailsRosterList.setLayoutOrientation(JList.HORIZONTAL_WRAP); detailsRosterPanel.add (detailsRosterList, BorderLayout.CENTER); detailsRosterRemoveBtn = new JButton ("Entfernen"); detailsRosterRemoveBtn.addActionListener(this); JPanel rbPanel = new JPanel (new FlowLayout (FlowLayout.LEADING)); rbPanel.add (detailsRosterRemoveBtn); detailsRosterRemoveBtn.setEnabled(false); detailsRosterPanel.add (rbPanel, BorderLayout.SOUTH); detailsBottomPanel.add (detailsRosterPanel, BorderLayout.NORTH); JPanel detailsCommentPanel = new JPanel (new BorderLayout()); detailsCommentPanel.add(new JLabel ("Bemerkung"), BorderLayout.NORTH); detailsCommentText = new JTextArea (); detailsCommentText.getDocument().addDocumentListener(this); detailsCommentPanel.add(detailsCommentText, BorderLayout.CENTER); detailsBottomPanel.add (detailsCommentPanel, BorderLayout.CENTER); panelDetails.add (detailsBottomPanel, BorderLayout.CENTER); // create panel with trip start times panelStartTime = new JPanel ( new FlowLayout (FlowLayout.LEADING)); panelStartTime.setBackground(new Color (220, 220, 220)); JScrollPane startTimesScrollPane = new JScrollPane (panelStartTime); tabpanePlanningSteps.addTab("Zeiten", startTimesScrollPane); // create panel with print previews panelPreview = new PrintOutPanel (targetDay); panelPreview.setBackground(new Color (220, 220, 220)); tabpanePlanningSteps.addTab("Drucken", panelPreview); /* * Add center panel with buttons */ JPanel btnPanel = new JPanel ( ); btnPanel.setLayout( new GridLayout (9,1) ); btnAdd = new JButton ("+ Hinzu"); btnPanel.add(btnAdd); Dimension minSize = new Dimension(5, 10); Dimension prefSize = new Dimension(5, 10); Dimension maxSize = new Dimension(5, 20); btnUpdate = new JButton ("\u23CE Ersetzen"); btnPanel.add(btnUpdate); btnCopy = new JButton ("Kopie"); btnCopy.setEnabled(false); btnPanel.add(btnCopy); btnPanel.add(new Box.Filler(minSize, prefSize, maxSize)); btnUp = new JButton ("\u2206 Auf"); btnUp.setEnabled(false); btnPanel.add (btnUp); btnDown = new JButton ("\u2207 Ab"); btnDown.setEnabled(false); btnPanel.add (btnDown); btnPanel.add(new Box.Filler(minSize, prefSize, maxSize)); btnDelete = new JButton ("\u2297 L\u00F6schen"); btnDelete.setEnabled(false); btnPanel.add(btnDelete); JPanel btnWrapper = new JPanel (new GridBagLayout()); JPanel btnAreaPanel = new JPanel (new BorderLayout ()); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = 1; c.gridx = 0; c.gridy = 1; c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.CENTER; btnWrapper.add(btnPanel, c); btnAreaPanel.add(btnWrapper, BorderLayout.CENTER); showAllRivers = new JCheckBox("Alle Flüsse"); showAllRivers.setSelected(true); showAllRivers.addActionListener(this); c.gridy = 0; c.fill = GridBagConstraints.VERTICAL; JPanel showAllRiversPanel = new JPanel (new BorderLayout ()); showAllRiversPanel.add (showAllRivers, BorderLayout.PAGE_START); c.anchor = GridBagConstraints.PAGE_START; // btnAreaPanel.add (showAllRiversPanel, c); btnAreaPanel.add (showAllRiversPanel, BorderLayout.PAGE_START); btnAdd.addActionListener(this); btnAdd.setActionCommand("Add"); btnUpdate.addActionListener(this); btnUpdate.setActionCommand("Update"); btnDelete.addActionListener(this); btnDelete.setActionCommand("Delete"); btnUp.addActionListener(this); btnUp.setActionCommand("Up"); btnDown.addActionListener(this); btnDown.setActionCommand("Down"); btnCopy.addActionListener(this); btnCopy.setActionCommand("Copy"); // left panel for trip list and buttons leftPanel = new JPanel (new BorderLayout ()); leftPanel.add(new JScrollPane(tripList), BorderLayout.CENTER); leftPanel.add(btnAreaPanel, BorderLayout.EAST); // split pane in the center of the layout JSplitPane sp = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, leftPanel, tabpanePlanningSteps); add (headerPanel, BorderLayout.NORTH); c.gridwidth = 1; c.gridx = 0; c.gridy = 1; c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.WEST; add (sp, BorderLayout.CENTER); //Provide minimum sizes for the two components in the split pane leftPanel.setMinimumSize(new Dimension(350, 200)); tabpanePlanningSteps.setMinimumSize(new Dimension(200, 200)); tabpanePlanningSteps.addChangeListener(this); }
3
public static void main(String[] args) { FileIO loader = new FileIO(); BoardState startState=null, endState = null; if (args.length !=3) { System.out.println("Error: Invalid command line arguments." + newLine +"Arguments should be in the form of " + "< initial puzzle state file > < goal puzzle state file > < mode >"); System.exit(1); } try { startState = loader.loadPuzzle(new File(args[0])); endState = loader.loadPuzzle(new File(args[1])); } catch (FileNotFoundException e) { System.out.println("Error: File Not Found"); System.exit(1); } if (args[2].equals("bfs")) { BFS searcher = new BFS(startState, endState); searcher.solve(); } else if (args[2].equals("dfs")) { DFS searcher = new DFS(startState, endState); searcher.solve(); } else if (args[2].equals("astar1")) { AStar searcher = new AStar(startState, endState, new Heuristics((byte)0,endState)); searcher.solve(); } else if (args[2].equals("astar2")) { AStar searcher = new AStar(startState, endState, new Heuristics((byte)1,endState)); searcher.solve(); } else { System.out.println("Error: Invalid mode argument, acceptable arguments are 'bfs', 'dfs', 'astar1', or 'astar2'"); System.exit(1); } }
6
void fixNeighbors(NeighborFind<T> neighborStrategy, ProxyProvider<T> proxyProvider) { Collection<T> realNeighbors = neighborStrategy.getNeighborsFor(field); this.detailedCombinations = new double[realNeighbors.size() + 1]; for (T neighbor : realNeighbors) { if (neighborStrategy.isFoundAndisMine(neighbor)) { this.found++; continue; // A found mine is not, and should not be, in a fieldproxy } FieldProxy<T> proxy = proxyProvider.getProxyFor(neighbor); if (proxy == null) { continue; } FieldGroup<T> neighborGroup = proxy.group; if (neighborGroup != null) { // Ignore zero-probability neighborGroups if (neighborGroup.getProbability() == 0) { continue; } // Increase the number of neighbors Integer currentNeighborAmount = neighbors.get(neighborGroup); if (currentNeighborAmount == null) { neighbors.put(neighborGroup, 1); } else neighbors.put(neighborGroup, currentNeighborAmount + 1); } } }
6
public MediaWiki.InterwikiPrefixes getInterwikiPrefixes() throws IOException { preferenceLock.readLock().lock(); try { MediaWiki.InterwikiPrefixes result; if ((interwikiPrefixCache != null) && ((result = interwikiPrefixCache.get()) != null)) return result; } finally { preferenceLock.readLock().unlock(); } // Not cached. Get, cache and return the result now. final Map<String, String> getParams = paramValuesToMap("action", "query", "format", "xml", "meta", "siteinfo", "siprop", "interwikimap"); final String url = createApiGetUrl(getParams); final Map<String, Boolean> areLocal = new HashMap<String, Boolean>(); final Map<String, String> urlPatterns = new HashMap<String, String>(); final Map<String, String> languages = new HashMap<String, String>(); networkLock.lock(); try { final InputStream in = get(url); final Document xml = parse(in); // no checkError: no errors declared for this action final NodeList interwikiMapTags = xml.getElementsByTagName("interwikimap"); if (interwikiMapTags.getLength() >= 1) { final Element interwikiMapTag = (Element) interwikiMapTags.item(0); final NodeList iwTags = interwikiMapTag.getElementsByTagName("iw"); for (int i = 0; i < iwTags.getLength(); i++) { final Element iwTag = (Element) iwTags.item(i); final String name = iwTag.getAttribute("prefix"); urlPatterns.put(name, iwTag.getAttribute("url")); if (iwTag.hasAttribute("language")) { languages.put(name, iwTag.getAttribute("language")); } areLocal.put(name, iwTag.hasAttribute("local")); } } final Map<String, MediaWiki.InterwikiPrefix> interwikiPrefixes = new TreeMap<String, InterwikiPrefix>(); for (final String name : urlPatterns.keySet()) { interwikiPrefixes.put(name, new MediaWiki.InterwikiPrefix(name, languages.get(name), urlPatterns.get(name), areLocal.get(name))); } final MediaWiki.InterwikiPrefixes result = new MediaWiki.InterwikiPrefixes(interwikiPrefixes); preferenceLock.writeLock().lock(); try { interwikiPrefixCache = new SoftReference<MediaWiki.InterwikiPrefixes>(result); } finally { preferenceLock.writeLock().unlock(); } return result; } finally { networkLock.unlock(); } }
6
public void setFrozen(Configuration configuration) { ConfigurationButton button = (ConfigurationButton) configurationToButtonMap .get(configuration); if (button == null) return; if (button.state == ConfigurationButton.NORMAL) button.setState(ConfigurationButton.FREEZE); button.doClick(); }
2
@Override public void buildFloralComposition(String fileName) throws DAOException { Document doc = null; try { doc = documentBuilder.parse(fileName); Element root = doc.getDocumentElement(); NodeList cutFlowerList = root.getElementsByTagName(TagConstants.CUT_FLOWER_TAG); for (int i = 0; i < cutFlowerList.getLength(); i++) { Element cutFlowerElement = (Element) cutFlowerList.item(i); CutFlower cutFlower = buildCutFlower(cutFlowerElement); floralComposition.addFlower(cutFlower); } NodeList naturalFlowerList = root.getElementsByTagName(TagConstants.NATURAL_FLOWER_TAG); for (int i = 0; i < naturalFlowerList.getLength(); i++) { Element naturalFlowerElement = (Element) naturalFlowerList.item(i); NaturalFlower naturalFlower = buildNaturalFlower(naturalFlowerElement); floralComposition.addFlower(naturalFlower); } NodeList artificialFlowerList = root.getElementsByTagName(TagConstants.ARTIFICIAL_FLOWER_TAG); for (int i = 0; i < artificialFlowerList.getLength(); i++) { Element artificialFlowerElement = (Element) artificialFlowerList.item(i); ArtificialFlower artificialFlower = buildArtificialFlower(artificialFlowerElement); floralComposition.addFlower(artificialFlower); } NodeList flowerBasketList = root.getElementsByTagName(TagConstants.FLOWER_BASKET_TAG); if (flowerBasketList.getLength() > 0) { Element flowerBasketElement = (Element) flowerBasketList.item(0); FlowerBasket flowerBasket = buildFlowerBasket(flowerBasketElement); floralComposition.setFlowerPackaging(flowerBasket); } else { NodeList packagingPaperList = root.getElementsByTagName(TagConstants.PACKAGING_PAPER_TAG); if (packagingPaperList.getLength() > 0) { Element packagingPaperElement = (Element) packagingPaperList.item(0); PackagingPaper packagingPaper = buildPackagingPaper(packagingPaperElement); floralComposition.setFlowerPackaging(packagingPaper); } } } catch (SAXException e) { throw new DAOException("Parsing failure. " + e.getMessage(), e); } catch (IOException e) { throw new DAOException("File or I/O error. " + e.getMessage(), e); } }
7
public static void main(String[] args) throws MalformedURLException { OpenCVImageDecoder imageDecoder = new OpenCVImageDecoder(); String searchString = null; URL url = null; WebPicture picture = null; ////////////////////////////////// // BEGIN Test 1: lion on lion picture ////////////////////////////////// searchString = "lion"; url = new URL("http://gowild.wwf.org.uk/wp-content/uploads/factfiles_lion_01.jpg"); picture = new WebPicture(url); try { System.out.println("[IMAGE_DECODER] Search for: " + searchString + " in " + url.toString()); System.out.println("[IMAGE_DECODER] Found enaugh matches: " + imageDecoder.foundObjectInImage(picture, searchString)); } catch(IOException e) { System.out.println("[IMAGE_DECODER] Source imgae cant be readed from the internet."); throw new IllegalArgumentException("[IMAGE_DECODER] Source imgae cant be readed from the internet."); } System.out.println(); ////////////////////////////////// // END Test 1: lion on lion picture ////////////////////////////////// ////////////////////////////////// // BEGIN Test 2: lena on car picture ////////////////////////////////// searchString = "lena"; url = new URL("http://www.sixt.com/uploads/pics/mercedes_slk-sixt_rent_a_car.png"); picture = new WebPicture(url); try { System.out.println("[IMAGE_DECODER] Search for: " + searchString + " in " + url.toString()); System.out.println("[IMAGE_DECODER] Found enaugh matches: " + imageDecoder.foundObjectInImage(picture, searchString)); } catch(IOException e) { System.out.println("[IMAGE_DECODER] Source imgae cant be readed from the internet."); throw new IllegalArgumentException("[IMAGE_DECODER] Source imgae cant be readed from the internet."); } System.out.println(); ////////////////////////////////// // END Test 2: lena on car picture ////////////////////////////////// ////////////////////////////////// // BEGIN Test 3: lena on lena picture ////////////////////////////////// searchString = "lena"; url = new URL("http://www.cs.cmu.edu/~chuck/lennapg/len_std.jpg"); picture = new WebPicture(url); try { System.out.println("[IMAGE_DECODER] Search for: " + searchString + " in " + url.toString()); System.out.println("[IMAGE_DECODER] Found enaugh matches: " + imageDecoder.foundObjectInImage(picture, searchString)); } catch(IOException e) { System.out.println("[IMAGE_DECODER] Source imgae cant be readed from the internet."); throw new IllegalArgumentException("[IMAGE_DECODER] Source imgae cant be readed from the internet."); } System.out.println(); ////////////////////////////////// // END Test 3: lena on lena picture ////////////////////////////////// ////////////////////////////////// // BEGIN Test 4: elephant on lena picture ////////////////////////////////// searchString = "elephant"; url = new URL("http://www.cs.cmu.edu/~chuck/lennapg/len_std.jpg"); picture = new WebPicture(url); try { System.out.println("[IMAGE_DECODER] Search for: " + searchString + " in " + url.toString()); System.out.println("[IMAGE_DECODER] Found enaugh matches: " + imageDecoder.foundObjectInImage(picture, searchString)); } catch(IOException e) { System.out.println("[IMAGE_DECODER] Source imgae cant be readed from the internet."); throw new IllegalArgumentException("[IMAGE_DECODER] Source imgae cant be readed from the internet."); } ////////////////////////////////// // END Test 4: elephant on lena picture ////////////////////////////////// }
4
public void replaceBytes(int offset, int len, byte[] bytes) { byte[] removed = null; if (len>0) { removed = new byte[len]; doc.remove(offset, len, removed); } byte[] added = null; if (bytes!=null && bytes.length>0) { doc.insertBytes(offset, bytes); added = (byte[])bytes.clone(); } if (removed!=null || added!=null) { undoManager.addEdit( new BytesReplacedUndoableEdit(offset, removed, added)); fireTableDataChanged(); int addCount = added==null ? 0 : added.length; int remCount = removed==null ? 0 : removed.length; editor.fireHexEditorEvent(offset, addCount, remCount); } }
7
public void buttonP() { if(bNew.contains(Main.mse)) { Main.soundPlayer.menuKlick(); Main.Screen = "modeSelection"; Main.renderer.startRenderer = null; } else if(bLoad.contains(Main.mse)) { try { Main.soundPlayer.menuKlick(); JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new FileNameExtensionFilter("GameData [.dat]", "dat")); new File(Main.loc + "Saves/").mkdirs(); chooser.setCurrentDirectory(new File(Main.loc + "Saves/")); int returnVal = chooser.showOpenDialog(Main.main); if(returnVal == JFileChooser.APPROVE_OPTION) { Main.startGame(DataIO.load(chooser.getSelectedFile()), false); } } catch(Exception e){e.printStackTrace();} Main.renderer.startRenderer = null; } else if(bOptions.contains(Main.mse)) { Main.Screen = "options"; Main.renderer.startRenderer = null; } else if(bCredits.contains(Main.mse)) { Main.renderer.credits = new CreditsRenderer(); Main.soundPlayer.play("Sounds/Music/Music1.wav"); Main.Screen = "credits"; Main.renderer.startRenderer = null; } else if(bQuit.contains(Main.mse)) { // Main.main.close(); } }
7
private void insert(char[] a, int i, int minIndex) {// O(n)+O(n) if (minIndex > i) { char tmp = a[minIndex]; System.arraycopy(a, i, a, i + 1, minIndex - i); a[i] = tmp; } }
1
private void addValidators() { quantityoutlet.setInputVerifier(new AbstractValidator(this, quantityoutlet, "Ongeldige waarde! Verwacht formaat: x.y, groter dan 0.0") { @Override protected boolean validationCriteria(JComponent c) { if (autobox.getSelectedIndex() == 0) { return true; } try { return Double.parseDouble(((JTextField) c).getText()) > 0; } catch (Exception e) { return false; } } }); txtNumber.setInputVerifier(new AbstractValidator(this, txtNumber, "Dit nummer moet precies 6 tekens lang en geldig uniek zijn.") { @Override protected boolean validationCriteria(JComponent c) { if (txtNumber.getText().length() != 6) { return false; } try { int nr = Integer.parseInt(txtNumber.getText()); int year = nr / 10000; String dateString = new DateFormatter(new SimpleDateFormat("yy")).valueToString(datepicker.getDate()); if (Integer.parseInt(dateString) != year) { return false; } return !Database.driver().getInvoicesByNumber().keySet().contains(nr); } catch (Exception e) { return false; } } }); txtReduction.setInputVerifier(new AbstractValidator(this, txtReduction, "Ongeldige waarde! Kies een positief getal tussen 0 en 100 of laat dit veld leeg (=0 % korting)") { @Override protected boolean validationCriteria(JComponent c) { if (txtReduction.getText().isEmpty()) { return true; } try { double s = Double.parseDouble(((JTextField) c).getText()); return s >= 0.0 && s <= 100.0; } catch (Exception e) { return false; } } }); }
8
public ItemStack addToItem(ItemStack item, int enchantLevel) { ItemMeta meta = item.getItemMeta(); List<String> metaLore = meta.getLore() == null ? new ArrayList<String>() : meta.getLore(); for (String lore : metaLore) { if (lore.contains(this.enchantName)) { // Confirm that the enchanting name is the same String loreName = ENameParser.parseName(lore); if (loreName == null) continue; if (!enchantName.equalsIgnoreCase(loreName)) continue; // Compare the enchantment levels String[] pieces = lore.split(" "); int level = ERomanNumeral.getValueOf(pieces[pieces.length - 1]); if (level == 0) continue; // Leave higher enchantments alone if (level >= enchantLevel) return item; // Replace lower enchantments List<String> newLore = meta.getLore(); newLore.remove(lore); meta.setLore(newLore); break; } } // Add the enchantment metaLore.add(0, ChatColor.GRAY + this.enchantName + " " + ERomanNumeral.numeralOf(enchantLevel)); meta.setLore(metaLore); item.setItemMeta(meta); return item; }
7
private String getUserList() { StringBuilder sb = new StringBuilder(); for (String name : clients.keySet()) { sb.append("\n\t"); sb.append(name); } return sb.toString(); }
1
@Override public int hashCode() { int hash = 7; hash = 29 * hash + (this.type != null ? this.type.hashCode() : 0); hash = 29 * hash + (int) (this.length ^ (this.length >>> 32)); hash = 29 * hash + (int) (this.sizeof ^ (this.sizeof >>> 32)); hash = 29 * hash + (this.isConstant ? 1 : 0); hash = 29 * hash + (this.parent != null ? this.parent.hashCode() : 0); hash = 29 * hash + (int) (this.ptr ^ (this.ptr >>> 32)); return hash; }
3
public void actionPerformed(ActionEvent e) { if (aliens.size()==0) { ingame = false; } ArrayList ms = craft.getMissiles(); for (int i = 0; i < ms.size(); i++) { Missile m = (Missile) ms.get(i); if (m.isVisible()) m.move(); else ms.remove(i); } for (int i = 0; i < aliens.size(); i++) { Alien a = (Alien) aliens.get(i); if (a.isVisible()) a.move(); else aliens.remove(i); } craft.move(); checkCollisions(); repaint(); }
5
public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException { final List<Method> methods = new ArrayList<Method>(32); doWithMethods(leafClass, new MethodCallback() { public void doWith(Method method) { boolean knownSignature = false; Method methodBeingOverriddenWithCovariantReturnType = null; for (Method existingMethod : methods) { if (method.getName().equals(existingMethod.getName()) && Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) { // is this a covariant return type situation? if (existingMethod.getReturnType() != method.getReturnType() && existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) { methodBeingOverriddenWithCovariantReturnType = existingMethod; } else { knownSignature = true; } break; } } if (methodBeingOverriddenWithCovariantReturnType != null) { methods.remove(methodBeingOverriddenWithCovariantReturnType); } if (!knownSignature && !isCglibRenamedMethod(method)) { methods.add(method); } } }); return methods.toArray(new Method[methods.size()]); }
9
@Override public void actionPerformed(ActionEvent e) { if(e.getSource() == createMatrix){ createMatrix(); } else if (e.getSource() == selectMatrix){ displayMatrix(); } else if (e.getSource() == deleteMatrix){ deleteSelectedMatrix(); } else if(e.getSource() == transposeButton){ function_transpose(); } else if(e.getSource() == detButton){ function_getDet(); } else if(e.getSource() == rowRedButton){ function_rowReduce(); } else if(e.getSource() == inverseButton){ function_getInverse(); } else if(e.getSource() == helpButton){ displayHelp(); } }
8