method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
6eafed5d-ebda-4a12-b05f-ca4c31f11ca3
7
public String strStr(String haystack, String needle) { // Start typing your Java solution below // DO NOT write main() function int m = haystack.length(); int n = needle.length(); if (n == 0) return haystack; if (m == 0 || m < n) return null; int[] next = getNext(needle); int i = 0, j = 0; while (i < m) { if (j == -1 || haystack.charAt(i) == needle.charAt(j)) { i++; j++; // 与i一起递增 } else { j = next[j]; // 递减,因此递减次数不会超过i的递增次数(m),因此总代价也是2*m = O(m) } if (j == n) return haystack.substring(i - n); } return null; }
904a2143-491f-4d0e-9347-13b2189426b5
8
@Override public boolean execute(MOB mob, List<String> commands, int metaFlags) throws java.io.IOException { if((mob==null)||(mob.playerStats()==null)) return false; if(commands.size()<2) { final String wrap=(mob.playerStats().getWrap()!=0)?(""+mob.playerStats().getWrap()):"Disabled"; mob.tell(L("Change your line wrap to what? Your current line wrap setting is: @x1. Enter a number larger than 10 or 'disable'.",wrap)); return false; } final String newWrap=CMParms.combine(commands,1); int newVal=mob.playerStats().getWrap(); if((CMath.isInteger(newWrap))&&(CMath.s_int(newWrap)>10)) newVal=CMath.s_int(newWrap); else if("DISABLED".startsWith(newWrap.toUpperCase())) newVal=0; else { mob.tell(L("'@x1' is not a valid setting. Enter a number larger than 10 or 'disable'.",newWrap)); return false; } mob.playerStats().setWrap(newVal); final String wrap=(mob.playerStats().getWrap()!=0)?(""+mob.playerStats().getWrap()):"Disabled"; mob.tell(L("Your new line wrap setting is: @x1.",wrap)); return false; }
9b31d3ef-7767-46c4-9063-5d76e74faa47
5
public void getImportLines( String fileName ) { File exportFile = new File( fileName ); BufferedReader br = null; try { br = new BufferedReader( new FileReader( exportFile ) ); String line = ""; // find start of protected imports while ( !line.startsWith( "import" ) ) { line = br.readLine(); if ( line == null ) break; } while ( line != null ) { addImport( line ); line = br.readLine(); } br.close(); } catch ( FileNotFoundException e ) { // Ignored if file doesn't exist. } catch ( IOException e ) { e.printStackTrace(); } }
0aacf392-63d4-408c-aefd-7594c63ab80e
9
private void processLine(RdpPacket_Localised data, LineOrder line, int present, boolean delta) { if ((present & 0x01) != 0) line.setMixmode(data.getLittleEndian16()); if ((present & 0x02) != 0) line.setStartX(setCoordinate(data, line.getStartX(), delta)); if ((present & 0x04) != 0) line.setStartY(setCoordinate(data, line.getStartY(), delta)); if ((present & 0x08) != 0) line.setEndX(setCoordinate(data, line.getEndX(), delta)); if ((present & 0x10) != 0) line.setEndY(setCoordinate(data, line.getEndY(), delta)); if ((present & 0x20) != 0) line.setBackgroundColor(setColor(data)); if ((present & 0x40) != 0) line.setOpcode(data.get8()); parsePen(data, line.getPen(), present >> 7); // if(logger.isInfoEnabled()) logger.info("Line from // ("+line.getStartX()+","+line.getStartY()+") to // ("+line.getEndX()+","+line.getEndY()+")"); if (line.getOpcode() < 0x01 || line.getOpcode() > 0x10) { logger.warn("bad ROP2 0x" + line.getOpcode()); return; } // now draw the line surface.drawLineOrder(line); }
c08eca70-622d-4a86-91ba-d5d6156abd55
5
public void mouseDragged(MouseEvent e) { if (mouseDown == true) { if (e.getX() < mouseX) cube.rotateXZ(ROTATIONSPEED); else if (e.getX() > mouseX) cube.rotateXZ(-ROTATIONSPEED); mouseX = e.getX(); if (e.getY() < mouseY) cube.rotateYZ(ROTATIONSPEED); else if (e.getY() > mouseY) cube.rotateYZ(-ROTATIONSPEED); mouseY = e.getY(); repaint(); } }
23cab06e-3d51-4d52-89c9-9071d6c6b02b
3
public static void sendRemainingTime(CommandSender sender, Main main) { Date date = main.getDM().getNextArena(); String time = ""; if (!date.isTomorrow()) { Time comparedTime = Time.compareInaccurate(date.getInaccurateTime(), Time.currentInnacurateTime()); System.out.println(comparedTime); if (comparedTime != null) time = comparedTime.toString(); } else { time = "tomorrow"; } Chat.sendMessage(sender, date.isTomorrow() ? Message.GAME_STARTING_TOMORROW : Message.GAME_STARTING_IN, time); }
c3a8f2e2-5a13-4160-906b-02cc55e11df7
3
private boolean touchWall(double xt, double yt) { return (xt <= (Board.WIDTH - this.width)) && (xt > this.width) && (yt <= Board.HEIGHT - this.height) && (yt > 0); }
79ce14d8-b49c-4158-ac47-4c5b741e2ddf
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final WhoHasRequest other = (WhoHasRequest) obj; if (limits == null) { if (other.limits != null) return false; } else if (!limits.equals(other.limits)) return false; if (object == null) { if (other.object != null) return false; } else if (!object.equals(other.object)) return false; return true; }
91610271-96c3-4d92-b9a7-d693b49434cd
7
private String useRbondVariables(String s, int frame) { int n = model.getRBondCount(); if (n <= 0) return s; int lb = s.indexOf("%rbond["); int rb = s.indexOf("].", lb); int lb0 = -1; String v; int i; RBond bond; while (lb != -1 && rb != -1) { v = s.substring(lb + 7, rb); double x = parseMathExpression(v); if (Double.isNaN(x)) break; i = (int) Math.round(x); if (i < 0 || i >= n) { out(ScriptEvent.FAILED, "Radial bond " + i + " does not exist."); break; } v = escapeMetaCharacters(v); bond = model.getRBond(i); s = replaceAll(s, "%rbond\\[" + v + "\\]\\.length", bond.getLength(frame)); s = replaceAll(s, "%rbond\\[" + v + "\\]\\.strength", bond.getStrength()); s = replaceAll(s, "%rbond\\[" + v + "\\]\\.bondlength", bond.getLength()); s = replaceAll(s, "%rbond\\[" + v + "\\]\\.atom1", bond.atom1.getIndex()); s = replaceAll(s, "%rbond\\[" + v + "\\]\\.atom2", bond.atom2.getIndex()); lb0 = lb; lb = s.indexOf("%rbond["); if (lb0 == lb) // infinite loop break; rb = s.indexOf("].", lb); } return s; }
b02f4c50-9756-4005-96cb-01a4862c4943
3
void setImage(Path image, Brandingsize size) { switch (size) { case SMALL: this.imgSmall = image; break; case MEDIUM: this.imgMedium = image; break; case LARGE: this.imgLarge = image; break; default: throw new IllegalArgumentException(); } }
e3549aae-4d89-48be-9ea3-fc507495f25d
4
public static void main(String[] args) { boolean check; long i = 21; while(true) { check = true; for(int j = 1; j < 21; j++) { if(i % j != 0) check = false; } if(check) { System.out.println(i); break; } i++; } }
d03953f8-679f-4ec1-8e46-ce80798f6e6a
1
public void print() { while (q.size() != 0) { System.out.println(getNumber()); } }
e7190cf1-cf0b-460e-bf4a-d950e581653a
5
@Override public void paintComponents(Graphics g) { if (!this.skin.getAccButtonPosition().equals(Position.NONE)) { Graphics g2 = g.create(); int x, y; int w, h; Rectangle bounds = this.parent.getBounds(); if (this.skin.isChanged() || (this.ground == null) || (this.symbol == null)) { try { String p = this.skin.getImgPath_StandardBtn(Imagetype.DEFAULT).toString() .replaceFirst(Constants.DEFAULT_SKINIMAGE_TYPE, Constants.DEFAULT_INPUTIMAGE_TYPE); this.ground = ImageIO.read(new File(p)); p = this.skin.getImgPath_AccessSym().toString() .replaceFirst(Constants.DEFAULT_SKINIMAGE_TYPE, Constants.DEFAULT_INPUTIMAGE_TYPE); this.symbol = ImageIO.read(new File(p)); } catch (IOException e) { ; } } w = this.skin.getAccButtonWidth(); h = this.skin.getAccButtonHeight(); x = 30; y = bounds.height - h - 30; g2.drawImage(this.ground, x, y, w, h, null); g2.setClip(x, y, w, h); x += (w / 2) - (this.symbol.getWidth() / 2); g2.drawImage(this.symbol, x, y + 2, null); } }
30249fd3-3b0f-486d-a26e-0f88a07c426b
4
@Override public void run() { while (runGameLoop) { if (traced()) { System.out.println("game loop:"); } updateGameStatus(); handleCollisions(); frame.repaint(); if (is(TraceFlag.DRAWS)) { System.out.println("\trepaint"); } try { Thread.sleep(frameTime); } catch (InterruptedException e) { e.printStackTrace(); } } }
af7a775e-8330-4718-a014-68724ac0adf2
2
private void convertPixelToRGB() { rgbArray = new int[height][width][3]; int rgb; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { rgb = img.getRGB(col, row); rgbArray[row][col][0] = (rgb >> 16) & 0xff; //red rgbArray[row][col][1] = (rgb >> 8) & 0xff; // green rgbArray[row][col][2] = rgb & 0xff; // blue } } convertRGBtoYCbCr(); }
5851a932-3fd6-49b1-8a85-3bb4e4d07b57
0
public int f() { return 1; }
fbeab8ea-504a-469d-ae7a-d19d283edc82
2
public MemberValue getMemberValue(String name) { if (members == null) return null; else { Pair p = (Pair)members.get(name); if (p == null) return null; else return p.value; } }
01eb8b49-5997-4eda-91e2-8d81ff591bd1
9
public static TUnit doLeverage(TUnit inputUnit, ArrayList<TUnit> translationMemories, int fuzzyLimit, boolean checkFile, boolean checkID) { //Check fuzzy limit if (fuzzyLimit<0) { fuzzyLimit=0; }else if (fuzzyLimit>100) { fuzzyLimit=100; } if (inputUnit==null || translationMemories==null ) return inputUnit; TUnit outputUnit = new TUnit("","",""); //Start leverage outputUnit = strictLeverage(inputUnit, translationMemories, checkFile, checkID); // If Stric leverage failed to get a match, try loose leverage if fuzzyLimit is less than 100 if (inputUnit.originalString.length() >0 && outputUnit.translatedString.length() ==0 && fuzzyLimit<100) { outputUnit = looseLeverage(inputUnit,translationMemories, fuzzyLimit); } // if no matches found, set the return value to original unit if (inputUnit.originalString.length() >0 && outputUnit.translatedString.length() ==0) { outputUnit = inputUnit; } return outputUnit; }
8123d861-5a99-49d9-ae19-80427e4b6c65
7
public static Cons cppGetStaticVariableDefinitions(Stella_Class renamed_Class) { { Cons staticmembervardefs = Stella.NIL; { Slot slot = null; Iterator iter000 = renamed_Class.classSlots(); while (iter000.nextP()) { slot = ((Slot)(iter000.value)); if (Stella_Object.storageSlotP(slot) && (StorageSlot.nativeSlotP(((StorageSlot)(slot))) && ((((StorageSlot)(slot)).allocation() == Stella.KWD_CLASS) && ((!((StorageSlot)(slot)).slotHardwiredP) && ((!slot.slotMarkedP) && (Slot.nativeSlotHome(slot, renamed_Class) == renamed_Class)))))) { staticmembervardefs = Cons.cons(StorageSlot.cppYieldStaticMemberAllocationTree(((StorageSlot)(slot)), renamed_Class), staticmembervardefs); } } } return (staticmembervardefs); } }
162ed396-cd61-40c1-8536-072d553a1412
8
String exceptionMessage(ExceptionEvent event) { ObjectReference exc = event.exception(); ReferenceType excType = exc.referenceType(); try { // this is the logical approach, but gives "Unexpected JDWP Error: 502" in invokeMethod // even if we suspend-and-resume the thread t /*ThreadReference t = event.thread(); Method mm = excType.methodsByName("getMessage").get(0); t.suspend(); Value v = exc.invokeMethod(t, mm, new ArrayList<Value>(), 0); t.resume(); StringReference sr = (StringReference) v; String detail = sr.value();*/ // so instead we just look for the longest detailMessage String detail = ""; for (Field ff: excType.allFields()) if (ff.name().equals("detailMessage")) { StringReference sr = (StringReference) exc.getValue(ff); String thisMsg = sr == null ? null : sr.value(); if (thisMsg != null && thisMsg.length() > detail.length()) detail = thisMsg; } if (detail.equals("")) return excType.name(); // NullPointerException has no detail msg return excType.name()+": "+detail; } catch (Exception e) { System.out.println("Failed to convert exception"); System.out.println(e); e.printStackTrace(System.out); for (Field ff : excType.visibleFields()) System.out.println(ff); return "fail dynamic message lookup"; } }
aad1d568-7d9f-49cc-824a-a89216ed53b8
8
private void pushTerm(BytesRef text) throws IOException { int limit = Math.min(lastTerm.length(), text.length); //if (DEBUG) System.out.println("\nterm: " + text.utf8ToString()); // Find common prefix between last term and current term: int pos = 0; while (pos < limit && lastTerm.byteAt(pos) == text.bytes[text.offset+pos]) { pos++; } //if (DEBUG) System.out.println(" shared=" + pos + " lastTerm.length=" + lastTerm.length()); // Close the "abandoned" suffix now: for(int i=lastTerm.length()-1;i>=pos;i--) { // How many items on top of the stack share the current suffix // we are closing: int prefixTopSize = pending.size() - prefixStarts[i]; while (prefixTopSize >= minItemsInPrefix) { //if (DEBUG) System.out.println(" pop: i=" + i + " prefixTopSize=" + prefixTopSize + " minItemsInBlock=" + minItemsInPrefix); savePrefixes(i+1, prefixTopSize); //prefixStarts[i] -= prefixTopSize; //if (DEBUG) System.out.println(" after savePrefixes: " + (pending.size() - prefixStarts[i]) + " pending.size()=" + pending.size() + " start=" + prefixStarts[i]); // For large floor blocks, it's possible we should now re-run on the new prefix terms we just created: prefixTopSize = pending.size() - prefixStarts[i]; } } if (prefixStarts.length < text.length) { prefixStarts = ArrayUtil.grow(prefixStarts, text.length); } // Init new tail: for(int i=pos;i<text.length;i++) { prefixStarts[i] = pending.size(); } lastTerm.copyBytes(text); // Only append the first (optional) empty string, no the fake last one used to close all prefixes: if (text.length > 0 || pending.isEmpty()) { byte[] termBytes = new byte[text.length]; System.arraycopy(text.bytes, text.offset, termBytes, 0, text.length); pending.add(termBytes); } }
55c80179-0f2e-4ef6-b8ef-62e5c42a67e5
5
@Test public void depthest11opponent5() { for(int i = 0; i < BIG_INT; i++) { int numPlayers = 6; //assume/require > 1, < 7 Player[] playerList = new Player[numPlayers]; ArrayList<Color> factionList = Faction.allFactions(); playerList[0] = new Player(chooseFaction(factionList), new SimpleAI()); playerList[1] = new Player(chooseFaction(factionList), new DepthEstAI(1,1,new StandardEstimator())); playerList[2] = new Player(chooseFaction(factionList), new SimpleAI()); playerList[3] = new Player(chooseFaction(factionList), new SimpleAI()); playerList[4] = new Player(chooseFaction(factionList), new SimpleAI()); playerList[5] = new Player(chooseFaction(factionList), new SimpleAI()); Color check = playerList[1].getFaction(); GameState state = new GameState(playerList, new Board(), gameDeck, gameBag, score); Set<Player> winners = Game.run(state, new StandardSettings()); boolean won = false; for(Player p : winners) { if(p.getFaction().equals(check)) { won = true; wins++; if(winners.size() > 1) { tie++; } } } if(!won) { loss++; } } assertEquals(true, wins/(wins+loss) > .8); }
c2ecd6cc-8746-409a-9e10-f8a1ee9a6862
3
public static void allocateHuffmanCodeLengths (final int[] array, final int maximumLength) { switch (array.length) { case 2: array[1] = 1; case 1: array[0] = 1; return; } /* Pass 1 : Set extended parent pointers */ setExtendedParentPointers (array); /* Pass 2 : Find number of nodes to relocate in order to achieve maximum code length */ int nodesToRelocate = findNodesToRelocate (array, maximumLength); /* Pass 3 : Generate code lengths */ if ((array[0] % array.length) >= nodesToRelocate) { allocateNodeLengths (array); } else { int insertDepth = maximumLength - (32 - Integer.numberOfLeadingZeros (nodesToRelocate - 1)); allocateNodeLengthsWithRelocation (array, nodesToRelocate, insertDepth); } }
a814b640-c1ad-471c-83a3-a527e5853878
5
private void addJob(ArrayList<String> players, String job, CommandSender sender) { job = job.toLowerCase(); if (PlayerJobs.getJobsList().get(job) == null) { sender.sendMessage(ChatColor.RED + _modText.getAdminCommand("exist", PlayerCache.getLang(sender.getName())).addVariables(job, "", sender.getName())); return; } Iterator<String> it = players.iterator(); while (it.hasNext()) { String play = (String)it.next(); if (play == null) { sender.sendMessage(ChatColor.RED + _modText.getAdminAdd("offline", PlayerCache.getLang(sender.getName())).addVariables(job, "", sender.getName())); return; } if (PlayerCache.hasJob(play, job)) sender.sendMessage(ChatColor.GRAY + _modText.getAdminAdd("hasjob", PlayerCache.getLang(sender.getName())).addVariables(job, play, sender.getName())); else { PlayerCache.addJob(play, job); sender.sendMessage(ChatColor.GRAY + _modText.getAdminAdd("added", PlayerCache.getLang(sender.getName())).addVariables(job, play, sender.getName())); if (Bukkit.getPlayer(play) != null) { PrettyText text = new PrettyText(); String str = ChatColor.GRAY + _modText.getAdminAdd("padded", PlayerCache.getLang(sender.getName())).addVariables(job, play, sender.getName()); text.formatPlayerText(str, Bukkit.getPlayer(play)); } } } }
b6013701-b0ef-4597-8e31-1013d3043ba2
7
public Object nextContent() throws JSONException { char c; StringBuffer sb; do { c = next(); } while (Character.isWhitespace(c)); if (c == 0) { return null; } if (c == '<') { return XML.LT; } sb = new StringBuffer(); for (;;) { if (c == '<' || c == 0) { back(); return sb.toString().trim(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } c = next(); } }
60ac5036-08bd-4606-8c0b-609b2d081ad1
2
@Override public void actionPerformed(ActionEvent e) { OutlinerDocument doc = (OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched(); OutlinerCellRendererImpl textArea = doc.panel.layout.getUIComponent(doc.tree.getEditingNode()); if (textArea == null) { return; } Node node = textArea.node; JoeTree tree = node.getTree(); OutlineLayoutManager layout = tree.getDocument().panel.layout; if (doc.tree.getComponentFocus() == OutlineLayoutManager.ICON) { MergeAction.merge(node, tree, layout, true); } }
34772488-f1e9-4fa8-9e0b-3932afe67f85
3
public static void main(String[] args) { Display.setTitle("This is a game."); try { Display.setDisplayMode(new DisplayMode(1280, 720)); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); System.out.println("Failed to initialize the display"); } GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPushMatrix(); GL11.glLoadIdentity(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDisable(GL11.GL_LIGHTING); GL11.glOrtho(0, 1280, 0, 720, 1, -1); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glLoadIdentity(); BaseTextureLoader.load(); p.setX(640); p.setY(360); //g.setFont(new org,newdawn.slick.Font("Times New Roman", java.awt.Font.PLAIN, 12)); //g.setFont(TTypeF.font); TestRender1.testInit(); while(!Display.isCloseRequested() && !exitOnNextCycle) { sysNano = System.nanoTime(); //Display.setTitle(Mouse.getX() + " " + Mouse.getY()); glClear(GL_COLOR_BUFFER_BIT); BaseRenderer.render(); long done = System.nanoTime(); long d = done - sysNano; //TTypeF.drawString(32, 700, String.format("%d", 1000000000 / d) + " fps", new org.newdawn.slick.Color(1.0f, 1.0f, 0.0f)); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glMatrixMode(GL11.GL_PROJECTION_MATRIX); GL11.glLoadIdentity(); GL11.glPopMatrix(); Display.update(); Display.sync(fps); } Display.destroy(); System.exit(0); }
953e8d7c-9d18-4c76-8417-85b296e284e2
0
public int getMarq(int indice){ return tabMarq[indice]; }
0c648a75-47f3-407f-8884-9e50afb83eca
2
public static boolean anyKeyPress(){ for(int i = 0; i < NUM_KEYS; i++) if(keys[i]) return true; return false; }
6522d39c-294c-4932-b44f-7c1a7209da8f
1
private void toFastboot_adbMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toFastboot_adbMenuActionPerformed try { adbController.rebootDevice(selectedDevice, RebootTo.BOOTLOADER); } catch (IOException ex) { logger.log(Level.ERROR, "An error occurred while rebooting device " + selectedDevice.getSerial() + " to Fastboot: " + ex.toString() + "\n" + "The error stack trace will be printed to the console..."); ex.printStackTrace(System.err); } }//GEN-LAST:event_toFastboot_adbMenuActionPerformed
d1a1e703-1502-4234-8aed-8fd455b29e81
7
public static void main(String[] args) throws Exception //TODO handle exception differently? { engine = GameEngine.getInstance(); MapFactory mf = new MapFactory(50, 50); //this method is where an exception could, but won't, be thrown. GameMap map = mf.createDefaultSizeMap("LargeSwamp"); engine.bindMap(map); //Create Player's Towers Tower p1Tow = new BaseTower(); Point p1Pos = map.getTowerPos(); String p1Name = "Player1", p2Name = "Player2"; Player player = new Player(p1Name, p1Tow, p1Pos.x, p1Pos.y); Tower p2Tow = new StrongTowerDecorator(new BaseTower()); Point p2Pos = map.getTower2Pos(); Player player2 = new Player(p2Name, p2Tow, p2Pos.x, p2Pos.y); int roundCount = 1; //start game engine.display("~~~~~~~Tower Defense Game Framework Demo~~~~~~~"); map.addHomeGrounds(); //Start of core loop while (p1Tow.getHP() > 0 && p2Tow.getHP() > 0) { Scanner scanner = new Scanner(System.in); engine.display("Begin Placement phase..."); engine.display(p1Name + "'s turn: You have " + player.getPoints() + " points available."); takeTurn(player, scanner); engine.display(p2Name + "'s turn: You have " + player2.getPoints() + " points available."); takeTurn(player2, scanner); //start wave phase for (int i = 0; i < 5; i++) { //Report Wave number engine.display("Round " + roundCount + " - Wave " + (i + 1)); //p1 minion spawn Minion p1Min = p1Tow.spawnMinion(); //p2 minion spawn Minion p2Min = p2Tow.spawnMinion(); //spoof minions finding and confronting one another engine.display("Opposing minions have confronted one another. They will engage in combat!"); //minions fight continuously while both are still alive while (p1Min.getHealth() > 0 && p2Min.getHealth() > 0) { //TODO randomise who attacks first maybe? engine.display(p1Name + "'s Minion attacking..."); p1Min.attackObject(p2Min); engine.display(p2Name + "'s Minion attacking..."); p2Min.attackObject(p1Min); } //spoof surviving minion finding its way to enemy tower if (p1Min.getHealth() <= 0) { engine.display(p1Name + "'s Minion is dead, " + p2Name + "'s Minion has found its way to " + p1Name + "'s tower!"); player2.setPoints(player2.getPoints() + 300); p2Min.attackObject(p1Tow); } else { engine.display(p2Name + "'s Minion is dead, " + p1Name + "'s Minion has found its way to " + p2Name + "'s tower!"); player.setPoints(player.getPoints() + 300); p1Min.attackObject(p2Tow); } } roundCount++; } //Game over; One of the players has won. if (p1Tow.getHP() <= 0) { engine.display(p1Name + ", you have won! Congratulations!"); } else { engine.display(p2Name + ", you have won! Congratulations!"); } }
13ce5d60-0f59-460b-9bf2-fb41462ab46b
5
public static ArrayList<Fine> getAllFines(){ try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ArrayList<Fine> fineList = new ArrayList<Fine>(); try { Statement stmnt = conn.createStatement(); String sql = "SELECT * FROM Fines"; ResultSet res = stmnt.executeQuery(sql); while(res.next()) { fine = new Fine(res.getInt("fine_id"), res.getInt("transaction_id"), res.getInt("member_id"), res.getFloat("fine_amount"), res.getBoolean("paid")); fineList.add(fine); } } catch(SQLException e) { System.out.println(e); } return fineList; }
eceb81b1-e1cd-4c21-ad50-a82d90325840
6
private static int partition(int[] a, int lo, int hi) { int i = lo; int j = hi; while(true) { while(a[++i] < a[lo]) { if(i == hi) break; } while(a[lo] < a[--j]) { if(j == lo) break; } if(i >= j) break; exch(a, i, j); } exch(a, lo, j); // Puts the low thing in the middle I guess return j; }
02a53c31-6def-48cd-8545-69adf483974d
3
@Override public void actionPerformed(int ID) { switch(ID){ case 0: this.setVisible(false); guiManager.startGame(); break; case 1: this.setVisible(false); guiManager.showOptionsMenu(); break; case 2: guiManager.closeGame(); break; } }
264454f1-9f30-4c85-820c-c8bea03c08f5
9
public int remap(int oldDocID) { if (oldDocID < minDocID) // Unaffected by merge return oldDocID; else if (oldDocID >= maxDocID) // This doc was "after" the merge, so simple shift return oldDocID - docShift; else { // Binary search to locate this document & find its new docID int lo = 0; // search starts array int hi = docMaps.length - 1; // for first element less while (hi >= lo) { int mid = (lo + hi) >>> 1; int midValue = starts[mid]; if (oldDocID < midValue) hi = mid - 1; else if (oldDocID > midValue) lo = mid + 1; else { // found a match while (mid+1 < docMaps.length && starts[mid+1] == midValue) { mid++; // scan to last match } if (docMaps[mid] != null) return newStarts[mid] + docMaps[mid][oldDocID-starts[mid]]; else return newStarts[mid] + oldDocID-starts[mid]; } } if (docMaps[hi] != null) return newStarts[hi] + docMaps[hi][oldDocID-starts[hi]]; else return newStarts[hi] + oldDocID-starts[hi]; } }
de6cf386-5a7b-4408-9756-00959307f967
8
@Override protected void refreshFromRemote() throws IOException { CachedUrlResolver urlResolver = new CachedUrlResolver(); String urlRef = getUrl().getRef(); String partNum = PartFactory.getInstance().scrapeText(urlRef, startId, endId).toUpperCase(); String queryUrl = queryUrlTemplate.replaceAll("\\{PART\\}", partNum); String price = null; String queryContent = urlResolver.get(new URL(queryUrl)); String title = PartFactory.getInstance().scrapeText(queryContent, startTitle, endTitle); setTitle(title); price = PartFactory.getInstance().scrapeText(queryContent, startPrice, endPrice); if (price != null && price.length() == 0) { HttpURLConnection conn = (HttpURLConnection) new URL(userDataUrl).openConnection(); conn.connect(); Map<String, List<String>> headerFields = conn.getHeaderFields(); List<String> setCookies = headerFields.get("Set-Cookie"); String cookies = ""; if (setCookies != null) { for (String setCookie : setCookies) { cookies += setCookie.split(";")[0] + ";"; } } String detailUrl = detailQueryTemplate.replaceAll("\\{PART\\}", partNum); urlResolver.setBasicAuth("firebom@firepick.org", "McSecret123"); urlResolver.setCookies(cookies); String detailContent = urlResolver.get(new URL(detailUrl)); String[] details = PartFactory.getInstance().scrapeText(detailContent, startDetail, endDetail).split(","); String detailItemString = PartFactory.getInstance().scrapeText(urlRef, startDetailItem, endDetailIndex); int detailItem = 0; try { detailItem = Integer.parseInt(detailItemString) - 1; } catch (NumberFormatException e) { // do nothing } String detailPriceUrl = detailPriceQueryTemplate.replaceAll("\\{DETAIL\\}", details[detailItem]).replaceAll("\\{PART\\}", partNum); urlResolver.setCookies(cookies); String detailPriceContent = urlResolver.get(new URL(detailPriceUrl)); price = PartFactory.getInstance().scrapeText(detailPriceContent, startDetailPrice, endDetailPrice); } if (price != null) { setPackageCost(Double.parseDouble(price)); } String packageUnits = PartFactory.getInstance().scrapeText(queryContent, startPackageUnits, endPackageUnits); if (packageUnits != null) { double value = Double.parseDouble(packageUnits); if (value == 0) { value = 1; } setPackageUnits(value); } setId(partNum); }
3fedfd1a-6a1a-46c9-87a7-1f855e6a94ff
5
private static int show(int t[]) { final char VIDE = '*'; // constante du charactère lorsque la case est vide int i; // contient un compteur String output = ""; // contient le tableau à être afficher // première ligne for(i = 0; i < t.length; i++) { output += "Case "+(i+1); if(i != t.length-1) output += "\t"; } output += "\n"; // deuxième ligne for(i = 0; i < t.length; i++) { if(t[i] == 0) output += "["+VIDE+"]"; else output += "["+t[i]+"]"; if(i != t.length-1) output += "\t"; } JOptionPane.showMessageDialog(null, new JTextArea(output)); return 0; }
433eb9ff-1ebb-4dc8-ba72-f57e096db107
1
public void start(ClassPool pool) throws NotFoundException { classPool = pool; final String msg = "javassist.tools.reflect.Sample is not found or broken."; try { CtClass c = classPool.get("javassist.tools.reflect.Sample"); trapMethod = c.getDeclaredMethod("trap"); trapStaticMethod = c.getDeclaredMethod("trapStatic"); trapRead = c.getDeclaredMethod("trapRead"); trapWrite = c.getDeclaredMethod("trapWrite"); readParam = new CtClass[] { classPool.get("java.lang.Object") }; } catch (NotFoundException e) { throw new RuntimeException(msg); } }
083e5ee5-236a-4693-8eb1-8ac081f71bd6
3
public static HashSet<Row> collectContainerRows(List<Row> rows, HashSet<Row> containers) { for (Row row : rows) { if (row.canHaveChildren()) { containers.add(row); if (row.hasChildren()) { collectContainerRows(row.getChildren(), containers); } } } return containers; }
4d9f3f18-72af-409d-be24-47fd4c411a39
3
public PrimaryApproach() { numGraph = new ArrayList<PositionGraph>(); boxProbability = new Probability [9][9]; for(int j=0;j<9;j++) { for(int k=0;k<9;k++) { boxProbability[j][k]=new Probability (); } } for(int i=0; i < 9; i++){ PositionGraph temp = new PositionGraph(); numGraph.add(temp); } }
c11e9682-072a-4372-98b4-7c082579ed03
2
@Override public void updateIngredient(Ingredient c) throws IngredientRepositoryException { validate(c); for(int i = 0; i<ingredientRepository.size(); i++){ if(ingredientRepository.get(i).getIngredientId() == c.getIngredientId()){ c.setName(c.getName().toUpperCase()); ingredientRepository.set(i, c); return; } } }
81faf190-5776-4648-8b0e-d8827e809460
5
private double calNocturnas(int h1, int m1, double h) { int horaEnt = h1; double minutoEnt = m1; double nocturnas; double horas = h; double ent = horaEnt + (minutoEnt / 60); if (ent <= 6) { nocturnas = (6 - ent); if (nocturnas > horas) { nocturnas = horas; } } else if (ent > 22) { nocturnas = horas; } else { nocturnas = horas - (Math.abs(22 - ent)); } if (nocturnas > 8) { nocturnas = 8; } else if (nocturnas < 0) { nocturnas = 0; } return nocturnas; }
b5b49b45-0576-4fde-bb1c-14cb0adc1e8b
4
public void generateWave() { int numStars,starPosX=0,starPosY=0,starWidth,starHeight,starVelocity, starHgap; int r,g,b; Color starColor; //generate num of stars numStars = MIN_NUM_STARS + (int) (Math.random()*(MAX_NUM_STARS-MIN_NUM_STARS)); //generate stars wave for (int i=0; i<numStars; i++) { //generate star width starWidth = MIN_STAR_WIDTH + (int) (Math.random()*(MAX_STAR_WIDTH-MIN_STAR_WIDTH)); //star is circle, height=width starHeight=starWidth; //generate color r = 100 + (int) (Math.random()*(255-100)); g = 100 + (int) (Math.random()*(255-100)); b = 100 + (int) (Math.random()*(255-100)); starColor = new Color(r,g,b); //set star Hgap starHgap = (int) (Game.SCREEN_DIMENSION.getWidth()-numStars*starWidth)/(numStars+1); //set star pos Y starPosY=-starHeight; //set star pos X if (i!=0) starPosX=waveStars.get(i-1).getPosX() + waveStars.get(i-1).getWidth(); //posX += randomly to starHgap starPosX+=starHgap; if (i==0) starPosX=0; //remove star Hgap left //set velocity starVelocity = (MAX_STAR_WIDTH + 1 - starWidth); //add star. @Param starPosX + random value for remove right star hgap waveStars.add(new Star(starPosX+(int)(Math.random()*starHgap), starPosY, starWidth, starHeight, starColor, starVelocity)); } /* reassemble array with stars. (solve bug with line stars) */ //how much stars to remove? int starsForRemove = (int) (Math.random()*waveStars.size()/2); while (starsForRemove!=0) { waveStars.remove((int)(Math.random()*waveStars.size())); //remove random star for array starsForRemove--; } };
7ff07676-2b70-4bfe-a400-2e5ef8be5d6f
0
public void setCtrFormaPago(String ctrFormaPago) { this.ctrFormaPago = ctrFormaPago; }
bb52a643-eb57-4ea3-b686-74984f395e15
8
public void addViewListener(final YController controller) { this.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { if (ev.getStateChange() == ItemEvent.SELECTED) { // checking if event is really triggered by user... if (!settingModelValue) { // if combo is in "forceListItem" mode and the field is not editable, // we return the last valid value so that the selection is cancelled: if (!isEditable() && forceListItem) { try { setModelValue(validValue); } catch (YException ex) { controller.handleException(ex); } } else { // updating model only if editing has truly stopped (focus is lost from editor): if (!updateModelOnlyWhenFocusLost) { controller.updateModelAndController(YComboBox.this); if (moveCaretInSelection) editorField.setCaretPosition(0); } } } } } }); this.editorField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { if (updateModelOnlyWhenFocusLost) { controller.updateModelAndController(YComboBox.this); } } }); }
3ecd4f0c-41c8-4ca4-9fd7-fd69329f93ec
2
private void writeBit(int bit) throws IOException { if (bit == 0) this.bits <<= 1; else this.bits = this.bits << 1|1; this.offSet++; if (this.offSet == 8) { this.ecrire.write(this.bits); this.bits = 0; this.offSet = 0; } }
05a27880-7d37-46ad-9fc7-22c7cd02cc36
5
public void ejecutarComputadora(String mov){ if(mov != null){ switch(mov){ case "up": this.arriba(); break; case "down": this.abajo(); break; case "left": this.izquierda(); break; case "right": this.derecha(); break; } } }
72b85d8f-2cd2-48da-bee6-d4a4508ab35b
3
protected void _processWalks(WalkArray walkArray, int[] atVertices) { long[] walks = ((LongWalkArray)walkArray).getArray(); long t1 = System.currentTimeMillis(); for(int i=0; i < walks.length; i++) { long w = walks[i]; if (ignoreWalk(w)) { continue; } int atVertex = atVertices[i]; int firstKey = getFirstKey(w, atVertex); int secondKey = getSecondKey(w, atVertex); int value = getValue(w, atVertex); ensureExists(firstKey, secondKey); IntegerBuffer buffer = buffers.get(firstKey).get(secondKey); synchronized (buffer) { buffer.add(value); } } long tt = (System.currentTimeMillis() - t1); if (tt > 1000) { logger.info("Processing " + walks.length + " took " + tt + " ms."); } }
fda32e8c-1579-4cd1-85ca-97081cc38477
8
public MovingObjectPosition collisionRayTrace(World par1World, int par2, int par3, int par4, Vec3 par5Vec3, Vec3 par6Vec3) { MovingObjectPosition amovingobjectposition[] = new MovingObjectPosition[8]; int i = par1World.getBlockMetadata(par2, par3, par4); int j = i & 3; boolean flag = (i & 4) == 4; int ai[] = field_72159_a[j + (flag ? 4 : 0)]; field_72156_cr = true; for (int k = 0; k < 8; k++) { field_72160_cs = k; int ai2[] = ai; int l = ai2.length; for (int j1 = 0; j1 < l; j1++) { int l1 = ai2[j1]; if (l1 != k); } amovingobjectposition[k] = super.collisionRayTrace(par1World, par2, par3, par4, par5Vec3, par6Vec3); } int ai1[] = ai; double d = ai1.length; for (int i1 = 0; i1 < d; i1++) { int k1 = ai1[i1]; amovingobjectposition[k1] = null; } MovingObjectPosition movingobjectposition = null; d = 0.0D; MovingObjectPosition amovingobjectposition1[] = amovingobjectposition; int i2 = amovingobjectposition1.length; for (int j2 = 0; j2 < i2; j2++) { MovingObjectPosition movingobjectposition1 = amovingobjectposition1[j2]; if (movingobjectposition1 == null) { continue; } double d1 = movingobjectposition1.hitVec.squareDistanceTo(par6Vec3); if (d1 > d) { movingobjectposition = movingobjectposition1; d = d1; } } return movingobjectposition; }
7ed75f6a-3ffa-4f1e-a812-ceefe93f266f
2
public static int arrayEqualUntil(char[] a, char[] b, int aStart, int bStart, int length) { for(int i=0;i<length;i++) { if(a[aStart+i] != b[bStart+i]) { return i-1; } } return length-1; }
a59826dd-ea22-4c4a-90fc-b80c123059b0
8
public void addToGroup(GroupAi g, Piece p) { if (p == null || g.pieces.contains(p) || (g.pieces.size() > 0 && g.pieces.toArray(new Piece[0])[0].team != p.team)) { return; } int row = p.where.row; int col = p.where.col; g.pieces.add(p); if (col > 0) { addToGroup(g, squares[row][col - 1].piece); } if (row > 0) { addToGroup(g, squares[row - 1][col].piece); } if (row < 8) { addToGroup(g, squares[row + 1][col].piece); } if (col < 8) { addToGroup(g, squares[row][col + 1].piece); } }
53ecd945-e135-40cc-affb-e257a9ec1cdb
6
public void runMenu () { //do while loop for the menu do { // initialise instance variables displayMainMenu (); promptChoice(); if (choice == 1) { //navigates the user to English to BLISS System.out.println("\f"); getEnglishWord(); getToMenu(); System.out.println("\f"); } else if(choice == 2) { //navigates the user to BLISS to English System.out.println("\f"); getBlissNumber(); getToMenu(); System.out.println("\f"); } else if(choice == 3) { System.out.println("\f"); // navigates the user to the instructions instructions(); getToMenu(); System.out.println("\f"); } else if(choice == 4) { //navigates the user to the dictionary System.out.println("\f"); theTranslator.printTree(); getToMenu(); System.out.println("\f"); } else if(choice == 5) { //exits the program System.out.println("\f"); exit(); } else { //catch incase user enters invalid input System.out.println("\f"); System.out.println("Sorry your option was not found. Please Try again."); } } while(true); }
23553142-09ed-4bb0-a7fb-2091ae3fed64
0
public static int getTotalGamesPlayed() { return totalGamesPlayed; }
687f2fb0-2537-4065-91fb-44b91c33777a
0
public void onTick(Instrument instrument, ITick tick) throws JFException { }
4db81604-7da7-476e-9af1-5cb0b3796dcc
7
public static void checkVersion(){ if(!global.checkUpdate) return; URLDownloader url=new URLDownloader("http://javablock.sourceforge.net/version", ""); //url.get1(); String v; v=url.get1(); String ver=""+global.version; if(true) return ; if(v!=null) if(Integer.parseInt(v)>Integer.parseInt(ver)){ try { int an=JOptionPane.showConfirmDialog(null,translator.get("popup.newVersion"), translator.get("popup.newVersion.head"), JOptionPane.YES_NO_OPTION); if(an==JOptionPane.YES_OPTION) java.awt.Desktop.getDesktop().browse( new URI("http://javablock.sf.net/")); } catch (URISyntaxException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } }
4457eeab-f692-4585-986a-c683cb79174d
5
private boolean legalMove(int from_x,int from_y,int to_x, int to_y) { int dir_x, dir_y; int dist; dir_x=(int)Math.signum(to_x-from_x); dir_y=(int)Math.signum(to_y-from_y); if ((dir_x==0) && (dir_y==0)) return false; dist=computeDistance(from_x,from_y,dir_x,dir_y); if (dir_x==0) return (dist==Math.abs(to_y-from_y)); if (dir_y==0) return (dist==Math.abs(to_x-from_x)); if (Math.abs(to_y-from_y)!=Math.abs(to_x-from_x)) return false; return (dist==Math.abs(to_y-from_y)); }
a0c9625a-8eef-4464-b008-6f8ec7baa2b5
2
public Board generateFromCharArray(char[][] input) { AState[][] map = new AState[input.length][input[0].length]; for(int rowNum = 0; rowNum < input.length; rowNum++) { for(int colNum = 0; colNum < input[rowNum].length; colNum++) { boolean block = input[rowNum][colNum] == 'x'; boolean start = input[rowNum][colNum] == 's'; boolean goal = input[rowNum][colNum] == 'g'; map[rowNum][colNum] = new AState(colNum, rowNum, block, start, goal); } } return new Board(map); }
0b1a126b-f284-4387-9983-dda34bb034e1
3
public static Double[] calculatePrecisionAndRecall() { Double[] precisionAndRecall = new Double[2]; double relevantDocumentsRetrieved = 0; double totalRetrievedDocuments = resultsDocPairs.size(); Iterator it = resultsDocPairs.entrySet().iterator(); while (it.hasNext()) { Map.Entry termEntry = (Map.Entry) it.next(); for (int i = 0; i < knownPlagiarism.size(); i++) { if (termEntry.getKey().equals(knownPlagiarism.get(i))) { relevantDocumentsRetrieved++; } } } double precision = ((relevantDocumentsRetrieved / totalRetrievedDocuments) * 100); double recall = ((relevantDocumentsRetrieved / (knownPlagiarism.size() / 2)) * 100); precisionAndRecall[PRECISION] = precision; precisionAndRecall[RECALL] = recall; return precisionAndRecall; }
71d846a8-648a-469c-b04e-aa5848433724
7
private static void manageExtends(ClassDiagram system, Map<String, RegexPartialMatch> arg, final Entity entity) { if (arg.get("EXTENDS").get(1) != null) { final Mode mode = arg.get("EXTENDS").get(1).equalsIgnoreCase("extends") ? Mode.EXTENDS : Mode.IMPLEMENTS; final String other = arg.get("EXTENDS").get(2); EntityType type2 = EntityType.CLASS; if (mode == Mode.IMPLEMENTS) { type2 = EntityType.INTERFACE; } if (mode == Mode.EXTENDS && entity.getType() == EntityType.INTERFACE) { type2 = EntityType.INTERFACE; } final IEntity cl2 = system.getOrCreateClass(other, type2); LinkType typeLink = new LinkType(LinkDecor.NONE, LinkDecor.EXTENDS); if (type2 == EntityType.INTERFACE && entity.getType() != EntityType.INTERFACE) { typeLink = typeLink.getDashed(); } final Link link = new Link(cl2, entity, typeLink, null, 2, null, null, system.getLabeldistance(), system.getLabelangle()); system.addLink(link); } }
ce9f0c0b-508f-40df-b345-368b719353c4
9
public synchronized void checkThread(Callable workToDo, Callable callback, Integer limitRate) throws DropCountExceededException { if (workToDo != null) { try { this.checkThread(null, callback, null); workToDo.call(); this.releaseThread(); } catch (Exception e) { throw new DropCountExceededException(e); } } else { Method callingMethod = queryCallingMethod(); LOGGER.debug("method = {} : {}", callingMethod, channelCount.containsKey(callingMethod)); Integer localLimitRate; if (callingMethod.getAnnotation(LimitRate.class) != null) { localLimitRate = callingMethod.getAnnotation(LimitRate.class).value(); } else { if (callingMethod.getAnnotation(LimitRateProperty.class) != null) { String propertyName = callingMethod.getAnnotation(LimitRateProperty.class).name(); localLimitRate = Integer.parseInt(System.getProperty(propertyName)); } else { localLimitRate = limitRate; } } if (localLimitRate == null) { throw new DropCountExceededException("Could not evaluate LimitRate value!"); } if (channelCount.containsKey(callingMethod)) { if (channelCount.get(callingMethod).getMaxCount() != localLimitRate) { channelCount.remove(callingMethod); channelCount.put(callingMethod, new VO(localLimitRate)); } } else { channelCount.put(callingMethod, new VO(localLimitRate)); } LOGGER.debug("[{}] maxCount:{}", callingMethod, channelCount.get(callingMethod).getMaxCount()); LOGGER.debug("[{}] threadCount:{}", callingMethod, channelCount.get(callingMethod).getThreadCount()); if (channelCount.get(callingMethod).getThreadCount().get() < channelCount.get(callingMethod).getMaxCount()) { channelCount.get(callingMethod).getThreadCount().incrementAndGet(); } else { if (callback == null) { throw new DropCountExceededException(); } else { callback.call(); } } } }
6ee0775c-1382-4827-ab1b-85bb5ae37c34
9
public void init(){ String incoming = null; int currentIndex = 0; BufferedReader input; Socket connectionSocket; boolean rulesSend = false; try{ serverSocket = new ServerSocket(port); System.out.println("Server is running at port " +port); while(true){ try{ if(serverSocket.isClosed()){ serverSocket = new ServerSocket(port); connectionSocket = serverSocket.accept(); input = new BufferedReader(new InputStreamReader(connectionSocket. getInputStream())); } //are listening to connectionSocket = serverSocket.accept(); //Read the request from the client from the socket interface //into the buffer. input = new BufferedReader(new InputStreamReader(connectionSocket. getInputStream())); /* * magic number * 26 is the number of letters in Latin alphabet */ if(clients.size()>=26){ PrintStream os = new PrintStream(connectionSocket.getOutputStream()); os.println(EXIT); os.close(); System.out.println("Closing socket"); connectionSocket.close(); } incoming = input.readLine(); if(incoming.matches(PLAYER_NAME_PREFIX+".+")){ incoming = incoming.substring(incoming.indexOf(";")+1); Connection c = new Connection(connectionSocket, incoming, ++playerID); c.playerSymbol = symbols[symbolIndex]; ++symbolIndex; PlayerData p = new PlayerData(c.playerName, c.playerSymbol, c.playerID); playerList.put(c.playerID, p); clients.add(c); incoming=null; } if(clients.size()>=2){ if(!rulesSend){ sendRulesToPlayers(); rulesSend = true; } playTheGame(nextPlayer()); } if(clients.size()>2){ // add new player and send him game rules String tempSymbol=getNewSymbol(); Connection player = clients.get(currentIndex); clients.get(currentIndex).playerSymbol = tempSymbol; addPlayer(clients.get(currentIndex)); player.send("#"+Integer.toString(size)); player.send("#"+Integer.toString(symNum)); player.send("#"+Integer.toString(player.playerID)); player.send("#"+tempSymbol); sendMessageToPlayers(NEW_PLAYER+";"+player.playerName+";"+player.playerID+";"+player.playerSymbol, player); } currentIndex++; }catch(Exception e){ System.out.println("Error: EXCEPTION"); System.out.println("Error: CAUSE: "+e.getCause()); e.printStackTrace(); } } }catch(IOException e){ System.out.println("ERROR: \n"+e.getMessage()); } }
544a14b7-aa54-42e5-bad9-6e697c2666b4
0
public final AbstractHash<K> getHash() { return hash; }
532d9ccf-3cd7-4724-b6f9-dd2039e801cd
5
private Color verticalWinner() { for (int i = 0; i < board.length; i++) { Color current = Color.NONE; int length = 0; for (int j = 0; j < board[0].length; j++) { if (current == board[i][j]) { length += 1; } else { current = board[i][j]; length = 1; } if (length >= 4 && current.isNotNone()) { return current; } } } return Color.NONE; }
d5e4a029-44ef-4b72-992a-69efd3fcc224
8
public ArrayList<SalesStaticsBean> querySales(String main_type,String name,String issue_date_begin ,String issue_date_end){ ArrayList<SalesStaticsBean> al = new ArrayList<SalesStaticsBean>(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; SalesStaticsBean s = null; try { conn = DBUtils.getConnection(); String sql = "select orders.issue_date odate,products.product_seq seq,products.name pname,order_product.num num,order_product.num*products.price total from order_product,orders,products where order_product.order_seq=orders.order_seq and order_product.product_seq=products.product_seq and products.name Like ?"; if(main_type != null&&!(main_type.equals(""))){ sql +="and products.product_seq='"+main_type+"'"; } if(issue_date_begin != null&&!(issue_date_begin.equals(""))){ sql += "and orders.issue_date>=to_date('"+issue_date_begin+"','yyyy-mm-dd')" ; } if(issue_date_end != null&&!(issue_date_end.equals(""))){ sql += "and orders.issue_date<=to_date('"+ issue_date_end +"','yyyy-mm-dd')" ; } pstmt = conn.prepareStatement(sql); pstmt.setString(1, '%'+name+'%'); rs = pstmt.executeQuery(); while(rs.next()) { s = new SalesStaticsBean(); String date = rs.getString("odate"); String product_type = rs.getString("seq"); String product_name = rs.getString("pname"); int num = Integer.parseInt(rs.getString("num")); double total = Double.parseDouble(rs.getString("total")); s.setDate(date); s.setProduct_type(product_type); s.setProduct_name(product_name); s.setNum(num); s.setTotal(total); al.add(s); } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtils.closeDB(conn, pstmt, rs); } return al; }
650bc1f5-70d6-45d1-8c55-232b5e5fb35c
3
public void actionPerformed(ActionEvent event) { // ActionEvent from "connect" Button if(event.getSource() == buttonConnect) { String host = txtHost.getText(); int port = Integer.parseInt(txtPort.getText()); try { // Generate a TCP Client and start it as a Thread tcpclient = new TCPClient(new Socket(host, port), txtConsole); tcpclient.start(); tcpclient.send(txtName.getText()); // Update UI txtHost.setEnabled(false); txtPort.setEnabled(false); txtName.setEnabled(false); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Es konnte keine Verbindung hergestellt werden!", "Fehler", JOptionPane.ERROR_MESSAGE); } } // ActionEvent from "send" Button if(event.getSource() == buttonSend) { String msg = txtMessage.getText(); tcpclient.send(msg); } }
74342f28-a57a-4cf5-8429-2caa44354f7c
3
public static void main(String[] args) { // ResultSetHandler<Object[]> resultSetHandler = new ResultSetHandler<Object[]>() { // public Object[] handle(ResultSet rs) throws SQLException { // if (!rs.next()) { // return null; // } // // ResultSetMetaData meta = rs.getMetaData(); // int cols = meta.getColumnCount(); // Object[] result = new Object[cols]; // // for (int i = 0; i < cols; i++) { // result[i] = rs.getObject(i + 1); // } // // return result; // } // }; ResultSetHandler<List<User>> resultSetHandler = new BeanListHandler<User>(User.class); Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "123456"); QueryRunner run = new QueryRunner(); List<User> u = run.query( conn, "SELECT * FROM user WHERE id=?", resultSetHandler, "1"); System.out.println(u.get(0).getBirthday()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { DbUtils.close(conn); } catch (SQLException e) { e.printStackTrace(); } } }
9b2ed469-4c45-427a-aa9e-c8f551a9c794
1
public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } }
425f93f4-b905-4526-863d-0d343361df25
8
public static void main(String[] args) { Assert.checkNonNull(inputFileName, "InputFileName cannot be null"); try { // String buffer for storing the output StringBuilder output = new StringBuilder(); // read and parse input file URL fileUrl = classLoader.getResource(inputFileName); if (fileUrl == null) { System.out.println("File URL null. EXITING!"); return; } String filePath = fileUrl.getPath(); BufferedReader reader = Files.newBufferedReader(Paths.get(filePath), StandardCharsets.UTF_8); String strLine; int lineNumber = 0; int noOfTestCases = -1; int activeTestCaseNumber = 0; int lineInTestCase = 0; int answer1 = -1; int answer2 = -1; List<String> round1Rows = new ArrayList<>(); List<String> round2Rows = new ArrayList<>(); while ((strLine = reader.readLine()) != null) { if (lineNumber == 0) { noOfTestCases = Integer.parseInt(strLine); activeTestCaseNumber ++; lineInTestCase ++; } else { if (lineInTestCase <= 10) { if (lineInTestCase == 1) { answer1 = Integer.parseInt(strLine); } else if (lineInTestCase == 6) { answer2 = Integer.parseInt(strLine); } else { if (answer2 == -1) { round1Rows.add(strLine); } else { round2Rows.add(strLine); } } lineInTestCase ++; } else { // Now that a test case has been parsed, compute output for // this test case // Invoke algorithm here String solutionToTestCase = compute(answer1, answer2, round1Rows, round2Rows); // Prepare output string System.out.println(solutionToTestCase); output.append("Case #").append(activeTestCaseNumber).append(": ").append(solutionToTestCase); output.append("\n"); // Prepare next test case answer1 = Integer.parseInt(strLine); lineInTestCase = 2; answer2 = -1; round1Rows = new ArrayList<>(); round2Rows = new ArrayList<>(); activeTestCaseNumber ++; } } lineNumber++; } // Compute last test case String solutionToTestCase = compute(answer1, answer2, round1Rows, round2Rows); // Prepare output string System.out.println(solutionToTestCase); output.append("Case #").append(activeTestCaseNumber).append(": ").append(solutionToTestCase); output.append("\n"); // Pass output string to method to write to file writeOutputToFile(output.toString()); } catch (IOException e) { e.printStackTrace(); } }
b3965bf9-6752-468e-9aed-7760519552ac
9
private byte[] loadCompressedBinaryData(InputStream is) throws IOException, UnsupportedEncodingException { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int bytesRead; // load md5 sum MessageDigest md; try { md = MessageDigest.getInstance(DIGEST_MD52); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } byte[] md5 = new byte[md.getDigestLength()]; bytesRead = is.read(md5, 0, md5.length); if (bytesRead != md.getDigestLength()) throw new IOException(UNEXPECTED_END_OF_FILE); // load size bytesRead = is.read(buffer, 0, 4); if (bytesRead != 4) throw new IOException(UNEXPECTED_END_OF_FILE); int dataSize = (((int) buffer[3] & 0xFF) << 24) | (((int) buffer[2] & 0xFF) << 16) | (((int) buffer[1] & 0xFF) << 8) | ((int) buffer[0] & 0xFF); log.debug("uncompressed file size: " + dataSize); GZIPInputStream gzipIs = new GZIPInputStream(is); while ((bytesRead = gzipIs.read(buffer)) != -1) { md.update(buffer, 0, bytesRead); output.write(buffer, 0, bytesRead); if (dumpData) System.out.print(new String(buffer, 0, bytesRead, CHARSET_cp1252)); } if (dumpData) System.out.println(); buffer = md.digest(); for (int i = 0; i < buffer.length; i++) if (buffer[i] != md5[i]) throw new IOException("MD5 mismatch"); if (output.size() != dataSize) throw new IOException(String.format( "File size mismatch: %d instead of %d", output.size(), dataSize)); log.debug("MD5 ok"); return output.toByteArray(); }
a0013efd-1212-4d05-8375-0ab0d4495b04
5
public void close() { if (_isAlive){ try { _clientSocket.close(); if (_in != null){ _clientSocket.shutdownInput(); _in.close(); } if (_out != null){ _clientSocket.shutdownOutput(); _out.close(); } } catch (IOException e){ if (!_serverStop.getValue()) System.out.println("Exception in closing I/O"); } } }
6ddcb3a7-e014-450a-bb33-1f9608b59ac1
0
public Status getByValue(String value) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Status.class); criteria.add(Restrictions.eq("value", value)); return (Status) criteria.uniqueResult(); }
4fbd58c6-6bf1-4190-807a-791281353210
4
public boolean ColumnExists(Connection conn, String tname, String cname) { DatabaseMetaData md; ResultSet rs; try { md = conn.getMetaData(); } catch (SQLException e) { // This shouldn't really happen plugin.Warn("Unable to read DatabaseMetaData from DB connection!"); e.printStackTrace(); return false; } try { plugin.Debug("Getting list of table columns"); rs = md.getColumns(null, null, tname, cname); } catch (SQLException e) { // This shouldn't really happen plugin.Warn("Unable to getColumns from DatabaseMetaData!"); e.printStackTrace(); return false; } try { if (rs.next()) { // Table exists return true; } } catch (SQLException e) { // This shouldn't really happen plugin.Warn("Unable to iterate column resultSet!"); e.printStackTrace(); } return false; }
781eb604-2c5c-46b8-b530-201c5e2a08df
2
public void addMacro(String name, String command){ if(!macros.containsKey(name)) { // we have a new macro println("/"+name+" {"+command+"} def"); macros.put(name, command); } else { if(!macros.get(name).equals(command)){ //print it as it is different to the one specified before with the same name println("/"+name+" {"+command+"} def"); //replace the one in the map by this one. macros.put(name, command); } } }
87a85b5e-e938-45a2-9e35-7e22fe4c7549
6
* @param unit The <code>Unit</code> to load. * @param goods The <code>Goods</code> to load. * @return An <code>Element</code> encapsulating this action. */ public Element loadCargo(ServerPlayer serverPlayer, Unit unit, Goods goods) { ChangeSet cs = new ChangeSet(); Location oldLocation = goods.getLocation(); goods.adjustAmount(); moveGoods(goods, unit); boolean moved = false; if (unit.getInitialMovesLeft() != unit.getMovesLeft()) { unit.setMovesLeft(0); moved = true; } Unit oldUnit = null; if (oldLocation instanceof Unit) { oldUnit = (Unit) oldLocation; if (oldUnit.getInitialMovesLeft() != oldUnit.getMovesLeft()) { oldUnit.setMovesLeft(0); } else { oldUnit = null; } } // Update the goodsContainers only if within a settlement, // otherwise update the shared location so that others can // see capacity changes. if (unit.getSettlement() != null) { cs.add(See.only(serverPlayer), oldLocation.getGoodsContainer()); cs.add(See.only(serverPlayer), unit.getGoodsContainer()); if (moved) { cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); } if (oldUnit != null) { cs.addPartial(See.only(serverPlayer), oldUnit, "movesLeft"); } } else { cs.add(See.perhaps(), (FreeColGameObject) unit.getLocation()); } // Others might see capacity change. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); }
a18df3bf-7057-4821-b3ac-51e519932a64
4
@Override public ByteBuffer getMessage() { buffer.clear(); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putShort((short) 0xaaa6); // sig buffer.putShort((short) 40); // byte len buffer.put((byte) 1); // rcmNodeId; buffer.put((byte) 0); // reserved for (short val : pwm) { buffer.putShort(val); } for (byte val : relay) { buffer.put(val); } for (byte val : solenoid) { buffer.put(val); } for (byte val : led) { buffer.put(val); } buffer.put((byte) 0); // empty short checksum = (short) Utilities.checksum(buffer, 0, 38); buffer.putShort(checksum); return buffer; }
368b14b4-3236-41c7-afe8-09b3fd9a1ebe
4
AbstractNode term() { AbstractNode node = factor(); while (test(MUL) || test(DIV)) { if (test(MUL)) { read(MUL, "*"); node = new BinOpNode(MUL_OP, node, factor()); } else if (test(DIV)) { read(DIV, "/"); node = new BinOpNode(DIV_OP, node, factor()); } } return node; }
c750114c-2912-4930-88fc-f3e87baeaf16
5
@Override public void actionPerformed(ActionEvent e) { try { if (e.getSource() == this.view.getJbCancel()) { this.view.dispose(); } else if (e.getSource() == this.view.getJbLoad()) { if (this.view.getJtTable().getSelectedRow() >= 0) { int rowIndex = this.view.getJtTable().getSelectedRow(); Workflow wf = new Workflow(Integer.parseInt((String)this.view.getJtTable().getValueAt(rowIndex, 0))); SimulationFrame simulationFrame = new SimulationFrame(); wf.InitWorkflow(true); Shared.getInstance().setWf(wf); SimulationFrameController simulationFrameController = new SimulationFrameController(simulationFrame); simulationFrame.setActionListener(simulationFrameController); if (((String)this.view.getJtTable().getValueAt(rowIndex, 3)).equals("YES")) { Shared.getInstance().setAutorecover(true); } else { Shared.getInstance().setAutorecover(false); } this.view.dispose(); this.view.getCaller().dispose(); } } else { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } catch (Exception ex) { //JOptionPane.showMessageDialog(null, "Error: "+ ex.getMessage(), "Autentification error" , JOptionPane.ERROR_MESSAGE); System.err.println(ex.getMessage()); } }
bfe8f0e0-3482-4d12-847b-30342a04892c
7
@Override public boolean save(News news) throws DaoException { if (null == news) { return false; } PooledConnection connection = null; PreparedStatement pStatement = null; try { connection = (PooledConnection) cp.takeConnection(); pStatement = connection.prepareStatement(NewsDaoStatement.createNews.getStatement(), new String[] {NewsFields.ID.getContent()}); pStatement.setString(1, news.getTitle()); pStatement.setString(2, news.getBrief()); pStatement.setString(3, news.getContent()); pStatement.setDate(4, news.getDate()); int result = pStatement.executeUpdate(); if (result > 0) { ResultSet rs = pStatement.getGeneratedKeys(); if (rs.next()) { news.setId(rs.getInt(1)); return true; } else { throw new DaoException("Id was not generated"); } } else { return false; } } catch (NoConnectionException | ConnectionSQLException e) { log.error("Can't take connection from ConnectionPool", e); throw new DaoException("Can't take connection from ConnectionPool", e); } catch (SQLException e) { log.error("Error in SQL statement " + NewsDaoStatement.createNews.getStatement(), e); throw new DaoException("Error in SQL statement " + NewsDaoStatement.createNews.getStatement(), e); } finally { if (null != connection) { try { this.closeStatement(pStatement); cp.releaseConnection(connection); } catch (ConnectionSQLException e) { log.error("Can't release connection back", e); throw new DaoException("Can't release connection back", e); } } } }
cd63254d-3dc8-4550-9b7c-2c9187e3edec
8
@Override public void cover(ImageBit[][] list) { ImageBit ib = new ImageBit(); for (int i = 0; i < 50; i++) { for (int j = 0; j < 50; j++) { ib = list[i][j]; if (ib.isCovered()) { continue; } LegoUtil.cover(ib, list, this.width, this.height, BlockType.SixAndOne); if (ib.isCovered()) { System.out.println(ib.getX() + "," + ib.getY() + "," + ib.getRGB() + "," + ib.isCovered() + "," + ib.getBlockType()); sixAndOneList.add(ib); draw(g, ib, this.width, this.height); } } } for (int i = 0; i < 50; i++) { for (int j = 0; j < 50; j++) { ib = list[i][j]; if (ib.isCovered()) { continue; } LegoUtil.cover(ib, list, this.height, this.width, BlockType.OneAndSix); if (ib.isCovered()) { System.out.println(ib.getX() + "," + ib.getY() + "," + ib.getRGB() + "," + ib.isCovered() + "," + ib.getBlockType()); oneAndSixList.add(ib); draw(g, ib, this.height, this.width); } } } }
ce18025c-8fea-4c28-bace-5b314f37ffca
6
@Override public void buttonClicked(ButtonEvent event) { switch (event.getButton().getType()) { case SERVER: if (event.getButton().isActive()) networkHandler.shutDown(); else networkHandler.startServer(port); break; case CLIENT: if (event.getButton().isActive()) networkHandler.shutDown(); else networkHandler.startClient(hostname, port); break; case SUBMIT: updateConfig(event); toggleOptions(); break; case OPTIONS: toggleOptions(); break; } }
3c5a1b75-cc66-4ad6-ad29-d6118e711d0f
6
public Shape(SimpleFeature f, String tipo){ // Algunos conversores de DATUM cambian el formato de double a int en el .shp // FECHAALATA y FECHABAJA siempre existen if (f.getAttribute("FECHAALTA") instanceof Double){ double fa = (Double) f.getAttribute("FECHAALTA"); fechaAlta = (long) fa; } else if (f.getAttribute("FECHAALTA") instanceof Long){ fechaAlta = (Long) f.getAttribute("FECHAALTA"); } else if (f.getAttribute("FECHAALTA") instanceof Integer){ int fa = (Integer) f.getAttribute("FECHAALTA"); fechaAlta = (long) fa; } else System.out.println("["+new Timestamp(new Date().getTime())+"] No se reconoce el tipo del atributo FECHAALTA " + f.getAttribute("FECHAALTA").getClass().getName()); if (f.getAttribute("FECHABAJA") instanceof Integer){ int fb = (Integer) f.getAttribute("FECHABAJA"); fechaBaja = (long) fb; } else if (f.getAttribute("FECHABAJA") instanceof Double){ double fb = (Double) f.getAttribute("FECHABAJA"); fechaBaja = (long) fb; } else if (f.getAttribute("FECHABAJA") instanceof Long){ fechaBaja = (Long) f.getAttribute("FECHABAJA"); } else System.out.println("["+new Timestamp(new Date().getTime())+"] No se reconoce el tipo del atributo FECHABAJA" + f.getAttribute("FECHABAJA").getClass().getName()); // Si queremos coger todos los atributos del .shp /*this.atributos = new ArrayList<ShapeAttribute>(); for (int x = 1; x < f.getAttributes().size(); x++){ atributos.add(new ShapeAttribute(f.getFeatureType().getDescriptor(x).getType(), f.getAttributes().get(x))); }*/ }
92ddd8f5-889f-4d03-a88f-cdf6d4dcd495
3
public static void getTraitDescription(Tidy tidy, Document doc, Trait[] traits) { try { XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("//div[@id = 'bodyContent']/p/text() |" + "//div[@id = 'bodyContent']/p/a/text()"); NodeList nodes = (NodeList)expr.evaluate(doc, XPathConstants.NODESET); String totalString = ""; for(int i = 5; i < nodes.getLength(); i++) { totalString += nodes.item(i).getNodeValue(); } String[] traitDescriptions = totalString.split("Per point:"); for(int i = 0; i < 5; i++) { traits[i].setDescription(traitDescriptions[i]); } }catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
4a56790c-661c-4a5c-96c0-dd2325fe2bef
2
public MWUizer(String resource) { InputStream myResource = getClass().getResourceAsStream(resource); if (myResource == null) { MWUSet=new HashSet<String>(); System.err.println("I couldn't open the resource "+resource); System.exit(0); } else { MWUSet = loadResource(myResource); try { myResource.close(); } catch (IOException e) { } } MWUSpacers=new HashSet<String>(); MWUSpacers.add("<p>"); MWUSpacers.add("<br>"); MWUSpacers.add("&nbsp;"); MWUSpacers.add("<u>"); MWUSpacers.add("</u>"); MWUSpacers.add("<small>"); MWUSpacers.add("</small>"); }
58431f0c-613e-41c3-a5ad-4b02c57c19be
0
public FromFileGridFactory(String filename) { this.filename = filename; }
72a0bd28-a292-4264-a807-d382714810fc
1
public final void unlink() { if (previous == null) { } else { previous.next = next; next.previous = previous; next = null; previous = null; } }
410ff6c3-5ef6-41db-b0ae-b03c7e6e639c
9
public static void parse(File csvFile) { BufferedReader br = null; String line = ""; String cvsSplitBy = " = "; try { HashMap<String, String> map = new HashMap<String, String>(); br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { String[] property = line.split(cvsSplitBy); if(property.length <2) break; if (property[0].contains("SessionID")) property[0] = "SessionID"; map.put(property[0], property[1].replaceAll("^\"|\"$", "").trim()); //System.out.println("label= " + property[0] + " , value=" + property[1].replaceAll("^\"|\"$", "").trim() + "]"); } Speaker speaker = new Speaker(map); do{ //System.out.println(line); String[] split = line.split("\\s+\"\\S+\"\\s+"); //System.out.println("label= " + split[0] + " , value=" + split[1].replaceAll("^\"|\"$", "").trim() + "]"); String filename = split[0]; String path = ""; if(!(split[0].equalsIgnoreCase(Globals.NO_RECORDING))) path = csvFile.getParent()+File.separator; String question = split[1].substring(1, split[1].length()-1).trim(); //System.out.println(split[1]); db.updateDatabase(path, filename, question, speaker); } while ((line = br.readLine()) != null); read = read + "\n- "+ csvFile.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }
ae9e14fe-29ab-4009-8567-d33c7b5daa4c
0
@Override public void keyTyped(KeyEvent e) { unprocessedEvents.add(e); }
b40a7eb8-2a08-4b67-889e-1c083b79d6a4
3
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tests = sc.nextInt(); String []in = new String[tests]; int i=0; while(tests>0 && i<in.length){ tests--; in[i] = sc.next(); i++; } for (String str : in){ System.out.println(solve(str)); } sc.close(); }
bfc7dc4e-6cde-4bf2-a9b1-8e2e07818cc5
7
public static LinkedList addlists(LinkedList a, LinkedList b){ LinkedList result=new LinkedList(); //Logic is to iterate node by node and do simple addition of the digits as you iterate through the nodes //create two iterator nodes Node ita=a.head; Node itb=b.head; int carry=0; while(ita!=null || itb!=null){ //add the digits if(ita!=null&&itb!=null){ int val=ita.getData()+itb.getData()+carry; if(val>=10){ val=val%10; carry=1; } else{ carry=0; } result.addToEnd(val); ita=ita.next; itb=itb.next; }else if(ita!=null){ int val=ita.getData(); result.addToEnd(val); ita=ita.next; }else{ int val=itb.getData(); result.addToEnd(val); itb=itb.next; } } if(carry==1){ result.addToEnd(1); } return result; }
44326dc7-847a-404a-baa5-6e0b358d86a9
3
private int italicHandler(char[] chars, int i) { basicText.append("\\i "); String plainWord = ""; while (chars[i] != ' ') i++; i++; while (chars[i] != '}' && i < chars.length) { plainWord = plainWord + chars[i]; i++; } basicText.append(plainWord); basicText.append(" \\i"); return i; }
1fed1586-2d0d-4c50-91d2-2e080f93bf15
2
public synchronized void recordAndAddSequenceNumberToOutgoingPacket(Packet packet) { //ignore null packets if(packet == null) return; //add sequence number to packet lastSentPacketSequenceNumber = Packet.nextSequenceNumber(lastSentPacketSequenceNumber); packet.setSequenceNumber(lastSentPacketSequenceNumber); //add packet to array of sent packets lastSentPacketIndex++; if(lastSentPacketIndex == PacketRecorder.NUM_SENT_PACKETS_STORED) lastSentPacketIndex = 0; sentPackets[lastSentPacketIndex] = new PacketReceipt(packet); }
ee42aaa8-4b76-4ea9-aff4-1f5ec5ce7da5
6
public boolean validationSplit(String input) { // initialise instance variables boolean validated = false; String[] firstValidationArray = input.split(";"); //for loop that has an array to validate bliss numbers. for(int i=0;i< firstValidationArray.length;i++) { String[] secondValidationArray = firstValidationArray[i].split(","); for(int z=0;z< secondValidationArray.length;z++) { //try & catch method try { int validatingInts = Integer.parseInt(secondValidationArray[z]); if (validatingInts >= 1 && validatingInts <= 32 || validatingInts >= 101) { //if number is bigger than 1 and less than 32 or less than 101 validated = true; } else { //if not then return this validated = false; } } catch (NumberFormatException nfe) { //error prevention catch validated = false; } } } return validated; }
9d733abf-81fd-40b0-b1b6-a140f3b5138c
0
public void setColumnValue(Object columnValue) { this.columnValue = columnValue; }
53b5e528-a2ee-4168-ad62-661e5f365ab6
9
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TeamMapKey other = (TeamMapKey) obj; if (map == null) { if (other.map != null) { return false; } } else if (!map.equals(other.map)) { return false; } if (team == null) { if (other.team != null) { return false; } } else if (!team.equals(other.team)) { return false; } return true; }
f475b2a4-ea47-4bea-945f-e50e986dc3ca
4
@Test public void testTwitter() throws InterruptedException { try { loadDocument(); } catch (ParserConfigurationException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (SAXException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } // Create a new instance of the Firefox driver // Notice that the remainder of the code relies on the interface, // not the implementation. WebDriver driver = new FirefoxDriver(); // And now use this to visit Twitter driver.get("https://twitter.com"); // Alternatively the same thing can be done like this // driver.navigate().to("https://twitter.com"); // should open the sign-in page // Could be slow ... WebElement waitForPageLoad = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.presenceOfElementLocated(By.xpath("//button[@class = 'submit btn primary-btn flex-table-btn js-submit']"))); // Are you signed in auto? No? WebElement signInNeeded = driver.findElement(By.xpath("//button[@class = 'submit btn primary-btn flex-table-btn js-submit']")); // This is OK for confirming the page, but could be dangerous for input -- there are a couple if (signInNeeded != null) { signIn(driver); } else { // We're signed into the account and on our Home (feed) page, so change the password changePassword(driver); } };
8514fcf8-8df7-48bd-ab05-ba05fc1ebb6b
5
public TaskList read(File importFile) throws TaskIOException { if (importFile == null) { log.warn(ApplicationSettings.getInstance().getLocalizedMessage("log.err.file")); return new TaskList("Empty"); } m_taskList = new TaskList(importFile.getName()); log.info(ApplicationSettings.getInstance().getLocalizedMessage("log.read.file") + " " + importFile.getName()); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp; try { sp = spf.newSAXParser(); SAXHandler sh = new SAXHandler(); sp.parse(importFile, sh); } catch (ParserConfigurationException e) { String error = ApplicationSettings.getInstance().getLocalizedMessage("txmlfr.createsax") + ": " + e.getLocalizedMessage(); log.error(error); throw new TaskIOException(error); } catch (SAXException e) { String error = ApplicationSettings.getInstance().getLocalizedMessage("txmlfr.createsax") + ": " + e.getLocalizedMessage(); log.error(error); throw new TaskIOException(error); } catch (IOException e) { String error = ApplicationSettings.getInstance().getLocalizedMessage("txmlfr.io") + ": " + e.getLocalizedMessage(); log.error(error); throw new TaskIOException(error); } catch (Exception e) { log.error(e.getLocalizedMessage()); throw new TaskIOException(ApplicationSettings.getInstance().getLocalizedMessage("log.err.tlparse")); } return m_taskList; }
a1ac0846-3c34-4c80-9f2c-932de7d6ab3b
2
public static void main(String[] args) { Random rand = new Random(47); Map<Integer, Integer> m = new HashMap<Integer, Integer>(); for (int i = 0; i < 10000; i++) { // Produce a number between 0 and 20: int r = rand.nextInt(20); Integer freq = m.get(r); m.put(r, freq == null ? 1 : freq + 1); } System.out.println(m); }
780a3656-e52d-4e9b-92bb-ccafdf1ea740
6
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(VtnTipoReporte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VtnTipoReporte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VtnTipoReporte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VtnTipoReporte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VtnTipoReporte().setVisible(true); } }); }
dc8281a3-ac63-4297-96ea-d1f7c9c33609
1
public static FavoritesWindow getInstance() { if (instance == null) instance = new FavoritesWindow(); return instance; }
7fb60671-f32f-4aba-b599-296c348ffa05
2
public ReachableFieldsOnChessboard() { Chessboard chessBoard = new Chessboard (); Chessboard.Chesspiece[] pieces = new Chessboard.Chesspiece[6]; pieces[0] = chessBoard.new Pawn ('w', 'P'); pieces[1] = chessBoard.new Rook ('b', 'R'); pieces[2] = chessBoard.new Queen ('w', 'Q'); pieces[3] = chessBoard.new Bishop ('w', 'B'); pieces[4] = chessBoard.new King ('b', 'K'); pieces[5] = chessBoard.new Knight ('w', 'N'); for(int i = 0; i < pieces.length; i++) { try { pieces[i].moveTo(pieces[i].row, pieces[i].column); pieces[i].markReachableFields(); System.out.println(chessBoard); pieces[i].unmarkReachableFields(); pieces[i].moveOut(); } catch (NotValidFieldException e) { e.printStackTrace(); } } }