text
stringlengths
14
410k
label
int32
0
9
@Override public void excecuteCommand(String channel, String sender, String message) throws Exception { this.channel = channel; String[] args = message.split(" "); switch(args[1]) { case "start": if(GAMES.containsKey(sender)) { GAMES.get(sender).start(); } else { GAMES.put(sender, new Blackjack()); } break; case "hit": if(GAMES.containsKey(sender) && GAMES.get(sender).isStarted) { GAMES.get(sender).hit(); } else { sendMessage(channel, "Please use !blackjack start first."); } break; case "stand": if(GAMES.containsKey(sender) && GAMES.get(sender).isStarted) { GAMES.get(sender).dealerHit(); } else { sendMessage(channel, "Please use !blackjack start first."); } break; default: break; } }
8
public static boolean computeCell(boolean[][] world, int col, int row) { // liveCell is true if the cell at position (col,row) in world is live boolean liveCell = getCell(world, col, row); // neighbours is the number of live neighbours to cell (col,row) int neighbours = countNeighbours(world, col, row); // we will return this value at the end of the method to indicate whether // cell (col,row) should be live in the next generation boolean nextCell = false; // A live cell with less than two neighbours dies (underpopulation) if (neighbours < 2) nextCell = false; // A live cell with two or three neighbours lives (a balanced population) if (liveCell && (neighbours == 2 || neighbours == 3)) nextCell = true; // A live cell with more than three neighbours dies (overcrowding) if (liveCell && neighbours > 3) nextCell = false; // A dead cell with exactly three live neighbours comes alive if (!liveCell && neighbours == 3) nextCell = true; return nextCell; }
8
public static float GetAxis(String axis) { if (axis.equalsIgnoreCase("Horizontal")) { if (Keyboard.isKeyDown(Keyboard.KEY_D)) { return 1; } if (Keyboard.isKeyDown(Keyboard.KEY_A)) { return -1; } return 0; } else if (axis.equalsIgnoreCase("Vertical")) { if (Keyboard.isKeyDown(Keyboard.KEY_W)) { return 1; } if (Keyboard.isKeyDown(Keyboard.KEY_S)) { return -1; } return 0; } else { GuiHandler.AddMessage("Invalid axis: "+axis); return 0; } }
6
public void createResPackDir(File file){ if(getExtension(file) == null){ if(!file.exists())createDir(file);//Create resourcepack folder createDir(new File(file.getPath() + "/assets"));//create assets folder if(!new File(file.getPath() + "/assets/minecraft").exists())createDir(new File(file.getPath() + "/assets/minecraft")); if(!new File(file.getPath() + "/assets/minecraft/models").exists())createDir(new File(file.getPath() + "/assets/minecraft/models"));//create models folder if(!new File(file.getPath() + "/assets/minecraft/models/block").exists())createDir(new File(file.getPath() + "/assets/minecraft/models/block")); if(!new File(file.getPath() + "/assets/minecraft/models/item").exists())createDir(new File(file.getPath() + "/assets/minecraft/models/item")); if(!new File(file.getPath() + "/assets/minecraft/textures").exists())createDir(new File(file.getPath() + "/assets/minecraft/textures"));//create textures folder if(!new File(file.getPath() + "/assets/minecraft/textures/blocks").exists())createDir(new File(file.getPath() + "/assets/minecraft/textures/blocks")); if(!new File(file.getPath() + "/assets/minecraft/textures/items").exists())createDir(new File(file.getPath() + "/assets/minecraft/textures/items")); }else{ System.out.println("Error creating resource pack! "); } }
9
private static <T> PartitionList<T> eparition(PartitionListElement<T> tail2) { PartitionList<T> returner = new PartitionList<T>(); for(int i = 1; i <= tail2.size(); i++){ PartitionListItem<T> partition = OrderConstrainedPartitionList.partition(tail2, i); returner.add(partition); if(partition.size() > 1){ PartitionListElement<T> head = partition.get(0); PartitionListElement<T> tail = new PartitionListElement<T>(); for(int j = 1; j < partition.size(); j++){ for(T backend : partition.get(j)) tail.add(backend); } //if(count-- > 0) System.out.println(count + "::" + "Head:" + head.toString() + " ; Tail: " + tail.toString()); PartitionList<T> tail_results = eparition(tail); for(PartitionListItem<T> tails : tail_results){ PartitionListItem<T> merged = new PartitionListItem<T>(); merged.add(head); for(PartitionListElement<T> mergeTail : tails){ merged.add(mergeTail); } returner.add(merged); //if(count-- > 0) System.out.println(count + ":: added" + merged.toString()); } } //if(count-- > 0) System.out.println(count + "::" +partition.size() + " <-- Number of partitions -->" + partition.toString()); } return returner; }
6
private URL getURL(String filename) { URL url = null; try { url = this.getClass().getResource(filename); } catch (Exception e) { System.out.println("Error en " + e.toString()); } return url; }
1
private Enemy getEnemyById(String id) { for (Enemy e : getEnemies()) { if (e.getId().equals(id)) return e; } return null; }
2
public void pushPlusOperator(){ ((Vector)operatorStack).add(0, new PlusOperator()); }
0
public Object whoIsRight(Object a, Object b) { Random r = new Random(); if(r.nextBoolean()) { return a; } return b; }
1
private boolean inPoly(FastVector ob, double x, double y) { //brief on how this works //it draws a line horizontally from the point to the right (infinitly) //it then sees how many lines of the polygon intersect this, //if it is even then the point is // outside the polygon if it's odd then it's inside the polygon int count = 0; double vecx, vecy; double change; double x1, y1, x2, y2; for (int noa = 1; noa < ob.size() - 2; noa += 2) { y1 = ((Double)ob.elementAt(noa+1)).doubleValue(); y2 = ((Double)ob.elementAt(noa+3)).doubleValue(); if ((y1 <= y && y < y2) || (y2 < y && y <= y1)) { //then continue tests. vecy = y2 - y1; if (vecy == 0) { //then lines are parallel stop tests for this line } else { x1 = ((Double)ob.elementAt(noa)).doubleValue(); x2 = ((Double)ob.elementAt(noa+2)).doubleValue(); vecx = x2 - x1; change = (y - y1) / vecy; if (vecx * change + x1 >= x) { //then add to count as an intersected line count++; } } } } if ((count % 2) == 1) { //then lies inside polygon //System.out.println("in"); return true; } else { //System.out.println("out"); return false; } //System.out.println("WHAT?!?!?!?!!?!??!?!"); //return false; }
8
private void buildTrees(final Block firstBlock, final Map labelPos) { db(" Building trees for " + firstBlock); // Maps a "catch block" (beginning of exception handler that // stores the exception) to a "catch body" (the code immediately // follows the "catch block" -- the rest of the handler). final HashMap catchBodies = new HashMap( method.tryCatches().size() * 2 + 1); final Iterator tryCatches = method.tryCatches().iterator(); while (tryCatches.hasNext()) { final TryCatch tc = (TryCatch) tryCatches.next(); // We create two blocks for each handler. // catchBlock is the handler target. It contains the code // which saves the exception on the operand stack. // catchBody is the block following the handler target. // It contains the code for the exception handler body. // We need to split these two blocks so that the handler target // cannot possibly be a loop header. // This block will be the target of the exception handler. final Block catchBlock = newBlock(); // This block will hold the instructions in the catch body. final Block catchBody = (Block) getNode(tc.handler()); catchBodies.put(catchBlock, catchBody); // Make sure we include the new block in any protected area // containing the catch body. Integer pos = (Integer) labelPos.get(tc.handler()); labelPos.put(catchBlock.label(), pos); addEdge(catchBlock, catchBody); trace.add(trace.indexOf(catchBody), catchBlock); Type type = tc.type(); if (type == null) { type = Type.NULL; } catchBlocks.add(catchBlock); // Save the exception to the stack. final StackExpr lhs = new StackExpr(0, Type.THROWABLE); final CatchExpr rhs = new CatchExpr(type, Type.THROWABLE); final StoreExpr store = new StoreExpr(lhs, rhs, Type.THROWABLE); // Build the tree for the exception handler target block. final Tree tree = new Tree(catchBlock, new OperandStack()); catchBlock.setTree(tree); tree.addStmt(new ExprStmt(store)); tree.addStmt(new GotoStmt(catchBody)); // Create the Handler. final Integer start = (Integer) labelPos.get(tc.start()); final Integer end = (Integer) labelPos.get(tc.end()); final Handler handler = new Handler(catchBlock, type); handlers.put(catchBlock, handler); final Iterator blocks = nodes().iterator(); // Examine all of the basic blocks in this CFG. If the block's // offset into the code is between the start and end points of // the TryCatch, then it is a protected block. So, the block // should be added to the Handler's list of protected blocks. while (blocks.hasNext()) { final Block block = (Block) blocks.next(); pos = (Integer) labelPos.get(block.label()); if (pos == null) { // This is one of the special blocks such as the source, // sink, and init block. continue; } if (start.intValue() <= pos.intValue()) { if ((end == null) || (pos.intValue() < end.intValue())) { handler.protectedBlocks().add(block); } } } } addEdge(srcBlock, iniBlock); addEdge(srcBlock, snkBlock); addEdge(iniBlock, firstBlock); buildSpecialTrees(catchBodies, labelPos); // Build the trees for the blocks reachable from the firstBlock. buildTreeForBlock(firstBlock, iniBlock.tree().stack(), null, labelPos, catchBodies); }
7
public static void compileGafAssetsFile(String prjCompileDir, String prjGameName, String prjDir) { File selectedFile = new File(prjCompileDir + File.separator + prjGameName.toLowerCase() + ".assets.cache.jar"); File content = new File(prjDir); File[] files = content.listFiles(); assert files != null; Main.log.warning("Starting GafAssetsCompiler for " + selectedFile.toString()); List<File> preparedFiles = new ArrayList<File>(); for (File f : files) { if (!f.isDirectory()) { int code = checkAndAddFile(preparedFiles, f); if (code == 0) { Main.log.severe("The compiler has returned error code 0 : invalid_argument_#size"); return; } else if (code == 1) { Main.log.severe("The compiler has returned error code 1 : invalid_argument_#extention"); return; } else if (code == 2) { Main.log.severe("The compiler has returned error code 2 : unknown_error"); return; } else if (code == 3) { Main.log.severe("The compiler has returned error code 3 : file_load_failure"); return; } } else { addDirectoryToCompileList(f, preparedFiles); } } File[] finalFiles = new File[preparedFiles.size()]; for (int i = 0; i < preparedFiles.size(); i++) { finalFiles[i] = preparedFiles.get(i); } try { craeteZip(finalFiles, selectedFile); File finalFile = new File(prjCompileDir + File.separator + prjGameName.toLowerCase() + ".assets.gaf"); GAFCompiler.compileAssetsFileFromZip(selectedFile, finalFile); selectedFile.delete(); } catch (IOException e1) { Main.log.warning("GafAssetsCompiler failure"); Main.log.severe("Compiler has stopped running, closing..."); return; } Main.log.fine("GafAssetsCompiler succeeded !"); }
8
public void setModelValue(Object obj) { if (autoInsertCancel) { this.autoInsertCancel = false; } // closing the editor if for some reason it is still active: if (this.getCellEditor() != null) { this.getCellEditor().stopCellEditing(); } if (obj == null) { data = EMPTY_MODEL; } else { if (!(obj instanceof Collection)) { throw new YException( "Table model must be instance of Collection."); } else { this.modelCollection = (Collection) obj; // creating the real table model... this.data = new ArrayList(modelCollection.size()); Iterator it = modelCollection.iterator(); while (it.hasNext()) { Object rowObj = it.next(); if (isRendered(rowObj)) { data.add(rowObj); } } } } tableModel.fireTableDataChanged(); }
6
public String getTunnisteet(){ String palautettava = ""; for (String tunniste : tunnisteet) { palautettava += tunniste + " "; } return palautettava; }
1
public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // setup for collecting optional entity info... Shape entityArea = null; EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } IntervalXYDataset intervalDataset = (IntervalXYDataset) dataset; double x = intervalDataset.getXValue(series, item); double yLow = intervalDataset.getStartYValue(series, item); double yHigh = intervalDataset.getEndYValue(series, item); RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double xx = domainAxis.valueToJava2D(x, dataArea, xAxisLocation); double yyLow = rangeAxis.valueToJava2D(yLow, dataArea, yAxisLocation); double yyHigh = rangeAxis.valueToJava2D(yHigh, dataArea, yAxisLocation); Paint p = getItemPaint(series, item); Stroke s = getItemStroke(series, item); Line2D line = null; Shape shape = getItemShape(series, item); Shape top = null; Shape bottom = null; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(yyLow, xx, yyHigh, xx); top = ShapeUtilities.createTranslatedShape(shape, yyHigh, xx); bottom = ShapeUtilities.createTranslatedShape(shape, yyLow, xx); } else if (orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(xx, yyLow, xx, yyHigh); top = ShapeUtilities.createTranslatedShape(shape, xx, yyHigh); bottom = ShapeUtilities.createTranslatedShape(shape, xx, yyLow); } g2.setPaint(p); g2.setStroke(s); g2.draw(line); g2.fill(top); g2.fill(bottom); // add an entity for the item... if (entities != null) { if (entityArea == null) { entityArea = line.getBounds(); } String tip = null; XYToolTipGenerator generator = getToolTipGenerator(series, item); if (generator != null) { tip = generator.generateToolTip(dataset, series, item); } String url = null; if (getURLGenerator() != null) { url = getURLGenerator().generateURL(dataset, series, item); } XYItemEntity entity = new XYItemEntity( entityArea, dataset, series, item, tip, url ); entities.add(entity); } }
7
public JSONWriter object() throws JSONException { if (this.mode == 'i') { this.mode = 'o'; } if (this.mode == 'o' || this.mode == 'a') { this.append("{"); this.push(new JSONObject()); this.comma = false; return this; } throw new JSONException("Misplaced object."); }
3
public static Map<Class<? extends Object>, List<String>> config(String path) throws NoConfigException { Map<Class<? extends Object>, List<String>> ret = configs.get(path); if (null == ret) return initConfig(path); return ret; }
3
public Object showScoreList(String term) { String command = "show;student_score_list;" + term; ArrayList<String> list = null; String[][] content = null; try { NetService client = initNetService(); client.sendCommand(command); list = client.receiveList(); content = new String[list.size()][]; for (int i = 0; i < list.size(); i++) { content[i] = list.get(i).split(";"); } for (int i = 0; i < content.length; i++) { for (int j = 0; j < content[i].length; j++) { if (content[i][j].equals("-1")) { content[i][j] = ""; } } } client.shutDownConnection(); } catch (Exception e) { e.printStackTrace(); return Feedback.INTERNET_ERROR; } return content; }
5
public boolean canMove() { Grid<Actor> gr = getGrid(); if (gr == null) return false; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection()); if (!gr.isValid(next)) return false; Actor neighbor = gr.get(next); return (neighbor == null) || (neighbor instanceof Flower); // ok to move into empty location or onto flower // not ok to move onto any other actor }
3
public static void testSeqRead() throws IOException{ Read rd = new Read(); rd.startTest(); }
0
public void lastStep(Context ctx) { ctx.setState(null); }
0
@Override public void removeExtension(String ext) { extensions.remove(ext); }
0
public double timeLengthRank(double percentage) { boolean cutOffNotOkay=true;//determines if cut off is appropriate Collections.sort(library,TimeLengthComparator.getTL()); double percentageOfMean=percentage*1.5; while(cutOffNotOkay) { int count=0; double cutoff= tlMean *percentageOfMean; // the cut off is a certain percentage of the mean for(int i=0;i<library.size();i++) { if(library.get(i).getTimeLength()<cutoff) { library.get(i).setTLRank(library.size()); count++; } else break; } int rank=1; if(count<oneCount*1.65) // the number of songs below the cut off should be in between 1.15 and 1.65 times the number of songs that by default will be { if(count>oneCount*1.15) { library.get(count).setTLRank(rank); for(int i=count+1;i<library.size();i++) { if(library.get(i).getTimeLength()>library.get(i-1).getTimeLength()) { rank++; library.get(i).setTLRank(rank); } else library.get(i).setTLRank(rank); } cutOffNotOkay=false; } else percentageOfMean=percentageOfMean+0.025; // the % was too small } else percentageOfMean=percentageOfMean-0.025; // the % was too big } return (percentageOfMean/1.5); }
7
public static void main(String[] args) throws Exception { ObjectOutput out = new ObjectOutputStream(new FileOutputStream("X.file")); Alien quellek = new Alien(); out.writeObject(quellek); out.close(); }
0
public void setAlphabet(String regex) { int i = 0; for (char c = regex.charAt(i); i < regex.length(); i++) { if (c == '[') { break; } } if (i >= regex.length()) { throw new IllegalArgumentException("Regex may only contain a group"); } for (char c = regex.charAt(i); i < regex.length(); i++) { if (c == ']') { break; } } if (i < regex.length()) { throw new IllegalArgumentException("Regex may only contain a group"); } alphabet = new Revex(regex); }
6
public void clickTutorial() { state.clickTutorial(); }
0
public static void main(String[] args) { Model m = new Model(); m.getSearchFormats().add("mp3"); m.getSearchFormats().add("mov"); m.getSearchFormats().add("m4v"); m.getSearchKeywords().add("Videos"); m.getSearchKeywords().add("movies"); Controller controller = new Controller(m); final testFrame t = new testFrame(controller); try { controller.initialize(); } catch (IOException ex) { Logger.getLogger(GetMovies.class.getName()).log(Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { t.setLocationRelativeTo(null); t.setVisible(true); } }); }
1
public void close () { boolean wasConnected = isConnected; isConnected = false; tcp.close(); if (udp != null && udp.connectedAddress != null) udp.close(); if (wasConnected) { notifyDisconnected(); if (INFO) info("kryonet", this + " disconnected."); } setConnected(false); }
4
public void reachableReference(Reference ref, boolean isVirtual) { String clName = ref.getClazz(); if (clName.charAt(0) == '[') /* Can't represent arrays */ return; ClassIdentifier ident = getClassIdentifier(clName.substring(1, clName.length() - 1).replace('/', '.')); if (ident != null) ident.reachableReference(ref, isVirtual); }
2
protected TemplateIssue createTemplateIssue(String sourcePath, CompileEvent event) { SourceInfo info = event.getSourceInfo(); if (info == null) { return null; } CompilationUnit unit = event.getCompilationUnit(); if (unit == null) { return null; } Date lastModifiedDate = new Date(new File(sourcePath).lastModified()); String message = event.getMessage(); String detailedMessage = event.getDetailedMessage(); String sourceInfoMessage = event.getSourceInfoMessage(); int lineNumber = -1; int startPos = -1; int eEndPos = -1; int detailPos = -1; int linePos = -1; String lineStr = null; String underline = null; try { lineNumber = info.getLine(); startPos = info.getStartPosition(); eEndPos = info.getEndPosition(); detailPos = info.getDetailPosition(); if (mOpenReader == null || mOpenUnit != unit || mOpenReader.getLineNumber() >= lineNumber) { if (mOpenReader != null) { mOpenReader.close(); } mOpenUnit = unit; mOpenReader = new LinePositionReader(new BufferedReader(unit.getReader())); } mOpenReader.skipForwardToLine(lineNumber); linePos = mOpenReader.getNextPosition(); lineStr = mOpenReader.readLine(); lineStr = LinePositionReader.cleanWhitespace(lineStr); int indentSize = startPos - linePos; String indent = LinePositionReader.createSequence(' ', indentSize); int markerSize = eEndPos - startPos + 1; String marker = LinePositionReader.createSequence('^', markerSize); underline = indent + marker; } catch (IOException ex) { mLog.error(ex); } int state = -1; if (event.isError()) { state = TemplateIssue.ERROR; } else if (event.isWarning()) { state = TemplateIssue.WARNING; } return new TemplateIssue (sourcePath, lastModifiedDate, state, message, detailedMessage, sourceInfoMessage, lineStr, underline, lineNumber, startPos, eEndPos, startPos - linePos, eEndPos - linePos + 1, detailPos - linePos); }
9
private void runParkingDisplay(Scanner scan, PrintWriter pout, String spotNumber) { spot = garage.searchBySpotNumber(spotNumber); if(!isConnectionAvailable(spotNumber)) { System.out.println("Another display is connected to spot #" + spotNumber); sendMessage("another", pout); return; } addDisplay(spotNumber, pout, spot); sendMessage(spot.getParkingType(), pout); boolean correct = true; while(scan.hasNextLine()) { String oneLine = scan.nextLine(); if(oneLine.equals("leave")) { if(correct) spot.removeAssignedUser(); else correct = true; } else if(oneLine.equals("wrong")) { wrongUserDetected("Wrong user detected on parking spot #" + spot.getParkingNumber()); if(spot.isAvailable()) { ParkingUser user = new GuestUser(); spot.assignParkingSpot(user); } else correct = false; } } }
6
public static boolean isReservedMinusOp(String candidate) { int START_STATE = 0; int TERMINAL_STATE = 1; char next; if (candidate.length()!=1){ return false; } int state = START_STATE; for (int i = 0; i < candidate.length(); i++) { next = candidate.charAt(i); switch (state) { case 0: switch ( next ) { case '-': state++; break; default : state = -1; } break; } } if ( state == TERMINAL_STATE ) return true; else return false; }
5
String checkSecurity(int iLevel, javax.servlet.http.HttpSession session, javax.servlet.http.HttpServletResponse response, javax.servlet.http.HttpServletRequest request){ try { Object o1 = session.getAttribute("UserID"); Object o2 = session.getAttribute("UserRights"); boolean bRedirect = false; if ( o1 == null || o2 == null ) { bRedirect = true; } if ( ! bRedirect ) { if ( (o1.toString()).equals("")) { bRedirect = true; } else if ( (new Integer(o2.toString())).intValue() < iLevel) { bRedirect = true; } } if ( bRedirect ) { response.sendRedirect("Login.jsp?querystring=" + toURL(request.getQueryString()) + "&ret_page=" + toURL(request.getRequestURI())); return "sendRedirect"; } } catch(Exception e){}; return ""; }
7
@Override public byte[] getData() { if (ptr != 0) { return null; } else { if (isConstant()) { if (length > getMaxSizeOf32bitArray()) return null; byte[] out = new byte[(int) length]; for (int i = 0; i < length; i++) { out[i] = data[0]; } return out; } else { return data; } } }
4
private void action(final String input) throws ParseException { String s1; s1 = calcWeekDay(input); System.out.println(s1); }
0
public boolean isValidStatus(String status){ if(status.equals("available") || status.equals("lost") ||status.equals("checked-out")||status.equals("in-queue")) return true; else return false; }
4
@Override public void onNeighborBlockChange(Block blockChanged) { int meta = tileEntity.getBlockMetadata(); boolean valid = isRailValid(getWorld(), tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, meta); if (!valid) { Block blockTrack = getBlock(); blockTrack.dropBlockAsItem(getWorld(), tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, 0, 0); getWorld().setBlockToAir(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); return; } if (blockChanged != null && blockChanged.canProvidePower() && isFlexibleRail() && RailTools.countAdjecentTracks(getWorld(), tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord) == 3) switchTrack(false); testPower(); }
5
public String getPlayersName() { String resultName = ""; for (Player player : players) { resultName += player.getName() + "\n"; } return resultName; }
1
public static Object fromReflectType(String typeSig, Object value) { switch (typeSig.charAt(0)) { case 'Z': return new Integer(((Boolean) value).booleanValue() ? 1 : 0); case 'B': case 'S': return new Integer(((Number) value).intValue()); case 'C': return new Integer(((Character) value).charValue()); default: return value; } }
5
private Item nextToCatalogue() { float quality = Float.POSITIVE_INFINITY ; Item catalogued = null ; for (Item i : stocks.matches(DATALINKS)) { if (! (i.refers instanceof Skill)) continue ; if (i.quality < quality) { catalogued = i ; quality = i.quality ; } } if (catalogued == null || catalogued.quality >= 5) return null ; return catalogued ; }
5
public static void rotateLeft2(int[] array, int shift) { if (shift <= 0 || array == null || array.length <= shift) { throw new IllegalArgumentException("Invalid args"); } int n = array.length; int i, j, k, temp; for (i = 0; i < GCD.gcd(shift, n); i++) { /* move i-th values of blocks */ temp = array[i]; j = i; while (true) { k = j + shift; if (k >= n) { k = k - n; } if (k == i) { break; } array[j] = array[k]; j = k; } array[j] = temp; } }
7
public static boolean destroy(String alias) { if(aliasMap.containsKey(alias)) { Shader removed = aliasMap.get(alias); Iterator<Entry<String, Shader>> it = aliasMap.entrySet().iterator(); while(it.hasNext()) { Entry<String, Shader> entry = it.next(); if(entry.getValue().equals(removed)) it.remove(); } return true; } else { System.err.println("Alias "+alias+" was not in the aliasMap, return false"); return false; } }
3
static void tumblep_drawsprites(osd_bitmap bitmap) { int offs; for (offs = 0;offs < 0x800;offs += 8) { int x,y,sprite,colour,multi,fx,fy,inc,flash; sprite = spriteram.READ_WORD(offs+2) & 0x3fff; if (sprite==0) continue; y = spriteram.READ_WORD(offs); flash=y&0x1000; if (flash!=0 && (cpu_getcurrentframe() & 1)!=0) continue; x = spriteram.READ_WORD(offs+4); colour = (x >>9) & 0xf; fx = y & 0x2000; fy = y & 0x4000; multi = (1 << ((y & 0x0600) >> 9)) - 1; /* 1x, 2x, 4x, 8x height */ x = x & 0x01ff; y = y & 0x01ff; if (x >= 320) x -= 512; if (y >= 256) y -= 512; y = 240 - y; x = 304 - x; sprite &= ~multi; if (fy != 0) inc = -1; else { sprite += multi; inc = 1; } while (multi >= 0) { drawgfx(bitmap,Machine.gfx[3], sprite - multi * inc, colour, fx,fy, x,y - 16 * multi, Machine.drv.visible_area,TRANSPARENCY_PEN,0); multi--; } } }
8
public String getUnprocessedInput() { return myUnprocessedInput; }
0
@Override public List<Aluno> Buscar(Aluno obj) { String sql = "select a from Aluno a"; String filtros = ""; if(obj != null){ if(obj.getId() != null){ filtros += "a.id = " + obj.getId(); } if(obj.getMatricula() > 0){ if(filtros.length() > 0) filtros += " and "; filtros += "a.matricula = " + obj.getMatricula() ; } //verificar se a busca do nome é em USUARIODAO if(obj.getNome() != null){ if(filtros.length() > 0) filtros += " and "; filtros += "a.nome like '%" + obj.getNome() + "%'"; } } if(filtros.length() > 0){ sql += " where " + filtros; } Query consulta = manager.createQuery(sql); return consulta.getResultList(); }
7
public synchronized Collection getRefClasses() { ClassFile cf = getClassFile2(); if (cf != null) { ClassMap cm = new ClassMap() { public void put(String oldname, String newname) { put0(oldname, newname); } public Object get(Object jvmClassName) { String n = toJavaName((String)jvmClassName); put0(n, n); return null; } public void fix(String name) {} }; cf.renameClass(cm); return cm.values(); } else return null; }
1
public Destination to(String s) { return new Destination(s); }
0
@Override public int read() { FileInputStream fis = null; try { fis = new FileInputStream(src); } catch (FileNotFoundException e1) { return -1; } int result = -1; try { fis.skip(byteCounter++); result = fis.read(); } catch (IOException e) { e.printStackTrace(); } try { fis.close(); } catch (IOException e) { e.printStackTrace(); } return result; }
3
protected ExportData createExportData() throws RrdException { if ( sources == null) throw new RrdException( "Sources not calculated, no data to return." ); // Now create a RrdDataSet object containing the results Source[] sourceSet; String[][] export = def.getExportDatasources(); HashMap legends = new HashMap( export.length ); if ( def.isStrict() ) { sourceSet = new Def[ export.length ]; for ( int i = 0; i < export.length; i++ ) sourceSet[i] = createReducedDef( getSource( export[i][0] ) ); } else { sourceSet = new Def[ sources.length ]; for ( int i = 0; i < sources.length; i++ ) { sourceSet[i] = createReducedDef( sources[i] ); legends.put( sourceSet[i].getName(), sourceSet[i].getName() ); } } for ( int i = 0; i < export.length; i++ ) legends.put( export[i][0], export[i][1] ); long[] reducedTs = new long[ reducedNumRows ]; System.arraycopy( timestamps, 0, reducedTs, 0, reducedNumRows ); return new ExportData( reducedTs, sourceSet, legends ); }
5
public void act(List<Actor> newFoxes) { incrementAge(); incrementHunger(); if(isAlive()) { giveBirth(newFoxes); // Move towards a source of food if found. Location newLocation = findFood(); if(newLocation == null) { // No food found - try to move to a free location. newLocation = getField().freeAdjacentLocation(getLocation()); } // See if it was possible to move. if(newLocation != null) { setLocation(newLocation); } else { // Overcrowding. setDead(); } } }
3
@Override protected DPLotSizingDecision getDecision(DPBackwardRecursionPeriod[] periods, int setupPeriod, int nextSetupPeriod, double alpha) throws ConvolutionNotDefinedException{ //Get the vector of aggregated demand (there is no ADI in static uncertainty) RealDistribution[] demand = new RealDistribution[nextSetupPeriod]; for (int i = 0; i < demand.length; i++){ demand[i] = periods[i].period.totalDemand(); } //Get the total production up to the beginning of the next setup period (i.e. exclusively!) RealDistribution totalDemandUpToNextSetupPeriod = Convoluter.convolute(demand); double totalProductionUpToNextSetupPeriod = totalDemandUpToNextSetupPeriod.inverseCumulativeProbability(alpha); //Start with the setup cost double decisionCost = periods[setupPeriod].period.getSetupCost(); //Calculate and add the inventory cost for (int tau = setupPeriod; tau < nextSetupPeriod; tau++){ RealDistribution totalDemandDistribution = Convoluter.convolute(demand, tau+1); StockFunction stockFunction = new StockFunction(totalDemandDistribution); decisionCost += periods[tau].period.getInventoryHoldingCost()*stockFunction.value(totalProductionUpToNextSetupPeriod); } //Calculate the production before the setup period to get the lot size double totalProductionUpToSetupPeriod = 0.0; if (setupPeriod > 0){ RealDistribution totalDemandUpToSetupPeriod = Convoluter.convolute(demand, setupPeriod); totalProductionUpToSetupPeriod = totalDemandUpToSetupPeriod.inverseCumulativeProbability(alpha); } //return return new DPLotSizingDecision(periods[nextSetupPeriod], decisionCost, totalProductionUpToNextSetupPeriod-totalProductionUpToSetupPeriod); }
3
public static String getPremier(String date, String state) { date = date.replaceAll("-", ""); DB db = _mongo.getDB(DATABASE_NAME); DBCollection coll = db.getCollection(COLLECTION_PREMIER); BasicDBObject query = new BasicDBObject(); query.put("start.date", new BasicDBObject("$lte", date)); query.put("state", "" + state); DBCursor cur = coll.find(query); cur.sort(new BasicDBObject("start.date", -1)); //.limit(1); DBObject doc = null; if (cur.hasNext()) { doc = cur.next(); return doc.toString(); } return ""; }
1
private static void method495(char ac[]) { int i = 0; for(int j = 0; j < ac.length; j++) { if(method496(ac[j])) ac[i] = ac[j]; else ac[i] = ' '; if(i == 0 || ac[i] != ' ' || ac[i - 1] != ' ') i++; } for(int k = i; k < ac.length; k++) ac[k] = ' '; }
6
public Object[] lookupCflow(String name) { if (cflow == null) cflow = new Hashtable(); return (Object[])cflow.get(name); }
1
@Test public void testMoveBackward() { Random rand = Mockito.mock(Random.class); // On s'assure que le terrain et toujours franchissable. Mockito.when(rand.nextInt(Land.CountLand())).thenReturn(0); Robot r = new Robot(); r.land(new Coordinates(0,0), new LandSensor(rand)); try { Assert.assertEquals(0, r.getXposition()); Assert.assertEquals(0, r.getYposition()); r.moveBackward(); Assert.assertEquals(0, r.getXposition()); Assert.assertEquals(-1, r.getYposition()); r.turnRight(); r.moveBackward(); Assert.assertEquals(-1, r.getXposition()); Assert.assertEquals(-1, r.getYposition()); r.turnRight(); r.moveBackward(); Assert.assertEquals(-1, r.getXposition()); Assert.assertEquals(0, r.getYposition()); r.turnRight(); r.moveBackward(); Assert.assertEquals(0, r.getXposition()); Assert.assertEquals(0, r.getYposition()); } catch (UnlandedRobotException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (InsufficientChargeException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (LandSensorDefaillance landSensorDefaillance) { landSensorDefaillance.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (InaccessibleCoordinate inaccessibleCoordinate) { inaccessibleCoordinate.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } }
4
private static boolean matchesSeq(String[] words, String[]... sequence) { // If there aren't enough words to possibly // match the sequence, return false if(words.length < sequence.length) { return false; } // For each item in the sequence, ensure the // word is one of the possibilities given for(int i = 0; i < sequence.length; i++) { String word = words[i]; String[] possibilities = sequence[i]; // If it isn't, return false if(!matchesAny(word, possibilities)) { return false; } } // If each item in the sequence // had a match, return true return true; }
3
@Override public HTTPResponse handle(HTTPRequest req) { String HTTPAuthUsername = Config.getString(HOST, "AuthUsername", ""); if ( !HTTPAuthUsername.equals("") ) { String responseAuthHeader = req.getHeader("Authorization"); if ( responseAuthHeader.equals("") ) { HTTPResponse response = ErrorFactory.notAuthorized(); response.addResponseHeader("WWW-Authenticate", "Basic realm=\""+Config.getString(HOST, "AuthRealm", "Secure Site")+"\""); return response; } else { String authString = responseAuthHeader.split(" ")[0]; String correctString = HTTPAuthUsername+":"+Config.getString(HOST, "AuthPassword", ""); correctString = DatatypeConverter.printBase64Binary(correctString.getBytes()); if ( authString.equals(correctString) ) return ErrorFactory.notAuthorized(); } } String path = req.getPath(); if ( path.substring(path.length()-1, path.length()).equals("/") ) path += "index.html"; File f = new File(docRoot+"/"+path); if ( f.getName().split("\\.")[1].equals("cgi") ) return new CGIExecute(f.getAbsolutePath()).handle(req); else if ( f.exists() ) { try { @SuppressWarnings("resource") FileReader reader = new FileReader(f); String fileData = ""; while ( reader.ready() ) { char[] data = new char[50]; reader.read(data, 0, data.length); fileData += new String(data); } return new HTTPResponse(200, fileData); } catch (Exception e) { return ErrorFactory.internalServerError("Error serving file"); } } return ErrorFactory.notFound(); }
8
public static String getFeeders(ArrayList<TeamMatch> matches) { boolean ground = false, feeder = false; for (TeamMatch match : matches) { if (Arrays.asList(match.getIntakes()).contains(TeamMatch.Intake.GroundPickup)) { ground = true; } else if (Arrays.asList(match.getIntakes()).contains(TeamMatch.Intake.FeederStation)) { feeder = true; } } if (ground && !feeder) { return "Ground"; } else if (!ground && feeder) { return "Feeder Station"; } else if (ground && feeder) { return "Both"; } else { return "None"; } }
9
public void mousePressed(MouseEvent e) { super.mousePressed(e); int selectedRow = m_tree.getRowForLocation(e.getX(), e.getY()); TreePath selectedPath = m_tree.getPathForLocation(e.getX(), e.getY()); if (selectedRow != -1) { if (e.getClickCount() == 1) { if (SwingUtilities.isRightMouseButton(e)) showContextMenu(selectedRow, selectedPath, e); } else if (e.getClickCount() == 2) { if (SwingUtilities.isLeftMouseButton(e)) showDoubleClickMenu(selectedRow, selectedPath, e); } } }
5
private Object[] loadRow(DataStructures obj){ return new Object[] { Integer.toString(tableModelArrays.getRowCount()+1), obj.getType(), Integer.toString(obj.getLength(0)), obj.getState(), obj.kitSize() }; }
0
private void setIcon(BufferedImage image) { Component root = SwingUtilities.getRoot(this); if (root instanceof JFrame || root instanceof Frame) { Frame frame = (Frame)root; frame.setIconImage(image); } }
2
public Queue(){}
0
private static void keccakPad() { if ((bitsInQueue % 8) != 0) { // The bits are numbered from 0=LSB to 7=MSB byte padByte = (byte) (1 << (bitsInQueue % 8)); dataQueue[bitsInQueue / 8] |= padByte; bitsInQueue += 8 - (bitsInQueue % 8); } else { dataQueue[bitsInQueue / 8] = 0x01; bitsInQueue += 8; } if (bitsInQueue == rate) { absorbQueue(); } dataQueue[bitsInQueue / 8] = diversifier; bitsInQueue += 8; if (bitsInQueue == rate) { absorbQueue(); } dataQueue[bitsInQueue / 8] = (byte) (rate / 8); bitsInQueue += 8; if (bitsInQueue == rate) { absorbQueue(); } dataQueue[bitsInQueue / 8] = 0x01; bitsInQueue += 8; if (bitsInQueue > 0) { absorbQueue(); } System.arraycopy(state, 0, dataQueue, 0, rate / 8); }
5
private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) { String eol = System.getProperty("line.separator", "\n"); StringBuffer expected = new StringBuffer(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } expected.append(eol).append(" "); } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += " " + tokenImage[tok.kind]; retval += " \""; retval += add_escapes(tok.image); retval += " \""; tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected.toString(); return retval; }
8
public void decodeFrame() throws DecoderException { num_subbands = header.number_of_subbands(); subbands = new Subband[32]; mode = header.mode(); createSubbands(); readAllocation(); readScaleFactorSelection(); if ((crc != null) || header.checksum_ok()) { readScaleFactors(); readSampleData(); } }
2
@Override public void setPixel(int x, int y, int c) { int bx = x / 8; int by = y / 8; int offs = bx + by * (width / 8) - tileOffset; if (offs < 0) return; offs *= 64; offs += x % 8 + 8 * (y % 8); if (offs < 0) return; if (offs >= data.length) return; data[offs] = (byte) c; }
3
private static List<String> fillCollection(){ List<String> features = new ArrayList<String>(); HashMap<String,String> components = new HashMap<String, String>(); components.put("Settings", "Settings"); components.put("Map", "Map"); components.put("Attachment", "Attachment"); components.put("BGColor", "BGColor"); components.put("Game", "TTTGame"); components.put("Print", "Print"); components.put("Incognito", "Incognito"); components.put("Availability", "Availability"); components.put("History", "ChatHistory"); components.put("None", "None"); components.put("Image", "Image"); components.put("ChatBot", "Bot"); //where is the actual chatbot feature in the app? is it used? components.put("Template", "Template"); for(String values : ARGS) features.add(components.get(values).toString()); if (ARGS.length > 0)//why? features.add("comp"); features.add("Templet"); features.add("com"); features.add("pla"); features.add("chatsys"); features.add("client"); features.add("server"); features.add(".svn"); features.add("prop-base"); features.add("text-base"); features.add("annotation"); features.add("META-INF"); features.add(".settings"); features.add("icon"); features.add("src"); return features; }
2
public RepositoryVm getRepoFiles(String repositoryName, String baseUrl) throws IOException { String organizationName = ApplicationProperties.getProperties().getProperty(PropertiesConstants.GITHUB_ORGANIZATION); Repository repository = getRepository(organizationName, repositoryName); Release latestRelease = getLatestRelease(repository); RepositoryVm repositoryVm = createRepositoryVm(repository, baseUrl, latestRelease); HashMap<String, DataFile> repoFileData = getRepoFileData(repositoryName, baseUrl); List<RepositoryFileVm> repositoryFiles = new ArrayList<>(); for (String fileName : repoFileData.keySet()) { if (!Utils.isDataFilePath(fileName)) { continue; } DataFile dataFile = repoFileData.get(fileName); RepositoryFileVm repositoryFile = new RepositoryFileVm(); repositoryFile.setName(fileName); if (Utils.isCataloguePath(fileName)) { repositoryFile.setType(StringUtils.capitalize(DataType.CATALOGUE.toString())); } else if (Utils.isGameSytstemPath(fileName)) { repositoryFile.setType(StringUtils.capitalize(DataType.GAME_SYSTEM.toString())); } else if (Utils.isRosterPath(fileName)) { repositoryFile.setType(StringUtils.capitalize(DataType.ROSTER.toString())); } repositoryFile.setDataFileUrl(Utils.checkUrl(baseUrl + "/" + repository.getName() + "/" + fileName)); repositoryFile.setIssueUrl(Utils.checkUrl(baseUrl + "/" + repository.getName() + "/" + fileName + "/issue")); String uncompressedFileName = Utils.getUncompressedFileName(fileName); repositoryFile.setGitHubUrl(Utils.checkUrl(repositoryVm.getGitHubUrl() + "/blob/master/" + uncompressedFileName)); repositoryFile.setRevision(dataFile.getRevision()); repositoryFile.setAuthorName(dataFile.getAuthorName()); repositoryFile.setAuthorContact(dataFile.getAuthorContact()); repositoryFile.setAuthorUrl(dataFile.getAuthorUrl()); repositoryFiles.add(repositoryFile); } Collections.sort(repositoryFiles, new Comparator<RepositoryFileVm>() { @Override public int compare(RepositoryFileVm o1, RepositoryFileVm o2) { String o1Type = o1.getType().toLowerCase(); String o2Type = o2.getType().toLowerCase(); if (o1Type.equals(DataType.CATALOGUE.toString()) && o2Type.equals(DataType.GAME_SYSTEM.toString())) { return 1; } else if (o1Type.equals(DataType.GAME_SYSTEM.toString()) && o2Type.equals(DataType.CATALOGUE.toString())) { return -1; } return o1.getName().compareTo(o2.getName()); } }); repositoryVm.setRepositoryFiles(repositoryFiles); return repositoryVm; }
9
public void mergeClips(Collection<SpriteClip> mergeClips) { if (mergeClips == null || mergeClips.size() == 0) { return; } if (mergeClips.size() == 1) { /** * If only 1 clip is selected, then find overlapping clips and merge them. */ SpriteClip selectedClip = mergeClips.iterator().next(); Collection<SpriteClip> overlappingSprites = new HashSet(); overlappingSprites.add(selectedClip); for (SpriteClip currentClip : clips) { if (selectedClip != currentClip && currentClip.getBoundingBox().intersects(selectedClip.getBoundingBox())) { overlappingSprites.add(currentClip); } } /* Once done, only merge if 2 sprites overlap */ if (overlappingSprites.size() >= 2) { clips.removeAll(overlappingSprites); SpriteClip newMergedClip = SpriteClip.makeMergedClip(overlappingSprites); clips.add(newMergedClip); } } else { // merge the selected clips clips.removeAll(mergeClips); SpriteClip newMergedClip = SpriteClip.makeMergedClip(mergeClips); clips.add(newMergedClip); } }
7
public IrodsFile asFile() throws IrodsException { if (exists()) { if (irodsFile.isFile()) { return (this instanceof JargonFile) ? (IrodsFile) this : new JargonFile(conn, irodsFile); } else { throw new IrodsException("irods object already exists and is not a file: " + getFullPath()); } } else { return new JargonFile(conn, irodsFile); } }
3
public TableListener(JTable table, Preference pref) { setTable(table); setPreference(pref); }
0
@Override public void renderControl(Graphics2D g) { BufferedImage control = new BufferedImage(this.getSize().getWidth(), this.getSize().getHeight(), BufferedImage.TYPE_INT_ARGB); BufferedImage itemsImage = new BufferedImage(this.getSize().getWidth() -10, 64 * this.Items.size(), BufferedImage.TYPE_INT_ARGB); this.drawItems(itemsImage.createGraphics()); Graphics2D g2d = (Graphics2D) control.getGraphics(); // Background if(this.getBackgroundColor() != null) { g2d.setColor(this.getBackgroundColor()); g2d.fillRect(0,0,this.getSize().getWidth(),this.getSize().getHeight()); } // Border if(this.BorderColor != null) { g2d.setColor(this.BorderColor); g2d.drawRect(0,0,this.getSize().getWidth() -1,this.getSize().getHeight() -1); } // Scrollbar g2d.setColor(this.ScrollBarColor); g2d.fillRect(this.getSize().getWidth() - 10,0,10,this.getSize().getHeight()); g2d.drawRect(this.getSize().getWidth() - 10,0, 9, this.getSize().getHeight() -1); // Scrollbutton Top Rectangle RectTop = new Rectangle(this.getSize().getWidth() - 10, 0, 10, 10); int ptX[] = {RectTop.x + 2, RectTop.x + 8, RectTop.x + 8}; int ptY[] = {RectTop.y + 2, RectTop.y + 2, RectTop.y + 8}; g2d.setColor(this.ScrollIconColor); g2d.fillPolygon(ptX, ptY, 3); // Scrollbutton bottom Rectangle RectBottom = new Rectangle(this.getSize().getWidth() - 10, this.getSize().getHeight() - 10, 10, 10); int pbX[] = {RectBottom.x + 2, RectBottom.x + 8, RectBottom.x + 8}; int pbY[] = {RectBottom.y + 8, RectBottom.y + 8, RectBottom.y + 2}; g2d.setColor(this.ScrollIconColor); g2d.fillPolygon(pbX, pbY, 3); // Items g2d.drawImage(itemsImage, 0, -this.ScrollYValue, this.getSize().getWidth() -10, 64 * this.Items.size(), null); g.drawImage(control, this.getLocation().getX(), this.getLocation().getY(), this.getSize().getWidth(), this.getSize().getHeight(), null); }
2
public void deleteHostFromTeams(String hostName){ try { cs = con.prepareCall("{call DELETE_HOST_FROM_TEAMS(?)}"); cs.setString(1, hostName); cs.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } }
1
public void pickedUpCoin(int xH, int yH) { Rectangle heroCoin = new Rectangle(xH, yH, 50, 50); if (rc1.intersects(heroCoin)) { coinPicked1 = true; button1Used = true; } if (rc2.intersects(heroCoin)) { coinPicked2 = true; button2Used = true; } if (rc3.intersects(heroCoin)) { coinPicked3 = true; button3Used = true; } if (rc4.intersects(heroCoin)) { coinPicked4 = true; button4Used = true; } }
4
public static void save() { try { File f; f = new File(System.getProperty("user.home") + "\\.Awesome Mario Remake\\MarioData.save"); if (!f.exists()) { f.createNewFile(); } FileOutputStream fos = new FileOutputStream(System.getProperty("user.home") + "\\.Awesome Mario Remake\\MarioData.save"); ObjectOutputStream oos = new ObjectOutputStream(fos); MarioData saveObject = MarioData.getMarioData(); oos.writeObject(saveObject); oos.close(); } catch (IOException ex) { //System.out.println(ex); JOptionPane.showMessageDialog(null, "Er is een fout opgetreden \n Voor het bevoegde gezag:" + ex, "Het lezen is mislukt", JOptionPane.WARNING_MESSAGE); } }
2
public LaenderGraph() { this.initKarte(); }
0
private void paintMarker(Graphics g) { Rectangle inside = getInside(); int length = (getOrientation() == HORIZONTAL) ? inside.width : inside.height; int[] xPoints, yPoints; int value = (int) (Math.max( 0, Math.min((1.0 / (getMaximum() - getMinimum())) * (getValue() - getMinimum()), 1)) * length); int valueBorder; if (getOrientation() == HORIZONTAL) { int xMiddle = inside.x + value; int yTop = inside.y; int yMiddle = (int) (inside.y + inside.height * 0.5); xPoints = new int[] { xMiddle - yMiddle, xMiddle, xMiddle + yMiddle }; yPoints = new int[] { yTop, yMiddle, yTop }; valueBorder = (int) (yMiddle * 0.2); } else { int yMiddle = (int) (inside.y + inside.height - value); int xMiddle = (int) (inside.x + inside.width * 0.5); int xTop = (int) (inside.x + inside.width); yPoints = new int[] { yMiddle - xMiddle, yMiddle, yMiddle + xMiddle }; xPoints = new int[] { xTop, xMiddle, xTop }; valueBorder = (int) (xMiddle * 0.2); } valueBorder = Math.max(1, valueBorder); Color actualColor = Color.YELLOW; AimSection[] sections = getSections(); int position = 0; for (int i = 0; i < sections.length; i++) { AimSection section = sections[i]; if (i == sections.length - 1) { actualColor = section.getColor(); break; } int newPosition = position + (int) (length * section.getSize()); if (value >= position && value <= newPosition) { actualColor = section.getColor(); break; } position = newPosition; } g.setColor(actualColor); g.fillPolygon(xPoints, yPoints, 3); g.setColor(Null.nvl(getAimColor(), Color.BLACK)); if (g instanceof Graphics2D) { Graphics2D g2d = (Graphics2D) g; g2d.setStroke(new BasicStroke(valueBorder, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); } g.drawPolygon(xPoints, yPoints, 3); }
7
public static void getControlSelect(Global global, GameContainer container){ if (global.getCurrent().getMenu().getName().equals("controlselect")){ Input input = container.getInput(); for (int i=0; i<Keyboard.KEYBOARD_SIZE; i++){ if (input.isKeyDown(i) && !input.isKeyDown(Input.KEY_LMENU)){ if (global.getCurrent().getMenu().getMenuItemByName("txt_key").getText().equals("Left")){ global.getOptions().setLeft(i); global.getMenuByName("controls").getMenuItemByName("txt_left").setText("Left: "+input.getKeyName(i)); } else if (global.getCurrent().getMenu().getMenuItemByName("txt_key").getText().equals("Right")){ global.getOptions().setRight(i); global.getMenuByName("controls").getMenuItemByName("txt_right").setText("Right: "+input.getKeyName(i)); } else if (global.getCurrent().getMenu().getMenuItemByName("txt_key").getText().equals("Jump")){ global.getOptions().setJump(i); global.getMenuByName("controls").getMenuItemByName("txt_jump").setText("Jump: "+input.getKeyName(i)); } else if (global.getCurrent().getMenu().getMenuItemByName("txt_key").getText().equals("Pause")){ global.getOptions().setPause(i); global.getMenuByName("controls").getMenuItemByName("txt_pause").setText("Pause: "+input.getKeyName(i)); } global.getCurrent().setMenu(global.getMenuByName("controls")); break; } } } }
8
protected void readImage() { ix = readShort(); // (sub)image position & size iy = readShort(); iw = readShort(); ih = readShort(); int packed = read(); lctFlag = (packed & 0x80) != 0; // 1 - local color table flag interlace = (packed & 0x40) != 0; // 2 - interlace flag // 3 - sort flag // 4-5 - reserved lctSize = 2 << (packed & 7); // 6-8 - local color table size if (lctFlag) { lct = readColorTable(lctSize); // read table act = lct; // make local table active } else { act = gct; // make global table active if (bgIndex == transIndex) bgColor = 0; } int save = 0; if (transparency) { save = act[transIndex]; act[transIndex] = 0; // set transparent color if specified } if (act == null) { status = STATUS_FORMAT_ERROR; // no color table defined } if (err()) return; decodeImageData(); // decode pixel data skip(); if (err()) return; frameCount++; // create new image to receive frame data image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); setPixels(); // transfer pixel data to image frames.add(new GifFrame(image, delay)); // add image to frame list if (transparency) { act[transIndex] = save; } resetFrame(); }
7
public static void generateNQueens(int[] position,int insertN,int n) { for (int i=0;i<n;i++){ position[insertN-1] = i; boolean satis = true; for (int j=0;j<insertN-1;j++){ if(insertN-1-j==position[insertN-1]-position[j]||insertN-1-j==position[j]-position[insertN-1]|| position[insertN-1]==position[j]){ satis = false; continue; } } if(satis){ if(insertN == n){ result++; return; } else { generateNQueens( position,insertN+1,n); } } } }
7
public int numDistinct(String S, String T) { int[][] dp = new int[T.length() + 1][S.length() + 1]; dp[0][0] = 1; //first column all 0 for (int i = 1; i <= T.length(); i++) { dp[i][0] = 0; } //first row all 1 for (int j = 1; j <= S.length(); j++) { dp[0][j] = 1; } //find match, then +1 for (int i = 1; i <= T.length(); i++) { for (int j = 1; j <= S.length(); j++) { dp[i][j] = dp[i][j - 1]; if (T.charAt(i - 1) == S.charAt(j - 1)) { dp[i][j] += dp[i - 1][j - 1]; } } } //return the number of last postion return dp[T.length()][S.length()]; }
5
public static int showOptionDialog(Component parentComponent, Object message, String title, boolean resizable, int optionType, int messageType, Icon icon, Object[] options, Object initialValue) { JOptionPane pane = new JOptionPane(message, messageType, optionType, icon, options, initialValue); pane.setUI(new SizeAwareBasicOptionPaneUI(pane.getUI())); pane.setInitialValue(initialValue); pane.setComponentOrientation((parentComponent == null ? JOptionPane.getRootFrame() : parentComponent).getComponentOrientation()); final JDialog dialog = pane.createDialog(getWindowForComponent(parentComponent), title); WindowSizeEnforcer.monitor(dialog); pane.selectInitialValue(); dialog.setResizable(resizable); final Component field = getFirstFocusableField(message); if (field != null) { dialog.addWindowFocusListener(new WindowAdapter() { @Override public void windowGainedFocus(WindowEvent event) { field.requestFocus(); dialog.removeWindowFocusListener(this); } }); } dialog.setVisible(true); dialog.dispose(); pane.setMessage(null); Object selectedValue = pane.getValue(); if (selectedValue != null) { if (options == null) { if (selectedValue instanceof Integer) { return ((Integer) selectedValue).intValue(); } } else { for (int i = 0; i < options.length; i++) { if (options[i].equals(selectedValue)) { return i; } } } } return JOptionPane.CLOSED_OPTION; }
7
@Test public void NotOccupiedName() throws Exception { LoginCheck logCh = new LoginCheck(); name = "sunny00000000000"; if (kesh.containsKey(name)) { assertFalse(kesh.get(name)); } else { boolean result = logCh.validate(name); kesh.put(name, result); assertFalse(result); } }
1
@Override public void method2() { System.out.println("Running: method2()"); }
0
private void removeAppActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeAppActionPerformed try { int result = JOptionPane.showConfirmDialog(null, CONFIRM_MSG, CONFIRM_MSG_TITLE, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { logger.log(Level.INFO, "=============== Removing Application \"" + jList1.getSelectedValue() + "\" from device (" + device.toString() + ")! ==============="); logger.log(Level.INFO, "ADB Output: " + device.getPackageController().uninstallApplication(false, jList1.getSelectedValue().toString())); logger.log(Level.INFO, "===============/Removing Application \"" + jList1.getSelectedValue() + "\" from device (" + device.toString() + ")!\\==============="); } } catch (IOException ex) { logger.log(Level.ERROR, "An error occurred while removing the application from the device: " + ex.toString() + "\n" + "The error stack trace will be printed to the console..."); ex.printStackTrace(System.err); } }//GEN-LAST:event_removeAppActionPerformed
2
public static void main(String[] args) throws ParserConfigurationException, SAXException, XMLStreamException { CommandLineParser clParser = new BasicParser(); Options options = new Options(); Option optFile = new Option(OPT_FILE, "file", true, "path to keepass xml file"); optFile.setArgName("path"); Option optHelp = new Option("h", "help", false, "print this message"); options.addOption(optFile); options.addOption(optHelp); try { CommandLine cl = clParser.parse(options, args); if (cl.hasOption("h")) { printUsage(options); } else { String path = cl.getOptionValue(OPT_FILE); readData(path); } } catch (ParseException e) { System.err.println("Unexpected error: " + e.getMessage()); printUsage(options); } }
2
public void set(final int portal, final Location block){ if(portal == 1) this.one = block; else if(portal == 2) this.two = block; else throw new IllegalArgumentException("Portal number must be 1 or 2"); }
2
@Override public int getWidth() { return width; }
0
public static void main(String[] args) { DataModel model = new DataModel(); SentenceSegmentation segmentation = new SentenceSegmentation(); List<Integer> list1 = model.getKeys1(); for (int i = 0; i < list1.size(); i++) { // dohvati tekst ključa koji se nalazi na i-toj poziciji liste int key = list1.get(i); String text = model.getElement(key); try { segmentation.loadAbbreviations("Hrvatski.txt"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } int splitPosition = segmentation.splitSearch(text); if (splitPosition == -1) { continue; } model.splitElement(key, splitPosition + 1, segmentation.safe); segmentation.safe = true; } }
5
@Override public void mouseDragged(MouseEvent evt) { if (!SwingUtilities.isLeftMouseButton(evt)) return; Point current = evt.getPoint(); double x = viewer.getCenter().getX(); double y = viewer.getCenter().getY(); if(prev != null){ x += prev.x - current.x; y += prev.y - current.y; } if (!viewer.isNegativeYAllowed()) { if (y < 0) { y = 0; } } int maxHeight = (int) (viewer.getTileFactory().getMapSize(viewer.getZoom()).getHeight() * viewer .getTileFactory().getTileSize(viewer.getZoom())); if (y > maxHeight) { y = maxHeight; } prev = current; viewer.setCenter(new Point2D.Double(x, y)); viewer.repaint(); }
5
public void handlePressedKeys(ArrayList<KeyButtons> keyPressed) { if (keyPressed.contains(KeyButtons.LEFT)) { left = true; } if (keyPressed.contains(KeyButtons.RIGHT)) { right = true; } if (keyPressed.contains(KeyButtons.UP)) { up = true; } if (keyPressed.contains(KeyButtons.DOWN)) { down = true; } if (keyPressed.contains(KeyButtons.CONFIRM)) { confirm = true; } }
5
public int getSelection() { if(selectionOvalY == 3) return 1; else if(selectionOvalY == 27) return 2; else if(selectionOvalY == 51) return 3; else if(selectionOvalY == 75) return 4; else if(selectionOvalY == 99) return 5; else if(selectionOvalY == 123) return 6; else if(selectionOvalY == 147) return 7; else if(selectionOvalY == 171) return 8; else return 0; }
8
@Override public void onRelocateTag( TagView tagViewToRelocate, TagView tagViewRelocationRef, InsertionPoint insertionPoint ) { //Prevent modification between two similar TagLists if( !this.containsTagView( tagViewToRelocate ) || !this.containsTagView( tagViewRelocationRef ) ) return; int fromIndex = -1; int toIndex = -1; for( int i = 0; i < this.tagItems.size(); i++ ) if( this.tagItems.get( i ).getTagView().equals( tagViewToRelocate ) ) fromIndex = i; else if( this.tagItems.get( i ).getTagView().equals( tagViewRelocationRef ) ) if( InsertionPoint.BEFORE == insertionPoint ) toIndex = i; else toIndex = i + 1; //Reorder tagItem list this.tagItems.add( toIndex, this.tagItems.get( fromIndex ) ); this.tagItems.remove( fromIndex > toIndex ? fromIndex + 1 : fromIndex ); //Reset TagListView for( TagItem tagItem : this.tagItems ) { this.tagListView.getTagsPanel().remove( tagItem.getTagView() ); this.tagListView.getTagsPanel().add( tagItem.getTagView() ); } }
8
private static void configureLoggerWrapperByConfigurator (LoggerWrapper loggerWrapper, Node configNode) { boolean goOn = true; Node classNameNode = configNode.getAttributes ().getNamedItem ("class-name"); String className = "(unknown)"; if (goOn) { if (classNameNode != null) { className = classNameNode.getTextContent ().trim (); } else { Exception ex = new Exception ("No meaningful class name node for LoggerWrapper " + loggerWrapper.getName ()); LogHelperDebug.printError (ex.getMessage (), ex, true); goOn = false; } } NodeList configSubnodes = configNode.getChildNodes (); Node configuration = null; if (goOn) { for (int subnodeIndex = 0; subnodeIndex < configSubnodes.getLength (); subnodeIndex++) { Node subnode = configSubnodes.item (subnodeIndex); String subnodeName = subnode.getNodeName ().trim ().toLowerCase (); if (subnodeName.equals ("configuration")) { configuration = subnode; break; } } if (configuration == null) { LogHelperDebug.printError ("No configuration node for configurator " + className, false); goOn = false; } } LoggerWrapperConfigurator configurator = null; if (goOn) { configurator = LoggerWrapperConfigurator.getInstance (className, loggerWrapper, configuration); if (configurator == null) { LogHelperDebug.printError ("No configurator instance returned for " + className, false); goOn = false; } } if (goOn) { boolean configuratorResult = configurator.configure (); LogHelperDebug.printMessage ("Has LoggerWrapper configurator " + className + " exited successfully? - " + configuratorResult, false); } }
9
@Override @SuppressWarnings("unchecked") public JsonElement serialize(GeoJsonObject src, Type typeOfSrc, JsonSerializationContext context) { Class<GeoJsonObject> cls; try { cls = (Class<GeoJsonObject>)Class.forName(GeoJson.class.getPackage().getName().concat(".").concat(src.getType())); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new JsonSyntaxException(e.getMessage()); } GsonBuilder builder = new GsonBuilder(); GeoJson.registerAdapters(builder); return builder.create().toJsonTree(src, cls); }
1
public static Transition[] getTransitionsForProduction( Production production, VariableDependencyGraph graph) { ArrayList list = new ArrayList(); String v1 = production.getLHS(); ProductionChecker pc = new ProductionChecker(); String rhs = production.getRHS(); for (int k = 0; k < rhs.length(); k++) { char ch = rhs.charAt(k); if (ProductionChecker.isVariable(ch)) { StringBuffer buffer = new StringBuffer(); buffer.append(ch); list.add(getTransition(v1, buffer.toString(), graph)); } } return (Transition[]) list.toArray(new Transition[0]); }
2
private AndroidMethod parseMethod(Matcher m) { assert(m.group(1) != null && m.group(2) != null && m.group(3) != null && m.group(4) != null); int groupIdx = 1; //class name String className = m.group(groupIdx++).trim(); //return type String returnType = m.group(groupIdx++).trim(); //method name String methodName = m.group(groupIdx++).trim(); //method parameter List<String> methodParameters = new ArrayList<String>(); String params = m.group(groupIdx++).trim(); if (!params.isEmpty()) for (String parameter : params.split(",")) methodParameters.add(parameter.trim()); //create method signature return new AndroidMethod(methodName, methodParameters, returnType, className); }
5
public String calculateResult(String expression) { String result = parseExpression(expression); Double lastOperand = 0.0; // If no exception pop the top operand if (result.equals("")) { lastOperand = operands.top(); operands.pop(); } // If no operands are left set result to the last operand if (operands.isEmpty() && result.equals("")) result = lastOperand.toString(); // If operands remain, but not previous exceptions an operation needs to // be performed on the remaining operands if (!operands.isEmpty() && result.equals("")) result = "Invalid expression. There are two operands left, but no " + "operator."; // The result is out of range, throw an exception if (lastOperand < -500000000 || lastOperand > 1000000000) result = "The answer is out of the range -500,000,000 to 1,000,000,000"; return result; }
7
@Override public void actionPerformed(ActionEvent arg0) { Component f = ui; while ((f != null) && (!(f instanceof Window))) f = f.getParent(); if (arg0.getActionCommand().equalsIgnoreCase("Cancel")) { if (f != null) f.setVisible(false); } else if (arg0.getActionCommand().equalsIgnoreCase("Save")) { if (name.getText().length() == 0) JOptionPane.showConfirmDialog(ui, "Name cannot be empty", "ERROR", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); else if (url.getText().length() == 0) JOptionPane.showConfirmDialog(ui, "Image URL cannot be empty", "ERROR", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); else { // Fetch the URL to validate setName(name.getText()); setImageURL(url.getText()); save(); if (f != null) f.setVisible(false); } } }
8
@Override protected void dispatchEvent(AWTEvent event) { // Potentially intercept KeyEvents if (event.getID() == KeyEvent.KEY_TYPED || event.getID() == KeyEvent.KEY_PRESSED || event.getID() == KeyEvent.KEY_RELEASED) { KeyEvent keyEvent = (KeyEvent)event; KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(keyEvent); // When using Key Bindings, the source of the KeyEvent will be // the Window. Check each panel belonging to the source Window. for (DisabledPanel panel: panels.keySet()) { Window panelWindow = SwingUtilities.windowForComponent(panel); // A binding was found so just return without dispatching it. if (panelWindow == keyEvent.getComponent() && searchForKeyBinding(panel, keyStroke)) return; } } // Dispatch normally super.dispatchEvent(event); }
6