text
stringlengths
14
410k
label
int32
0
9
@Test public void randomTest() { final Random rng = new Random(1337); for(int n = 0; n < 1_000; n++) { Array<Integer> arr = emptyArray(); final ArrayList<Integer> list = new ArrayList<Integer>(n); for(int i = 0; i < n; i++) { final int insPos = rng.nextInt(i + 1); arr = arr.insertBefore(insPos, i); list.add(insPos, i); } final ListIterator<Integer> it1 = arr.iterator(), it2 = list.listIterator(); int pos = 0; for(int i = 0; i < 100; i++) { final int k = rng.nextInt(n + 1); if(rng.nextBoolean()) { for(int j = 0; j < k; j++) { assertEquals(pos, it2.nextIndex()); assertEquals(pos, it1.nextIndex()); assertEquals(pos - 1, it2.previousIndex()); assertEquals(pos - 1, it1.previousIndex()); if(it2.hasNext()) { assertTrue(it1.hasNext()); final int exp = it2.next(); final int got = it1.next(); assertEquals(exp, got); pos++; } else { assertFalse(it1.hasNext()); continue; } } } else { for(int j = 0; j < k; j++) { assertEquals(pos, it2.nextIndex()); assertEquals(pos, it1.nextIndex()); assertEquals(pos - 1, it2.previousIndex()); assertEquals(pos - 1, it1.previousIndex()); if(it2.hasPrevious()) { assertTrue(it1.hasPrevious()); pos--; final int exp = it2.previous(); final int got = it1.previous(); assertEquals(exp, got); } else { assertFalse(it1.hasPrevious()); continue; } } } } } }
8
public void runServer(ConfigurationForServer configuration) { configuration.setProperties(properties); if (configuration.isInvalid()) exitStatus = 1; if (configuration.showHelp()) { System.out.println(configuration.getHelpText()); } else { try { webDaemon.start(configuration); } catch (Exception e) { throw new RuntimeException(e); } } }
3
public void fireMarkerEvent(final MarkerEvent EVENT) { final EventHandler<MarkerEvent> HANDLER; final EventType TYPE = EVENT.getEventType(); if (MarkerEvent.MARKER_EXCEEDED == TYPE) { HANDLER = getOnMarkerExceeded(); } else if (MarkerEvent.MARKER_UNDERRUN == TYPE) { HANDLER = getOnMarkerUnderrun(); } else { HANDLER = null; } if (null == HANDLER) return; HANDLER.handle(EVENT); }
3
private void generateMethod(Method method, String className) { CodeVisitor mw = _classWriter.visitMethod(method.getModifiers() ^ ACC_ABSTRACT, method.getName(), Type.getMethodDescriptor(method), toInternalNames(method.getExceptionTypes()), null ); Class type = getClassOfMethodSubject(method); if (isPrimitive(method)) { if (isReader(method)) { generatePrimitiveReader(mw, method, className); } else { generatePrimitiveWriter(mw, method, className); } } else if (type == Reader.class || type == Writer.class) { if (isReader(method)) { generateObjectReaderFromReader(mw, method, className); } else { generateObjectWriterToWriter(mw, method, className); } } else if (type == InputStream.class || type == OutputStream.class) { if (isReader(method)) { generateObjectReaderFromInputStream(mw, method, className); } else { generateObjectWriterToOutputStream(mw, method, className); } } else { if (isReader(method)) { generateObjectReader(mw, method, className); } else { generateObjectWriter(mw, method, className); } } }
9
private String shrtTip() { String tt = shorttip(); if (tt != null) { tt = RichText.Parser.quote(tt); if (meter > 0) { tt = tt + " (" + meter + "%)"; } if (FEP != null) { tt += FEP; } if (curio_stat != null && qmult > 0) { if(UI.instance.wnd_char != null) tt += "\nLP: $col[205,205,0]{" + Math.round(curio_stat.baseLP * qmult * UI.instance.wnd_char.getExpMode()) + "}"; if (meter > 0) { double time = (double)meter / 100; tt += " in " + min2hours(curio_stat.studyTime - (int)(curio_stat.studyTime * time)); } tt += " Att: " + curio_stat.attention; } } return tt; }
7
private boolean Recargo(float importe) { if (importe < 0) { return false; } if (importe > saldo) { return false; } saldo -= importe; return true; }
2
@SuppressWarnings("unchecked") private static <E extends Comparable<E>> void merge(E[] array, int leftStart, int leftEnd, int rightStart, int rightEnd) { int length = rightEnd - leftStart + 1; E[] mergedArray = (E[]) Array.newInstance(array[0].getClass(), length); int index = leftStart; for (int i = 0; i < length; i++) { if (leftStart <= leftEnd && (rightStart > rightEnd || array[leftStart].compareTo(array[rightStart]) <= 0)) // <= for stable sort mergedArray[i] = array[leftStart++]; else mergedArray[i] = array[rightStart++]; } // copy mergedArray back into original array for (int i = 0; i < length; i++) array[index++] = mergedArray[i]; }
5
private static OAuthError extractErrorMessage(String jsonText) { OAuthError oauthError = new OAuthError(); try { JsonFactory jsonFactory = new JsonFactory(); JsonParser jParser = jsonFactory.createJsonParser(jsonText); while (jParser.nextToken() != JsonToken.END_OBJECT) { String fieldname = jParser.getCurrentName(); if ("message".equals(fieldname)) { // current token is "message", // move to next, which is "message"'s value jParser.nextToken(); String errorMessage = jParser.getText(); oauthError.setErrorMessage(errorMessage); logger.debug("errorMessage: " + errorMessage); } else if ("type".equals(fieldname)) { jParser.nextToken(); String errorType = jParser.getText(); oauthError.setErrorType(errorType); logger.debug("errorType: " + errorType); } else if ("code".equals(fieldname)) { jParser.nextToken(); String errorCode = jParser.getText(); oauthError.setErrorCode(errorCode); logger.debug("errorCode: " + errorCode); } else if ("error_subcode".equals(fieldname)) { jParser.nextToken(); String errorSubcode = jParser.getText(); oauthError.setErrorSubcode(errorSubcode); logger.debug("errorSubcode: " + errorSubcode); } } jParser.close(); } catch (JsonGenerationException e) { logger.error("JsonGenerationException received: " + e); } catch (JsonMappingException e) { logger.error("JsonMappingException received: " + e); } catch (IOException e) { logger.error("IOException received: " + e); } return oauthError; }
8
public void layout () { if (sizeInvalid) { computeSize(); if (lastPrefHeight != prefHeight) { lastPrefHeight = prefHeight; invalidateHierarchy(); } } SnapshotArray<Actor> children = getChildren(); float groupWidth = getWidth(); float x = 0; float y = getHeight(); float maxHeight = 0; for (int i = 0, n = children.size; i < n; i++) { Actor child = children.get(i); float width = child.getWidth(); float height = child.getHeight(); if (child instanceof Layout) { Layout layout = (Layout) child; width = layout.getPrefWidth(); height = layout.getPrefHeight(); } if (x + width <= groupWidth) { maxHeight = Math.max(height, maxHeight); } else { y -= maxHeight + spacing; maxHeight = height; x = 0; } child.setBounds(x, y - height, width, height); x += width + spacing; } }
5
public static boolean isThis(Expression thisExpr, ClassInfo clazz) { return ((thisExpr instanceof ThisOperator) && (((ThisOperator) thisExpr) .getClassInfo() == clazz)); }
1
private void applyRegexHighlighting(JTextComponent comp, Pattern pattern) { Matcher matcher = pattern.matcher(comp.getText()); Highlighter h = comp.getHighlighter(); h.removeAllHighlights(); while(matcher.find()) { try { h.addHighlight(matcher.start(), matcher.end(), regexPainter); } catch(Exception e) { throw new RuntimeException(e); } } }
2
public void removeFiles(List<String> names) { if (names == null) { throw new IllegalArgumentException("names is null"); } boolean changed = false; for (String name : names) { if (name == null) { throw new IllegalArgumentException("names contains a null entry."); } if (mNameToFileDigest.containsKey(name)) { mNameToFileDigest.remove(name); changed = true; } } if (changed) { purge(); } }
5
public TupleFour<String[], Integer, String, String[]> [] countNetLogoTurtles(TupleFour<String[], Integer, String, String[]> [] agentDetails) throws Exception { TupleFour<String[], Integer, String, String[]> [] returnArray = agentDetails; int typesOfAgent = 0; int noAgentsFound = 0; while(true) { try { boolean agentMatched = false; for (int i = 0; i < agentDetails.length; i++) { //throws a clastcastException if 'nobody' is returned Agent agent = (Agent) App.app().report("turtle "+ noAgentsFound); String reportedBreed = ""+agent; reportedBreed = reportedBreed.split(" ")[0]; log.info(reportedBreed + " vs "+ agentDetails[i].First[0]); if (reportedBreed.equalsIgnoreCase(agentDetails[i].First[0])) { //found matching breed typesOfAgent ++; int noThisBreed = (int)((double) App.app().report("count " + agentDetails[i].First[1])); noAgentsFound = noAgentsFound + noThisBreed; TupleFour<String[], Integer, String, String[]> tempAgent = new TupleFour<String[], Integer, String, String[]> (agentDetails[i].First, noThisBreed, agentDetails[i].Third, agentDetails[i].Fourth); returnArray[i]=tempAgent; agentMatched = true; break; } } if (!agentMatched) { // didnt find a bod match for the netlogo agent throw new Exception(); } } catch (CompilerException c) { //this should never happen log.error("UNHANDLED EXCEPTION IN SIMMANAGER"); throw new Exception(); } catch (ClassCastException b) { //no more types of agent if (typesOfAgent == 0) { //error didnt find any agents log.error("Could not indentify any breed matches, please ensure you have properly specified your breeds in NetLogo and BODNetLogo."); } else { log.info("Successfully indentified: "+ typesOfAgent+ ", different breeds, and a total of: " + noAgentsFound + " turtles"); } break; } catch (Exception e) { e.printStackTrace(); String reportedBreed = ""; try { reportedBreed = ""+App.app().report("turtle "+ noAgentsFound); } catch (CompilerException e1) { //this should never happen log.error("UNHANDLED EXCEPTION IN SIMMANAGER"); throw new Exception(); } reportedBreed = reportedBreed.split(" ")[0]; log.error("Could not find BOD specification for all agents, found "+typesOfAgent+ " (or more) NetLogo Breeds, but only " +agentDetails.length+" BOD specifications, " + "Missing agent: " + reportedBreed); } } return returnArray; }
9
public void handleKeyRelease(int value) { switch (value) { case MinuetoKeyboard.KEY_UP: this.keyUp = false; break; case MinuetoKeyboard.KEY_LEFT: this.keyLeft = false; break; case MinuetoKeyboard.KEY_RIGHT: this.keyRight = false; break; case MinuetoKeyboard.KEY_DOWN: this.keyDown = false; break; default: System.out.println(value); } }
4
private void teleport(CommandSender sender, String[] args) { if (!sender.hasPermission("graveyard.command.teleport")) { noPermission(sender); return; } else if (!(sender instanceof Player)) { noConsole(sender); return; } if (args.length == 1) { commandLine(sender); sender.sendMessage(ChatColor.GRAY + "/graveyard" + ChatColor.WHITE + " tp " + ChatColor.RED + "Name"); sender.sendMessage(ChatColor.WHITE + "Teleports player to the specified spawn point."); commandLine(sender); return; } Player player = (Player) sender; String pointname = GraveyardUtils.makeString(args); if (SpawnPoint.exists(pointname)) { player.teleport(SpawnPoint.get(pointname).getLocation()); player.sendMessage("Teleporting to: " + pointname); } else { player.sendMessage("Spawnpoint '" + pointname + "' does not exist."); } }
4
public static ArrayList<BufferedImage[]> loadMultiAnimation(int[] frames, int width, int height, String path){ try { ArrayList<BufferedImage[]> sprites; final BufferedImage spritesheet = ImageIO.read(Images.class.getClass().getResourceAsStream(path)); sprites = new ArrayList<BufferedImage[]>(); for (int i = 0; i < frames.length; i++) { final BufferedImage[] bi = new BufferedImage[frames[i]]; for (int j = 0; j < frames[i]; j++) bi[j] = spritesheet.getSubimage(j * width, i * height, width, height); sprites.add(bi); } return sprites; } catch (final Exception e) { e.printStackTrace(); System.out.println("Failed to load " + path + ". Shutting down system."); System.exit(0); } return null; }
3
static public String removeExtraSlash(String inStr) { int slashLoc = inStr.indexOf("://"); int l = inStr.length(); int hold = slashLoc + 3; slashLoc = inStr.indexOf("//", hold); while (slashLoc > 0 && slashLoc < l) { hold = slashLoc; while (hold < l && inStr.charAt(hold) == '/') hold ++; if (hold >= l) { inStr = inStr.substring(0, slashLoc+1); break; } else inStr = inStr.substring(0, slashLoc+1) + inStr.substring(hold); slashLoc = inStr.indexOf("//", hold); l = inStr.length(); } return inStr; }
5
private void processInheritanceMap() { for (Iterator<String> it = inheritenceMap.keySet().iterator(); it.hasNext(); ) { String childType = it.next(); String parentType = inheritenceMap.get(childType); if (!childType.isEmpty() && !parentType.isEmpty()) { VariableMap childAttrs = typeAttrMap.get(childType); VariableMap parentAttrs = typeAttrMap.get(parentType); if (childAttrs != null && parentAttrs != null) { for (int i=0; i<parentAttrs.getSize(); i++) { Variable attr = parentAttrs.get(i); if (attr != null && childAttrs.get(attr.getName()) == null) { childAttrs.add(attr); } } } } } }
8
public void resetAllGameActions() { for (int i=0; i<keyActions.length; i++) { if (keyActions[i] != null) { keyActions[i].reset(); } } for (int i=0; i<mouseActions.length; i++) { if (mouseActions[i] != null) { mouseActions[i].reset(); } } }
4
public String toString() { String s = (returnType != null) ? returnType.debugName() : "NULL TYPE"; //$NON-NLS-1$ s += " "; //$NON-NLS-1$ s += (selector != null) ? new String(selector) : "UNNAMED METHOD"; //$NON-NLS-1$ s += "("; //$NON-NLS-1$ if (parameters != null) { if (parameters != Binding.NO_PARAMETERS) { for (int i = 0, length = parameters.length; i < length; i++) { if (i > 0) s += ", "; //$NON-NLS-1$ s += (parameters[i] != null) ? parameters[i].debugName() : "NULL TYPE"; //$NON-NLS-1$ } } } else { s += "NULL PARAMETERS"; //$NON-NLS-1$ } s += ") "; //$NON-NLS-1$ return s; }
7
public initiateRemoval() { this.requireLogin = true; this.addParamConstraint("id", ParamCons.INTEGER); this.addRtnCode(405, "permission denied"); this.addRtnCode(406, "venue not found"); this.addRtnCode(407, "already removing"); }
0
private void acao139() throws SemanticError { int numeroEsperado = idMetodoChamado.getParametros().size(); if(numeroParametrosAtuais != numeroEsperado) throw new SemanticError("Número de parâmetros atuais deveria ser " + numeroEsperado); }
1
public boolean estCleValable(String k) { int i=0; boolean trouve=false; while(i<k.length() && !trouve) { if(!ALPHABET.contains(""+k.charAt(i))&&!ALPHABET.toUpperCase().contains(""+k.charAt(i))&&(k.charAt(i)!=' ')) { trouve=true; JOptionPane.showMessageDialog(null, "Veuillez saisir une cl constitue uniquement d'une suite de lettres majuscules et minuscule non accentues","Cle incorrecte",JOptionPane.ERROR_MESSAGE); } i++; } return !trouve; }
5
@Override public void actionPerformed(ActionEvent e) { try { JFileChooser chooser = new JFileChooser(); UIManager.put("FileChooser.fileNameLabelText", "Имя файла:"); UIManager.put("FileChooser.saveInLabelText", "Каталог:"); UIManager.put("FileChooser.filesOfTypeLabelText", "Типы файлов:"); UIManager.put("FileChooser.cancelButtonText", "Отмена"); UIManager.put("FileChooser.saveButtonText", "Сохранить"); UIManager.put("FileChooser.saveButtonToolTipText", "Сохранить изображение"); UIManager.put("FileChooser.cancelButtonToolTipText", "Закрыть диалог"); chooser.updateUI(); //chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int result = chooser.showSaveDialog(null); if (result == chooser.APPROVE_OPTION){ ImageIO.write(GUI.getImage(100), "PNG", new File(chooser.getSelectedFile()+ ".png")); } chooser = null; } catch (IOException ex) { System.out.println(ex.toString()); } }
2
@Override public void move(){ if(side == true){ if(!engine.getPhysics().canMove(this, this.getLocation().getX()+5, this.getLocation().getY()+5)) engine.getPhysics().usePhysics(this, this.getLocation().getX()+5, this.getLocation().getY()); else { side = false; setNext(1);} if( !engine.getPhysics().canMove(this, this.getLocation().getX()+5, this.getLocation().getY())){ side = false; setNext(1);} }else{ if(!engine.getPhysics().canMove(this, this.getLocation().getX()-5, this.getLocation().getY()+5)) engine.getPhysics().usePhysics(this, this.getLocation().getX()-5, this.getLocation().getY()); else{ side = true; setNext(2);} if( !engine.getPhysics().canMove(this, this.getLocation().getX()-5, this.getLocation().getY())){ side = true; setNext(2);} } engine.getPhysics().useGravity(this, getLocation().getX(), getLocation().getY()); ticks++; if(ticks >= 10 && engine.getPhysics().canMove(this, this.getLocation().getX(), this.getLocation().getY()-5-6*10)){ engine.getPhysics().usePhysics(this, this.getLocation().getX(), this.getLocation().getY()-5); ticks = 0; } }
7
public static LevelState getLevel(int level) { Gilbert gilbs; ArrayList<Planet> planetsArray; Collectable collect; switch (level) { case 1: // gilbert gilbs = new Gilbert(800, 600, -1, 0); // planets array planetsArray = new ArrayList<>(); planetsArray.add(new Planet(640, 360, 1000f, 100f)); // collectable collect = new Collectable(Collectable.makePoints(740, 260, 540, 460)); return new LevelState(gilbs, planetsArray, collect); case 2: // gilbert gilbs = new Gilbert(620, 360, 1, 1); // planets array planetsArray = new ArrayList<>(); planetsArray.add(new Planet(220, 360, 1000f, 100f)); planetsArray.add(new Planet(1020, 360, 1000f, 100f)); // collectable collect = new Collectable(Collectable.makePoints(150, 500, 1160, 400)); return new LevelState(gilbs, planetsArray, collect); case 3: // gilbert gilbs = new Gilbert(800, 600, -1, 0); // planets array planetsArray = new ArrayList<>(); planetsArray.add(new Planet(800, 400, 1000f, 100f)); planetsArray.add(new Planet(500, 300, 1000f, 100f)); // collectable collect = new Collectable(Collectable.makePoints(300, 300, 1000, 600)); return new LevelState(gilbs, planetsArray, collect); case 4: // gilbert gilbs = new Gilbert(800, 600, 2, 0); // planets array planetsArray = new ArrayList<>(); planetsArray.add(new Planet(900, 400, 1500f, 150f)); planetsArray.add(new Planet(400, 200, 1000f, 100f)); // collectable collect = new Collectable(Collectable.makePoints(480, 360, 740, 260, 1100, 400)); return new LevelState(gilbs, planetsArray, collect); case 5: // gilbert gilbs = new Gilbert(800, 600, 2, 0); // planets array planetsArray = new ArrayList<>(); planetsArray.add(new Planet(350, 450, 1000f, 100f)); planetsArray.add(new Planet(650, 350, 1500f, 150f)); planetsArray.add(new Planet(950, 250, 1000f, 100f)); // collectable collect = new Collectable(Collectable.makePoints(150, 500, 820, 260)); return new LevelState(gilbs, planetsArray, collect); case 6: // gilbert gilbs = new Gilbert(800, 600, 2, 0); // planets array planetsArray = new ArrayList<>(); planetsArray.add(new Planet(150, 150, 500f, 50f)); planetsArray.add(new Planet(250, 350, 500f, 50f)); planetsArray.add(new Planet(350, 250, 500f, 50f)); planetsArray.add(new Planet(450, 450, 500f, 50f)); planetsArray.add(new Planet(550, 350, 500f, 50f)); planetsArray.add(new Planet(650, 250, 500f, 50f)); planetsArray.add(new Planet(750, 450, 500f, 50f)); planetsArray.add(new Planet(850, 350, 500f, 50f)); planetsArray.add(new Planet(950, 250, 500f, 50f)); // collectable collect = new Collectable(Collectable.makePoints(350, 400, 175, 250)); return new LevelState(gilbs, planetsArray, collect); case 7: // gilbert gilbs = new Gilbert(MID_X + 150, MID_Y + 10, 2, 3); // planets array planetsArray = new ArrayList<>(); for (float t = 0.0f; t < 2.0f * Math.PI; t += Math.PI * 0.25f) { planetsArray.add(new Planet((float) (MID_X + THIRD1_Y * Math.sin(t)), (float) (MID_Y + THIRD1_Y * Math.cos(t)), 500.0f, 50.0f)); } planetsArray.remove(0); // collectable collect = new Collectable( Collectable.makePoints(MID_X, MID_Y, EIGHTH2_X, EIGHTH2_Y, MID_X, MID_Y)); return new LevelState(gilbs, planetsArray, collect); case 8: // gilbert gilbs = new Gilbert(800, 550, 2, 1); // planets array planetsArray = new ArrayList<>(); planetsArray.add(new Planet(EIGHTH5_X, EIGHTH5_Y, 500f, 50f)); planetsArray.add(new Planet(EIGHTH4_X, EIGHTH4_Y, 500f, 50f)); planetsArray.add(new Planet(EIGHTH3_X, EIGHTH3_Y, 500f, 50f)); planetsArray.add(new Planet(EIGHTH3_X, EIGHTH5_Y, 500f, 50f)); planetsArray.add(new Planet(EIGHTH5_X, EIGHTH3_Y, 500f, 50f)); // collectable collect = new Collectable(Collectable .makePoints(EIGHTH3_X, MID_Y, MID_X, EIGHTH3_Y, EIGHTH5_X, MID_Y, MID_X, EIGHTH5_Y)); return new LevelState(gilbs, planetsArray, collect); default: return null; } }
9
public MicroRequestHandler(Vector<File> imageQueue) { this.imageQueue = imageQueue; }
0
private TreeElement handleClass(HashMap classes, ClassInfo clazz) { if (clazz == null) return root; TreeElement elem = (TreeElement) classes.get(clazz); if (elem != null) return elem; elem = new TreeElement(clazz.getName()); classes.put(clazz, elem); if (!clazz.isInterface()) { ClassInfo superClazz = clazz.getSuperclass(); handleClass(classes, superClazz).addChild(elem); } ClassInfo[] ifaces = clazz.getInterfaces(); for (int i = 0; i < ifaces.length; i++) handleClass(classes, ifaces[i]).addChild(elem); if (ifaces.length == 0 && clazz.isInterface()) root.addChild(elem); return elem; }
6
private long parseFileDate(String age, String fileName, String folderPath) { Pattern p = Pattern.compile(" "); String [] splitted = p.split(age); long count = Long.parseLong(splitted[0]); long date = (new Date()).getTime(); long fileDate = 0; long step = 0; if (splitted[1].startsWith("second")) { step = 1000l; } else if (splitted[1].startsWith("minute")) { step = 1000l*60; } else if (splitted[1].startsWith("hour")) { step = 1000l*60*60; } else if (splitted[1].startsWith("day")) { step = 1000l*60*60*24; } else if (splitted[1].startsWith("week")) { step = 1000l*60*60*24*7; } else if (splitted[1].startsWith("month")) { step = 1000l*60*60*24*31; } else if (splitted[1].startsWith("year")) { step = 1000l*60*60*24*365; } fileDate = date - (count+1)*step; File localFile = new File(getRepositoryFolderName()+"/"+folderPath+"/"+fileName); if (localFile.exists() && (Math.abs(fileDate - localFile.lastModified()) < step)) { fileDate = localFile.lastModified(); } //System.out.println("datestring: " + splitted[0] + "; "+ splitted[1] + "; count: " +count+ "; date: "+date+"; filedate: "+fileDate); return fileDate; }
9
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final CanDDeliveryOrderItemDetailPK other = (CanDDeliveryOrderItemDetailPK) obj; if (!Objects.equals(this.szDocId, other.szDocId)) { return false; } if (!Objects.equals(this.shItemNumber, other.shItemNumber)) { return false; } if (!Objects.equals(this.szProductId, other.szProductId)) { return false; } return true; }
5
public void run() { ar.configure(ClientActionRobot.intToByteArray(id)); //load the initial level (default 1) ar.loadLevel(); GameState state; while (true) { state = solve(); //If the level is solved , go to the next level if (state == GameState.WON) { System.out.println(" loading the level " + (currentLevel + 1) ); ar.loadLevel(++currentLevel); //display the global best scores int[] scores = ar.checkScore(); System.out.println("The global best score: "); for (int i = 0; i < scores.length ; i ++) { System.out.print( " level " + (i+1) + ": " + scores[i]); } System.out.println(); System.out.println(" My score: "); scores = ar.checkMyScore(); for (int i = 0; i < scores.length ; i ++) { System.out.print( " level " + (i+1) + ": " + scores[i]); } System.out.println(); // make a new trajectory planner whenever a new level is entered tp = new TrajectoryPlanner(); // first shot on this level, try high shot first firstShot = true; } else //If lost, then restart the level if (state == GameState.LOST) { System.out.println("restart"); ar.restartLevel(); } else if (state == GameState.LEVEL_SELECTION) { System.out.println("unexpected level selection page, go to the last current level : " + currentLevel); ar.loadLevel(currentLevel); } else if (state == GameState.MAIN_MENU) { System.out .println("unexpected main menu page, reload the level : " + currentLevel); ar.loadLevel(currentLevel); } else if (state == GameState.EPISODE_MENU) { System.out.println("unexpected episode menu page, reload the level: " + currentLevel); ar.loadLevel(currentLevel); } } }
8
public static int findKth(int[] A, int A_start, int[] B, int B_start, int k) { if (A_start >= A.length) return B[B_start + k - 1]; if (B_start >= B.length) return A[A_start + k - 1]; if (k == 1) return Math.min(A[A_start], B[B_start]); int A_key = A_start + k / 2 - 1 < A.length ? A[A_start + k / 2 - 1] : Integer.MAX_VALUE; int B_key = B_start + k / 2 - 1 < B.length ? B[B_start + k / 2 - 1] : Integer.MAX_VALUE; if (A_key < B_key) { // we should keep find kth from A_start + k / 2 in A return findKth(A, A_start + k / 2, B, B_start, k - k / 2); } else { // we should keep find kth from B_start + k / 2 in B return findKth(A, A_start, B, B_start + k / 2, k - k / 2); } }
6
public Timer getTimer() { boolean test = false; if (test || m_test) { System.out.println("Game :: getTimer() BEGIN"); } if (test || m_test) { System.out.println("Game :: getTimer() END"); } return m_timer; }
4
static private void setDB(int skipStage) { try { //First we try and see if we have our databasefile in the same working directory String pa = Paths.get("").toAbsolutePath().toString() + File.separator + "MICEDB.FDB"; DB.setPath(pa); } catch (InfException e) { // we didnt have it in working directory, try to find it in a settingsfile. if (Files.exists(Paths.get("MICEsettings.ini"))) { try {//found settingsfile, trying to get path DB.setPath(readDBFromSettingsFile()); } catch (InfException ex) { // no valid path was found in settingsfile, show dialogue for user to chose where it is. int chosen; if (skipStage != 1) { chosen = showDBOkDialoge(); } else { chosen = 1; } if (chosen == 1) { String dbPath = dbFileChooser(); try { DB.setPath(dbPath); writeDBToSettingsFile(dbPath); } catch (InfException exe) { showSureDialogue(); } } else { showSureDialogue(); } } } else { initSettingsFile(); //if no settingsfile was found, init one int chosen; if (skipStage != 1) { chosen = showDBOkDialoge(); } else { chosen = 1; } if (chosen == 1) { try { String path = dbFileChooser(); DB.setPath(path); writeDBToSettingsFile(path); //writing the path for later use } catch (InfException ex) { showSureDialogue(); } } else { showSureDialogue(); } } } }
9
public Object nextContent() throws JSONException { char c; StringBuilder sb; do { c = next(); } while (Character.isWhitespace(c)); if (c == 0) { return null; } if (c == '<') { return XML.LT; } sb = new StringBuilder(); for (;;) { if (c == '<' || c == 0) { back(); return sb.toString().trim(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } c = next(); } }
7
public ClientInfo(String t_name, String t_ip, int t_portId) { name = t_name; ip = t_ip; portId = t_portId; }
0
private static String getCommandName(String commandAsStr) { int whiteSpaceIndex = commandAsStr.indexOf(" "); if (whiteSpaceIndex == -1) { return commandAsStr; } String commandName = commandAsStr.substring(0, whiteSpaceIndex); return commandName.trim(); }
1
public void test(){ assert state == State.OK; // get the internal thread number int i = getInternalThreadId(); // activate setState(i, State.GUARD); try{Thread.sleep(1+i);}catch(Throwable ignore){}; // guard if( getState(i+1) != State.IDLE ){ setState(i, State.WAIT); } else{ setState(i, State.ACTIVE); } System.out.println("THREAD-" + i + ":\tstate " + getState(i) ); try{Thread.sleep(1+i);}catch(Throwable ignore){}; // assert: one thread must not be ACTIVE if( state0 == State.ACTIVE && state1 == State.ACTIVE ){ state = State.ERROR; } assert state0 != State.ACTIVE || state1 != State.ACTIVE; // deactivate setState(i, State.IDLE); try{Thread.sleep(1+i);}catch(Throwable ignore){}; }
7
public static void startupQuery() { { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/LOGIC", Stella.$STARTUP_TIME_PHASE$ > 1)); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { _StartupQuery.helpStartupQuery1(); _StartupQuery.helpStartupQuery2(); _StartupQuery.helpStartupQuery3(); _StartupQuery.helpStartupQuery4(); } if (Stella.currentStartupTimePhaseP(4)) { _StartupQuery.helpStartupQuery5(); } if (Stella.currentStartupTimePhaseP(5)) { _StartupQuery.helpStartupQuery6(); } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { _StartupQuery.helpStartupQuery7(); _StartupQuery.helpStartupQuery8(); _StartupQuery.helpStartupQuery9(); _StartupQuery.helpStartupQuery10(); } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("LOGIC"))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL NORMAL-INFERENCE NORMAL-INFERENCE-LEVEL (NEW NORMAL-INFERENCE-LEVEL :KEYWORD :NORMAL))"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL BACKTRACKING-INFERENCE BACKTRACKING-INFERENCE-LEVEL (NEW BACKTRACKING-INFERENCE-LEVEL :KEYWORD :BACKTRACKING))"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL SUBSUMPTION-INFERENCE SUBSUMPTION-INFERENCE-LEVEL (NEW SUBSUMPTION-INFERENCE-LEVEL :KEYWORD :SUBSUMPTION))"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL SHALLOW-INFERENCE SHALLOW-INFERENCE-LEVEL (NEW SHALLOW-INFERENCE-LEVEL :KEYWORD :SHALLOW))"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL ASSERTION-INFERENCE ASSERTION-INFERENCE-LEVEL (NEW ASSERTION-INFERENCE-LEVEL :KEYWORD :ASSERTION))"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL REFUTATION-INFERENCE REFUTATION-INFERENCE-LEVEL (NEW REFUTATION-INFERENCE-LEVEL :KEYWORD :REFUTATION))"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *INFERENCELEVEL* NORMAL-INFERENCE-LEVEL NORMAL-INFERENCE :DOCUMENTATION \"Specifies the level/depth of inference applied\nduring a query. Possible values are:\n :ASSERTION -- database lookup with no inheritance;\n :SHALLOW -- includes database lookup, computed predicates and specialists;\n :SUBSUMPTION -- shallow plus cached subsumption links and equality reasoning;\n :BACKTRACKING -- all of the above plus backtracking over rules;\n :NORMAL -- all of the above plus universal introduction;\n :REFUTATION -- all of the above plus disjunctive implication introduction and refutation.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *DONTUSEDEFAULTKNOWLEDGE?* BOOLEAN FALSE :DOCUMENTATION \"Controls whether queries use default knowledge or not.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MAXIMUM-BACKTRACKING-DEPTH* INTEGER *DEFAULT-MAXIMUM-DEPTH* :DOCUMENTATION \"Value for the maximum depth allowable during\nbacktrack search.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *TYPE-CHECK-STRATEGY* KEYWORD :LOOKUP :DOCUMENTATION \"Determines whether there is a slow but thorough type test\nwhen variables are bound, a fast but very shallow one, or none. Values\nare :NONE, :LOOKUP, :DISJOINT. The default is :LOOKUP.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *DUPLICATE-SUBGOAL-STRATEGY* KEYWORD :DUPLICATE-GOALS :DOCUMENTATION \"Determines what kind of duplicate subgoal test to use. Choices\nare :DUPLICATE-RULES, :DUPLICATE-GOALS, and :DUPLICATE-GOALS-WITH-CACHING.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *DUPLICATE-GOAL-SEARCH-DEPTH* INTEGER NULL :DOCUMENTATION \"Sets the maximum number of frames search looking for\na duplicate subgoal. Default value is infinite. Possibly this should\nbe replaced by a function that increases with depth of search.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *DUPLICATE-RULE-SEARCH-DEPTH* INTEGER NULL :DOCUMENTATION \"Set limit on number of frames searched looking for\na duplicate rule. Default value is infinite.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *GLOBALLY-CLOSED-COLLECTIONS?* BOOLEAN FALSE :DOCUMENTATION \"If TRUE, all collections are assumed to be closed.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *GENERATE-ALL-PROOFS?* BOOLEAN FALSE :DOCUMENTATION \"If TRUE, the backchainer follows all lines of proof\nfor each goal, rather than switching to a new goal once the first proof\nof a goal is achieved. The partial matcher sets this variable to\nTRUE to force generation of proofs having possibly different\nweights.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *QUERYITERATOR* QUERY-ITERATOR NULL :DOCUMENTATION \"Points to the query iterator for the currently executing query.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *DEFAULT-MAXIMUM-DEPTH* INTEGER 25 :DOCUMENTATION \"Possibly a good value for the maximum backtracking depth.\nMore testing is needed.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *INITIAL-BACKTRACKING-DEPTH* INTEGER 5 :DOCUMENTATION \"Value of the initial depth used during an interative\ndeepening search.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *ITERATIVE-DEEPENING-MODE?* BOOLEAN FALSE :DOCUMENTATION \"Default setting. If TRUE, queries are evaluated\nusing iterative deepening from depth '*initial-backtracking-depth*'\nto depth '*maximum-backtracking-depth*'.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *EMIT-THINKING-DOTS?* BOOLEAN TRUE :DOCUMENTATION \"When TRUE, various kinds of characters are\nemitted to STANDARD-OUTPUT while PowerLoom is 'thinking'.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *THINKING-DOT-COUNTER* INTEGER 0 :DOCUMENTATION \"Used to determine when to generate linefeeds\nafter forty-or-so thinking dots.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *THINKING-DOT-TABLE* (PROPERTY-LIST OF KEYWORD CHARACTER-WRAPPER) (NEW PROPERTY-LIST :THE-PLIST (BQUOTE (:UPCLASSIFY |&| (WRAP-LITERAL #\\u) :DOWNCLASSIFY |&| (WRAP-LITERAL #\\d) :PROPAGATE |&| (WRAP-LITERAL #\\f) :PARTIAL-MATCH |&| (WRAP-LITERAL #\\p)))) :DOCUMENTATION \"Maps kind of thinking keywords to characters.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *BOOLEAN-VECTOR-INDEX* BOOLEAN-VECTOR-INDEX-NODE (NEW BOOLEAN-VECTOR-INDEX-NODE :THE-VECTOR (NEW BOOLEAN-VECTOR :ARRAY-SIZE 0)) :DOCUMENTATION \"Points to the head of a discrimination tree of containing\nall boolean vectors.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *PRINTINFRAME* CONTROL-FRAME NULL :DOCUMENTATION \"If set, controls diagnostic printing by making\nvariable bindings appear relative to the frame '*printInFrame*'.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CONTROL-FRAME-ID-COUNTER* INTEGER -1 :DOCUMENTATION \"Generates unique IDs for control frames. Used only for debugging.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *REVERSEPOLARITY?* BOOLEAN FALSE :PUBLIC? TRUE :DOCUMENTATION \"Signals atomic proposition provers that polarity is negative.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *TRACE-DISJOINTNESS-SUBGOALS?* BOOLEAN FALSE :DOCUMENTATION \"If true and goal tracing is on, subgoals of disjointness\nqueries will also be traced.\" :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *DUPLICATEINSTANCESCACHECROSSOVERPOINT* INTEGER 20 :DOCUMENTATION \"Point where a cache of generated instances in a \ndescription extension iterator is switched from a list to a hash table\")"); Logic.defineExplanationPhrase(Logic.KWD_DEPTH_CUTOFF, Logic.KWD_TECHNICAL, "because of an inference depth cutoff", Stella.NIL); Logic.defineExplanationPhrase(Logic.KWD_DEPTH_CUTOFF, Logic.KWD_LAY, "because the maximum inference search depth was exceeded", Stella.NIL); Logic.defineExplanationPhrase(Logic.KWD_TIMEOUT, Logic.KWD_TECHNICAL, "because of an inference timeout", Stella.NIL); Logic.defineExplanationPhrase(Logic.KWD_TIMEOUT, Logic.KWD_LAY, "because the allotted inference CPU time was exceeded", Stella.NIL); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *QUERY-ITERATOR-DEBUG-ID-COUNTER* INTEGER 0)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MOST-RECENT-QUERY* QUERY-ITERATOR NULL)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *INLINE-QUERY-CACHE* (KEY-VALUE-MAP OF SYMBOL (LIST OF QUERY-ITERATOR)) (NEW KEY-VALUE-MAP) :DOCUMENTATION \"Caches queries used in-line by code, so that they don't have to\nbe reparsed and reoptimized each time they are invoked.\" :THREAD-LOCAL? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MAX-CACHED-QUERIES-PER-ID* INTEGER 10)"); Logic.defineExplanationPhrase(Logic.KWD_ASSERT_FROM_QUERY, Logic.KWD_TECHNICAL, "because it was asserted from a query", Stella.NIL); Logic.defineExplanationPhrase(Logic.KWD_ASSERT_FROM_QUERY, Logic.KWD_LAY, "because it was asserted from a query", Stella.NIL); } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
7
public static int HeapExtractMax(List<Integer> array){ if(array.size() < 1){ System.out.println("Nothing in heap..."); } int maximum = array.get(0); array.set(0, array.get(array.size()-1)); array.remove(array.size()-1); MaxHeapify(array, 1); return maximum; }
1
public static int check(Point point, Rectangle bounds) { int value = 0; if (point.x == bounds.left) { value |= LEFT; } if (point.x == bounds.right) { value |= RIGHT; } if (point.y == bounds.top) { value |= TOP; } if (point.y == bounds.bottom) { value |= BOTTOM; } return value; }
4
private void doType(int keycode) { boolean shift = (keycode != KeyEvent.VK_ENTER && ((keyboard.getShifts() & (1 << SHIFT)) != 0)); boolean ctrl = (keycode != KeyEvent.VK_ENTER && ((keyboard.getShifts() & (1 << CTRL)) != 0)); boolean alt = (keycode != KeyEvent.VK_ENTER && ((keyboard.getShifts() & (1 << ALT)) != 0)); if (shift) press(KeyEvent.VK_SHIFT); if (ctrl) press(KeyEvent.VK_CONTROL); if (alt) press(KeyEvent.VK_ALT); type(keycode); if (shift) release(KeyEvent.VK_SHIFT); if (ctrl) release(KeyEvent.VK_CONTROL); if (alt) release(KeyEvent.VK_ALT); }
9
public boolean type(char key, java.awt.event.KeyEvent ev) { if ((key >= '0') && (key <= '9')) { int opt = (key == '0') ? 10 : (key - '1'); if (opt < menuOptions.length) wdgmsg("cl", opt); ui.grabkeys(null); return (true); } else if (key == 27) { wdgmsg("cl", -1); ui.grabkeys(null); return (true); } return (false); }
5
public static void updateLocale(Language language) { String l = Settings.getLocaleLanguage().getLanguageString(); String c = Settings.getLocaleLanguage().getCountryString(); Locale currentLocale = new Locale(l, c); PropertyResourceBundle localeRes = null; try (FileInputStream fis = new FileInputStream(Constants.PROGRAM_LOCALE_PATH.resolve( Constants.PROGRAM_I18N + "_" + currentLocale.getLanguage() + "_" + currentLocale.getCountry() + Constants.PROGRAM_I18N_SUFFIX).toFile())) { localeRes = new PropertyResourceBundle(fis); fis.close(); } catch (IOException e) { LOGGER.warn(e); } if (localeRes != null) { GUIStrings.initLocale(localeRes); if (chooser != null) { chooser.updateLocale(); chooser.repaint(); } if (editor != null) { editor.updateLocale(); editor.repaint(); } } else { handleUnhandableProblem("Error while reading locale file!", "updateLocale()"); } }
4
@Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException { String password = (String)usernamePasswordAuthenticationToken.getCredentials(); if (!StringUtils.hasText(password)) { logger.warn("Username {}: no password provided", username); throw new BadCredentialsException("Please enter password"); } User foundUser = userService.getUserByName(username); if (foundUser == null) { logger.warn("Username {}: no password provided", username); throw new UsernameNotFoundException("Invalid login"); } if (!encoder.matches(password, foundUser.getPassword())){ logger.warn("Password is incorrect!!"); throw new BadCredentialsException("wrong password"); } final List<GrantedAuthority> authorities; if (foundUser.getRole().compareTo(User.ROLES.ROLE_USER) == 0){ authorities = AuthorityUtils.createAuthorityList(foundUser.getRole().toString()); }else { authorities = AuthorityUtils.NO_AUTHORITIES; } return new org.springframework.security.core.userdetails.User(username, password, true, true, true, true, authorities); }
4
public void processBill() { QueryWarehouse bank = new QueryWarehouse(); Date date = new Date(); String currentDate = df.format(date); int compid = this.getCompanyIdCombo(comboCompany.getSelectedIndex()); String tempQuery = "insert into joincompany_member_hdr (billdt) values ('"+currentDate+"')"; Statement stmt = null; int billid = 0; this.connect(); try { stmt = conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } ResultSet rs; String compnameTemp = null; int compidTemp = 0; int memberidTemp = 0; String lastnameTemp = null; String firstnameTemp = null; String midinitTemp = null; try { stmt.executeQuery(tempQuery); tempQuery = bank.maxBillId(); rs = stmt.executeQuery(tempQuery); if(rs.next()) billid = rs.getInt("billid"); rs = null; //System.out.println(billid); tempQuery = bank.joinDistinct(compid); rs = stmt.executeQuery(tempQuery); if(rs.next()) { compnameTemp = rs.getString("compname"); compidTemp = rs.getInt("compid"); memberidTemp = rs.getInt("memberid"); lastnameTemp = rs.getString("lastname"); firstnameTemp = rs.getString("firstname"); midinitTemp = rs.getString("midinit"); } } catch(Exception x) { x.printStackTrace(); } rs = null; ResultSet ps; try { //STEP ZERO : INITIATE BILLID tempQuery = "insert into joincompany_member (compname,compid,memberid,lastname,firstname,midinit,billid) values('"+compnameTemp+"','"+compidTemp+"','"+memberidTemp+"','"+lastnameTemp+"','"+firstnameTemp+"','"+midinitTemp+"','"+billid+"')"; //STEP ONE - INSERT COMPANY - MEMBER JOIN stmt.addBatch(tempQuery); //STEP TWO tempQuery = bank.currentMonthPeriod(finalFrom, finalUntil); stmt.addBatch(tempQuery); //STEP THREE int[] executeBatch = stmt.executeBatch(); tempQuery = bank.selectJoinCompanyMember(compid); ps = stmt.executeQuery(tempQuery); while(ps.next()) { firstname.add(ps.getString("firstname")); lastname.add(ps.getString("lastname")); midinit.add(ps.getString("midinit")); loanType.add(ps.getString("loantype")); monAmort.add(ps.getFloat("mon_amort")); } this.billReport(); } catch (SQLException e) { e.printStackTrace(); } catch (JRException ex) { Logger.getLogger(ProcessBillStatement.class.getName()).log(Level.SEVERE, null, ex); } finally { this.disconnect(); } }
7
public static void main(String[] args) { try { List<Thread> threads = new ArrayList<Thread> (CLIENTS); JobDispatcher dispatcher = new JobDispatcher(); dispatcher.start(); JobProcessingService service1 = new JobProcessingService("1"); JobProcessingService service2 = new JobProcessingService("2"); JobProcessingService service3 = new JobProcessingService("3"); service1.start(); service2.start(); service3.start(); for (int i = 0; i < CLIENTS; i++) { Thread thread = new Thread(new JobProcessingClient(EXECUTIONS)); threads.add(thread); thread.start(); } for (int i = 0; i < CLIENTS; i++){ try { threads.get(i).join(); } catch (InterruptedException e) { System.err.println("Interrupted!"); } } dispatcher.shutDown(); } catch (RemoteException e) { System.err.println("Failed to shutdown dispatcher/servers."); e.printStackTrace(); } catch (AccessControlException e) { System.err .println("Permissions not correct, try to add this to your VM Args:\n"); System.err .println("-Djava.rmi.server.codebase=file:$pathToBin\n" + "-Djava.rmi.server.hostname=localhost\n" + "-Djava.security.policy=file:$pathToBin/server.policy"); } }
5
public void insert(Player player) throws NamingException { String INSERT_STMT="insert into player(name,address,city,province,postal_code) values(?,?,?,?,?)"; // JDBC variables DataSource ds = null; Connection connection = null; PreparedStatement insert_stmt = null; try { // Retrieve the DataSource from JNDI Context ctx = new InitialContext(); if (ctx == null) { throw new RuntimeException("JNDI Context could not be found."); } ds = (DataSource) ctx.lookup("jdbc/myDatasource"); if (ds == null) { throw new RuntimeException("DataSource could not be found."); } // Get a database connection connection = ds.getConnection("root","btes"); // Create SQL INSERT statement insert_stmt = connection.prepareStatement(INSERT_STMT,Statement.RETURN_GENERATED_KEYS); insert_stmt.setString(1,player.getName()); insert_stmt.setString(2,player.getAddress()); insert_stmt.setString(3,player.getCity()); insert_stmt.setString(4,player.getProvince()); insert_stmt.setString(5,player.getPostalcode()); int id = insert_stmt.executeUpdate(); ResultSet generatedKeys = insert_stmt.getGeneratedKeys(); if (generatedKeys.next()) { player.setPID(generatedKeys.getInt(1)); System.out.println("player id--"+player.getPID()); } else { throw new SQLException("Creating user failed, no generated key obtained."); } // Get the next Player object ID }catch (SQLException e) { throw new RuntimeException("A database error occured. " + e.getMessage()); // Handle any JNDI errors } catch (NamingException e) { throw new RuntimeException("A JNDI error occured. " + e.getMessage()); // Clean up JDBC resources } finally { if (insert_stmt != null) { try { insert_stmt.close(); } catch (SQLException e) { } } if (connection != null) { try { connection.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } }
9
public AttributeInfo copy(ConstPool newCp, Map classnames) throws RuntimeCopyException { try { return new StackMapTable(newCp, new Copier(this.constPool, info, newCp).doit()); } catch (BadBytecode e) { throw new RuntimeCopyException("bad bytecode. fatal?"); } }
1
protected <T> boolean checkIColors(T obj1, T obj2) { /** Convert IColor-s from the colors teachpack to java.awt.Color */ if (obj1.getClass().getName().equals("colors.Red")) return obj2.getClass().getName().equals("colors.Red"); if (obj1.getClass().getName().equals("colors.White")) return obj2.getClass().getName().equals("colors.White"); if (obj1.getClass().getName().equals("colors.Blue")) return obj2.getClass().getName().equals("colors.Blue"); if (obj1.getClass().getName().equals("colors.Black")) return obj2.getClass().getName().equals("colors.Black"); if (obj1.getClass().getName().equals("colors.Green")) return obj2.getClass().getName().equals("colors.Green"); if (obj1.getClass().getName().equals("colors.Yellow")) return obj2.getClass().getName().equals("colors.Yellow"); return false; }
6
public void visitInnerClass(final String name, final String outerName, final String innerName, final int access) { if (innerClasses == null) { innerClasses = new ByteVector(); } ++innerClassesCount; innerClasses.putShort(name == null ? 0 : newClass(name)); innerClasses.putShort(outerName == null ? 0 : newClass(outerName)); innerClasses.putShort(innerName == null ? 0 : newUTF8(innerName)); innerClasses.putShort(access); }
4
private void addReference(final int sourcePosition, final int referencePosition) { if (srcAndRefPositions == null) { srcAndRefPositions = new int[6]; } if (referenceCount >= srcAndRefPositions.length) { int[] a = new int[srcAndRefPositions.length + 6]; System.arraycopy(srcAndRefPositions, 0, a, 0, srcAndRefPositions.length); srcAndRefPositions = a; } srcAndRefPositions[referenceCount++] = sourcePosition; srcAndRefPositions[referenceCount++] = referencePosition; }
2
public void generarDOT_DesdeArchivo() { FileWriter archivoAutomata = null; PrintWriter pw = null; nombreAutomata = JOptionPane.showInputDialog("Por favor, indique el nombre del archivo DOT que describe al automata"); this.nombreAutomata += ".dot"; try { //archivoAutomata = new FileWriter("C:\\GraphViz\\bin\\generadosyF\\" + nombreAutomata); // una ruta alternativa archivoAutomata = new FileWriter("ArchivosDOT\\" + nombreAutomata); pw = new PrintWriter(archivoAutomata); String estadoInicial = obtenerEstadoInicial(); pw.println("digraph finite_state_machine {"); pw.println("rankdir=LR;"); pw.println("node [shape = point ]; qi;"); pw.print("node [shape = doublecircle];"); System.out.println("digraph finite_state_machine {"); System.out.println("rankdir=LR;"); System.out.println("node [shape = point ]; qi;"); System.out.println("node [shape = doublecircle];"); ArrayList estadosFinales = obtenerEstadosFinales(); for (int i = 0; i < estadosFinales.size(); i++) { pw.print((String) estadosFinales.get(i) + ";"); System.out.println((String) estadosFinales.get(i) + ";"); } pw.println(); pw.println("node [shape = circle];"); pw.println("qi -> " + estadoInicial + ";"); System.out.println("node [shape = circle];"); System.out.println("qi ->" + estadoInicial + ";"); for (int l = 0; l < automata.size(); l++) { //ciclo principal, recorre automata String[] transicionesEstado = automata.get(l).toString().split(":"); // toma la linea completa: 0:a;1:b;-:c;-:@;- y la parte por : for (int j = 1; j < transicionesEstado.length; j++) { // resulta un arreglo del siguiente modo: transicionesEstado = {"0" , "a;1" , "b;-" , "c;-" , "@;-"} String fragmentoTransic = transicionesEstado[j]; // toma un elemento del arreglo que se geeró despues de split if (!fragmentoTransic.contains("-")) { // se quita ; y ahora cada elemento es del tipo: a,1,5,6,9 ... (se sabe que el primer elemento es el simbolo de transición y los siguientes son estados) String[] simboloyEstados = fragmentoTransic.replace(";", ",").split(","); for (int k = 1; k < simboloyEstados.length; k++) { //q2 -> q3 [ label = "0" ]; pw.println(transicionesEstado[0].replace("*", "") + " -> " + simboloyEstados[k] + "[ label = \"" + simboloyEstados[0] + "\" ];"); System.out.println(transicionesEstado[0].replace("*", "") + " -> " + simboloyEstados[k] + "[ label = \"" + simboloyEstados[0] + "\" ];"); } } } } pw.println("}"); System.out.println("}"); } catch (IOException ex) { Logger.getLogger(AFN.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (null != archivoAutomata) { archivoAutomata.close(); JOptionPane.showMessageDialog(null, "El archivo " + nombreAutomata + " se gener\u00f3 satisfactoriamente"); } } catch (Exception e2) { e2.printStackTrace(); } } }
8
public Model(int col, int row) { this.board = new CellState[col][row]; for (int j = 0; j < row; ++j) { for (int i = 0; i < col; ++i) { this.board[i][j] = CellState.EMPTY; } } // nextPlayer(); }
2
public DefaultHandler(boolean consoleLogging, String fileName) throws FreeColException { this.consoleLogging = consoleLogging; File file = new File(fileName); if (file.exists()) { if (file.isDirectory()) { throw new FreeColException("Log file \"" + fileName + "\" could not be created."); } else if (file.isFile()) { file.delete(); } } try { file.createNewFile(); } catch (IOException e) { throw new FreeColException("Log file \"" + fileName + "\" could not be created: " + e.getMessage()); } if (!file.canWrite()) { throw new FreeColException("Can not write in log file \"" + fileName + "\"."); } try { fileWriter = new FileWriter(file); } catch (IOException e) { throw new FreeColException("Can not write in log file \"" + fileName + "\"."); } // We should use XMLFormatter here in the future // or maybe a self-made HTMLFormatter. setFormatter(new TextFormatter()); try { String str = "FreeCol game version: " + FreeCol.getRevision() + "\nFreeCol protocol version: " + DOMMessage.getFreeColProtocolVersion() + "\n\nJava vendor: " + System.getProperty("java.vendor") + "\nJava version: " + System.getProperty("java.version") + "\nJava WM name: " + System.getProperty("java.vm.name") + "\nJava WM vendor: " + System.getProperty("java.vm.vendor") + "\nJava WM version: " + System.getProperty("java.vm.version") + "\n\nOS name: " + System.getProperty("os.name") + "\nOS architecture: " + System.getProperty("os.arch") + "\nOS version: " + System.getProperty("os.version") + "\n\n"; fileWriter.write(str, 0, str.length()); } catch (IOException e) { e.printStackTrace(); } }
7
public boolean handles(HTTPRequest req) { return req.getPath().matches(PATH)&&req.getHost().matches(HOST); }
1
protected void powerUpTimer() { int type = (int) (Math.round(Math.random() * 5)); powerUpList.add(new PowerUp(type)); if (fixedSpeed == false) { ball.increaseSpeed(); } //A chance to create a black hole is 1/6 if (type == 0) { isBlackHole = true; } }
2
public void chasePlayer(){ if(abs(this.x - player.getX()) > abs(this.y - player.getY())){ if(player.getX() < this.getX()){ this.dx = -1; if(this.dy > 0){ dy -= .03; } else{ dy += .03; } } if(player.getX() > this.getX()){ this.dx = 1; if(this.dy > 0){ dy -= .03; } else{ dy += .03; } } } else { if(player.getY() > this.getY()){ this.dy = 1; if(this.dx > 0){ dx -= .03; } else{ dx += .03; } } if(player.getY() < this.getY()){ this.dy = -1; } if(this.dx > 0){ dx -= .03; } else{ dx += .03; } } }
9
public void setHasVisited(boolean hasVisited) { this.hasVisited = hasVisited; }
0
public int getEndLineNumber() { return endLineNumber; }
0
private void formPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_formPropertyChange if (evt.getPropertyName().equals("LadattuProfiili")) { if (palkanlaskenta.getProfiili() != null) { LadattuProfiili.setText(palkanlaskenta.getProfiili().toString()); } } if (evt.getPropertyName().equals("LataaTyopaivat")) { if (palkanlaskenta.getProfiili() != null) { malli.clear(); this.tyopaivat = palkanlaskenta.getProfiili().getTyopaivat(); for (int i = 0; i < tyopaivat.size(); i++) { malli.addElement(tyopaivat.get(i)); } } } }//GEN-LAST:event_formPropertyChange
5
public void jasmin() { try{ // jasmine uses a ".j" extension by default String name = browseClass() + ".j"; String fileName = parseFileDir(name) + parseFileName(name) + "." + parseFileExt(name); // make sure there is a place to put it if (!parseFileDir(name).equals("")) { // test if directory for the class exists File f = new File("jasper.out" + File.separatorChar + parseFileDir(name)); fileName = "jasper.out" + File.separatorChar + fileName; // if the directory path does exist, then create it under the current directory if (!f.exists()) f.mkdirs(); } // open up the output stream to write the file PrintStream out = new PrintStream(new FileOutputStream(fileName)); // print the .source directive attributes.jasmin(out); // print the .class or .interface directive if ((accessFlags & 0x0200) > 0) { out.print(pad(".interface", SPACER)); } else { out.print(pad(".class", SPACER)); } out.println(accessString() + pool.toString(thisClass)); // print the .super directive if (superClass > 0) out.println(pad(".super", SPACER) + pool.toString(superClass)); // print the .implements directives interfaces.jasmin(out); out.println(""); // print the .field directives fields.jasmin(out); out.println(""); // print the .method directives methods.jasmin(out); // echo that the jasmine file has been completed System.out.println("Generated: " + fileName); } catch (IOException e) { // report the error System.out.println(e); } }
5
@Override public void load() { if (vertexLocation != null) { ResourceText txt = ResourceManager.getText(vertexLocation); txt.load(); vertexSource = txt.getText(); } if (fragmentLocation != null) { ResourceText txt = ResourceManager.getText(fragmentLocation); txt.load(); fragmentSource = txt.getText(); } if (vertexSource == null || fragmentSource == null) { new KatamaException("Could not load shader, missing some code!", "Vertex shader: " + (vertexSource != null ? "found" : "NOT FOUND!"), "Fragment shader: " + (fragmentSource != null ? "found" : "NOT FOUND!")).printStackTrace(); System.exit(-1); } }
6
private void loadHashMap() { // load from a file formatted like this: // #HEX color // e.g #FFFFFF white File colorMap = new File("colormap.txt"); try { BufferedReader in = new BufferedReader(new FileReader(colorMap)); while (in.ready()) { String line = in.readLine(); // make sure it matches the format if (line.matches("#[a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]?[a-fA-F0-9]?[a-fA-F0-9]?\\s\\w+")) { int spacePos = line.indexOf('\t'); if (spacePos == -1) { spacePos = line.indexOf(' '); // has used a space instead of tab } if (spacePos != -1) { // System.out.println(line.substring(0, spacePos) + "=" + line.substring(spacePos+1)); hexToColors.put(line.substring(0, spacePos), line.substring(spacePos + 1)); } } } in.close(); } catch (Exception e) { e.printStackTrace(); } }
5
private void performFileActions() throws Exception { if(!PERFORM_FILE_ACTIONS) return; for(IFile fileAction : fileActions) { if(fileAction == null) break; fileAction.perform(); fileAction.shutdownNow(); } }
3
public boolean isAnagrams(String a, String b) { if (a == null || b == null) { return false; } if (a.isEmpty() || b.isEmpty()) { if (a.isEmpty() && b.isEmpty()) { return true; } else { return false; } } if (a.length()!=b.length()){ return false; } int l=a.length(); for(int i=0;i<l;i++){ if(a.charAt(i)!=b.charAt(l-i-1)){ return false; } } return true; }
9
@Override public void update(GameContainer gc, int d) throws SlickException { for (int x = 0; x < tiles.length; x++){ for (int y = 0; y < tiles[x].length; y++){ if (tiles[x][y] != null) tiles[x][y].update(d); } } }
3
public static List<Command> readList(String pathName) { List<Command> list = new ArrayList<Command>(); ObjectInputStream oin = null; try { File f = new File(pathName); if (f.exists()) { oin = new ObjectInputStream(new BufferedInputStream( new FileInputStream(f))); list = (List<Command>)oin.readObject(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (oin != null) { oin.close(); } } catch (IOException e) { e.printStackTrace(); } } return list; }
4
public static String getDynamicStorageLocation () { if (CommandLineSettings.getSettings().getDynamicDir() != null && !CommandLineSettings.getSettings().getDynamicDir().isEmpty()) { return CommandLineSettings.getSettings().getDynamicDir(); } switch (getCurrentOS()) { case WINDOWS: return System.getenv("APPDATA") + "/CRACKEDftntlauncher/"; case MACOSX: return cachedUserHome + "/Library/Application Support/CRACKEDftntlauncher/"; case UNIX: return cachedUserHome + "/.CRACKEDftntlauncher/"; default: return getDefInstallPath() + "/temp/"; } }
5
public BigDecimal median_as_BigDecimal() { BigDecimal median = BigDecimal.ZERO; switch (type) { case 1: case 12: BigDecimal[] bd = this.getArray_as_BigDecimal(); median = Stat.median(bd); bd = null; break; case 14: throw new IllegalArgumentException("Complex median value not supported"); default: throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!"); } return median; }
3
private Object executeExpression(Value value, EntityMapping entity, ColumnMapping column, ResultSet records){ Object result_value = null; if(value == null){ return result_value; } if(value instanceof SqlValue){ return executeSql(value,entity,column,records); }else if(value instanceof ExpValue){ if(value.getValue().contains("$")){ result_value = replaceVariables(value.getValue(),entity.getVariables(),entity,records); } } return result_value; }
4
public void visitAddressStoreStmt(final AddressStoreStmt stmt) { if (CodeGenerator.DEBUG) { System.out.println("code for " + stmt); } genPostponed(stmt); final Subroutine sub = stmt.sub(); Assert.isTrue(sub.returnAddress() != null); method.addInstruction(Opcode.opcx_astore, sub.returnAddress()); stackHeight -= 1; }
1
private void createToolBar(Composite parent) { ToolBar toolbar = new ToolBar (parent, SWT.NONE); String group = null; for (int i = 0; i < tools.length; i++) { Tool tool = tools[i]; if (group != null && !tool.group.equals(group)) { new ToolItem (toolbar, SWT.SEPARATOR); } group = tool.group; ToolItem item = addToolItem(toolbar, tool); if (i == Default_tool || i == Default_fill || i == Default_linestyle) item.setSelection(true); } }
6
@Override public double getDblVal() { String s = getStringVal(); try { Double d = new Double( s ); return d; } catch( NumberFormatException n ) { getXfRec(); if( myxf.isDatePattern() ) { // use it try { String format = myxf.getFormatPattern(); WorkBookHandle.simpledateformat.applyPattern( format ); java.util.Date d = WorkBookHandle.simpledateformat.parse( s ); Calendar c = new GregorianCalendar(); c.setTime( d ); return DateConverter.getXLSDateVal( c ); } catch( Exception e ) { // fall through } } Calendar c = DateConverter.convertStringToCalendar( s ); if( c == null ) { return Double.NaN; } return DateConverter.getXLSDateVal( c ); } }
4
static boolean checkUUIDFormat(String uuid) { boolean result = true; int delimCnt = 0; int delimPos = 0; if (uuid == null) { return false; } for (delimPos = 0; delimPos < uuid.length(); delimPos++) { if (uuid.charAt(delimPos) == '-') { delimCnt++; result = result && (delimPos == 8 || delimPos == 13 || delimPos == 18 || delimPos == 23); } } return result && UUID_SEGMENT_COUNT == delimCnt && UUID_LENGTH == delimPos; }
9
public static int calcvalue(String token) { int result = 0; if (token.equals("RA")) { return backend.Register.r[15].b; } else if (token.equals("SP")) { return backend.Register.r[14].b; } else if (token.startsWith("R")) { int no3 = backend.Register.convertRegister(token); if(no3==-1) { FrontEnd.appendToPane(FrontEnd.statuswindow,"ERROR(" + backend.ScanFile.current_line + ") Invalid Register Accesed Returning Zero\n",Color.RED); return 0; } result = backend.Register.r[no3].b; } else if (Myfunction.isInteger(token) == 0) { FrontEnd.appendToPane(FrontEnd.statuswindow,"ERROR(" + backend.ScanFile.current_line + ") Invalid Immediate "+token+" Decimal Or Hex Format Allowed \n",Color.RED); // frontend.FrontEnd.statuswindow.append("ERROR(" + backend.ScanFile.current_line + ")" + token + " isnot a valid operand."); //frontend.FrontEnd.statuswindow.setCaretPosition(frontend.FrontEnd.statuswindow.getText().length()); frontend.FrontEnd.exceptionraised++; } else { result = Myfunction.getimme((token)); } return result; }
5
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton6ActionPerformed {//GEN-HEADEREND:event_jButton6ActionPerformed world.choiceMade("right"); }//GEN-LAST:event_jButton6ActionPerformed
0
public void draw(Graphics g) { for (int i = 1; i < body.size(); i++) { int x = body.get(i).getX(); int y = body.get(i).getY(); g.setColor(Color.GREEN); g.fillRect(x, y, Block.WIDTH, Block.HEIGTH); g.setColor(Color.BLACK); g.drawRect(x, y, Block.WIDTH, Block.HEIGTH); } g.setColor(Color.red); g.fillRect(body.get(0).getX(), body.get(0).getY(), Block.WIDTH, Block.HEIGTH); g.setColor(Color.BLACK); g.drawRect(body.get(0).getX(), body.get(0).getY(), Block.WIDTH, Block.HEIGTH); }
1
public void onEnable() { //Fill our hashmap of material aliases with the ones permitted. PopulateMaterials(); //Load the markets, deliveries and revenue load(); //If we didn't load the markets, make them if(markets == null) { markets = new HashMap<Material, Market>(); for( Material mat : materials.values() ) { markets.put(mat, new Market(this, mat)); } } //If we didn't load any revenue, start blank if(revenue == null) { revenue = new HashMap<String, Double>(); } //If we didn't load any deliveries, start blank if(deliveries == null) { deliveries = new HashMap<String, List<EEItemStack>>(); } //Make sure vault has connected to an economy. if (!setupEconomy() ) { getLogger().info("EmeraldExchange - Disabled due to no Vault dependency found!"); getServer().getPluginManager().disablePlugin(this); return; } //Now enable event listener new EEEventListener(this); //Now schedule a collection notification every 5 minutes getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { public void run() { //Notify all players. Player[] players = getServer().getOnlinePlayers(); for(Player player : players) { notifyPlayer(player.getName()); } } }, 5 * 60 * 20L, 5 * 60 * 20L); //The above line is initial delay of 5 minutes, repeating every 5 minutes getLogger().info("EmeraldExchange Enabled."); }
6
public static void main(String[] args) throws FileNotFoundException, JSONException, IOException { CommonParameters commonParams = new CommonParameters(); CommandSubmit submitCommand = new CommandSubmit(); CommandStatus statusCommand = new CommandStatus(); CommandCancel cancelCommand = new CommandCancel(); CommandClean cleanCommand = new CommandClean(); JCommander commander = new JCommander(commonParams); commander.addCommand(CommandSubmit.NAME, submitCommand); commander.addCommand(CommandStatus.NAME, statusCommand); try { commander.parse(args); String parsedCommand = commander.getParsedCommand(); if (parsedCommand.equals(CommandSubmit.NAME)) { submit(submitCommand.jobFile, commonParams.endpoint); } else if (parsedCommand.equals(CommandStatus.NAME)) { status(statusCommand.jobId, commonParams.endpoint); } else if (parsedCommand.equals(CommandCancel.NAME)) { cancel(cancelCommand.jobId, commonParams.endpoint); } else if (parsedCommand.equals(CommandClean.NAME)) { clean(cleanCommand.jobId, commonParams.endpoint); } else { commander.usage(); } } catch (ParameterException e) { commander.usage(); } }
5
@Override public boolean onCommand(CommandSender sender, Command cmd, String firstArg, String[] args) { /* * /---- [arena, list, join] * | /---- [arenaName] * | | /---- [create, delete, set, check, regen, reload] * | | | /---- [digregion, playerspawn, exitpoint] * | | | | /---- other arguments * | | | | | * | | | | | * args[0] | args[1] | args[2] | args[3] | args[4] ... */ if (!(sender instanceof Player)) { sender.sendMessage("DigDug commands can only be performed by a player!"); return true; } //Initialize the pSender variable // Player pSender = (Player) sender; String commandName = cmd.getName(); //Check if the command is for digdug if (commandName.equals("dd") | commandName.equals("digdug")) { //Check if there were any arguments. Else return. if (args == null || args.length == 0) { sender.sendMessage(msg.getMsg("cmd_dd_usage")); return true; } String commandBase = args[0].toLowerCase(); switch (commandBase) { case "arena": cmdArena(sender, args); break; case "list": cmdList(sender); break; case "join": if (args.length >= 2) { cmdJoin(sender, args[1]); } else { sender.sendMessage(msg.getMsg("cmd_join_usage")); } break; default: sender.sendMessage(msg.getMsg("cmd_dd_usage")); break; } } else { return false; } return true; }
8
public static void writePredictionsToFile(String testFile, String outputFileName, HashMap<Long, HashMap<Long, Double>> ratingPredictions) throws IOException{ FileWriter fileWriter = new FileWriter(outputFileName); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); Scanner scan = new Scanner(new File(testFile)); String line = null; boolean firstLine = true; long currentUser = -1; HashMap<Long, Double> currentUserPredictions = new HashMap<Long, Double>(); //read and ignore first line (headers) line = scan.nextLine(); do { line = scan.nextLine(); String[] pair = line.split(","); if(pair.length != 2){ System.err.println("Error: test file has wrong format. It must be a 2-column CSV."); System.exit(1); } long item = Long.parseLong(pair[0].trim()); long user = Long.parseLong(pair[1].trim()); if(user != currentUser){ if(!ratingPredictions.containsKey(user)){ System.err.println("Error: test file contains user with uncomputed prediction."); System.exit(1); } currentUserPredictions = ratingPredictions.get(user); } if(!currentUserPredictions.containsKey(item)){ System.err.println("Error: test file contains item with uncomputed prediction."); System.exit(1); } double prediction = currentUserPredictions.get(item); if(!firstLine) bufferedWriter.newLine(); if(firstLine){firstLine=false;} bufferedWriter.write(String.valueOf(prediction)); } while (scan.hasNext()); bufferedWriter.close(); }
7
public Method getSetter(String aname, BaseModelMBean bean, Object resource) throws AttributeNotFoundException, MBeanException, ReflectionException { // Cache may be needed for getters, but it is a really bad idea for setters, this is far // less frequent. Method m=null;//(Method)setAttMap.get( name ); if( m==null ) { AttributeInfo attrInfo = (AttributeInfo)attributes.get(aname); if (attrInfo == null) throw new AttributeNotFoundException(" Cannot find attribute " + aname); // Look up the actual operation to be used String setMethod = attrInfo.getSetMethod(); if (setMethod == null) throw new AttributeNotFoundException("Cannot find attribute " + aname + " set method name"); String argType=attrInfo.getType(); Class signature[] = new Class[] { BaseModelMBean.getAttributeClass( argType ) }; Object object = null; NoSuchMethodException exception = null; try { object = bean; m = object.getClass().getMethod(setMethod, signature); } catch (NoSuchMethodException e) { exception = e;; } if( m== null && resource != null ) { try { object = resource; m = object.getClass().getMethod(setMethod, signature); exception=null; } catch (NoSuchMethodException e) { exception = e; } } if( exception != null ) throw new ReflectionException(exception, "Cannot find setter method " + setMethod + " " + resource); //setAttMap.put( name, m ); } return m; }
8
public void setTableSwitchJump(int switchStart, int caseIndex, int jumpTarget) { if (!(0 <= jumpTarget && jumpTarget <= itsCodeBufferTop)) throw new IllegalArgumentException("Bad jump target: "+jumpTarget); if (!(caseIndex >= -1)) throw new IllegalArgumentException("Bad case index: "+caseIndex); int padSize = 3 & ~switchStart; // == 3 - switchStart % 4 int caseOffset; if (caseIndex < 0) { // default label caseOffset = switchStart + 1 + padSize; } else { caseOffset = switchStart + 1 + padSize + 4 * (3 + caseIndex); } if (!(0 <= switchStart && switchStart <= itsCodeBufferTop - 4 * 4 - padSize - 1)) { throw new IllegalArgumentException( switchStart+" is outside a possible range of tableswitch" +" in already generated code"); } if ((0xFF & itsCodeBuffer[switchStart]) != ByteCode.TABLESWITCH) { throw new IllegalArgumentException( switchStart+" is not offset of tableswitch statement"); } if (!(0 <= caseOffset && caseOffset + 4 <= itsCodeBufferTop)) { // caseIndex >= -1 does not guarantee that caseOffset >= 0 due // to a possible overflow. throw new IllegalArgumentException( "Too big case index: "+caseIndex); } // ALERT: perhaps check against case bounds? putInt32(jumpTarget - switchStart, itsCodeBuffer, caseOffset); }
9
public String getBlogLabel() { return blogLabel; }
0
private LicenseNumber(String nameIdentifier, int yearOfIssue, int serialNumber, String stringRepresentation){ this.nameIdentifier=nameIdentifier; if(nameIdentifier.isEmpty()) throw new IllegalArgumentException("The name Identifier is null"); Date date = new Date(); Calendar cal = new GregorianCalendar(); cal.setTime(date); this.yearOfIssue = cal.get(Calendar.YEAR); Calendar todaysDate = Calendar.getInstance(); if (this.yearOfIssue > todaysDate.get(Calendar.YEAR)) throw new IllegalArgumentException("That is not a valid year of issue"); Random randomNumber = new Random(); this.serialNumber = randomNumber.nextInt(9) + 1; if (serialNumber < 0 || serialNumber > 10) throw new IllegalArgumentException("The number is not appropriate"); this.stringRepresentation = stringRepresentation; }
4
final public String TableRow() throws ParseException { String s; final StringBuffer buf = new StringBuffer(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case STRING: label_3: while (true) { s = jj_consume_token(STRING).image; buf.append(s); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case STRING: ; break; default: jj_la1[5] = jj_gen; break label_3; } } jj_consume_token(TABLE_STRING_END); s = buf.toString(); break; case CHARACTER: s = jj_consume_token(CHARACTER).image; token_source.backup(s.length()); s = String(IN_TABLE_STRING); break; default: jj_la1[6] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return s.trim();} throw new Error("Missing return statement in function"); }
7
@Test public void smallBoardWithKingAndQueen() { Map<String, Integer> figureQuantityMap = new HashMap<>(); figureQuantityMap.put(KING.toString(), 1); figureQuantityMap.put(QUEEN.toString(), 1); int dimension = 2; Set<String> boards = prepareBoardsWithKingAndQueen(figureQuantityMap, dimension); assertThat("more than 1 figure is present", boards.contains("kx\n" + "xx\n"), is(true)); assertThat("all elements are not present on each board", boards.stream() .filter(board -> !board.contains(BISHOP.getFigureAsString()) && !board.contains(ROOK.getFigureAsString()) && !board.contains(KNIGHT.getFigureAsString()) && board.contains(FIELD_UNDER_ATTACK_STRING) && !board.contains(EMPTY_FIELD_STRING) && leftOnlyFigures(board).length() == 1) .map(e -> 1) .reduce(0, (x, y) -> x + y), is(8)); }
5
private void initializeApp() { manager = Manager.getInstance(); for (Disc disc : manager.getDiscs().getDiscs()) { discSelector.addItem(disc.getName()); } currentProfile = manager.getProfiles().get("andersonmaaron"); currentCourse = manager.getCourses().get("Griggs Reservoir Park"); updateProfile(); }
1
@Override public void unInvoke() { if(!(affected instanceof MOB)) return; final MOB mob=(MOB)affected; if(canBeUninvoked()) doneTicking=true; super.unInvoke(); if(canBeUninvoked() && (mob!=null)) { final Room R=mob.location(); if((R!=null)&&(!mob.amDead())) { final CMMsg msg=CMClass.getMsg(mob,null,CMMsg.MSG_NOISYMOVEMENT,L("<S-NAME> regain(s) <S-HIS-HER> feet.")); if(R.okMessage(mob,msg)&&(!mob.amDead())) { R.send(mob,msg); CMLib.commands().postStand(mob,true); } } else mob.tell(L("You regain your feet.")); } }
8
public GetKeyDialog(JDialog owner, String title, boolean modal) { /** call base class constructor */ setTitle(title); setModal(modal); /** setup pointer to point to itself */ me = this; /** add keyboard event handler */ addKeyListener(new KeyAdapter() { /** * Handles key pressed events. * @param evt keyboard event */ public void keyPressed(KeyEvent evt) { /** if it's waiting for a key */ if (waitingForKey) { /** get index of key to set */ int i = keysBeingSet[0]; int j = keysBeingSet[1]; /** get the key pressed */ int newKey = evt.getKeyCode(); /** key used flag */ boolean keyUsed = false; /** see if the key is used already or not */ for (int p = 0; p < 4; ++p) { for (int k = 0; k < 5; ++k) { /** if key is used already */ if (keys[p][k] == newKey) { /** if it isn't the key being set */ if (!(p == i && j == k)) /** set key used flag to true */ keyUsed = true; } /** if key used flag is true, then exit loop */ if (keyUsed) break; } /** if key used flag is true, then exit loop */ if (keyUsed) break; } /** if key isn't used */ if (!keyUsed) { /** copy new key */ keys[i][j] = newKey; /** reset the key field */ keyFields[i][j].setText( KeyEvent.getKeyText(keys[i][j])); /** set waiting for key to false */ waitingForKey = false; /** destroy the dialog */ dispose(); } /** if key is used already */ else { /** then show an error dialog */ /** create the dialog content */ JOptionPane pane = new JOptionPane( "Key: [" + KeyEvent.getKeyText(newKey) + "] is used already. Pick a different key."); /** setup the dialog controls */ pane.setOptionType(-JOptionPane.NO_OPTION); pane.setMessageType(JOptionPane.ERROR_MESSAGE); /** create the dialog */ JDialog dialog = pane.createDialog(me, "Error"); /** set it so user can't resize the dialog */ dialog.setResizable(false); /** show the dialog */ dialog.show(); } } } }); /** set the dialog so the user can't resize it */ setResizable(false); /** set dialog size */ setSize(300, 0); int x = owner.getLocation().x + (owner.getSize().width - getSize().width) / 2; int y = owner.getLocation().y + (owner.getSize().width - getSize().height) / 2; /** center the dialog relative to the owner */ setLocation(x, y); /** finally show the dialog */ show(); }
9
private void movement(Ship[] ship){ //Hier werden die Bewegungen der einzelnen Schiffe durchgeführt. Ship s; //Das derzeitige Schiff Ship t; //Das Ziel von s double movement; //Die nötige Bewegung um den Befehl zu erfüllen double distance; //Der Abstand zwischen s und t for (int i = 0; i < ship.length; i++){ s = ship[i]; t = s.target; switch (s.order){ case 0: //longrangefire: Kampf auf maximale Waffenreichweite movement = Math.abs(distance(s, t) - s.maxrange - 10); if (distance(s, t) <= s.maxrange) s.location -= checkmove (s, movement); else s.location += checkmove (s, movement); break; case 1: //shortrangefire: Kampf auf optimale Waffenreichweite movement = Math.abs(distance(s, t) - s.minrange - 10); if (distance(s, t) <= s.minrange) s.location -= checkmove (s, movement); else s.location += checkmove (s, movement); break; case 2: //boarding: Entermanöver movement = distance(s, t); s.location += checkmove (s, movement); break; case 3: //ramming: Rammmanöver (tolle deutsche Rechtschreibung) movement = distance(s, t); s.location += checkmove (s, movement); break; case 4: //disengage: Rückzug aus gegnerischer Waffenreichweite /**TODO Sicherstellen, daß Schiffe mit diesem Befehl nicht die dem * Gegenr nächsten sind, ohne auf die Waffenreichweite des Feindes zu schielen. * Solange Es nicht beschossen wurde und ein eignes Kampfschiff näher am gegner ist * bleibt es an Ort und Stelle. Ansonsten fährt es eine Runde lang mit höchster * Geschwindigkeit vom Gegner weg.**/ default: //withdraw: Flucht (Feiglinge!) s.location -= s.speed; } } }
8
public void visit_fadd(final Instruction inst) { stackHeight -= 2; if (stackHeight < minStackHeight) { minStackHeight = stackHeight; } stackHeight += 1; }
1
public int getVersionCode() { return this.versionCode; }
0
@EventHandler(priority = EventPriority.NORMAL) public void onPickupItem(PlayerPickupItemEvent event){ Player player = event.getPlayer(); if(!player.hasPermission("NodeWhitelist.Whitelisted")){ if(!whitelistWaive.isWaived(player)){ if(!Config.GetBoolean("NoneWhitelisted.Restraints.Interact")){ event.setCancelled(true); } } } }
3
public void serverReceiveMessages() { String input; String inPart1; String inPart2; try { input = inClient.readLine(); if(input != null) { String pattern = "^([A-Z]+:)([a-zA-Z0-9:\\s]*)$"; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(input); //the communication from the client is very limited. They can only send //moves, quits, reset requests(and responses) and new game requests(and responses) if(m.find()) { inPart1 = m.group(1); inPart2 = m.group(2); if(inPart1.equals(communication.cMove)) { handleMove(inPart2); } else if(inPart1.equals(communication.cQuit)) { handleQuit(); } else if(inPart1.equals(communication.cReset)) { handleReset(inPart2); } else if(inPart1.equals(communication.cNew)) { handleNewgame(inPart2); } } } } catch (InterruptedIOException tiemout) { } catch(IOException outp) { System.out.println("Can not receive"); } }
8
@Override public void setKeyState(int key, boolean state) { byte index = -1; if(key == settings.forwardKey.key) { index = 0; } if(key == settings.backKey.key) { index = 1; } if(key == settings.leftKey.key) { index = 2; } if(key == settings.rightKey.key) { index = 3; } if(key == settings.jumpKey.key) { index = 4; } if(key == settings.runKey.key) { index = 5; } if(index >= 0) { keyStates[index] = state; } }
7
@Override public void paint ( Graphics gr ) { initDraw(gr); //Clean the Frame. switch(actualRole) { case PreGame: DrawPreGame(gr); break; case Contributor: DrawNumbersToInstantiate(gr); DrawGrid(gr); break; default: if (state == GameState.game) { DrawGrid(gr); } break; } }
3
static void tuneAll(Instrument[] e) { for (Instrument i : e) tune(i); }
1
protected void drawTransitions(Graphics g) { Graphics2D g2 = (Graphics2D) g; Set arrows = arrowToTransitionMap.keySet(); Iterator it = arrows.iterator(); while (it.hasNext()) { CurvedArrow arrow = (CurvedArrow) it.next(); if (arrow.myTransition.isSelected){ arrow.drawHighlight(g2); arrow.drawControlPoint(g2); } else arrow.draw(g2); } }
2