text
stringlengths
14
410k
label
int32
0
9
public void sendMessage(String msg) { try { writer.write(msg+"\n"); writer.flush(); } catch (IOException e) { System.out.println("Message send failed"); e.printStackTrace(); } }
1
public static boolean getBooleanValue(String attr) { return Boolean.parseBoolean(prop.getProperty(attr)); }
0
public Deck() { // Create an unshuffled deck of cards. deck = new Card[52]; int cardCt = 0; // How many cards have been created so far. for ( int nSuit = 0; nSuit <= 3; nSuit++ ) { for ( int nValue = 1; nValue <= 13; nValue++ ) { deck[cardCt] = new Card(nValue,nSuit); cardCt++; } } nCardsUsed = 0; }
2
private Class<?> eliminateEnumSubclass(Class<?> cls) { Class<?> sup = cls.getSuperclass(); if (sup != null && sup.getSuperclass() == Enum.class) { return sup; } return cls; }
5
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(relatorio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(relatorio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(relatorio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(relatorio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new relatorio().setVisible(true); } }); }
6
@Override public void run() { try { this.mapper = new Mapper("mapper.yaml"); } catch (FileNotFoundException e) { e.printStackTrace(); return; } JarLoader.load("minecraft_server.jar"); this.playerList = new ReflxPlayerList(this); this.commandHandler = new ReflxCommandHandler(this); this.eventManager = new ReflxEventManager(this); try { this.playerList.prepare(); } catch (NotFoundException | CannotCompileException e) { e.printStackTrace(); return; } Class minecraftServer; try { minecraftServer = Class.forName("net.minecraft.server.MinecraftServer"); Method main = minecraftServer.getDeclaredMethod("main", String[].class); String[] arguments = new String[]{ "nogui" }; main.invoke(null, (Object) arguments); } catch (Exception e) { e.printStackTrace(); return; } try { Field serverField = minecraftServer.getDeclaredField("j"); serverField.setAccessible(true); this.dedicatedServer = serverField.get(null); } catch (IllegalAccessException | NoSuchFieldException e) { e.printStackTrace(); return; } try { this.playerList.inject(); } catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException | NoSuchMethodException | CannotCompileException | InstantiationException | NotFoundException | InvocationTargetException e) { e.printStackTrace(); return; } try { this.commandHandler.inject(); } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); return; } this.pluginLoader = new ReflxPluginLoader(this); this.pluginLoader.load("plugins"); for (Plugin plugin : this.pluginLoader.getPlugins()) { plugin.onEnable(); } }
7
private Object[] scanBlockScalarBreaks(int indent) { // See the specification for details. StringBuilder chunks = new StringBuilder(); Mark endMark = reader.getMark(); int ff = 0; int col = this.reader.getColumn(); while (col < indent && reader.peek(ff) == ' ') { ff++; col++; } if (ff > 0) { reader.forward(ff); } String lineBreak = null; while ((lineBreak = scanLineBreak()).length() != 0) { chunks.append(lineBreak); endMark = reader.getMark(); ff = 0; col = this.reader.getColumn(); while (col < indent && reader.peek(ff) == ' ') { ff++; col++; } if (ff > 0) { reader.forward(ff); } } return new Object[] { chunks.toString(), endMark }; }
7
final void method2380(AbstractToolkit var_ha, int i, boolean bool, Class318_Sub1 class318_sub1, int i_0_, byte i_1_, int i_2_) { do { try { anInt9970++; if (i_1_ > -106) method2402(-5, (byte) 56); if (!(class318_sub1 instanceof Class318_Sub1_Sub1_Sub2)) break; Class318_Sub1_Sub1_Sub2 class318_sub1_sub1_sub2_3_ = (Class318_Sub1_Sub1_Sub2) class318_sub1; if (aClass64_9993 == null || class318_sub1_sub1_sub2_3_.aClass64_9993 == null) break; aClass64_9993.method613((class318_sub1_sub1_sub2_3_ .aClass64_9993), i_2_, i, i_0_, bool); } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("uo.N(" + (var_ha != null ? "{...}" : "null") + ',' + i + ',' + bool + ',' + (class318_sub1 != null ? "{...}" : "null") + ',' + i_0_ + ',' + i_1_ + ',' + i_2_ + ')')); } break; } while (false); }
8
public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; AffineTransform DEFAULT = g2.getTransform(); if(first!=null && !mazzo.isEmpty()) first.drawCartaBack(g2); if(!carteSpostate.isEmpty()){ Iterator<cartaPosFinale> it = carteSpostate.iterator(); while(it.hasNext()){ cartaPosFinale c = it.next(); int x= c.pos[0]; int y= c.pos[1]; AffineTransform at = AffineTransform.getTranslateInstance(x,y); g2.setTransform(at); c.carta.drawCarta(g2); } } if(visualizzata!=null){ AffineTransform at = AffineTransform.getTranslateInstance(dx,dy); g2.setTransform(at); visualizzata.drawCarta(g2); } g2.setTransform(DEFAULT); }
5
public boolean verify(JComponent input) { boolean allow = true; if (input instanceof JFormattedTextField) { JFormattedTextField textField = (JFormattedTextField)input; AbstractFormatter formatter = textField.getFormatter(); if (formatter != null) { String value = textField.getText(); if (value.length() != 0) { try { formatter.stringToValue(value); } catch (ParseException exc) { allow = false; } } else if (!optionalField) { allow = false; } } } return allow; }
5
private void handleOptions(int keyCode) { switch (keyCode) { case DeviceSpecification.LSK: case DeviceSpecification.CLEAR: if (applicationState.lastState() == ApplicationState.MAIN_MENU) { applicationState.setState(ApplicationState.MAIN_MENU); } else { applicationState.setState(ApplicationState.METRONOME_STOPPED); } break; case DeviceSpecification.RIGHT: case Canvas.KEY_NUM6: metronome.nextKit(view.supportedSounds()); break; case DeviceSpecification.LEFT: case Canvas.KEY_NUM4: metronome.previousKit(view.supportedSounds()); break; } }
7
public RegularEnvironment(RegularExpression expression) { super(expression); expression.addExpressionListener(new Listener()); }
0
protected void brew(int[] buf) { assert buf.length % 2 == 1; int i, v0, v1, sum, n; i = 1; while (i < buf.length) { n = CUPS; v0 = buf[i]; v1 = buf[i + 1]; sum = 0; while (n-- > 0) { sum += SUGAR; v0 += ((v1 << 4) + S[0] ^ v1) + (sum ^ (v1 >>> 5)) + S[1]; v1 += ((v0 << 4) + S[2] ^ v0) + (sum ^ (v0 >>> 5)) + S[3]; } buf[i] = v0; buf[i + 1] = v1; i += 2; } }
2
public static boolean check(int row, int col) { for (int prev = 1; prev < col; prev++) if (board[prev] == row // Verify row || (Math.abs(board[prev] - row) == Math.abs(prev - col))) // Verify // diagonals return false; return true; }
3
static List<String> cortarPalabras (String texto, int cantidadDeLetras){ List<String> lstFinal= new ArrayList<String>(); StringBuilder builder= new StringBuilder(); if(texto.split(" ").length > 0){ String[] arrayAux = texto.split(" "); List<String> lstPalabras= Arrays.asList(arrayAux); List<String> lstAuxiliar= new ArrayList<String>(); int cont=0; int sumadorLetras=0; for (String string : lstPalabras) { if(string.length()>cantidadDeLetras){ while (string.length()>cantidadDeLetras ) { lstAuxiliar.add(string.substring(0, cantidadDeLetras)); string= string.substring(cantidadDeLetras, string.length()); } if(string.length()>0 ){ lstAuxiliar.add(string.substring(0, string.length()) + " "); } }else{ lstAuxiliar.add(string + " "); } } for (String string : lstAuxiliar) { sumadorLetras+= string.length(); if(cont==0){ builder.append(string); }else{ if(sumadorLetras > cantidadDeLetras){ lstFinal.add(builder.toString()); builder.delete(0, builder.length()); builder.append(string); sumadorLetras= string.length(); }else{ builder.append(string); } } cont++; } if (builder.length()>0) lstFinal.add(builder.toString()); } return lstFinal; }
9
public double resolveCollisionY(AABB other, double moveAmtY) { double newAmtY = moveAmtY; if (moveAmtY == 0.0) { return moveAmtY; } if (moveAmtY > 0) { // Our max == their min newAmtY = other.getMinY() - maxY; } else { // Our min == their max newAmtY = other.getMaxY() - minY; } if (Math.abs(newAmtY) < Math.abs(moveAmtY)) { moveAmtY = newAmtY; } return moveAmtY; }
3
@Override public void run(int iterations) { // Do iterations for (int i = 0; i < iterations; i++) { // Find the best 5 paths of the generated paths LimitedPriorityQueue lpq = new LimitedPriorityQueue(queueLimit, new Double(1)); // shortestPathLength. ArrayList<int[][]> chromosomes = getChromosomes(); for (int j = 0; j < chromosomes.size(); j++) { double length = fitness(chromosomes.get(j)); lpq.push(j, new Double(length)); } if (i % 1000 == 0) { lpq.printArray(i); //System.out.println("ZeroDeltaIterations: " + zeroDeltaIterations); System.out.println("Best path: " + fitness(bestPath)); } int[] indices = lpq.getIndices(); // Cross the values over to form new paths // System.out.println("Iterations without change: " + // zeroDeltaIterations + ". Swapping with probability: " + // (probability + zeroDeltaIterations * zeroDeltaAddition)); pmx(indices); if (fitness(chromosomes.get(indices[0])) < fitness(bestPath)) bestPath = chromosomes.get(indices[0]); // If iterations > 1000 then we keep the first 2 and scrap the rest. if (zeroDeltaIterations == 5000) { // If we've had 10,000 iterations with no change. Scrap all // (keep the best?) // We're probably stuck in a local minima randomise(); //for (int k = 0; k < 30; k++) { // chromosomes.add(generateRandomPath()); //} zeroDeltaIterations = 0; } else if (zeroDeltaIterations % 300 == 0 && zeroDeltaIterations >= 300) { // We've probably hit a local minima, so generate a lot more // random ones int[][] pathA = chromosomes.get(indices[0]); // int[][] pathB = chromosomes.get(1); chromosomes.clear(); chromosomes.add(pathA); // chromosomes.add(pathB); for (int k = 0; k < 200; k++) { chromosomes.add(generateRandomPath()); } } /*else if (zeroDeltaIterations % 500 == 0) { int[][] pathA = chromosomes.get(indices[0]); int[][] pathB = chromosomes.get(indices[1]); chromosomes.clear(); chromosomes.add(pathA); chromosomes.add(pathB); for (int k = 0; k < 15; k++) { // Add a copy of the existing path chromosomes.add(pathA); } }*/ double delta = fitness(chromosomes.get(indices[0])) - prevWeight; if (Math.abs(delta) < 0.2) { zeroDeltaIterations++; } else { zeroDeltaIterations = 0; } prevWeight = fitness(chromosomes.get(indices[0])); weights.add(new Double(fitness(bestPath))); } }
9
public static List<Laureate> filterByBirthYear(List<Laureate> inputList, List<String> ListOfTerms) { List<Laureate> outputList = new ArrayList<Laureate>(); // parse input, keep what matchs the terms. for (Laureate Awinner : inputList) { if (ListOfTerms.contains(Awinner.getBirth())) { outputList.add(Awinner); } } return outputList; }
2
private void initializeBuffer() { if (this.BufferGraphics != null) { this.BufferGraphics.dispose(); } if (this.BufferImage != null) this.BufferImage.flush(); Object localObject; if (this.ImageContainerParent == null) { localObject = this; } else { ImageContainer localImageContainer = this.ImageContainerParent; while (localImageContainer.getImageContainerParent() != null) { localImageContainer = localImageContainer.getImageContainerParent(); } localObject = localImageContainer; if (!localImageContainer.Added) { return; } } if (this.BufferSize == null) this.BufferImage = ((Component)localObject).createImage(getSize().width, getSize().height); else { this.BufferImage = ((Component)localObject).createImage(this.BufferSize.width, this.BufferSize.height); } this.BufferGraphics = this.BufferImage.getGraphics(); for (int i = 0; i < this.ImageContainerChildren.size(); i++) { ((ImageContainer)this.ImageContainerChildren.elementAt(i)).initializeBuffer(); } taintBuffer(); }
7
public SplashWindow(Frame f, String imgName) { super(f); this.imgName = imgName; tk = Toolkit.getDefaultToolkit(); splashImage = loadSplashImage(); showSplashScreen(); //f.addWindowListener(new WindowListener()); }
0
private void submit_modify_buttonActionPerformed(ActionEvent evt, String courseIDToModify) { Instructor instructor_taken; String instField = instruct_combo.getSelectedItem().toString(); instField = instField.substring(instField.indexOf("-") + 2); int instID = Integer.parseInt(instField); instructor_taken = (Instructor) AccountAccess .constructAccountObject(AccountAccess.accessUsername(instID)); Course new_course = new Course(course_name_field.getText(), course_id_field.getText(), instructor_taken, course_start_formatfield.getText(), course_end_formatfield.getText()); // Add the course to course db CourseAccess.modifyCourse(courseIDToModify, new_course); CourseAccess.clearTAs(course_id_field.getText()); // Add the TA to the TA table if (ta_list.getText() != null) { String[] tasplit = ta_list.getText().split(","); for (int i = 0; i < tasplit.length - 1; i++) { String[] ta = tasplit[i].split(" - "); CourseAccess.addTA(course_id_field.getText(), Integer.parseInt(ta[1].trim()), ta[0].trim()); } } if (accounts_list != null) { // Add the CSV file CourseAccess.clearStudentList(course_id_field.getText()); String student_name; String student_id; for (String i : accounts_list) { String[] arr = i.split(", "); student_name = arr[0]; student_id = arr[1]; // Push the student to the database CourseAccess .addStudent(student_name, Integer.parseInt(student_id), course_id_field.getText()); } } JOptionPane.showMessageDialog(this, "Course " + new_course.getCourseName() + " modified."); setOkToNav(); GUIUtils.getMasterFrame(this).goBack(); }
4
private void actionGetpiece (String key, String demande, OutputStream out) throws IOException { // Passer directement le string String[] tab = demande.split(" "); Object o = _hash.get(key); if (o != null){ Fichier f = (Fichier)o; if (_estMisAssertion) System.out.println("On me demande des pièce de mon fichier " + key); String[] index = ((String)demande.subSequence(demande.indexOf("[")+1,demande.indexOf("]"))).split(" "); String reponse = "data " + key + " ["; int i; boolean[] masque = f.getMasque(); String reponsePartielle = ""; int taille_piece = f.getTaillePiece(); byte lecteur[] = new byte[taille_piece]; int retour; int last_indice = (int) (f.getTaille()/f.getTaillePiece()); int last_taille = (int)f.getTaille() % f.getTaillePiece(); byte [] last_lecteur = new byte[last_taille]; for ( i=0 ; i<index.length ; i++){ // Si on a bien le i-ème index dans notre Buffermap int id = Integer.parseInt(index[i]); if (masque[id]){ // on ouvre le fichier dont on extrait les données RandomAccessFile file = new RandomAccessFile("Download/" + f.getName(), "r"); file.seek(id*taille_piece); if (id == last_indice) { retour = file.read(last_lecteur); reponsePartielle += id + ":" + new String(last_lecteur) + " "; } else { retour = file.read(lecteur); reponsePartielle += id + ":" + new String(lecteur) + " "; } } } if (_estMisAssertion) System.out.println(reponsePartielle.length() +":'"+reponsePartielle +"'"); reponse += reponsePartielle.substring(0,reponsePartielle.length() -1) + "]"; if (_estMisAssertion) System.out.println(">> " + reponse); out.write(reponse.getBytes()); out.flush(); } }
7
@Override public void perform(CommandSender sender, String[] args) { List<String> GymTypes = instance.getConfig().getStringList("GymTypes"); if (args.length == 2) { if (args[0].equalsIgnoreCase("List")) { for (String i : GymTypes) { if (args[1].equalsIgnoreCase(i)) { Integer count = 0; inform(sender, ChatColor.RED + "Leaders of " + i + ": "); for (String s : instance.getConfig().getStringList("Gyms." + i + ".Leaders")) { count++; inform(sender, count.toString() + ": " + s); } } } } } else { error(sender, "You need to type the gym you want to check. " + ChatColor.GREEN + "/gym list <gym> Or /leader list <gym>"); } }
5
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SpacePort spacePort = (SpacePort) o; if (averageStartsCount != spacePort.averageStartsCount) return false; if (name != null ? !name.equals(spacePort.name) : spacePort.name != null) return false; return true; }
6
public static List fromCollection(Collection c) { if ((c != null) && (c instanceof List)) { return (List)c; } if ((c == null) || (c.size() == 0)) { return new ArrayList(); } List list = new ArrayList(c.size()); Iterator itr = c.iterator(); while (itr.hasNext()) { list.add(itr.next()); } return list; }
5
public static void main(String args[]) { Scanner inFile = null; try { // Create a scanner to read the file, file name is parameter inFile = new Scanner(new File(System.getProperty("user.dir") + "/src/Files/numsort.dat")); } catch (FileNotFoundException e) { System.out.println("File not found!"); // Stop program if no file found System.exit(0); } //get info from file ArrayList<Integer> unsorted = new ArrayList<Integer>(); while (inFile.hasNext()) { unsorted.add(inFile.nextInt()); } //ouput original list System.out.println("Original List:"); for (int i = 0; i < unsorted.size(); i++) { System.out.print(unsorted.get(i) + "\t"); if ((i + 1) % 10 == 0) { System.out.print("\n"); } } //output sorted list System.out.println("Sorted List:"); ArrayList<Integer> sorted = sort(unsorted); for (int i = 0; i < sorted.size(); i++) { System.out.print(sorted.get(i) + "\t"); if ((i + 1) % 10 == 0) { System.out.print("\n"); } } System.out.println(); }
6
private final void method511(int i) { anInt1003++; for (Class348_Sub23 class348_sub23 = (Class348_Sub23) aClass356_1011.method3484(0); class348_sub23 != null; class348_sub23 = (Class348_Sub23) aClass356_1011.method3482(i + 2)) { if (class348_sub23 != aClass348_Sub23_Sub2_1001) { while (((Class348_Sub23) class348_sub23) .anOggStreamState6869.packetOut() == 1) class348_sub23.method2963(anOggPacket993, i ^ ~0x4001); } } if (aClass348_Sub23_Sub2_1001 != null) { if (i != -2) method518(null, (byte) 10); for (int i_1_ = 0; (i_1_ ^ 0xffffffff) > -11 && method507(false); i_1_++) { if ((((Class348_Sub23) aClass348_Sub23_Sub2_1001) .anOggStreamState6869.packetOut() ^ 0xffffffff) != -2) { method508(1); break; } aClass348_Sub23_Sub2_1001.method2963(anOggPacket993, 16384); } } }
8
protected void setSize(int size) { if (size < 0) { size = 9; } else if (size % 9 != 0) { size += 9 - (size % 9); } this.size = size; }
2
@EventHandler public void onUpdate(UpdateEvent e) { if (e.getUpdateType() == UpdateType.SECOND) { boolean isInHill = false; while (!isInHill) { if (enterQueue.size() > 0) { if (!arena.getCuboid().contains(enterQueue.peek().getLocation())) { Chat.sendMessage(enterQueue.remove(), Message.LEFT_HILL); resetPoints(enterQueue.peek()); } else isInHill = true; } else isInHill = true; } if (!enterQueue.isEmpty()) { addPoints(enterQueue.peek()); enterQueue.peek().sendRawMessage("test"); } } }
5
public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) { return null; } Stack<ListNode> s1 = new Stack<ListNode>(); Stack<ListNode> s2 = new Stack<ListNode>(); for (int i = 0; i < lists.length; i++) { s1.push(lists[i]); } while (true) { if(s1.size() == 1) { return s1.pop(); } while(!s1.isEmpty()) { ListNode p1 = s1.pop(); if(s1.isEmpty()) { s2.push(p1); } else { ListNode p2 = s1.pop(); s2.push(mergeTwoLists(p1, p2)); } } Stack<ListNode> temp = s1; s1 = s2; s2 = temp; } }
7
public int ScoreHand(Card[] Hand){ int Score=0; int Aces =0; System.out.println("---------------"); System.out.println(Hand[0].Value); System.out.println(Hand[1].Value); System.out.println(Hand[2].Value); System.out.println(Hand[3].Value); System.out.println("================"); for(int x=0;x<Hand.length;x++){ //-1 is the default value for undealt cards if(Hand[x].getValue()!=-1){ switch(Hand[x].getValue()){ case 0: //Ace System.out.println("found an ace"); Score=Score+11; Aces++; break; case 10: //Jack System.out.println("found a jack"); Score = Score+10; break; case 11: //Queen System.out.println("found a queen"); Score=Score+10; break; case 12: //King System.out.println("found a king"); Score=Score+10; break; default: System.out.println("found a "+(Hand[x].getValue()+1)); Score = Score + Hand[x].getValue()+1; break; } } } while(Aces!=0){ if(Score>21){ Score = Score-10; Aces--; }else{ break; } } if(Score>21){ Score=0; } return Score; }
9
public FordFulkersonAlgorithm(IWeightedGraph<N, Number> originalGraph, N source, N sink) { WeightedGraph<N, Number> graph = new WeightedGraph<N, Number>(true); List<WeightedEdge<N, Number>> edges = originalGraph.getEdges(); for(WeightedEdge<N, Number> edge : edges) { graph.addNode(edge.from); graph.addNode(edge.to); graph.addEdge(edge.from, edge.to, edge.weight); graph.addEdge(edge.to, edge.from, 0.0); flow.put(graph.edgesBetween(edge.from, edge.to).get(0), 0.0); flow.put(graph.edgesBetween(edge.to, edge.from).get(0), 0.0); } List<WeightedEdge<N, Number>> path = null; while((path = findPath(graph, source, sink, source, new LinkedList<WeightedEdge<N, Number>>())) != null) { double minCapacity = Double.MAX_VALUE; for(WeightedEdge<N, Number> edge : path) { minCapacity = Math.min(minCapacity, edge.weight.doubleValue() - flow.get(edge)); } for(WeightedEdge<N, Number> edge : path) { flow.put(graph.edgesBetween(edge.from, edge.to).get(0), (flow.containsKey(graph.edgesBetween(edge.from, edge.to).get(0)) ? flow.get(graph.edgesBetween(edge.from, edge.to).get(0)) : 0) + minCapacity); flow.put(graph.edgesBetween(edge.to, edge.from).get(0), (flow.containsKey(graph.edgesBetween(edge.to, edge.from).get(0)) ? flow.get(graph.edgesBetween(edge.to, edge.from).get(0)) : 0) - minCapacity); } } maxFlow = 0.0; edges = originalGraph.edgesFrom(source); for(WeightedEdge<N, Number> edge : edges) { maxFlow += flow.get(graph.edgesBetween(edge.from, edge.to).get(0)); } }
7
private final void closeElement() throws IOException { if (openElement) { w.write(">\n"); } openElement = false; }
1
@NonNull public void parseJSONtoMap (URL u, String name, HashMap<String, String> h, boolean testEntries, String location) { try { String json = IOUtils.toString(u); JsonElement element = new JsonParser().parse(json); int i = 10; if (element.isJsonObject()) { JsonObject jso = element.getAsJsonObject(); for (Entry<String, JsonElement> e : jso.entrySet()) { if (testEntries) { try { Logger.logInfo("Testing Server:" + e.getKey()); //test that the server will properly handle file DL's if it doesn't throw an error the web daemon should be functional IOUtils.toString(new URL("http://" + e.getValue().getAsString() + "/" + location)); h.put(e.getKey(), e.getValue().getAsString()); } catch (Exception ex) { Logger.logWarn((e.getValue().getAsString().contains("creeper") ? "CreeperHost" : "Curse") + " Server: " + e.getKey() + " was not accessible, ignoring." + ex.getMessage()); } if (i < 90) i += 10; LoadingDialog.setProgress(i); } else { h.put(e.getKey(), e.getValue().getAsString()); } } } } catch (Exception e2) { Logger.logError("Error parsing JSON " + name + " " + location, e2); } }
7
public String nextCDATA() throws JSONException { char c; int i; StringBuilder sb = new StringBuilder(); for (; ; ) { c = next(); if (end()) { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { sb.setLength(i); return sb.toString(); } } }
6
@Override public boolean run() { verbose = true; // Load reactome data Reactome reactome = new Reactome(); reactome.setVerbose(verbose); reactome.load(reactomeDir, geneIdsFile); // Load GTEX data if (verbose) Timer.showStdErr("Loading GTEx data"); Gtex gtex = new Gtex(); gtex.setVerbose(verbose); gtex.load(gtexSamples, gtexData); // Simulate reactome.run(gtex, nameMatch); // Results to STDOUT System.out.println(reactome.getMonitor().toString()); if (verbose) Timer.showStdErr("Done!"); return true; }
2
@SuppressWarnings("rawtypes") /** * Retrieve class names implementing the given interface existing somewhere in the basePackage */ public static List<String> getClassNamesImplementingInterface(Class interf, String basePackage) { List<String> classNames = new ArrayList<String>(); try { Class[] result = getClasses(basePackage); for (Class c : result) { if (!Modifier.isAbstract(c.getModifiers())) { for (Class implementingInterface : c.getInterfaces()) { if (implementingInterface.getName().equals(interf.getName())) { classNames.add(c.getCanonicalName()); } } } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return classNames; }
6
public byte[] decrypt(byte[] textEncrypted, String key){ byte[] decrypted = null; try{ //keygenerator.init(bits); // 192 and bits bits may not be available byte[] keyPadded = new byte[bits / 8]; for(int i = 0; i < bits / 8 && i < key.length(); i++){ keyPadded[i] = (byte)key.charAt(i); } /* Generate the secret key specs. */ SecretKeySpec mykey = new SecretKeySpec(keyPadded, "AES"); // Create the cipher desCipher = Cipher.getInstance("AES"); // Initialize the cipher for encryption desCipher.init(Cipher.DECRYPT_MODE, mykey); // Encrypt the text decrypted = desCipher.doFinal(textEncrypted); }catch(IllegalBlockSizeException e){ e.printStackTrace(); }catch(BadPaddingException e){ e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); System.out.println("error in desCipher.init"); //} } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return decrypted; }
7
private void initialize(boolean check) { setLayout(new GridLayout(7, 1)); numberOfFilesLabel = new JLabel("Number of Files \t:\t "); lineOfCodeLabel = new JLabel("Lines of Code \t:\t "); commentsLabel = new JLabel("Commented Lines \t:\t "); blankLinesLabel = new JLabel("Blank Lines \t:\t "); totalLinesLabel = new JLabel("Total Lines \t:\t "); if (check) { codeShareLabel = new JLabel("Share in Project \t:\t "); } }
1
public void MostraPesquisa(List<Usuario> usuario) { while (tmUsuario.getRowCount() > 0) { tmUsuario.removeRow(0); } if (!usuario.isEmpty()) { String[] linha = new String[]{null, null}; for (int i = 0; i < usuario.size(); i++) { tmUsuario.addRow(linha); tmUsuario.setValueAt(usuario.get(i).getNome(), i, 0); tmUsuario.setValueAt(usuario.get(i).getEmail(), i, 1); } } else { JOptionPane.showMessageDialog(null, "Usuário não cadastrado!", "Atenção!", 0); } }
3
public int canCompleteCircuit1(int[] gas, int[] cost) { for(int i =0;i< gas.length;i++){ if(gas[i] >= cost[i]){ if(canFinish(gas,cost,i)) return i; } } return -1; }
3
private static List<String> splitIntoIndividualLocants(String locantString) { List<String> individualLocants = new ArrayList<String>(); char[] charArray = locantString.toCharArray(); boolean inBracket =false; int indiceOfLastMatch =0; for (int i = 0; i < charArray.length; i++) { char c = charArray[i]; if (c==','){ if (!inBracket){ individualLocants.add(locantString.substring(indiceOfLastMatch, i)); indiceOfLastMatch = i+1; } } else if (c == '(' || c == '[' || c == '{') { inBracket =true; } else if(c == ')' || c == ']' || c == '}') { inBracket =false; } } individualLocants.add(locantString.substring(indiceOfLastMatch, charArray.length)); return individualLocants; }
9
private void calcProduction() { Arrays.fill(productionHolder, 0); for (Pattern pattern : plan.getPatterns()) { for (int i = 0; i < problem.size(); i++) { productionHolder[i] += pattern.getProduction(i); } } cachedUnderproductionAmount = 0; cachedOverproductionAmount = 0; cachedAverageUnderproductionRatio = 0; cachedMaximumUnderproductionRatio = 0; cachedAverageOverproductionRatio = 0; cachedMaximumOverproductionRatio = 0; for (int i = 0; i < problem.size(); i++) { int produced = productionHolder[i]; int ordered = problem.getOrder(i).getQuantity(); if (ordered > produced) { // underproduction cachedUnderproductionAmount += ordered - produced; double underproductionRatio = (ordered - produced) / (double) ordered; cachedAverageUnderproductionRatio += underproductionRatio; if (underproductionRatio > cachedMaximumUnderproductionRatio) { cachedMaximumUnderproductionRatio = underproductionRatio; } } else { // overproduction cachedOverproductionAmount += produced - ordered; double overproductionRatio = (produced - ordered) / (double) ordered; cachedAverageOverproductionRatio += overproductionRatio; if (overproductionRatio > cachedMaximumOverproductionRatio) { cachedMaximumOverproductionRatio = overproductionRatio; } } } cachedAverageUnderproductionRatio /= problem.size(); cachedAverageOverproductionRatio /= problem.size(); }
6
@Test public void pisteSetXJaSetYToimivat() { p.setX(10); assertTrue("Väärä siirretyn pisteen x", p.getX() == 10); p.setY(10); assertTrue("Väärä siirretyn pisteen y", p.getY() == 10); p.setXY(new Piste(20, 50)); assertTrue("Väärä siirretyn pisteen x", p.getX() == 20); assertTrue("Väärä siirretyn pisteen y", p.getY() == 50); }
0
public ConvertRegularGrammarToFSA(GrammarEnvironment environment) { super("Convert Right-Linear Grammar to FA", null); this.environment = environment; }
0
public boolean saveData(String data,String dataFile) { boolean test = false; if (test || m_test) { System.out.println("Saver :: saveData() BEGIN"); } try { setFile(dataFile); PrintWriter out = new PrintWriter(this.getFile()); //try reading file try { out.println(data + data.hashCode()); }finally { out.close(); } } catch (Exception exc) { System.err.println("Write Error"); return false; } if (test || m_test) { System.out.println("Saver :: saveData() END"); } return true; }
5
public void move(int Xa, int Ya) { if (Xa != 0 && Ya != 0) { move(Xa, 0); move(0, Ya); numSteps--; return; } numSteps++; if (!hasCollided(Xa, Ya)) { if (Ya < 0) { movingDir = 0; } if (Ya > 0) { movingDir = 1; } if (Xa < 0) { movingDir = 2; } if (Xa > 0) { movingDir = 3; } x += Xa * speed; y += Ya * speed; } }
7
public void validate(Object obj, Errors errors) { PriceIncrease pi = (PriceIncrease) obj; if (pi == null) { errors.rejectValue("percentage", "error.not-specified", null, "Value required."); } else { logger.info("Validating with " + pi + ": " + pi.getPercentage()); if (pi.getPercentage() > maxPercentage) { errors.rejectValue("percentage", "error.too-high", new Object[] {new Integer(maxPercentage)}, "Value too high."); } if (pi.getPercentage() <= minPercentage) { errors.rejectValue("percentage", "error.too-low", new Object[] {new Integer(minPercentage)}, "Value too low."); } } }
3
public static void filledRectangle(double x, double y, double halfWidth, double halfHeight) { if (halfWidth < 0) throw new RuntimeException("half width can't be negative"); if (halfHeight < 0) throw new RuntimeException("half height can't be negative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*halfWidth); double hs = factorY(2*halfHeight); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); }
4
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Cambios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Cambios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Cambios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Cambios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { Cambios dialog = new Cambios(new javax.swing.JFrame(), true); dialog.setLocationRelativeTo(null); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
public boolean canPlaceBlockOnSide(World par1World, int par2, int par3, int par4, int par5) { return (par5 == 1 && par1World.isBlockSolidOnSide(par2, par3 - 1, par4, 1)) || (par5 == 2 && par1World.isBlockSolidOnSide(par2, par3, par4 + 1, 2)) || (par5 == 3 && par1World.isBlockSolidOnSide(par2, par3, par4 - 1, 3)) || (par5 == 4 && par1World.isBlockSolidOnSide(par2 + 1, par3, par4, 4)) || (par5 == 5 && par1World.isBlockSolidOnSide(par2 - 1, par3, par4, 5)); }
9
private static Node<Integer> add_TailOnesDigitData_Internal(Node<Integer> num1, Node<Integer> num2, IntWrapper carry) { if (num1 == null && num2 == null) { return null; } Node<Integer> prevRes = null; if (num1 == null) { prevRes = add_TailOnesDigitData_Internal(null, num2.next, carry); } else if (num2 == null) { prevRes = add_TailOnesDigitData_Internal(num1.next, null, carry); } else { prevRes = add_TailOnesDigitData_Internal(num1.next, num2.next, carry); } Integer intData = null; if (num1 == null) { intData = num2.data + carry.i; } else if (num2 == null) { intData = num1.data + carry.i; } else { intData = num1.data + num2.data + carry.i; } carry.i = intData / 10; Node<Integer> newRes = new Node<Integer>(intData % 10); newRes.next = prevRes; return newRes; }
6
public List<PhpposLogEntrada> getPosLogEntradasFromFecha(Date desde, Date hasta){ DetachedCriteria criteria = DetachedCriteria.forClass(PhpposLogEntrada.class); criteria.add(Restrictions.between("fechaCreacion", desde, hasta)); return getHibernateTemplate().findByCriteria(criteria); }
0
@Override public void onCombatTick(int x, int y, Game game) { SinglePlayerGame spg = (SinglePlayerGame) game; List<Entity> neighbors = spg .getSquareNeighbors(x, y, 1); for (Entity entity : neighbors) { if (entity.id == human.id) { MortalEntity mortal = ((MortalEntity) entity); if (mortal.damage(4)) { spg.addAnimation(Animation.hitAnimationFor(4, entity, spg)); zombie.damageDealt += 4; zombie.kills++; human.deaths++; zombie.toSpawn.add(new Location(entity.x, entity.y)); } } else if (entity.id == wall.id) { ((MortalEntity) entity).damage(2); } else if (entity.id == juggernaut.id) { if (((MortalEntity) entity).damage(3)) { spg.addAnimation(Animation.hitAnimationFor(3, entity, spg)); zombie.damageDealt += 3; zombie.kills++; juggernaut.deaths++; } } } }
6
public void loadWord() { WordLoader w1 = getWordLoader(); try { String wordString = w1.getWord(); word = new HMWord(wordString); } catch (Exception e) { e.printStackTrace(); } }
1
private void loadAllClientReps(){//COMPLETE try { ResultSet dbAllClientReps = null; Statement statement; statement = connection.createStatement(); dbAllClientReps = statement.executeQuery( "SELECT ClientRep.clientRepID, ClientRep.organisationID, ClientRep.contactNo, ClientRep.email FROM ClientRep;"); while(dbAllClientReps.next()) { Client tempClient = null; User tempUser = null; for (int i=0; i<allClients.size();i++){ if(allClients.get(i).getClientID()==(dbAllClientReps.getInt("organisationID"))) { tempClient = (allClients.get(i)); } } for (int i=0; i<allUsers.size();i++){ if(allUsers.get(i).getUserID()==(dbAllClientReps.getInt("clientRepID"))) { tempUser = (allUsers.get(i)); } } ClientRep tempClientRep = new ClientRep(tempUser, tempClient, dbAllClientReps.getString("contactNo"), dbAllClientReps.getString("email")); allClientReps.addClientRep(tempClientRep); } } catch (SQLException ex) { Logger.getLogger(testFrame3Tim.class.getName()).log(Level.SEVERE, null, ex); } }
6
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(sender instanceof Player) { Player player = (Player) sender; if(plugin.confirm.containsKey(player)) { String group = plugin.confirm.get(player); @SuppressWarnings("unchecked") List<String> ranks = (List<String>) plugin.config.getList("Ranks"); for(String value : ranks) { String[] rank = value.split(","); String group1 = rank[0]; Double price = Double.parseDouble(rank[1]); if(group.equals(group1)) { if(plugin.economy.has(player.getName(), price)) { plugin.economy.withdrawPlayer(player.getName(), price); plugin.getPermissionsHandler().promote(player, group, PROMOTIONTYPE.BOUGHT); String msg = plugin.messages.getString("BoughtRank").replace("&", "\u00A7"); player.sendMessage(msg.replace("<group>", group)); plugin.confirm.remove(player); System.out.println("[PLAYER_COMMAND] " + player.getName() + ": /confirm"); System.out.println("[MasterPromote]Player " + player.getName() + " has bought " + group); return true; } else { String msg = plugin.messages.getString("NoMoney").replace("&", "\u00A7"); player.sendMessage(msg.replace("<group>", group)); return true; } } } } } else { System.out.println("[MasterPromote]You have to be a player to use this command!"); return true; } return false; }
5
public float getRecall(String[] manualSummaries, String[] generatedSummaries){ String manualSummary,generatedSummary; int matchCount=0; int manualSummaryCount=0; String[] manualOneGram = null,generatedOneGram = null; if(manualSummaries==null || generatedSummaries==null || manualSummaries.length!=generatedSummaries.length){ return 0.00f; } for(int i=0;i<manualSummaries.length;i++){ manualSummary = manualSummaries[i]; generatedSummary = generatedSummaries[i]; manualOneGram = manualSummary.split("[^\\p{L}\\p{Nd}]"); generatedOneGram = generatedSummary.split("[^\\p{L}\\p{Nd}]"); //matchCount = 0; for (String manualWord: manualOneGram){ for (String generatedWord: generatedOneGram){ if(generatedWord.equalsIgnoreCase(manualWord)){ matchCount++; break; } } } manualSummaryCount+=manualOneGram.length; } return ((float)matchCount/(float)manualSummaryCount); }
7
public void checkType(Symtab st) { exp1.setScope(scope); exp1.checkType(st); exp2.setScope(scope); exp2.checkType(st); if (!exp1.getType(st).equals("int") && !exp1.getType(st).equals("decimal")) Main.error("type error in mult!"); if (!exp2.getType(st).equals("int") && !exp2.getType(st).equals("decimal")) Main.error("type error in mult!"); }
4
private static int alphaBeta(Configuration conf, int alpha, int beta,byte depth,byte max){ if ((conf.whoWin() != 0) || (depth >= max)){ return evaluation(conf); } else{ int meilleur = Integer.MIN_VALUE; for (Configuration fconf : listeFils(conf)) { int suiv=-alphaBeta(fconf, -beta, -alpha, (byte) (depth+1),max); if (suiv > meilleur) { meilleur=suiv; if(meilleur > alpha){ alpha=meilleur; if (alpha >= beta) { return meilleur; } } } } return meilleur; } }
6
public void setPWfieldBorderthickness(int[] border) { if ((border == null) || (border.length != 4)) { this.pwfield_Borderthickness = UIBorderthicknessInits.PWFIELD.getBorderthickness(); } else { this.pwfield_Borderthickness = border; } somethingChanged(); }
2
private void showLoans() { List<Book> books = library.getLoanedBooks(); List<Cd> CDs = library.getLoanedCds(); List<Magazine> magazines = library.getLoanedMagazines(); boolean done = false; do { printHeader("Books"); int index = 1; printBooks(index, books); index += books.size(); printHeader("CDs"); printCDs(index, CDs); index += CDs.size(); printHeader("Magazines"); printMagazines(index, magazines); printFooter(); stream.println("1. return item."); stream.println("2. go back"); int userChoice = scanner.nextInt(); switch(userChoice) { case 1: stream.println("index: > "); index = scanner.nextInt() - 1; LibraryItem li = null; if (index < books.size()) { li = books.remove(index); } else { index -= books.size(); if (index < CDs.size()) { li = CDs.remove(index); } else { index -= CDs.size(); if (index < magazines.size()) { li = magazines.remove(index); } } } if (li != null) { library.returnLibraryItem(li); stream.println("returned"); } break; case 2: done = true; break; default: break; } } while(!done); }
7
@Test public void runTestButton4() throws IOException { InfoflowResults res = analyzeAPKFile("Callbacks_Button4.apk"); Assert.assertNotNull(res); Assert.assertEquals(1, res.size()); }
0
public static void main(String[] args) { if(args.length >= 1 && args[0].equals("debug")){ debug = true; } client1 = new Client(); try { //client1.buildGUI(); gui = new GUI(client1); config = new Config(); String tmp = config.getWindowTitle(); if (!tmp.equals("")) { client1.windowTitle = tmp; GUI.frame.setTitle(tmp); } tools = new Tools(client1); } catch (Exception e) { e.printStackTrace(); } }
4
public PlayerUpdate getUpdate(){ PlayerUpdate x = new PlayerUpdate(); if(sprite.equals(up)){ x.spriteDirection = "up"; } else if(sprite.equals(left)){ x.spriteDirection = "left"; } else if(sprite.equals(right)){ x.spriteDirection = "right"; } else{ x.spriteDirection = "down"; } x.username = username; x.x = absolutex; x.y = absolutey; return x; }
3
void render(){ for(int i = 0; i < 4; i++){ for(int j = 0; j < 4; j++){ int k = j*4+i; U.batch.draw(icons[j][i],U.h+U.SPRITESIZE, U.h-(k)*U.SPRITESIZE-U.SPRITESIZE*3/4,U.SPRITESIZE/2,U.SPRITESIZE/2); if(k%4 != 3){ if(statsArray[k] < minima[k]){ U.font.setColor(1, 0, 0, 1); U.batch.draw(arrows[0][0],U.h+U.SPRITESIZE*2, U.h-(k)*U.SPRITESIZE-U.SPRITESIZE*3/4,U.SPRITESIZE/2,U.SPRITESIZE/2); } else if(statsArray[k] > maxima[k]){ U.font.setColor(1, 0, 0, 1); U.batch.draw(arrows[0][1],U.h+U.SPRITESIZE*2, U.h-(k)*U.SPRITESIZE-U.SPRITESIZE*3/4,U.SPRITESIZE/2,U.SPRITESIZE/2); } else{ U.font.setColor(0,1,0,1); U.batch.draw(arrows[0][2],U.h+U.SPRITESIZE*2, U.h-(k)*U.SPRITESIZE-U.SPRITESIZE*3/4,U.SPRITESIZE/2,U.SPRITESIZE/2); } U.font.draw(U.batch, "" + statsArray[k] + " (" + minima[k] + "<->" + maxima[k] + ")",U.h+U.SPRITESIZE*3, U.h-(j*4+i)*U.SPRITESIZE-U.SPRITESIZE*1/4); } } } }
5
public String[] nextStrings(int n) throws IOException { String[] res = new String[n]; for (int i = 0; i < n; ++i) { res[i] = next(); } return res; }
1
private static int serLane(int[] width, int i, int j) { int currentMin = MAX_N; for (; i <= j; i++) { if (width[i] < currentMin) { currentMin = width[i]; } } return currentMin; }
2
@Override public void setEmail(String email) { super.setEmail(email); }
0
@Override public void destroy() { tree = null; oldValue = null; newValue = null; }
0
public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { JComboBox combo = (JComboBox) e.getSource(); int index = combo.getSelectedIndex(); System.out.println("./files/img/" + images[index]); display.setIcon(new ImageIcon("./files/img/" + images[index])); } }
1
public boolean insideBase(Player player) { for (Region region : HyperPVP.getMap().getRegions(RegionType.TEAM)) { if (region.hasLocation(player.getLocation())) { return true; } } return false; }
2
public final GalaxyXSemanticParser.modifier_return modifier() throws RecognitionException { GalaxyXSemanticParser.modifier_return retval = new GalaxyXSemanticParser.modifier_return(); retval.start = input.LT(1); int modifier_StartIndex = input.index(); CommonTree root_0 = null; Token set88=null; CommonTree set88_tree=null; try { if ( state.backtracking>0 && alreadyParsedRule(input, 14) ) { return retval; } // C:\\Users\\Timo\\EclipseProjects\\GalaxyX\\src\\com\\galaxyx\\parser\\GalaxyXSemanticParser.g:139:2: ( PUBLIC | PRIVATE ) // C:\\Users\\Timo\\EclipseProjects\\GalaxyX\\src\\com\\galaxyx\\parser\\GalaxyXSemanticParser.g: { root_0 = (CommonTree)adaptor.nil(); set88=(Token)input.LT(1); if ( (input.LA(1)>=PRIVATE && input.LA(1)<=PUBLIC) ) { input.consume(); if ( state.backtracking==0 ) adaptor.addChild(root_0, (CommonTree)adaptor.create(set88)); state.errorRecovery=false;state.failed=false; } else { if (state.backtracking>0) {state.failed=true; return retval;} MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } } retval.stop = input.LT(-1); if ( state.backtracking==0 ) { retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { if ( state.backtracking>0 ) { memoize(input, 14, modifier_StartIndex); } } return retval; }
9
private void switchToSpeedHost() throws FatalError { if (Config.getSpeedHost() != null) { try { String page = Utils.getString("speed/index"); int pos = page.indexOf("speedlink"); if (pos < 0) throw new NotFound(); page = page.substring(pos); pos = page.indexOf("\""); if (pos < 0) throw new NotFound(); page = page.substring(pos + 1); pos = page.indexOf("\""); if (pos < 0) throw new NotFound(); page = page.substring(0, pos); page = page.substring(Config.getSpeedHost().length()); Config.setHost(Config.getSpeedHost()); Utils.getString(page); getCharacter(); } catch (NotFound e) { } } }
5
private void initActions() { for (int i = 0; i < tools.length; ++i) { final Tool tool = tools[i]; String group = tool.group; if (group.equals("tool")) { tool.action = new Runnable() { public void run() { setPaintTool(tool.id); } }; } else if (group.equals("fill")) { tool.action = new Runnable() { public void run() { setFillType(tool.id); } }; } else if (group.equals("linestyle")) { tool.action = new Runnable() { public void run() { setLineStyle(tool.id); } }; } else if (group.equals("options")) { tool.action = new Runnable() { public void run() { FontDialog fontDialog = new FontDialog(paintSurface.getShell(), SWT.PRIMARY_MODAL); FontData[] fontDatum = toolSettings.commonFont.getFontData(); if (fontDatum != null && fontDatum.length > 0) { fontDialog.setFontList(fontDatum); } fontDialog.setText(getResourceString("options.Font.dialog.title")); paintSurface.hideRubberband(); FontData fontData = fontDialog.open(); paintSurface.showRubberband(); if (fontData != null) { try { Font font = new Font(mainComposite.getDisplay(), fontData); toolSettings.commonFont = font; updateToolSettings(); } catch (SWTException ex) { } } } }; } } }
9
public boolean _setSpeedX(int speedX) { if(speedX > -1) { this.speedX = speedX; return true; } else { return false; } }
1
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Message message1 = (Message) o; if (date != null ? !date.equals(message1.date) : message1.date != null) return false; if (message != null ? !message.equals(message1.message) : message1.message != null) return false; if (receiver != null ? !receiver.equals(message1.receiver) : message1.receiver != null) return false; return true; }
9
@Override public boolean apply(final SliceIntArray input, final SliceIntArray output) { if ((!SliceIntArray.isValid(input)) || (!SliceIntArray.isValid(output))) return false; final int nbThreads = this.delegates.length; ArrayList<Callable<Boolean>> filterTasks = new ArrayList<Callable<Boolean>>(nbThreads); final int area = this.height * this.stride; boolean res = true; for (int i=0; i<this.delegates.length; i++) { int srcIdx = (this.direction == HORIZONTAL) ? input.index + (area * i) / nbThreads : input.index + (this.width * i) / nbThreads; SliceIntArray src = new SliceIntArray(input.array, srcIdx); int dstIdx = (this.direction == HORIZONTAL) ? output.index + (area * i) / nbThreads : output.index + (this.width * i) / nbThreads; SliceIntArray dst = new SliceIntArray(output.array, dstIdx); filterTasks.add(new FilterTask(this.delegates[i], src, dst)); } try { List<Future<Boolean>> results = this.pool.invokeAll(filterTasks); for (Future<Boolean> fr : results) res &= fr.get(); } catch (InterruptedException e) { // Ignore } catch (ExecutionException e) { return false; } return res; }
8
private static void dumpDynamicNpcs(RT6CacheSystem system) { NpcDefinitionLoader loader = system.npcLoader; ScriptLoader scriptLoader = system.scriptLoader; PrintWriter writer = null; try { writer = new PrintWriter(new File("dynamic_npcs.java")); } catch (FileNotFoundException e) { e.printStackTrace(); return; } for (int id = 0; id < 0x20000; id++) { if (loader.canLoad(id)) { final NpcDefinition definition = loader.load(id); if (definition.childrenIds != null) { writer.println(definition); int mask = definition.childrenIds.length; if (definition.configId != -1) { writer.println("switch (ctx.varpbits.varpbit(" + definition.configId + ")) {"); } else { final Script script = scriptLoader.load(definition.scriptId); mask = script.mask(); writer.println("switch (" + script.code() + ") {"); } int[] childrenIds = definition.childrenIds; for (int i = 0; i < childrenIds.length; i++) { if (i > mask) { break; } int childrenId = childrenIds[i]; final NpcDefinition childDefinition = loader.canLoad(childrenId) ? loader.load(childrenId) : null; writer.print("\tcase " + i + ": \t " + childrenId + " " + (childDefinition == null ? "null" : childDefinition)); //writer.print("\tcase " + i + ": \t " + childrenId + " " + (childDefinition == null ? "null" : "\"" + childDefinition.name + "\" \"" + joiner.join(childDefinition.actions) + "\"")); writer.println(); } writer.println("}"); writer.println(); } } } writer.close(); }
9
private List<Move> possibleMoves() { final boolean mustAttack = state.mustAttack(); final List<Move> result = new ArrayList<>(); if (!mustAttack) { result.add(Move.PASS); } for (byte from = 0; from < Move.N_BOARD_LOCATIONS; from++) { if (state.getOwner(from) != state.getPlayerToMove()) { continue; } for (final BoardLocation to : toLocations(from)) { /* attack? */ final byte toB = Move.fromBoardLocation(to); final boolean canAttack = (state.getOwner(toB) == state.getPlayerToMove().opponent()) && (state.getHeight(from) >= state.getHeight(toB)); if (canAttack) { result.add(Move.attack(from, toB)); } final boolean canStrengthen = (state.getOwner(toB) == state.getPlayerToMove()) && !mustAttack; if (canStrengthen) { result.add(Move.strengthen(from, toB)); } } } return result; }
8
private boolean processDot_r(int x, int y, int owner, boolean mask[][]) { if(isOnBorder(x, y)) { return false; } if(map[x][y].owner == owner && map[x][y].status) { return true; } if(mask[x][y]) { return true; } mask[x][y] = true; if(!processDot_r(x+1, y, owner, mask)) { return false; } if(!processDot_r(x-1, y, owner, mask)) { return false; } if(!processDot_r(x, y+1, owner, mask)) { return false; } if(!processDot_r(x, y-1, owner, mask)) { return false; } return true; }
8
public void drawBarChart( Object[] data, int ageInterval) { setPaint(Color.DARK_GRAY); RoundingMode roundingMode = getRoundingMode(); BigDecimal cellWidth = getCellWidth(); int originCol = getOriginCol(); TreeMap<Long, BigDecimal> femaleAgeInYearsPopulationCount_TreeMap = (TreeMap<Long, BigDecimal>) data[0]; TreeMap<Long, BigDecimal> maleAgeInYearsPopulationCount_TreeMap = (TreeMap<Long, BigDecimal>) data[1]; Iterator<Map.Entry<Long, BigDecimal>> ite; Map.Entry<Long, BigDecimal> entry; Long age; BigDecimal population; int barGap = 4; // int barGapDiv2 = barGap / 2; // int barHeight = Generic_BigDecimal.divideRoundIfNecessary( // BigDecimal.valueOf(ageInterval), // getCellHeight(), // 0, // roundingMode).intValueExact() - barGap; int barHeight; BigDecimal cellHeight = getCellHeight(); if (cellHeight.compareTo(BigDecimal.ZERO) == 0) { barHeight = 1; } else { barHeight = Generic_BigDecimal.divideRoundIfNecessary( BigDecimal.valueOf(ageInterval), getCellHeight(), 0, roundingMode).intValue() - barGap; } if (barHeight < 1) { barHeight = 1; } // Draw Female bars ite = femaleAgeInYearsPopulationCount_TreeMap.entrySet().iterator(); while (ite.hasNext()) { entry = ite.next(); // For some reason sometimes we get a Integer instead of a Long! if (!(entry.getKey() instanceof Long)) { System.out.println(entry.getKey()); String s = String.valueOf(entry.getKey()); age = Long.valueOf(s); } else { age = entry.getKey(); } population = entry.getValue(); int barWidth = Generic_BigDecimal.divideRoundIfNecessary( population, cellWidth, 0, //roundingMode).intValueExact(); roundingMode).intValue(); // int barTopRow = coordinateToScreenRow( // BigDecimal.valueOf(age + ageInterval)) // + barGapDiv2; int barTopRow = coordinateToScreenRow( BigDecimal.valueOf(age + ageInterval)) + barGap; setPaint(Color.DARK_GRAY); // Rectangle2D r2 = new Rectangle2D.Double( // originCol, // barTopRow, // barWidth, // barHeight); fillRect( originCol, barTopRow, barWidth, barHeight); // setPaint(Color.BLACK); // draw(r2); } // Draw Male bars ite = maleAgeInYearsPopulationCount_TreeMap.entrySet().iterator(); while (ite.hasNext()) { entry = ite.next(); // For some reason sometimes we get a Integer instead of a Long! if (!(entry.getKey() instanceof Long)) { System.out.println(entry.getKey()); String s = String.valueOf(entry.getKey()); age = Long.valueOf(s); } else { age = entry.getKey(); } population = entry.getValue(); int barWidth = Generic_BigDecimal.divideRoundIfNecessary( population, cellWidth, 0, roundingMode).intValueExact(); // int barTopRow = coordinateToScreenRow( // BigDecimal.valueOf(age + ageInterval)) // + barGapDiv2; int barTopRow = coordinateToScreenRow( BigDecimal.valueOf(age + ageInterval)) + barGap; setPaint(Color.LIGHT_GRAY); // Rectangle2D r2 = new Rectangle2D.Double( // originCol - barWidth, // barTopRow, // barWidth, // barHeight); fillRect( originCol - barWidth, barTopRow, barWidth, barHeight); // setPaint(Color.BLACK); // draw(r2); } }
6
public static void main(String args[]) throws Exception { for (int i = 0; i < 10; i++) { System.out.println(GUID.generate()); } }//main
1
@Override public String getMixedString(UnicodeSet localeAlphabet, int length) { if(length == 0) { return ""; } if(length <= 0) { throw new IllegalArgumentException("Length must be greater than 0."); } ArrayList<int[]> alphabets = this.getCharacterSetList(); alphabets.add(getCharArray(localeAlphabet)); int numberOfAlphabets = alphabets.size(); if(alphabets == null || numberOfAlphabets == 0) { throw new IllegalArgumentException("No Alphabet specified."); } StringBuilder randomString = new StringBuilder(); for(int iterator=0; iterator < length; iterator++) { int index = RANDOM.nextInt(numberOfAlphabets); int[] alphabet = alphabets.get(index); int randomValue = RANDOM.nextInt(alphabet.length); int charValue = alphabet[randomValue]; randomString.append(Character.toChars(charValue)); } return randomString.toString(); }
5
private static void refreshAndSave(AbstractProject template, ImplementationBuildWrapper implementationBuildWrapper, XmlFile implementationXmlFile, String oldDescription, boolean oldDisabled, Map<TriggerDescriptor, Trigger> oldTriggers) throws IOException { TopLevelItem item = (TopLevelItem) Items.load(Jenkins.getInstance(), implementationXmlFile.getFile().getParentFile()); if(item instanceof AbstractProject) { AbstractProject newImplementation = (AbstractProject) item; //Use reflection to prevent it from auto-saving ReflectionUtils.setField(newImplementation, "description", oldDescription); ReflectionUtils.setField(newImplementation, "disabled", oldDisabled); //To resolve the issue #5 cast to List and not to Vector List<Trigger> triggers = ReflectionUtils.getField(List.class, newImplementation, "triggers"); triggers.clear(); for (Trigger trigger : oldTriggers.values()) { triggers.add(trigger); } DescribableList<BuildWrapper, Descriptor<BuildWrapper>> implementationBuildWrappers = ((BuildableItemWithBuildWrappers) newImplementation).getBuildWrappersList(); CopyOnWriteList data = ReflectionUtils.getField(CopyOnWriteList.class, implementationBuildWrappers, "data"); //strip out any template definitions or implementation definitions copied from the template List<BuildWrapper> toRemove = new LinkedList<BuildWrapper>(); for (BuildWrapper buildWrapper : implementationBuildWrappers) { if(buildWrapper instanceof TemplateBuildWrapper) { if(template.getName().equals(((TemplateBuildWrapper) buildWrapper).getTemplateName())) { toRemove.add(buildWrapper); } } else if(buildWrapper instanceof ImplementationBuildWrapper) { toRemove.add(buildWrapper); } } for (BuildWrapper buildWrapper : toRemove) { data.remove(buildWrapper); } //make sure the implementation definition is still in there data.add(implementationBuildWrapper); newImplementation.getConfigFile().write(newImplementation); //don't call save() because it calls the event handlers. item = (TopLevelItem) Items.load(Jenkins.getInstance(), implementationXmlFile.getFile().getParentFile()); putItemInJenkins(Jenkins.getInstance(), item); } }
7
public void fillHuffTable(Node root) { if(root == null) return; else { if( root.character != - 1) { //System.out.print(root.frequency + "-[" + (char)root.character + "] "); Code newCode = new Code(code); huffTable[root.character] = newCode; //System.out.println(newCode.toString()); } if(root.left != null) { code.addBit(0); fillHuffTable(root.left); } if(root.right != null) { code.addBit(1); fillHuffTable(root.right); } if(code.length() > 0) code.removeBit(); } }
5
public void addCommands(Object o) { try { interpreter.set("current_interpreter", interpreter); evaluations = "import graphtea.graph.graph.*;" + evaluations; evaluations = "import graphtea.ui.lang.*;" + evaluations; } catch (EvalError evalError) { evalError.printStackTrace(); } Class clazz = o.getClass(); for (Method m : clazz.getMethods()) { CommandAttitude cm = m.getAnnotation(CommandAttitude.class); if (cm != null) { commands.put(cm.name(), m); abbrs.put(cm.abbreviation(), cm.name()); methodObjects.put(m, o); String evaluation = cm.name() + "("; String temp = ""; if (m.getParameterTypes().length != 0) temp = "Object[] o = new Object[" + m.getParameterTypes().length + "];"; int i = 0; for (Class c : m.getParameterTypes()) { i++; evaluation += c.getSimpleName() + " x" + i + " ,"; temp += "o[" + (i - 1) + "] = x" + i + ";"; } evaluation = (m.getParameterTypes().length == 0 ? evaluation : evaluation.substring(0, evaluation.length() - 1)) + ")"; if (m.getParameterTypes().length == 0) evaluation += "{" + temp + "me.parseShell(\"" + cm.name() + "\"" + ",null,current_interpreter);}"; else evaluation += "{" + temp + "me.parseShell(\"" + cm.name() + "\"" + ",o,current_interpreter);}"; evaluations += evaluation + "\n"; } } try { interpreter.eval(evaluations); } catch (EvalError evalError) { evalError.printStackTrace(); } }
8
private void decreaseKeyUnchecked(Entry entry, double priority) { /* First, change the node's priority. */ entry.mPriority = priority; /* If the node no longer has a higher priority than its parent, cut it. * Note that this also means that if we try to run a delete operation * that decreases the key to -infinity, it's guaranteed to cut the node * from its parent. */ if (entry.mParent != null && entry.mPriority <= entry.mParent.mPriority) cutNode(entry); /* If our new value is the new min, mark it as such. Note that if we * ended up decreasing the key in a way that ties the current minimum * priority, this will change the min accordingly. */ if (entry.mPriority <= mMin.mPriority) mMin = entry; }
3
public static void writeImage(BufferedImage image, String fileName) throws IOException { if (fileName == null) return; int offset = fileName.lastIndexOf( "." ); if (offset == -1) { String message = "file suffix was not specified"; throw new IOException( message ); } String type = fileName.substring(offset + 1); if (types.contains(type)) ImageIO.write(image, type, new File( fileName )); else { String message = "unknown writer file suffix (" + type + ")"; throw new IOException( message ); } }
3
public static double[] scale( double fac, double[] vector ) { int n = vector.length; double[] res = new double[n]; for ( int i = 0; i < n; ++i ) res[i] = fac * vector[i]; return(res); }
1
public ListNode rotateRight(ListNode head, int n) { if (head == null) return null; int size = 1; ListNode tail = head; while (tail.next != null) { tail = tail.next; size++; } n = n % size; if (n == 0) return head; ListNode temp = head; for (int i = 1; i < size - n; i++) { temp = temp.next; } ListNode newHead = temp.next; tail.next = head; temp.next = null; return newHead; }
4
public static int search(int[] A, int target){ if(A.length == 0){ return -1; } int l = 0; int r = A.length-1; while(l<=r){ int mid = (l+r)/2; if(A[mid] == target){ return mid; } //the A[l..mid] is sorted, A[mid..r] is broken if(A[mid] > A[l]){ //target is in sorted part if(target >= A[l] && target < A[mid]){ r = mid-1; } //target is in broken part else{ l = mid+1; } } //the A[mid..r] is sorted, A[l..mid] is broken else if(A[mid] < A[l]){ //target is in sorted part if(target > A[mid] && target <= A[r]){ l = mid+1; } //target is in broken part else{ r = mid-1; } } //l==r or l+1 =r; else{ l++; } } return -1; }
9
public void setPrevCell(ProcessedCell c){ prevCell = c; if(c != null && c.getNextCell() != this){ c.setNextCell(this); } }
2
public void UserAvgStarDist() { int totalUserCnt = 0; Map<Double, Integer> UserAvgStarMap = new TreeMap<Double, Integer>(); for (User user:userMap.values()) { //System.out.println("hello"); double score = roundScore(user.average_stars); totalUserCnt += 1; if (!UserAvgStarMap.containsKey(score)) { UserAvgStarMap.put(score,0); } UserAvgStarMap.put(score,UserAvgStarMap.get(score)+1); } DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (Double d:UserAvgStarMap.keySet()) { dataset.setValue((double)UserAvgStarMap.get(d)/totalUserCnt,"Percentage",String.valueOf(d)); } JFreeChart chart = ChartFactory.createBarChart("User Average Score Distribution", "Avg Score", "Percentage", dataset, PlotOrientation.VERTICAL, false, true, false); try { ChartUtilities.saveChartAsJPEG(new File("barchart_user.jpg"), chart, 500, 300); } catch (IOException e) { System.err.println("Problem occurred creating chart."); } }
4
public boolean isSpeelveldKlaar(){ //kijkt of het speelveld klaar is om in te spelen if( obstructie == null || schutterAPositie == null || schutterAZone == null || schutterBPositie == null || schutterBZone == null || wind == null || schutterA == null || schutterB == null) return false; return true; }
8
public void pulse() { if (cnt == 100/MAIN_TIMER_TICK_RATE) { cnt = 0; if (enlarging) { tmp++; enlarge(); } else { tmp--; shrink(); } correctSize(); if (tmp == 0) { enlarging = true; } if (tmp == pulseSize) { enlarging = false; } } else { cnt++; } }
4
private static void writeIntoFile(String fileName) throws IOException { BufferedWriter bw = null; try { File f = new File(fileName); bw = new BufferedWriter(new FileWriter(f)); for(String s : GenerateForSpim.getCommandMap().get(GenerateForSpim.DEFAULT_METHOD)) { bw.write(s); bw.newLine(); } GenerateForSpim.getCommandMap().remove(GenerateForSpim.DEFAULT_METHOD); for(String key : GenerateForSpim.getCommandMap().keySet()) { bw.newLine(); for(String s : GenerateForSpim.getCommandMap().get(key)) { bw.write(s); bw.newLine(); } } } catch (IOException e) { System.out.println("Fehler: Unbekannter Fehler beim Schreibvorgang"); throw e; } finally { if(bw != null) { bw.close(); } } }
5
@Override public void move(Excel start, Excel finish) { if (start.getX() == begin.getX() && start.getY() == begin.getY()) { begin = finish; setColoredExes(); } if (start.getX() == end.getX() && start.getY() == end.getY()) { end = finish; setColoredExes(); } }
4
public int getDiameter() { switch(getPlacementRank()) { case DEFINITIVE: return DEFINITIVE_SIZE; case EXPECTANT: return EXPECTANT_SIZE; case LATENT: return LATENT_SIZE; case UNDEFINED: return UNDEFINED_SIZE; default: return -1; //error case } }
4
public static List<Tile> familarTile(IClientContext ctx) { final Tile location = ctx.players.local().tile(); List<Tile> tiles = new ArrayList<Tile>(); LogicailArea area = new LogicailArea(location.derive(-7, -7), location.derive(5, 5)); boolean edgeville = false; if (LocationAttribute.EDGEVILLE.isInLargeArea(ctx)) { edgeville = true; if (IMovement.Euclidean(location, EDGEVILLE_AREA_LEFT.getCentralTile()) < IMovement.Euclidean(location, EDGEVILLE_AREA_TOP.getCentralTile())) { area = EDGEVILLE_AREA_LEFT; } else { area = EDGEVILLE_AREA_TOP; } } for (Tile tile : area.getTileArray()) { final double distanceTo = location.distanceTo(tile); if (distanceTo > 2 && (edgeville || distanceTo < 9)) { tiles.add(tile); } } Iterator<Tile> iterator = tiles.iterator(); while (iterator.hasNext()) { final Tile next = iterator.next(); if (!next.matrix(ctx).reachable()) { iterator.remove(); } } Collections.shuffle(tiles); return tiles.isEmpty() ? tiles : tiles.subList(0, Math.min(6, tiles.size())); }
9