text
stringlengths
14
410k
label
int32
0
9
@Override protected void validateParameters(Map<String, String> parameters) { //mandatory parameters for multi use pipeline if (!parameters.containsKey("globalAmountLimit")) { throw new RuntimeException("globalAmountLimit is missing in parameters."); } //conditional parameters for multi use pipeline if (parameters.containsKey("isRecipientCobranding") && !parameters.containsKey("recipientTokenList")) { throw new RuntimeException("recipientTokenList is missing in parameters."); } if (parameters.containsKey("usageLimitType1") && !parameters.containsKey("usageLimitValue1")) { throw new RuntimeException("usageLimitValue1 is missing in parameters."); } if (parameters.containsKey("usageLimitType2") && !parameters.containsKey("usageLimitValue2")) { throw new RuntimeException("usageLimitValue2 is missing in parameters."); } }
7
public static void main(String[] args) throws Exception{ String fileName=args[0]; int jarPost=fileName.indexOf(".jar"); String jarName=fileName.substring(0,jarPost); // String jarName="ciku"; f = new ZipFile(fileName); Enumeration<? extends ZipEntry> en=f.entries(); Scanner checkAllAPI=new Scanner(new FileInputStream("android_java_api")); HashMap<String,Boolean> androidAllAPI=new HashMap<String,Boolean>(); while(checkAllAPI.hasNextLine()){ androidAllAPI.put(checkAllAPI.nextLine(), true); } checkAllAPI.close(); Scanner checkAPI=new Scanner(new FileInputStream("android_api")); HashMap<String,Boolean> androidAPI=new HashMap<String,Boolean>(); while(checkAPI.hasNextLine()){ androidAPI.put(checkAPI.nextLine(), true); } checkAPI.close(); ASTClassNode head=new ASTClassNode(); head.setName(jarName); while(en.hasMoreElements()){ ZipEntry e=en.nextElement(); String name=e.getName(); if(name.endsWith(".class")){ //for each .class file in jar do analysis // ClassLoader cl=ClassLoader.getSystemClassLoader(); // InputStream a=cl.getResourceAsStream("./QuickDictActivity.class"); // ClassReader cr=new ClassReader(a); ClassReader cr=new ClassReader(f.getInputStream(e)); ClassNode classNode=new ClassNode(); cr.accept(classNode, 0); HashMap<String,ASTFieldNode> fieldVariable=new HashMap<String,ASTFieldNode>(); ASTClassNode astClassNode=new ASTClassNode(); astClassNode.setName(classNode.name); astClassNode.setSuperName(classNode.superName); head.setChild(astClassNode); for(Object inter:classNode.interfaces){ astClassNode.addInterface(inter.toString()); } @SuppressWarnings("unchecked") List<MethodNode> mnList=(List<MethodNode>)classNode.methods; try{ for(MethodNode mn:mnList){ ASTfactory af=new ASTfactory(); af.generateFunctionAST(mn,fieldVariable); ASTFunctionNode functionNode=(ASTFunctionNode)af.getASTNode(); functionNode.setParentClass(astClassNode); astClassNode.setChild(functionNode); } }catch(Exception ex){ PrintWriter pwErr=new PrintWriter(new FileOutputStream(jarName+"_err.txt")); pwErr.println(ex.getMessage()); pwErr.close(); System.out.println("Failed: "+jarName); } } } ASTPrinter print=new ASTPrinter(head,jarName,androidAPI,androidAllAPI); print.makeMatrix(true); System.out.println("Succeed: "+jarName); }
8
private void parseEllipsoid(Map<String, String> params, DatumParameters datumParam) { double b = 0; String s; /* * // not supported by PROJ4 s = (String) params.get(Proj4Param.R); if (s != * null) a = Double.parseDouble(s); */ String code = params.get(Proj4Keyword.ellps); if (code != null) { Ellipsoid ellipsoid = registry.getEllipsoid(code); if (ellipsoid == null) { throw new InvalidValueException("Unknown ellipsoid: " + code); } datumParam.setEllipsoid(ellipsoid); } /* * Explicit parameters override ellps and datum settings */ s = params.get(Proj4Keyword.a); if (s != null) { double a = Double.parseDouble(s); datumParam.setA(a); } s = params.get(Proj4Keyword.es); if (s != null) { double es = Double.parseDouble(s); datumParam.setES(es); } s = params.get(Proj4Keyword.rf); if (s != null) { double rf = Double.parseDouble(s); datumParam.setRF(rf); } s = params.get(Proj4Keyword.f); if (s != null) { double f = Double.parseDouble(s); datumParam.setF(f); } s = params.get(Proj4Keyword.b); if (s != null) { b = Double.parseDouble(s); datumParam.setB(b); } if (b == 0) { b = datumParam.getA() * Math.sqrt(1. - datumParam.getES()); } parseEllipsoidModifiers(params, datumParam); /* * // None of these appear to be supported by PROJ4 ?? * * s = (String) * params.get(Proj4Param.R_A); if (s != null && Boolean.getBoolean(s)) { a *= * 1. - es * (SIXTH + es * (RA4 + es * RA6)); } else { s = (String) * params.get(Proj4Param.R_V); if (s != null && Boolean.getBoolean(s)) { a *= * 1. - es * (SIXTH + es * (RV4 + es * RV6)); } else { s = (String) * params.get(Proj4Param.R_a); if (s != null && Boolean.getBoolean(s)) { a = * .5 * (a + b); } else { s = (String) params.get(Proj4Param.R_g); if (s != * null && Boolean.getBoolean(s)) { a = Math.sqrt(a * b); } else { s = * (String) params.get(Proj4Param.R_h); if (s != null && * Boolean.getBoolean(s)) { a = 2. * a * b / (a + b); es = 0.; } else { s = * (String) params.get(Proj4Param.R_lat_a); if (s != null) { double tmp = * Math.sin(parseAngle(s)); if (Math.abs(tmp) > MapMath.HALFPI) throw new * ProjectionException("-11"); tmp = 1. - es * tmp * tmp; a *= .5 * (1. - es + * tmp) / (tmp * Math.sqrt(tmp)); es = 0.; } else { s = (String) * params.get(Proj4Param.R_lat_g); if (s != null) { double tmp = * Math.sin(parseAngle(s)); if (Math.abs(tmp) > MapMath.HALFPI) throw new * ProjectionException("-11"); tmp = 1. - es * tmp * tmp; a *= Math.sqrt(1. - * es) / tmp; es = 0.; } } } } } } } } */ }
8
public void alert(String msg){ for (Player p : Bukkit.getOnlinePlayers()) { if (p.hasPermission("hyperpvp.seereports")) { p.sendMessage(msg); } } }
2
public static void main(String[] argument) { try { if (argument.length == 4) { InputStream inputStream = new FileInputStream(argument[0]); OutputStream outputStream = new DeflaterOutputStream(new FileOutputStream(argument[1]), new Deflater(Integer.parseInt(argument[2]), Boolean.getBoolean(argument[3]))); int value = inputStream.read(); while (-1 != value) { outputStream.write(value); value = inputStream.read(); } } else if (argument.length == 2) { for (int level = -1; level < 10; ++level) { for (int nowrapInt = 0; nowrapInt < 2; ++nowrapInt) { boolean nowrap = (0 == nowrapInt); InputStream inputStream = new FileInputStream(argument[0]); OutputStream outputStream = new DeflaterOutputStream(new FileOutputStream(argument[1] + "." + String.valueOf(nowrap) + "." + String.valueOf(level)), new Deflater(level, nowrap)); int value = inputStream.read(); while (-1 != value) { outputStream.write(value); value = inputStream.read(); } outputStream.close(); inputStream.close(); } } } else { throw new RuntimeException("Usage: Compressor <uncompressed data file> <compressed data file> [<compression level> <nowrap>]"); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
7
private int edmondKarp() { int f = 0; // Det maximala flödet int m, bFlow; Edge v, u, ub; while (true) { // Infinate loop m = BFS(); if (DEBUG_EK) { System.err.println("m: " + m + " path: " + edgeArrayToString(path)); } // When the BFS doesn't find anymore augmenting paths if (m == 0) { break; // Break out of the infinate loop } f = f + m; // Update the total flow with the found path // Backtrack search, and write flow v = path[drain]; // Aslong as source != drain while (source != v.getEnd()) { // förändringar sparas inte i grafstrukturen utan endast lokalt u = path[v.getEnd()]; // Error handling if (u.getEnd() == v.getEnd() && u.getRestCapacity() > 0) { ub = u.getRetEdge(); u.setFlow(u.getFlow() + m); bFlow = ub.getFlow() - m; ub.setFlow(bFlow); if (DEBUG_EK) { System.err.println("[" + u + "] [ " + ub + "]"); } if (u.isDirection() && !u.isInResult()) { ansArr.add(u); u.setInResult(true); } } v = path[u.getStart()]; } } return f; }
9
public static Set<Node> findMostVisitedNodes(Set<TreeRandForest> ngfForest, int noNodes){ HashMap<Node, Integer> countNode = new HashMap<Node, Integer>(); // map Node to # visits for (TreeRandForest t : ngfForest){ for (Node n : t.features()){ if (countNode.containsKey(n)){ countNode.put(n, countNode.get(n)+1); } else { countNode.put(n, 1); } } } // find the highest visited nodes Set<Node> bestNodes = new HashSet<Node>(); PriorityQueue<NodeRanker> ranker = new PriorityQueue<NodeRanker>(); for (Node n : countNode.keySet()){ ranker.add(new NodeRanker(n, countNode.get(n))); } int i = 0; while (!ranker.isEmpty() && i < noNodes){ bestNodes.add(ranker.poll().n); i++; } System.err.println("Best nodes NGF:"); for (Node n : bestNodes){ System.err.println(n.label); } return bestNodes; }
7
@Override public double[] get2DData(int px, int pz, int sx, int sz) { double[] res = new double[sx*sz]; int ind = 0; for (int x = 0; x < sx; x++) for (int z = 0; z < sz; z++) { double xin = (x + px) / xScale; double yin = (z + pz) / zScale; double n0, n1, n2; // Noise contributions from the three corners // Skew the input space to determine which simplex cell we're in final double F2 = 0.5 * (Math.sqrt(3.0) - 1.0); double s = (xin + yin) * F2; // Hairy factor for 2D int i = fastfloor(xin + s); int j = fastfloor(yin + s); final double G2 = (3.0 - Math.sqrt(3.0)) / 6.0; double t = (i + j) * G2; double X0 = i - t; // Unskew the cell origin back to (x,y) space double Y0 = j - t; double x0 = xin - X0; // The x,y distances from the cell origin double y0 = yin - Y0; // For the 2D case, the simplex shape is an equilateral triangle. // Determine which simplex we are in. int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords if (x0 > y0) { i1 = 1; j1 = 0; } // lower triangle, XY order: (0,0)->(1,0)->(1,1) else { i1 = 0; j1 = 1; } // upper triangle, YX order: (0,0)->(0,1)->(1,1) // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-sqrt(3))/6 double x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords double y1 = y0 - j1 + G2; double x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords double y2 = y0 - 1.0 + 2.0 * G2; // Work out the hashed gradient indices of the three simplex corners int ii = i & 255; int jj = j & 255; int gi0 = perm[ii + perm[jj]] % 12; int gi1 = perm[ii + i1 + perm[jj + j1]] % 12; int gi2 = perm[ii + 1 + perm[jj + 1]] % 12; // Calculate the contribution from the three corners double t0 = 0.5 - x0 * x0 - y0 * y0; if (t0 < 0) { n0 = 0.0; } else { t0 *= t0; n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient } double t1 = 0.5 - x1 * x1 - y1 * y1; if (t1 < 0) { n1 = 0.0; } else { t1 *= t1; n1 = t1 * t1 * dot(grad3[gi1], x1, y1); } double t2 = 0.5 - x2 * x2 - y2 * y2; if (t2 < 0) { n2 = 0.0; } else { t2 *= t2; n2 = t2 * t2 * dot(grad3[gi2], x2, y2); } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. double val = 35.0 * (n0 + n1 + n2) + 0.5; res[ind++] = min + val * (max - min); } return res; }
6
public void notifyStopped(SoundRecord paramSoundRecord, boolean paramBoolean) { if (paramSoundRecord.getSoundListener() != null) { paramSoundRecord.getSoundListener().soundStopped(paramSoundRecord.getName(), paramBoolean ? 0 : this.muted ? 2 : 1); } this.soundRecords.removeElement(paramSoundRecord); }
3
public String printCreatures(){ String result = ""; for (int i = 0; i < this.creatures.size(); i++) { Creature tempItem = this.creatures.get(i); if (i == (this.creatures.size() - 1)) { if (tempItem.toString().substring(0, 3).equals("The")) { result += (tempItem.toString()); } else { result += (tempItem.toString() + ("(" + tempItem.getCourse().toString() + ")")); } } else { if (tempItem.toString().substring(0, 3).equals("The")) { result += (tempItem.toString() + ", "); } else { result += (tempItem.toString() + ("(" + tempItem.getCourse().toString() + ")") + ", "); } } } return result; }
4
public static RgbImage convertToRgb(HsvImage hsv) { RgbImage rgb = new RgbImage(hsv.getWidth(), hsv.getHeight()); for (int x = 0; x < rgb.getWidth(); x++) { for (int y = 0; y < rgb.getHeight(); y++) { RgbPixel px = convertPixel(hsv, x, y); rgb.setPixel(x, y, RED, px.red); rgb.setPixel(x, y, GREEN, px.green); rgb.setPixel(x, y, BLUE, px.blue); } } return rgb; }
2
@XmlElementDecl(namespace = "http://www.w3.org/2001/04/xmlenc#", name = "EncryptedKey") public JAXBElement<EncryptedKeyType> createEncryptedKey(EncryptedKeyType value) { return new JAXBElement<EncryptedKeyType>(_EncryptedKey_QNAME, EncryptedKeyType.class, null, value); }
0
public void exportCSV() { try { PrintWriter pw = new PrintWriter("export.csv"); pw.println("\"Step\",\"Server\",\"Application\",\"Links\""); int step = 0; for (int i = 0; i < bpgHistory.getApplicationHistory().get(step).size(); i++) { for (int j = 0; j < bpgHistory.getServerHistory().get(step).size(); j++) { int value = 0; for (String serverService : bpgHistory.getServerHistory().get(step).get(j).services) { if (bpgHistory.getApplicationHistory().get(step).get(i).services.contains(serverService)) { value++; } } pw.println("\"" + step + "\",\"" + bpgHistory.getServerHistory().get(step).get(j).name + "\",\"" + bpgHistory.getApplicationHistory().get(step).get(i).name + "\",\"" + value + "\""); } } step = bpgHistory.getStepNumber() - 1; for (int i = 0; i < bpgHistory.getApplicationHistory().get(step).size(); i++) { for (int j = 0; j < bpgHistory.getServerHistory().get(step).size(); j++) { int value = 0; for (String serverService : bpgHistory.getServerHistory().get(step).get(j).services) { if (bpgHistory.getApplicationHistory().get(step).get(i).services.contains(serverService)) { value++; } } pw.println("\"" + step + "\",\"" + bpgHistory.getServerHistory().get(step).get(j).name + "\",\"" + bpgHistory.getApplicationHistory().get(step).get(i).name + "\",\"" + value + "\""); } } } catch (FileNotFoundException e) { e.printStackTrace(); } }
9
private static boolean getKeyUp(int keyCode) { return !getKey(keyCode) && lastKeys[keyCode]; }
1
public ITestRefImpl(ITestParamState initRefParam) { ITestParamState useClassParam = initRefParam.getElement(USE_CLASS); if ( null != useClassParam && null != useClassParam.getValue() ) { try { this.useClass = Class.forName(useClassParam.getValue()); } catch (ClassNotFoundException e) { throw new ITestInitializationException(useClassParam.getValue(), e); } } else { useClass = null; } ITestParamState useParam = initRefParam.getElement(USE); if ( useParam != null ) { use = useParam.getValue(); } else { use = null; } ITestParamState assignParam = initRefParam.getElement(ASSIGN); if ( null != assignParam ) { if ( null == assignParam.getElement("0") ) { assign = new String[] { assignParam.getValue() }; } else { Collection<String> assignCol = new ArrayList<String>(); for (int i = 0;; i++) { ITestParamState assignP = assignParam.getElement(String.valueOf(i)); if ( null == assignP ) { break; } assignCol.add(assignP.getValue()); } assign = assignCol.toArray(new String[assignCol.size()]); } } else { assign = EMPTY_ASSIGNMENT; } }
8
public final void setLName(String lname) { if(lname == null || lname.isEmpty()){ throw new IllegalArgumentException(); } this.lName = lname; }
2
private boolean checkIfDFAisComplete() { Transition[] t=automaton.getTransitions(); State[] s=automaton.getStates(); TreeSet <String> reads=new TreeSet<String>(); for (int i=0; i<t.length; i++) { reads.add(t[i].getDescription()); } int count=0; for (int i=0; i<s.length; i++) { Transition[] tt=automaton.getTransitionsFromState(s[i]); if (tt.length<reads.size()) count++; } if (count==0) return true; return false; }
4
private List<String> retriveData(String projectionLink) throws IOException { List<String> playerData = new ArrayList<String>(); InputStream input = new URL(projectionLink).openStream(); try (BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"))) { // skips header information for (int i = 0; i < LINES_TO_SKIP; i++) br.readLine(); for (String line; (line = br.readLine()) != null; ) { if (line != null) { playerData.add(line); } } } return playerData; }
3
@Override public int compareTo(Contestant otherC) { // ugly, but works. :) // account for null: if (isNull() && otherC.isNull()) { return 0; } else if (isNull() && !otherC.isNull()) { return -1; } else if (!isNull() && otherC.isNull()) { return 1; } // otherwise both are not null: int result = getID().compareToIgnoreCase(otherC.getID()); if (result == 0) { result = getLastName().compareToIgnoreCase(otherC.getLastName()); if (result == 0) { result = getFirstName().compareToIgnoreCase(otherC.getLastName()); if (result == 0) { result = getTribe().compareTo(otherC.getTribe()); } } } return result; }
9
public void play(InputStream source) { // use a short, 100ms (1/10th sec) buffer for real-time // change to the sound stream int bufferSize = format.getFrameSize() * Math.round(format.getSampleRate() / 10); byte[] buffer = new byte[bufferSize]; // create a line to play to SourceDataLine line; try { DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); line = (SourceDataLine)AudioSystem.getLine(info); line.open(format, bufferSize); } catch (LineUnavailableException ex) { ex.printStackTrace(); return; } // start the line line.start(); int numBytesRead = 0; // copy data to the line try { while (numBytesRead != -1) { if (playing){ numBytesRead = source.read(buffer, 0, buffer.length); if (numBytesRead != -1) { line.write(buffer, 0, numBytesRead); } } else if (kill){ numBytesRead = -1; } } } catch (IOException ex) { ex.printStackTrace(); } // wait until all data is played, then close the line line.drain(); line.close(); }
6
private void fire(Type t, EventObject E) { Object[] listeners = ll.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { ((Listener) listeners[i + 1]).notice(t, E); } }
1
private boolean setAustinMap(String mapName){ Image mapImage = null; ImageIcon imageIcon; boolean hasFile = false; austinSearchPanel.appendText(">> Connecting... \n" + ">> Destination: " + urlStr + " \n"); if (url_status){//If URL connection is available, downloads the image. try { URL url = new URL(urlStr + mapName); //get the Houston map from the Server imageIcon = new ImageIcon(url); mapImage = imageIcon.getImage(); austinSearchPanel.appendText(">> Received the city Map from the remote URL server... \n"); hasFile = true; }catch(MalformedURLException em) { try{ //If URL connection is unavailable, get the local image instead. austinSearchPanel.appendText(">> Network resource file are unavailable... \n" + ">> Use the local file instead \n"); mapImage = getLocalImage(mapName, austinSearchPanel); hasFile = true; }catch(Exception ex){ printError(austinSearchPanel, ex, mapName); return false; } }catch(Exception e){ printError(austinSearchPanel, e, mapName); } }else{//If URL connection is unavailable, use the local image file. try{ // Get the local image instead. mapImage = getLocalImage(mapName, austinSearchPanel); austinSearchPanel.appendText(">> Network resource file are unavailable... \n" + ">> Use the local file instead \n"); mapImage = getLocalImage(mapName, austinSearchPanel); hasFile = true; }catch(Exception exc){ printError(austinSearchPanel, exc, mapName); } } if (hasFile){ mapCanvas.reset(mapImage); //resets the canvas with the new map return true; } return false; }
6
public void setItem(int index, int id, short dam, String title, String action, List<String> lore) throws IllegalArgumentException { String[] acpar = action.split("\\|"); if(acpar.length != 2) return; if(index < 0 || index > 26) throw new IllegalArgumentException("Index is "+(index < 0 ? "too small" : "too large")); ItemStack i = new ItemStack(id, 1, dam); ItemMeta meta = i.getItemMeta() == null ? i.getItemMeta() : Bukkit.getItemFactory().getItemMeta(i.getType()); meta.setDisplayName(ChatColor.RESET+title); meta.setLore(lore); i.setItemMeta(meta); this.contents[index] = i; this.slots[index] = new Slot(acpar[0], acpar[1]); }
5
public int[][] getPixels2i() { int r; int[][] pix = new int[ih][iw]; double[] tem = new double[ih * iw]; double max = 0, temp, re, im; System.out.println("还原图开始"); for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { re = fd[j * w + i].re(); im = fd[j * w + i].im(); temp = (int) Math.sqrt(re * re + im * im); System.out.print(temp+"\t"); if (max < temp) max = temp; tem[i + j * w] = temp; } System.out.println(); } System.out.println("还原图结束"); for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { //r = (int) (tem[i + j * w] / max); r = (int) (tem[i + j * w]); pix[j][i] = r; } } return pix; }
5
@Override public void setupJob(JobContext jobContext) throws IOException { /** * note: we don't really have to do anything here - * MongoDB is one of the few systems that don't require you to * create a database or collection before writing to it * * but in order to ingest a ton of data quickly we have to * pre-split the output collection * */ Configuration conf = jobContext.getConfiguration(); if(conf.getBoolean("mongo.output.skip_splitting", false)) return; String database = conf.get("mongo.output.database"); String collection = conf.get("mongo.output.collection"); // connect to global db Mongo m = new Mongo("localhost"); DB db = m.getDB(database); DB admindb = m.getDB("admin"); DB configdb = m.getDB("config"); // optionally drop the existing collection boolean drop = conf.getBoolean("mongo.output.drop", false); DBCollection coll = db.getCollection(collection); if(drop) { coll.drop(); } else { if(coll.count() > 0) { // don't shard an existing collection - may already be sharded ... return; } } // get a list of shards ArrayList<String> shards = new ArrayList<String>(); for(DBObject s : configdb.getCollection("shards").find()) { shards.add((String)s.get("_id")); } if(shards.size() < 2) { // don't let's be silly - nice sharded cluster, no shard return; } // shard the new output collection BasicDBObjectBuilder builder = new BasicDBObjectBuilder(); builder.add("enableSharding", database); admindb.command(builder.get()); builder = new BasicDBObjectBuilder(); builder.add("shardCollection", database + "." + collection); // just shard on _id - but user gets to decide what the _id is builder.add("key", new BasicDBObject("_id", 1)); admindb.command(builder.get()); // pre-split to get parallel writes // this http://www.mongodb.org/display/DOCS/Splitting+Chunks says // balancer moving chunks should take 5 minutes ... too long // wonder if moveChunk command is faster // well we could do it anyway - the jobs that can benefit from it will // check for user-submitted splitPoints String[] splits; String splitString = conf.get("mongo.output.split_points",""); // generate our own split points if necessary if(splitString.equals("")) { long max = (long)Math.pow(93.0, 5.0); long step = max / shards.size(); splits = new String[shards.size() -1]; // assume human readable keys for(int i=0; i < shards.size() - 1; i++) { splits[i] = splitPointForLong(step * (i+1)); } } else { splits = splitString.split(","); } HashMap<String, Object> splitCmd = new HashMap<String, Object>(); splitCmd.put("split", database + "." + collection); splitCmd.put("middle", ""); HashMap<String, Object> moveCmd = new HashMap<String, Object>(); moveCmd.put("moveChunk", database + "." + collection); moveCmd.put("find", ""); moveCmd.put("to", ""); // do the splitting and migrating // we assign chunks to shards in a round-robin manner int i=0; for(String split : splits) { splitCmd.remove("middle"); splitCmd.put("middle", new BasicDBObject("_id", split)); // create new chunk admindb.command(new BasicDBObject(splitCmd)); // move to shard moveCmd.remove("find"); moveCmd.put("find", new BasicDBObject("_id", split)); moveCmd.put("to", shards.get(i)); admindb.command(new BasicDBObject(moveCmd)); i = (i + 1) % shards.size(); } }
8
public void pickCode() { codeNum1 = (int) (Math.random()*10); do { codeNum2 = (int) (Math.random()*10); } while (codeNum2==codeNum1); do { codeNum3 = (int) (Math.random()*10); } while ((codeNum3==codeNum1)||(codeNum3==codeNum2)); do { codeNum4 = (int) (Math.random()*10); } while ((codeNum4==codeNum1)||(codeNum4==codeNum2)||(codeNum4==codeNum3)); }
6
private Move searchStrategy() { Move move = null; double maxCoinsPerMove = 0; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { Point p = board.getPoint(x, y); // Only focus on capturing neutral or opponent coins if (p.owner != id) { ArrayList<Move> moves = movesToDoubleValue(new Board(board), new Coord(x,y), pr, id); if (moves != null) { double coinsPerMove = p.value / moves.size(); if (coinsPerMove > maxCoinsPerMove) { maxCoinsPerMove = coinsPerMove; move = moves.get(0); // Actually make the first move in the sequence } } } } } // If we can't capture neutral or opponent coins, just make some valid move if (move == null) { for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { ArrayList<Coord> validMoves = board.validMovesFrom(x, y, pr); if (!validMoves.isEmpty()) { move = new Move(x, y, validMoves.get(0).x, validMoves.get(0).y, id); } } } } return move; }
9
public String beschrijving() { StringBuilder s = new StringBuilder(); s.append(standaardGegevens()); if (ouders != null) { if(ouders.getOuder1() != null) s.append("; 1e ouder: ").append(ouders.getOuder1().getNaam()); if(ouders.getOuder2() != null) s.append("; 2e ouder: ").append(ouders.getOuder2().getNaam()); } if (!gezinnen.isEmpty()) { s.append("; is ouder in gezin "); for (Gezin g : gezinnen) { s.append(g.getNr()).append(" "); } } return s.toString(); }
5
public double getValue() { return value; }
0
public void putAll( Map<? extends Character, ? extends Double> map ) { Iterator<? extends Entry<? extends Character,? extends Double>> it = map.entrySet().iterator(); for ( int i = map.size(); i-- > 0; ) { Entry<? extends Character,? extends Double> e = it.next(); this.put( e.getKey(), e.getValue() ); } }
8
String checkPrivCommand (String msg) { Scanner s = new Scanner(msg); String command = s.next(); int tableID = 0; if (s.hasNext(tablePattern)) { tableID = s.nextInt(); } String d = s.next(datePattern); String t = s.next(timePattern); String key = s.next(keyPattern[tableID]); String value = s.next(valuePattern[tableID]); String dummy; if (s.hasNext(hexcharPattern)) { dummy = s.next(hexcharPattern); } if (s.hasNext(defaultValuePattern)) // rpt2 { dummy = s.next(defaultValuePattern); } else { return null; } if (s.hasNext(defaultValuePattern)) // urcall { String urcall = s.next(defaultValuePattern); if (urcall.startsWith("PRIV")) { return urcall; } if (urcall.startsWith("VIS")) { return urcall; } if (urcall.startsWith("//")) { return urcall; } } return null; }
7
public int getLUSLength(){ //Run the LUS computations, if they haven't been done yet if (lus_cache.isEmpty()) getLUS(false); return lus_max_length; }
1
private void addBlockToRed() { debug("Adding block to red"); if (rLoc1.getBlock().getType() == Material.AIR) { rLoc1.getBlock().setType(Material.GOLD_BLOCK); } else if (rLoc2.getBlock().getType() == Material.AIR) { rLoc2.getBlock().setType(Material.GOLD_BLOCK); } else if (rLoc3.getBlock().getType() == Material.AIR) { rLoc3.getBlock().setType(Material.GOLD_BLOCK); } else if (rLoc4.getBlock().getType() == Material.AIR) { rLoc4.getBlock().setType(Material.GOLD_BLOCK); } }
4
public void method558(int i, int j) { if(i < 0 || i > versions.length || j < 0 || j > versions[i].length) return; if(versions[i][j] == 0) return; synchronized(nodeSubList) { for(OnDemandData onDemandData = (OnDemandData) nodeSubList.reverseGetFirst(); onDemandData != null; onDemandData = (OnDemandData) nodeSubList.reverseGetNext()) if(onDemandData.dataType == i && onDemandData.ID == j) return; OnDemandData onDemandData_1 = new OnDemandData(); onDemandData_1.dataType = i; onDemandData_1.ID = j; onDemandData_1.incomplete = true; synchronized(aClass19_1370) { aClass19_1370.insertHead(onDemandData_1); } nodeSubList.insertHead(onDemandData_1); } }
8
public static void deleteVelo(Velo velo) { Statement stat; try { stat = ConnexionDB.getConnection().createStatement(); stat.executeUpdate("delete from velo where id_velo="+ velo.getId_velo()); } catch (SQLException e) { while (e != null) { System.out.println(e.getErrorCode()); System.out.println(e.getMessage()); System.out.println(e.getSQLState()); e.printStackTrace(); e = e.getNextException(); } } }
2
public void gatherInformation() { StringBuilder builder = new StringBuilder(); //Append current date String date = new SimpleDateFormat("YYYY-MM-dd").format(new Date()); builder.append("Date="); builder.append(date); builder.append("\n"); if(Main.VERBOSE) System.out.println("[INFO] Gathering build date..."); if (!omitGit) { //Append Git information if(Main.VERBOSE) System.out.println("[INFO] Gathering Git information..."); builder.append("\n"); builder.append("##### Git Information #####"); builder.append("\n"); GitGrabber gitGrabber = new GitGrabber(commitDigits, builder); gitGrabber.grabData(); } if (!omitJVM) { //Append JVM information if(Main.VERBOSE) System.out.println("[INFO] Gathering JVM information..."); builder.append("\n"); builder.append("##### JVM Information #####"); builder.append("\n"); JVMGrabber jvmGrabber = new JVMGrabber(builder); jvmGrabber.grabData(); } if (!omitOS) { if(Main.VERBOSE) System.out.println("[INFO] Gathering OS information..."); //Append OS information builder.append("\n"); builder.append("##### OS Information #####"); builder.append("\n"); OSGrabber osGrabber = new OSGrabber(builder); osGrabber.grabData(); } Writer writer = new Writer(builder, outputLocation); writer.write(); System.out.println("Successfully written build data to specified file."); System.out.println("Process completed in " + (System.currentTimeMillis() - startTime) + " ms."); }
7
@Override public void contextInitialized(ServletContextEvent sce) { logger.info("Initialize JdbcRealm database"); Connection cnn = null; try { if (dataSource == null) { throw new IllegalStateException("DataSource not injected, verify in web.xml that 'metadata-complete' is not set to 'true'"); } cnn = dataSource.getConnection(); testDatabaseConnectivity(cnn); createTablesIfNotExist(cnn); insertUserIfNotExists("john", "doe", "user", cnn); insertUserIfNotExists("cloudbees", "beescloud", "user", cnn); } catch (Exception e) { logger.log(Level.SEVERE, "Exception starting app", e); } finally { closeQuietly(cnn); } }
2
@Override public void tick(int i, int j, int k) { Vector2 buttonPos = new Vector2((float) (pos.x+(dim.x-buttonWidth)*progress),pos.y); if(buttonPos.getColliderWithDim(new Vector2(buttonWidth,dim.y)).isPointInside(new Vector2(i,j)) && Remote2D.hasMouseBeenPressed()) { mouseDown = true; offset = i-buttonPos.x; } if(mouseDown && Mouse.isButtonDown(0)) { float xPos = i-offset+buttonWidth/2-pos.x; xPos = Math.max(buttonWidth/2, Math.min(dim.x-buttonWidth/2,xPos))-buttonWidth/2; progress = xPos/(dim.x-buttonWidth); } else if(!Mouse.isButtonDown(0)) mouseDown = false; }
5
private int[] getResList() { Object[] resList = super.getLocalResourceList(); int resourceID[] = null; // if we have any resource if ((resList != null) && (resList.length != 0)) { resourceID = new int[resList.length]; for (int x = 0; x < resList.length; x++) { // Resource list contains list of resource IDs resourceID[x] = ((Integer) resList[x]).intValue(); if (trace_flag == true) { System.out.println(super.get_name() + ": resource[" + x + "] = " + resourceID[x]); } } } return resourceID; }
4
@Override public void paint(Graphics g) { // Because of init ordering, this is required to not through null exceptions during init. if (bufferGraphics == null) return; // Get font sizes else if (mainFontMetrics == null) { mainFontMetrics = bufferGraphics.getFontMetrics(FontLoader.getMainFont()); mainTextHeightOffset = mainFontMetrics.getAscent() - mainFontMetrics.getDescent() - 1; secondaryFontMetrics = bufferGraphics.getFontMetrics(FontLoader.getSecondaryFont()); secondaryTextHeightOffset = secondaryFontMetrics.getAscent() - secondaryFontMetrics.getDescent() - 1; } // Clear screen. bufferGraphics.setColor(Color.WHITE); bufferGraphics.fillRect(0, 0, super.getWidth(), super.getHeight()); int tempX = (RECT_DIM + GAP)*selectX; int tempY = (RECT_DIM+GAP)*selectY; // Show cursor. if (selectShowing) { bufferGraphics.setColor(Color.DARK_GRAY); bufferGraphics.fillRect(tempX-3+GAP, tempY-3+GAP, RECT_DIM+6, RECT_DIM+6); } // Show tile rectangles and texts bufferGraphics.setFont(FontLoader.getMainFont()); for(int i = 0; i<15; i++) for(int k = 0; k<15; k++) { tempX = (RECT_DIM + GAP)*i+GAP; tempY = (RECT_DIM+GAP)*k+GAP; bufferGraphics.setColor(tileColors[i][k]); bufferGraphics.fillRect(tempX, tempY, RECT_DIM, RECT_DIM); bufferGraphics.setColor(letColors[i][k]); bufferGraphics.drawString(String.valueOf(let[i][k]), tempX + (RECT_DIM - mainFontMetrics.charWidth(let[i][k]))/2, tempY + (RECT_DIM + mainTextHeightOffset)/2 ); } // Show main message texts bufferGraphics.setFont(FontLoader.getSecondaryFont()); bufferGraphics.setColor(Color.BLACK); bufferGraphics.drawString(messageText[0], (super.getWidth() - secondaryFontMetrics.stringWidth(messageText[0]))/2, 18 + 15*(RECT_DIM + GAP)); bufferGraphics.drawString(messageText[1], (super.getWidth() - secondaryFontMetrics.stringWidth(messageText[1]))/2, 38 + 15*(RECT_DIM + GAP)); // After all are loaded, send them to the screen. g.drawImage(offscreen,0,0,this); }
5
public void mousePressed(MouseEvent e) { switch (subMode) { case Constants.EDIT_LUGAR: addPlace(e); break; case Constants.EDIT_TRANS: addTransition(e); break; case Constants.EDIT_LABEL: addMarker(e); break; case Constants.EDIT_ARC: setStartArc(e); break; case Constants.EDIT_MOUSE: selectObject(e); break; case Constants.EDIT_DELETE: deleteObject(e); break; case Constants.DRAW_ARC: addPointArc(e); break; case Constants.SIM_START: showInfoObjectAndFireTransition(e); break; } repaint(); }
8
int insertKeyRehash(double val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
9
private void doAesthetics() { setSize(new Dimension(220, 155)); setResizable(false); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLocationRelativeTo(null); mainPanel.setLayout(new BorderLayout()); mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (usernameField.getText().trim().isEmpty() || ipField.getText().trim().isEmpty() || portField.getText().trim().isEmpty()) { return; } new MainFrame(usernameField.getText().trim(), ipField.getText().trim(), Integer.parseInt(portField.getText().trim())); dispose(); } }); usernameField.setColumns(15); ipField.setColumns(15); portField.setColumns(5); gridLayout.setVgap(5); loginPanel.setBorder(BorderFactory.createEmptyBorder(3, 0, 0, 0)); labelsPanel.add(usernameLabel); labelsPanel.add(ipLabel); labelsPanel.add(portLabel); fieldsPanel.add(usernameField); fieldsPanel.add(ipField); fieldsPanel.add(portField); loginPanel.add(loginButton); mainPanel.add(labelsPanel, BorderLayout.WEST); mainPanel.add(fieldsPanel, BorderLayout.EAST); mainPanel.add(loginPanel, BorderLayout.SOUTH); add(mainPanel); }
3
@Override public boolean equals(Object other) { if (other instanceof Tuple) { Tuple otherTuple = (Tuple) other; return (( this.first == otherTuple.first || ( this.first != null && otherTuple.first != null && this.first.equals(otherTuple.first))) && ( this.second == otherTuple.second || ( this.second != null && otherTuple.second != null && this.second.equals(otherTuple.second))) ); } return false; }
8
private void merge(int left, int middle1, int middle2, int right) { int leftIndex= left; int rightIndex = middle2; int combIndex= left; int[] combArray= new int[array.length]; // output two subarrays before merging System.out.println( "merge: " + subarray( left, middle1 ) ); System.out.println( " " + subarray( middle2, right ) ); while(leftIndex <= middle1 && rightIndex <= right){ if(array[leftIndex] <= array[rightIndex]){ combArray[combIndex++]= array[leftIndex++]; } else{ combArray[combIndex++]= array[rightIndex++]; } }// end while // if the left array is empty if(leftIndex == middle2){ while(rightIndex <= right){ combArray[combIndex++]= array[rightIndex++]; } }else{// if the right array is empty while(leftIndex <= middle1){ combArray[combIndex++]= array[leftIndex++]; } }// end else // copy the array back to the original array for(int i=left; i<= right;i++){ array[i] = combArray[i]; } // print the merged array System.out.println(" "+ subarray(left, right)); System.out.println(); }// end method merge
7
public Instances instancesLoader() throws IOException { Instances data = null; data = new Instances(this.fr); this.closeFR(); // Close the file return deleteUselessAtributes(data); }
0
public static boolean checkForPalindrome(String s){ StringBuilder sb = new StringBuilder(s.length()); for(int i = s.length() -1 ; i >=0; i--){ sb.append(s.charAt(i)); } /* * Alternative method : * new StringBuilder(s).reverse().toString(); */ return s.equals(sb.toString()); }
1
private int moverListSolido(List listMovibles){ int vivos = 0; Iterator<Solido> itNave = listMovibles.iterator(); while(itNave.hasNext()){ Solido solido = itNave.next(); //lo movemos y retornamos su salud actual if(solido.mover() > 0) vivos++; } return vivos; }
2
public static List<Integer> retrieveDoctorFreeSlots(Date date, int doctorID) { DBMinder minder = DBMinder.instance(); ArrayList<Integer> toReturn = new ArrayList<Integer>(); Connection conn = minder.getConnection(); PreparedStatement ps; ResultSet rs; try { //retrieve hours working int timeBegin = -1, timeEnd = -1; ps = conn.prepareStatement("SELECT start_timeslot, end_timeslot FROM WorkDay WHERE doctor_id = ? AND day_of_week = (SELECT D - 1 FROM(SELECT TO_CHAR (?, 'D') D FROM DUAL))"); ps.setInt(1, doctorID); ps.setDate(2, date); rs = ps.executeQuery(); while(rs.next()) { timeBegin = rs.getInt(1); timeEnd = rs.getInt(2); } rs.close(); //expand hours working if(timeBegin != -1 && timeEnd != -1) { for(int i = timeBegin; i <= timeEnd; i++) { toReturn.add(new Integer(i)); } } //retrieve appointments that date ps = conn.prepareStatement("select time_slot_beginning, time_slot_end from appointment where doctor_id = ? and apt_date = ?"); ps.setInt(1, doctorID); ps.setDate(2, date); rs = ps.executeQuery(); //remove occupied time slots while(rs.next()) { timeBegin = rs.getInt(1); timeEnd = rs.getInt(2); for(int i = timeBegin; i <= timeEnd; i++) { toReturn.remove(new Integer(i)); } } rs.close(); //return list } catch(SQLException sqle) { sqle.printStackTrace(); } return toReturn; }
7
public static Keyword continueParallelStrategiesProofs(ParallelControlFrame pframe, Keyword lastmove) { if (lastmove == Logic.KWD_DOWN) { if (pframe.down != null) { ParallelControlFrame.enterParallelThread(pframe, null); return (Logic.KWD_MOVE_DOWN); } return (ControlFrame.continueCurrentOrNextStrategy(pframe)); } else if (lastmove == Logic.KWD_UP_TRUE) { ParallelControlFrame.exitParallelThread(pframe); if (pframe.unboundVariablesP) { } ControlFrame.propagateFrameTruthValue(pframe.result, pframe); if (pframe.down != null) { return (Logic.KWD_CONTINUING_SUCCESS); } else { return (Logic.KWD_FINAL_SUCCESS); } } else if (lastmove == Logic.KWD_UP_FAIL) { ParallelControlFrame.exitParallelThread(pframe); if (!(pframe.nextStrategies == Stella.NIL)) { pframe.state = Logic.KWD_STRATEGY; pframe.currentStrategy = null; return (ControlFrame.continueCurrentOrNextStrategy(pframe)); } ControlFrame.propagateFrameTruthValue(pframe.result, pframe); return (Logic.KWD_FAILURE); } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + lastmove + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } }
7
@Test public void testFindStrings_empty() throws Exception { Assert.assertEquals( Arrays.asList(), _xpath.findStrings("//li/text()") ); }
0
private AbstractButton getAbstractButton(ButtonModel bm) { if (getContentType().equals("text/plain")) return null; Component[] c = getComponents(); if (c == null || c.length == 0) return null; Container container = null; JComponent comp = null; for (Component x : c) { if (x instanceof Container) { container = (Container) x; comp = (JComponent) container.getComponent(0); if (comp instanceof AbstractButton) { if (bm == ((AbstractButton) comp).getModel()) return (AbstractButton) comp; } } } return null; }
7
private static void afficherCoursEtudiant() { ArrayList<Etudiant> listeEtudiant = ListeEtudiants.getInstance().getListe(); // Liste des etudiants int i = 0; // Compteur int element; // Nombre lu au clavier representant le numero d'un etudiant Etudiant choix = null; // Etudiant dont on veut faire afficher les cours String choixEtudiant; // Chaine de caractere lue au clavier representant un numero d'etudiant for (Etudiant etudiant : listeEtudiant) { if (i % 3 == 0) System.out.println((i+1) + ". " + etudiant.getCodePermanent() + "\t"); else System.out.println((i+1) + ". " + etudiant.getCodePermanent()); i++; } if (i > 1) { do { System.out.println("Choisissez l'etudiant dont vous voulez afficher les cours : "); choixEtudiant = Interface.lecture(); element = isNumeric(choixEtudiant) ? Integer.parseInt(choixEtudiant) : -1; if(element > 0 && element <= i) choix = listeEtudiant.get(element-1); } while( (element < 1 || element > i)); if (choix.getPremierCours() != null) { System.out.println("\nListe des cours de " + choix.getPrenom() + " " + choix.getNom()); System.out.println("================================================"); afficherCours(choix.getPremierCours()); } else System.out.println("L'etudiant choisit n'est inscrit a aucun cours!"); } else System.out.println("Il n'y a pas d'etudiants"); lecture(); menuPrincipal(); // Affichage du menu principal }
9
private boolean jj_3_28() { if (jj_3R_45()) return true; return false; }
1
public void SetToLastBusStopTicks(int toLastBusStopTicks) { //set the tick time bus got to the last bus stop this.toLastBusStopTicks = toLastBusStopTicks; }
0
public String columnsToGraphviz(Network network) { beginHeader(); { // command: dot -Tpng -Kfdp network.dot -o network.png int pos = 0; for (ColumnNode column : network.columnNodes()) { addHead(column.base, column.size, pos); for (Node node = column.base.top; node != column.base; node = node.top) { addNode(node, pos); } pos++; } for (ColumnNode column : network.columnNodes()) { addEdge(column.base, "B", column.base.top, "L"); for (Node node = column.base.top; node != column.base; node = node.top) { if (getColumn(node.left) < getColumn(node)) { addEdge(node, "L", node.left, "T"); } if (getColumn(node) < getColumn(node.right)) { addEdge(node, "R", node.right, "B"); } addEdge(node, "T", node.bottom, "R"); if (node.top != column.base) { addEdge(node, "B", node.top, "L"); } } } } endHeader(); return sb.toString(); }
7
public void testVehiclesRemoved() { TimeServer ts = new TimeServerLinked(); VehicleAcceptor sink = VehicleAcceptorFactory.newSink(ts); Vehicle[] cars = new Vehicle[5]; for (int i = 0; i < cars.length; i++) { cars[i] = VehicleFactory.newCar(ts, sink); sink.accept(cars[i]); } Assert.assertTrue(sink.getCars().size() == 5); ts.run(10); Assert.assertTrue(sink.getCars().size() == 0); }
1
public War readXML() throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Get the DOM Builder DocumentBuilder builder; builder = factory.newDocumentBuilder(); InputStream xml_file = ClassLoader .getSystemResourceAsStream("war.xml"); //check if we have xml file if (xml_file == null) { return war; } Document document = builder.parse(xml_file); // Load and Parse the XML document // document contains the complete XML as a Tree. // Iterating through the nodes and extracting the data. NodeList rootNodeList = document.getDocumentElement().getChildNodes(); // first we loop on 3 main array lists for (int i = 0; i < rootNodeList.getLength(); i++) { Node rootNode = rootNodeList.item(i); NodeList nodeList = rootNode.getChildNodes();// list of launchers // loop on each list to add launchers or destructors for (int j = 0; j < nodeList.getLength(); j++) { Node childNodeList = nodeList.item(j); this.addLauncherToArray(childNodeList, rootNode); // on each launcher or destructor we add a missile to it NodeList leafNode = childNodeList.getChildNodes(); for (int k = 0; k < leafNode.getLength(); k++) { Node missile = leafNode.item(k); this.addMissileToArray(missile, j); } } } return war; }
4
@Test public void testSimple() throws Exception { final Properties p = new Properties(); p.setProperty("type", "Zero"); final Properties[] configs = new Properties[]{p}; final FilterFactory ff = new FilterFactory(configs); final Filter[] filters = ff.getInstances(new MockConnectionProcessor()); Assert.assertEquals(1, filters.length); Assert.assertEquals(ZeroFilter.class.getName(), filters[0].getClass().getName()); }
0
public String toString() { String s = ""; if (child1 != null) { s = "(" + child1.toString() + ")"; } s = s + key1; if (child2 != null) { s = s + "(" + child2.toString() + ")"; } else if (keys > 1) { s = s + " "; } if (keys > 1) { s = s + key2; if (child3 != null) { s = s + "(" + child3.toString() + ")"; } else if (keys > 2) { s = s + " "; } } if (keys > 2) { s = s + key3; if (child4 != null) { s = s + "(" + child4.toString() + ")"; } } return s; }
8
private SpriteState createTileState(StateMap stateMap, int add, RawMemoryMap memoryMap, int scene, int frame, int scanLine) { byte[] upperTileData = new byte[16]; byte[] lowerTileData = new byte[16]; byte[] paletteData = new byte[8]; boolean flipHorizontally; boolean flipVertically; boolean objToBgPriority; TimeStamp inputTime = new TimeStamp(scene, frame, GbConstants.LINE_CYCLES * scanLine + 80 * GbConstants.DOUBLE_SPEED_FACTOR); int lcdc = memoryMap.getLCDC(inputTime); boolean obj8x16 = (lcdc & 0x4) != 0; int y = memoryMap.getOAM(add, inputTime); int x = memoryMap.getOAM(add + 1, inputTime); int firstRowScanLine = y - 16; for (int dy = 0; dy < 8; dy++) { int frameCycle = Math.max(0, firstRowScanLine + dy) * GbConstants.LINE_CYCLES + 80 * GbConstants.DOUBLE_SPEED_FACTOR; TimeStamp time = new TimeStamp(scene, frame, frameCycle); int tileNum = memoryMap.getOAM(add + 2, time); if (obj8x16) tileNum &= 0xFE; int tileAddress = 0x8000 + tileNum * 0x10; int attributes = memoryMap.getOAM(add + 3, time); int vramBank = (attributes & 0x08) >> 3; upperTileData[2 * dy] = (byte)memoryMap.getVramValue(vramBank, tileAddress + 2*dy, time); upperTileData[2 * dy + 1] = (byte)memoryMap.getVramValue(vramBank, tileAddress + 2*dy + 1, time); } if (obj8x16) { for (int dy = 0; dy < 8; dy++) { int frameCycle = Math.max(0, firstRowScanLine + dy + 8) * GbConstants.LINE_CYCLES + 80 * GbConstants.DOUBLE_SPEED_FACTOR; TimeStamp time = new TimeStamp(scene, frame, frameCycle); int tileNum = memoryMap.getOAM(add + 2, time); if (obj8x16) tileNum |= 0x01; int tileAddress = 0x8000 + tileNum * 0x10; int attributes = memoryMap.getOAM(add + 3, time); int vramBank = (attributes & 0x08) >> 3; lowerTileData[2 * dy] = (byte)memoryMap.getVramValue(vramBank, tileAddress + 2*dy, time); lowerTileData[2 * dy + 1] = (byte)memoryMap.getVramValue(vramBank, tileAddress + 2*dy + 1, time); } } int attributes = memoryMap.getOAM(add + 3, inputTime); int paletteIndex = attributes & 0x7; for (int i = 2; i < 8; i++) { // ignore color 0 paletteData[i] = (byte)memoryMap.getObjPaletteValue(paletteIndex * 8 + i, inputTime); if ((i & 1) != 0) paletteData[i] &= 0x7f; } PaletteEntry palette = stateMap.objPaletteRegistry.register(new Palette(paletteData)); if (obj8x16) { DoubleTileResult tileResult = stateMap.tileRegistry.registerForObj8x16(new Tile(upperTileData), new Tile(lowerTileData)); flipHorizontally = tileResult.flipHorizontally ^ ((attributes & 0x20) != 0); flipVertically = tileResult.flipVertically ^ ((attributes & 0x40) != 0); objToBgPriority = ((attributes & 0x80) != 0); return new SpriteState(y, x, tileResult.upperTile, tileResult.lowerTile, objToBgPriority, flipHorizontally, flipVertically, palette); } else { TileResult upperTileResult = stateMap.tileRegistry.registerForObj8x8(new Tile(upperTileData)); flipHorizontally = upperTileResult.flipHorizontally ^ ((attributes & 0x20) != 0); flipVertically = upperTileResult.flipVertically ^ ((attributes & 0x40) != 0); objToBgPriority = ((attributes & 0x80) != 0); return new SpriteState(y, x, upperTileResult.tile, null, objToBgPriority, flipHorizontally, flipVertically, palette); } }
8
public int getInt(Object key) { Number n = get(key); if (n == null) { return (int) 0; } return n.intValue(); }
1
protected final String escapeSlow(String s, int index) { int end = s.length(); // Get a destination buffer and setup some loop variables. char[] dest = DEST_TL.get(); int destIndex = 0; int unescapedChunkStart = 0; while (index < end) { int cp = codePointAt(s, index, end); if (cp < 0) { throw new IllegalArgumentException( "Trailing high surrogate at end of input"); } char[] escaped = escape(cp); if (escaped != null) { int charsSkipped = index - unescapedChunkStart; // This is the size needed to add the replacement, not the full // size needed by the string. We only regrow when we absolutely must. int sizeNeeded = destIndex + charsSkipped + escaped.length; if (dest.length < sizeNeeded) { int destLength = sizeNeeded + (end - index) + DEST_PAD; dest = growBuffer(dest, destIndex, destLength); } // If we have skipped any characters, we need to copy them now. if (charsSkipped > 0) { s.getChars(unescapedChunkStart, index, dest, destIndex); destIndex += charsSkipped; } if (escaped.length > 0) { System.arraycopy(escaped, 0, dest, destIndex, escaped.length); destIndex += escaped.length; } } unescapedChunkStart = index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1); index = nextEscapeIndex(s, unescapedChunkStart, end); } // Process trailing unescaped characters - no need to account for escaped // length or padding the allocation. int charsSkipped = end - unescapedChunkStart; if (charsSkipped > 0) { int endIndex = destIndex + charsSkipped; if (dest.length < endIndex) { dest = growBuffer(dest, destIndex, endIndex); } s.getChars(unescapedChunkStart, end, dest, destIndex); destIndex = endIndex; } return new String(dest, 0, destIndex); }
9
public boolean addItem(Item item) { final int oldAmount = (int) amountOf(item) ; if (super.addItem(item)) { final int inc = ((int) amountOf(item)) - oldAmount ; if (venue.inWorld() && inc != 0 && item.type.form != FORM_PROVISION) { String phrase = inc >= 0 ? "+" : "-" ; phrase+=" "+inc+" "+item.type.name ; venue.chat.addPhrase(phrase) ; } return true ; } return false ; }
5
@GET @Path("/v2.0/networks/{networkId}") @Produces({MediaType.APPLICATION_JSON, OpenstackNetProxyConstants.TYPE_RDF}) public Response showNetwork(@PathParam("networkId") String networkId, @HeaderParam("Accept") String accept) throws MalformedURLException, IOException{ if (accept.equals(OpenstackNetProxyConstants.TYPE_RDF)){ String dataFromKB=NetworkOntology.showNetwork(networkId); System.out.println(dataFromKB); System.out.println(accept); // XmlTester t=new XmlTester(); return Response.ok().status(200).header("Access-Control-Allow-Origin", "*").entity(dataFromKB).build(); } else{ System.out.println(this.URLpath+"/"+networkId); //Send HTTP request and receive a single Json content identified by an ID HttpURLConnection conn=HTTPConnector.HTTPConnect(new URL(this.URLpath+"/"+networkId), OpenstackNetProxyConstants.HTTP_METHOD_GET, null); String response=HTTPConnector.printStream(conn); Object result; result=(ExtendedNetwork) JsonUtility.fromResponseStringToObject(response, ExtendedNetwork.class); int responseCode=conn.getResponseCode(); HTTPConnector.HTTPDisconnect(conn); return Response.ok().status(responseCode).header("Access-Control-Allow-Origin", "*").entity(result).build(); } }
1
public static String unescape(String string) { int length = string.length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { char c = string.charAt(i); if (c == '+') { c = ' '; } else if (c == '%' && i + 2 < length) { int d = JSONTokener.dehexchar(string.charAt(i + 1)); int e = JSONTokener.dehexchar(string.charAt(i + 2)); if (d >= 0 && e >= 0) { c = (char)(d * 16 + e); i += 2; } } sb.append(c); } return sb.toString(); }
6
private void createContents(int coordX, int coordY) { timeDiagramsShell = new Shell(getParent(), SWT.BORDER | SWT.RESIZE | SWT.TITLE); timeDiagramsShell.setSize(563, 498); timeDiagramsShell.setMinimumSize(new Point(300, 300)); timeDiagramsShell.setBounds(coordX, coordY, WIDTH, HEIGHT); timeDiagramsShell.setText("Time Diagrams Window"); timeDiagramsShell.setLayout(new BorderLayout(0, 0)); SashForm sashForm = new SashForm(timeDiagramsShell, SWT.NONE); sashForm.setLayoutData(BorderLayout.CENTER); timeDiagramsShell.addControlListener(new ControlListener() { public void controlResized(ControlEvent arg0) { canvas.redraw(); } public void controlMoved(ControlEvent arg0) { canvas.redraw(); } }); timeDiagramsShell.addListener(SWT.Traverse, new Listener() { public void handleEvent(final Event event) { // hide the time diagrams window by Esc key ) if (event.character == SWT.ESC) { hide(); event.doit = false; } } }); timeDiagramsShell.addControlListener(new ControlListener() { public void controlResized(final ControlEvent e) { WIDTH = timeDiagramsShell.getSize().x; HEIGHT = timeDiagramsShell.getSize().y; } public void controlMoved(final ControlEvent e) { } }); image = new Image(Display.getDefault(), width, height); final Point origin = new Point(0, 0); canvas = new Canvas(sashForm, SWT.NO_BACKGROUND | SWT.V_SCROLL | SWT.H_SCROLL); canvas.setRedraw(true); final ScrollBar hBar = canvas.getHorizontalBar(); hBar.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { int hSelection = hBar.getSelection(); int destX = -hSelection - origin.x; Rectangle rect = image.getBounds(); canvas.scroll(destX, 0, 0, 0, rect.width, rect.height, false); origin.x = -hSelection; } }); final ScrollBar vBar = canvas.getVerticalBar(); vBar.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { int vSelection = vBar.getSelection(); int destY = -vSelection - origin.y; Rectangle rect = image.getBounds(); canvas.scroll(0, destY, 0, 0, rect.width, rect.height, false); origin.y = -vSelection; } }); canvas.addListener(SWT.Resize, new Listener() { public void handleEvent(Event e) { Rectangle rect = image.getBounds(); Rectangle client = canvas.getClientArea(); hBar.setMaximum(rect.width); vBar.setMaximum(rect.height); hBar.setThumb(Math.min(rect.width, client.width)); vBar.setThumb(Math.min(rect.height, client.height)); int hPage = rect.width - client.width; int vPage = rect.height - client.height; int hSelection = hBar.getSelection(); int vSelection = vBar.getSelection(); if (hSelection >= hPage) { if (hPage <= 0) hSelection = 0; origin.x = -hSelection; } if (vSelection >= vPage) { if (vPage <= 0) vSelection = 0; origin.y = -vSelection; } canvas.redraw(); } }); canvas.addListener(SWT.Paint, new Listener() { public void handleEvent(Event e) { GC gc = e.gc; redrawTimeDiagrams(); gc.drawImage(image, origin.x, origin.y); } }); tree = new Tree(sashForm, SWT.BORDER | SWT.CHECK | SWT.FULL_SELECTION); tree.setHeaderVisible(true); tree.setLinesVisible(true); tree.addSelectionListener(new SelectionListener() { private boolean isCurElementExpanded; public void widgetDefaultSelected(SelectionEvent event) { final TreeItem root = (TreeItem) event.item; isCurElementExpanded = !isCurElementExpanded; root.setExpanded(isCurElementExpanded); } public void widgetSelected(SelectionEvent event) { if (event.detail == SWT.CHECK) { final TreeItem root = (TreeItem) event.item; final boolean isChecked = root.getChecked(); for (TreeItem childItem : root.getItems()) { childItem.setChecked(isChecked); } canvas.redraw(); } } }); initializeTree(); sashForm.setWeights(new int[] { 2, 1 }); }
7
public void sendProbe() throws IOException { DatagramPacket findBroadcast = new DatagramPacket(probeData, probeData.length, broadcastTarget, Config.DISCOVERPORT); sock.send(findBroadcast); }
0
public final void applyProxySettings() { String proxyUrl = Configuration.getProperty("HTTP_PROXY_URL"); if (proxyUrl != null) { System.getProperties().put("http.proxyHost", proxyUrl); } String proxyPort = Configuration.getProperty("HTTP_PROXY_PORT"); if (proxyPort != null) { System.getProperties().put("http.proxyPort", proxyPort); } }
2
public int countLines(String filename) throws IOException { InputStream is = new BufferedInputStream(new FileInputStream(filename)); try { byte[] c = new byte[1024]; int count = 0; int readChars = 0; boolean empty = true; while ((readChars = is.read(c)) != -1) { empty = false; for (int i = 0; i < readChars; ++i) { if (c[i] == '\n') { ++count; } } } int result = ((count == 0 && !empty) ? 1 : count) +1; return result; } finally { is.close(); } }
5
private void startField(final Attributes attributes) { String attPosition = attributes.getValue("pos").toUpperCase(); tmpField = new Field(); tmpField.setPosition(FieldPosition.valueOf(attPosition)); tmpField.setType(attributes.getValue("type")); if (attributes.getValue("left") != null) { tmpField.setLeft(); } if (attributes.getValue("right") != null) { tmpField.setRight(); } if (attributes.getValue("up") != null) { tmpField.setUp(); } if (attributes.getValue("down") != null) { tmpField.setDown(); } }
4
public UserDatabase(){ // load login information from file file = new File("data.txt"); try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String username = scanner.next(); String password = scanner.next(); String rights = scanner.next(); boolean isStudent = true; // 0 for teacher, 1 for student if (rights.equals("0")) isStudent = false; users.add(new User(username, password, isStudent)); } scanner.close(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "Unable to find data.txt"); e.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } }
4
private void printObjectDebug(Object ob) { if (ob == null) { log.finer("null object found"); } else if (ob instanceof PObject) { PObject tmp = (PObject) ob; log.finer(tmp.getReference() + " " + tmp.toString()); } else if (ob instanceof Dictionary) { Dictionary tmp = (Dictionary) ob; log.finer(tmp.getPObjectReference() + " " + tmp.toString()); } else { log.finer(ob.getClass() + " " + ob.toString()); } }
3
private void addAllUniforms(String shaderText) { HashMap<String, ArrayList<GLSLStruct>> structs = findUniformStructs(shaderText); final String UNIFORM_KEYWORD = "uniform"; int uniformStartLocation = shaderText.indexOf(UNIFORM_KEYWORD); while(uniformStartLocation != -1) { if(!(uniformStartLocation != 0 && Character.isWhitespace(shaderText.charAt(uniformStartLocation - 1)) || shaderText.charAt(uniformStartLocation - 1) == ';' && Character.isWhitespace(shaderText.charAt(uniformStartLocation + UNIFORM_KEYWORD.length())))) continue; int begin = uniformStartLocation + UNIFORM_KEYWORD.length() + 1; int end = shaderText.indexOf(";", begin); String uniformLine = shaderText.substring(begin, end); int whiteSpacePos = uniformLine.indexOf(' '); String uniformName = uniformLine.substring(whiteSpacePos + 1, uniformLine.length()).trim(); String uniformType = uniformLine.substring(0, whiteSpacePos).trim(); resource.getUniformNames().add(uniformName); resource.getUniformTypes().add(uniformType); addUniform(uniformName, uniformType, structs); uniformStartLocation = shaderText.indexOf(UNIFORM_KEYWORD, uniformStartLocation + UNIFORM_KEYWORD.length()); } }
5
public static boolean isStraight(List<Card> cards) { boolean isStraight = true; int startValue = 0; // If the first card is an ACE and the last one a // TWO there might be a "small" straight (ACE, TWO, // THREE, ...), so than start with the second // highest card at index 1 // Avoid null pointers if (cards != null && cards.size() >= 5) { // If the first card is an ACE and the last one a TWO there might be // a "small" straight (ACE, TWO, THREE, ...) if (cards.get(0).getCardValue() == CardValueEnum.ACE && cards.get(cards.size() - 1).getCardValue() == CardValueEnum.TWO) { startValue = 1; } // Compare the values of the next cards until they differ, if there // is a straight starting with an ACE as a ONE, this will also be // detected for (int j = startValue; j < cards.size() - 1; j++) { Card currentCard = cards.get(j); Card nextCard = cards.get(j + 1); // Compare the cards values for a descending straight, the // ordinal values must be one apart for this if (currentCard.getCardValue().ordinal() != nextCard .getCardValue().ordinal() + 1) { isStraight = false; break; } } } else { isStraight = false; } return isStraight; }
6
public boolean rankMatch( LinkedHashMap<String, LinkedHashMap<String, String>> humanPropRoot, String correctName1, String correctName2) { if (humanPropRoot.containsKey(correctName1) && humanPropRoot.containsKey(correctName2)) return true; else return false; }
2
public int getSize() { return size; }
0
public CheckResultMessage checkSum4(int i, int j) { int r1 = get(17, 2); int c1 = get(18, 2); int tr1 = get(33, 5); int tc1 = get(34, 5); BigDecimal sum = new BigDecimal(0); if (checkVersion(file).equals("2003")) { for (File f : Main1.files1) { try { in = new FileInputStream(f); hWorkbook = new HSSFWorkbook(in); sum = sum.add(getValue(r1 + i, c1 + j, 3)); in.close(); } catch (Exception e) { } } try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); if (0 != getValue(tr1 + j, tc1 + i, 8).compareTo(sum)) { return error("支付机构单个账户表格sheet1-9的数据之和"+(c1 + i) + "行" + (r1 + j) + "列" + "出错"); } in.close(); } catch (Exception e) { } } else { for (File f : Main1.files1) { try { in = new FileInputStream(f); xWorkbook = new XSSFWorkbook(in); sum = sum.add(getValue1(r1 + i, c1 + j, 3)); in.close(); } catch (Exception e) { } } try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); if (0 != getValue1(tr1 + i, tc1 + j, 8).compareTo(sum)) { return error("支付机构单个账户表格sheet1-9的数据之和"+(c1 + i) + "行" + (r1 + j) + "列" + "出错"); } in.close(); } catch (Exception e) { } } return pass("支付机构单个账户表格sheet1-9的数据之和" +(c1 + i)+ "行" + (r1 + j) + "列" + "正确"); }
9
public void echo(Scanner in, PrintWriter out){ boolean done = false; while (!done && in.hasNextLine()) { String line = in.nextLine(); out.println("Echo: " + line); if (line.trim().equals(Constants.SHUTDOWN_MESSAGE)) done = true; } }
3
public void prettyPrint(){ for(int i = 0; i < x; i++){ for(int j = 0; j < y; j++){ System.out.print(mat[i][j]); System.out.print("\t"); } System.out.println(); } }
2
public ConverterAdapter(ConvertiblePair typeInfo, Converter<?, ?> converter) { this.converter = (Converter<Object, Object>) converter; this.typeInfo = typeInfo; }
2
public void method276(int y, int x) { GroundTile groundTile = groundTiles[0][x][y]; for (int z = 0; z < 3; z++) { GroundTile heightGroundTile = groundTiles[z][x][y] = groundTiles[z + 1][x][y]; if (heightGroundTile != null) { heightGroundTile.anInt1307--; for (int j1 = 0; j1 < heightGroundTile.anInt1317; j1++) { InteractiveObject interactiveObject = heightGroundTile.interactiveObjects[j1]; if ((interactiveObject.uid >> 29 & 3) == 2 && interactiveObject.x == x && interactiveObject.y == y) { interactiveObject.z--; } } } } if (groundTiles[0][x][y] == null) { groundTiles[0][x][y] = new GroundTile(0, x, y); } groundTiles[0][x][y].aGroundTile_1329 = groundTile; groundTiles[3][x][y] = null; }
7
public void testIsBefore_TOD() { TimeOfDay test1 = new TimeOfDay(10, 20, 30, 40); TimeOfDay test1a = new TimeOfDay(10, 20, 30, 40); assertEquals(false, test1.isBefore(test1a)); assertEquals(false, test1a.isBefore(test1)); assertEquals(false, test1.isBefore(test1)); assertEquals(false, test1a.isBefore(test1a)); TimeOfDay test2 = new TimeOfDay(10, 20, 35, 40); assertEquals(true, test1.isBefore(test2)); assertEquals(false, test2.isBefore(test1)); TimeOfDay test3 = new TimeOfDay(10, 20, 35, 40, GregorianChronology.getInstanceUTC()); assertEquals(true, test1.isBefore(test3)); assertEquals(false, test3.isBefore(test1)); assertEquals(false, test3.isBefore(test2)); try { new TimeOfDay(10, 20, 35, 40).isBefore(null); fail(); } catch (IllegalArgumentException ex) {} }
1
private void onDoneClick() throws IOException { for (ImageMarker marker: cornerAndControlMarkers) { if (marker.getID() == null) { JOptionPane.showMessageDialog(this, "You can't be done until you've " + "labeled every corner and control point!"); return; } } int choice; choice = JOptionPane.showConfirmDialog(null, "Would you like to do another picture??", "Message", JOptionPane.YES_NO_OPTION); if (choice==0) {//YES outputHelper(); cornerAXText.setText(""); cornerAYText.setText(""); cornerBXText.setText(""); cornerBYText.setText(""); cornerCXText.setText(""); cornerCYText.setText(""); cornerDXText.setText(""); cornerDYText.setText(""); sideLengthText.setText("8"); hfovText.setText(""); JPEGText.setText(""); framePoints.setVisible(true); framePoints.dispose(); }else if(choice==1) {//NO outputHelper(); framePoints.setVisible(false); framePoints.dispose(); this.setVisible(false); this.dispose(); } }
4
private static void startComboBox() { language.removeAllItems(); language.addItem(model.save.SettingsModel.getLocale().getDisplayLanguage( model.save.SettingsModel.getLocale())); Locale[] l = model.save.SettingsModel.getAllLocales(); for (int a=0; a< l.length; a++){ if (!(l[a]).equals(model.save.SettingsModel.getLocale())){ language.addItem(l[a].getDisplayLanguage(l[a])); } } language.setFont(MenuLookAndFeel.getLargeFont()); language.setBackground(MenuLookAndFeel.getInputFieldColor()); language.setBorder(resources.MenuLookAndFeel.getSettingsTextFieldFont()); }
2
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 Tuple<ArrayList<Vertex<T>>, Double> minimalPath( Vertex<T> src, Vertex<T> dest ) { ArrayList<Tuple<Pair<Vertex<T>>,Double>> verticesInPath = new ArrayList<Tuple<Pair<Vertex<T>>, Double>> (); ArrayList<Vertex<T>> visitedVertices = new ArrayList<Vertex<T>> (); final Comparator pathCostComparator = new Comparator() { public int compare( Object o1, Object o2 ) { Double i1 = ( ( Tuple<Vertex<T>, Double> ) o1 ). getSecondElement(); Double i2 = ( ( Tuple<Vertex<T>, Double> ) o2 ). getSecondElement(); return i1.compareTo( i2 ); } public boolean equals( Object obj ) { return false; } }; PriorityQueue<Tuple<Pair<Vertex<T>>, Double>> pq = new HeapPriorityQueue<Tuple<Pair<Vertex<T>>, Double>> ( pathCostComparator ); Tuple<Pair<Vertex<T>>, Double> pathTuple; // start with the source, which has a cost of 0 to get to itself pq.enqueue( new Tuple( new Pair( src, src ), 0.0 ) ); while ( !pq.isEmpty() ) { // get cheapest path to a vertex seen so far pathTuple = pq.dequeue(); // extract the fields of the tuple so we can work with them Pair<Vertex<T>> vertexPair = pathTuple.getFirstElement(); Vertex<T> v = vertexPair.getSecondElement(); double minCostToV = pathTuple.getSecondElement(); visitedVertices.add( v ); verticesInPath.add( pathTuple ); // if v is the destination vertex, we are done if ( v.equals( dest ) ) { // extract and return only the vertices on the cheapest // path from src to dest ArrayList<Vertex<T>> path = getPath( verticesInPath, src, dest ); return new Tuple<ArrayList<Vertex<T>>, Double> ( path, minCostToV ); } // okay, not done yet; look at the vertices adjacent to v ArrayList<Vertex<T>> neighbors = ( ArrayList<Vertex<T>> )this.getNeighbors( v ); while ( !neighbors.isEmpty() ) { Vertex<T> w = neighbors.remove( 0 ); // if we has been visited, we don't need to consider it if ( !visitedVertices.contains( w ) ) { // get the total cost to vertex v double minCostToW = minCostToV + this.getEdgeWeight( v, w ); pq.enqueue( new Tuple<Pair<Vertex<T>>, Double> ( new Pair( v, w ), minCostToW ) ); } } } return null; // failure! }
4
public JTextField getNumberOfPointsTextField() { return numberOfPointsTextField; }
0
public ExameDAO getExame(){ try{ EntityManager em = conecta(); if (em!=null){ String consulta = "SELECT e FROM Exame e WHERE e.idExame="+idExame; //System.out.println(consulta); Query q = em.createQuery(consulta); List<Exame> resultado = q.getResultList(); //System.out.println(resultado.toString()); ExameDAO exame = new ExameDAO(); for (Exame e: resultado){ exame = new ExameDAO(e.getIdExame(), e.getNome(), e.getValor()); } return exame; } return null; } catch (Exception e){ return null; } }
3
public static int numPandigital() { int ret = 0; HashSet<Integer> hs = new HashSet<Integer>(); String temp; for (int i = 2; i < 10000; i++) { for (int j = i; j < 10000; j++) { temp = i + "" + j + (i * j); if (temp.length() > 9) { break; } if (temp.length() == 9 && !hs.contains(i * j)) { if (isPandigital(temp)) { ret += i * j; hs.add(i * j); } } } } return ret; }
6
public void endElement(String namespaceURI, String localName, String rawName) throws SAXException { if (rawName.equals("authors")) { publication.addAuthor(content); } else if (rawName.equals("title")) { publication.setTitle(content); } else if (rawName.equals("school")) { publication.setSchool(content); } else if (rawName.equals("url")) { publication.setUrl(content); } else if (rawName.equals("pages")) { publication.setPages(content); } else if (rawName.equals("booktitle")) { publication.setBooktitle(content); } else if (rawName.equals("www")) { pubList.add(publication); if (pubList.size() == LIST_SIZE) { DB_helper.addPublicationsIntoDatabase(pubList); pubList.clear(); } } }
8
public static void robarFicha(boolean humano){ if (Domino.listaFicha.size()!=0){ int n = (int) Math.floor(Math.random() * Domino.listaFicha.size()); // int cabeza = this.listaFicha.get(n).getCabeza(); // int cola = this.listaFicha.get(n).getCola(); // this.listaFicha.remove(n); if(humano){ int x = Domino.listaFichaHumano.get(Domino.listaFichaHumano.size()-1).getX(); Domino.listaFichaHumano.add(Domino.listaFicha.get(n)); Domino.listaFichaHumano.get(Domino.listaFichaHumano.size()-1).posiocion(x+90, 433); }else{ Domino.listaFichaPc.add(Domino.listaFicha.get(n)); } Domino.listaFicha.remove(n); }else{ System.out.println("No hay fichas para robar"); } }
2
private boolean write (Pipe pipe_, Msg msg_) { if (!pipe_.write (msg_)) { Utils.swap(pipes, pipes.indexOf (pipe_), matching - 1); matching--; Utils.swap(pipes, pipes.indexOf (pipe_), active - 1); active--; Utils.swap(pipes, active, eligible - 1); eligible--; return false; } if (!msg_.has_more()) pipe_.flush (); return true; }
2
@Override public int getSize() { return opcode==XOpcode.LOADB?2:opcode==XOpcode.LOADS||opcode==XOpcode.LOADI||opcode==XOpcode.LOADF||opcode==XOpcode.LOADD||opcode==XOpcode.LOADT?3:1; }
6
@Override public void mousePressed(MouseEvent e) { mX = e.getX(); mY = e.getY(); pX = (int) Math.floor((mX - Game.MAPOFFX) / (double) Game.TILESIZE) + Game.xOff; pY = (int) Math.floor((mY - Game.MAPOFFY) / (double) Game.TILESIZE) + Game.yOff; switch(e.getButton()) { case MouseEvent.BUTTON1: //Left click found = false; canPath = true; Game.gui.update(mX, mY, true, 1); //System.out.println("pressed left"); break; case MouseEvent.BUTTON2: //Middle click Game.gui.update(mX, mY, true, 2); //System.out.println("pressed middle"); break; case MouseEvent.BUTTON3: //Right click Game.gui.update(mX, mY, true, 3); //System.out.println("pressed right"); break; } Game.gui.update(mX, mY); }
3
public int searchInsert(int[] A, int target) { int l = 0, r = A.length - 1; while(l <= r){ int m = (l+r) >> 1; if(A[m] < target) l = m + 1; else r = m - 1; } return l; }
2
public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; }
4
@Override public synchronized void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream()); String line = in.readLine(); if (line == null) { logger.error("Received invalid file request: null"); socket.close(); return; } String filename = path + File.separatorChar + line; line = in.readLine(); if (line == null) { logger.error("Received invalid position request: null"); socket.close(); return; } long pos = Long.parseLong(line); line = in.readLine(); if (line == null) { logger.error("Received invalid length request: null"); socket.close(); return; } int length = Integer.parseInt(line); logger.debug("Requested {} bytes at @{}", length, pos); RandomAccessFile file = new RandomAccessFile(filename, "r"); length = (int) Math.min(length, file.length() - pos); file.seek(pos); FileChannel channel = file.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(length); byte[] byteArray = new byte[BUFSIZE]; int numRead, numGet; int totalRead = 0; while ((numRead = channel.read(byteBuffer)) != -1 && totalRead < length) { if (numRead == 0) { continue; } byteBuffer.flip(); totalRead += numRead; while (byteBuffer.hasRemaining()) { numGet = Math.min(byteBuffer.remaining(), BUFSIZE); byteBuffer.get(byteArray, 0, numGet); out.write(byteArray, 0, numGet); } byteBuffer.clear(); logger.debug("Sent {} bytes from a total of {}", totalRead, length); } file.close(); out.flush(); out.close(); socket.close(); logger.info("Closed connection from {} after {} bytes.", socket.getInetAddress().getHostName(), totalRead); } catch (IOException | NumberFormatException e) { logger.error(e.getMessage(), e); } }
8
public double getPolarityIndex(String text) throws APIErrorException { // API settings String APIkey = "your_api_key"; String language = "eng"; String categories = "sentiment"; // Encodes text try { text = URLEncoder.encode(text,"ISO-8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // Builds request and response String APIrequest = "http://api.scanandtarget.com/api/1/scan.json?key=" + APIkey + "&lang=" + language + "&categories=" + categories + "&text=" + text; String APIresponse = ""; // Executes request URL url; try { url = new URL(APIrequest); BufferedReader responseReader = new BufferedReader( new InputStreamReader(url.openStream())); String line; while ((line = responseReader.readLine()) != null) { APIresponse += line; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Adapts response to JSON format Gson gson = new Gson(); ScanAndTargetResponse response = gson.fromJson(APIresponse, ScanAndTargetResponse.class); // Returns result (value) double value = 0; // default value returned if the API does not detect any sentiment if (response.isSuccess()) { // API call successful if (response.getCount() != 0) { // Mood detected in the text Sentiment[] sentiment = response.getGeneric().getSentiment(); for (int i = 0; i < sentiment.length; i++) { Classifier classifier = sentiment[i].getClassifier(); // Calculates value according to polarity if (classifier.getPolarity().equals("positive")) { value += sentiment[i].getRating(); } else if (classifier.getPolarity().equals("negative")) { value -= sentiment[i].getRating(); } } } } else { // ScanAndTarget API call fails throw new APIErrorException("An error occurs during the computation of positivity index (external call)"); } return value; }
9
public void loadAccounts () { try { BufferedReader freader = getAccountFile(); String str; while ((str = freader.readLine ()) != null) { Accounts.add (str.split (" ")); } } catch (Exception ex) { ex.printStackTrace (); } }
2