method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
95cb3649-ea35-455e-8759-4e8063ee9188
6
private void button3MousePressed(MouseEvent event) { if (!button3.isEnabled()) { return; } JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setDialogTitle("Trove Install Location"); if (TroveUtils.getTroveInstallLocation() != null) { chooser.setCurrentDirectory(new File(TroveUtils.getTroveInstallLocation())); } else { chooser.setCurrentDirectory(new File(".")); } int response = chooser.showOpenDialog(null); if (response == JFileChooser.OPEN_DIALOG) { File folder = chooser.getSelectedFile(); if (folder.isDirectory()) { if (!((new File(folder + File.separator + "Trove.exe")).exists())) { int dialogOption = JOptionPane.showOptionDialog(null, "Trove.exe is not found in this directory!\nAre you sure you want to change it to this directory?", "Trove Mod Loader", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null); if (dialogOption == JOptionPane.OK_OPTION) { setDirectory(folder); } } else { setDirectory(folder); } } } }
aa4f2247-35aa-4713-8229-e7ad34a122ff
2
public void handleKeyEvent(KeyEvent keyEvent) { // The code of the key that is associated with this event. int key = keyEvent.getKeyCode(); switch(keyEvent.getID()) { case KeyEvent.KEY_PRESSED: Log.debug("Pressed key: " + key); keyPressed.add(key); break; case KeyEvent.KEY_RELEASED: Log.debug("Released key: " + key); keyReleased.add(key); break; default: break; } }
cc8226c1-c4ec-4b8d-a52d-42529dde41e5
6
void settitle1 () { String S; if (BigTimer) S = Global.resourceString("Game_") + GameNumber + ": " + WhiteName + " " + formmoves(WhiteMoves) + " - " + BlackName + " " + formmoves(BlackMoves); else S = Global.resourceString("Game_") + GameNumber + ": " + WhiteName + " " + formtime(WhiteTime - WhiteRun) + " " + formmoves(WhiteMoves) + " - " + BlackName + " " + formtime(BlackTime - BlackRun) + " " + formmoves(BlackMoves); if (Global.getParameter("extrainformation", true)) S = S + " " + B.extraInformation(); if ( !S.equals(OldS)) { if ( !TimerInTitle) TL.setText(S); else setTitle(S); OldS = S; } if (BigTimer && HaveTime) { BL.setTime(WhiteTime - WhiteRun, BlackTime - BlackRun, WhiteMoves, BlackMoves, B.MyColor); BL.repaint(); } }
804d123d-12c8-49d2-b62e-7df321a4ec8a
5
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (!plugin.hasPerm(sender, "hunger", true)) { sender.sendMessage(ChatColor.YELLOW + "You do not have permission to use /" + label); return true; } if (args.length == 0) { if (plugin.isPlayer(sender)) { Player player = (Player) sender; player.setFoodLevel(20); player.setSaturation(20); player.sendMessage(CraftEssence.premessage + "You are no longer hungry!."); return true; } return false; } else if (args.length == 1) { if (plugin.playerMatch(args[0]) != null) { Player p = plugin.getServer().getPlayer(args[0]); p.setFoodLevel(20); p.setSaturation(20); p.sendMessage(CraftEssence.premessage + "You are no longer hungry!"); sender.sendMessage(CraftEssence.premessage + "You fed " + args[0] + ", they are no longer hungry."); return true; } else { sender.sendMessage(CraftEssence.premessage + "Player not found."); return true; } } else { sender.sendMessage(CraftEssence.premessage + "Invalid hunger command parameter."); return true; } }
d166ccb8-99e4-412e-a4f6-1f49767bca11
8
protected Language getAnimalSpeak(final MOB M) { if((M!=null) &&(canSpeakWithThis(M))) { final Race r=M.charStats().getMyRace(); for(Ability A : r.racialAbilities(M)) { if(((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_LANGUAGE) &&(A instanceof Language)) { Ability effectA=M.fetchEffect(A.ID()); if(effectA==null) { A.autoInvocation(M, false); A=M.fetchEffect(A.ID()); } if((effectA!=null)&&(((Language)effectA).beingSpoken(effectA.ID()))) return (Language)effectA; } } } return null; }
0d37f975-acd1-4ad6-98ce-fc1756f68399
0
public ProgramSetupThread(String pname) { this.pname = pname; }
b78632ae-ccbe-4d35-8233-2bd4372f147d
7
public void listCatalogs(String org) { this.vccPreCheck(); Organization orgObj = this.getOrganization(org); try { Formatter.printInfoLine("Catalogs:\n"); for (ReferenceType catalogRef : orgObj.getCatalogRefs()) { Catalog catalog = Catalog.getCatalogByReference(this.vcc, catalogRef); Formatter.printInfoLine(String.format("----\n%-20s - %s", catalogRef.getName(), catalog.getResource().getDescription())); List<CatalogItem> vapps = new ArrayList<CatalogItem>(); List<CatalogItem> media = new ArrayList<CatalogItem>(); for (ReferenceType itemRef : catalog.getCatalogItemReferences()) { CatalogItem item = CatalogItem.getCatalogItemByReference(this.vcc, itemRef); ReferenceType ref = item.getEntityReference(); if (ref.getType().equals(vCloudConstants.MediaType.VAPP_TEMPLATE)) { vapps.add(item); } else if (ref.getType().equals(vCloudConstants.MediaType.MEDIA)) { media.add(item); } } Formatter.printInfoLine("\tvApps:"); for (CatalogItem item : vapps) { Formatter.printInfoLine(String.format("\t\t%-20s - %s", item.getReference().getName(), item.getResource().getDescription().replace("\n", ", "))); } Formatter.printInfoLine("\tvMedia:"); for (CatalogItem item : media) { Formatter.printInfoLine(String.format("\t\t%-20s - %s", item.getReference().getName(), item.getResource().getDescription().replace("\n", ", "))); } } } catch (VCloudException e) { Formatter.printErrorLine("An error occured while retrieving Catalogs"); Formatter.printErrorLine(e.getLocalizedMessage()); System.exit(1); } }
0182c756-711f-4ea6-a3b9-6af7c7e69bd6
0
public static String get(String code) { return codes.get(code); }
fccb53ff-d0d8-4d7a-8389-1b0bc220891b
4
public double scoreCompetencesHash(Set<Competence> lstCompsCherche) { // On initialise scoreCompetences à 0 double scoreCompetences = 0; double poidsMotClef; double sommePoids; // On récupère toutes les compétences se situant dans la HashMap Set setComps = this.m_tblComps.keySet(); Competence setIterComps; // On initialise sommePoids à 0 sommePoids = 0; // System.out.println(scoreCompetences + "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOffre.java"); // System.out.println("HashMap size: " + this.m_tblComps.size()); // System.out.println("Competence nombre cherche : " + lstCompsCherche.size()); // Pour toutes les compétences cherhcés on réalise les vérifications suivantes // for (int p = 0; p < lstCompsCherche.size(); p++) { for (Competence comp : lstCompsCherche) { // On initialise le poidsMotClef à 0 poidsMotClef = 0; // System.out.println("Competence chercher nom : " + lstCompsCherche.get(p).getNomComp()); // On crée un iterator pour pouvoir parcourir la liste des compétences Iterator itrComps = setComps.iterator(); // System.out.println("hasNext : " + itrComps.hasNext()); // tant que l'on trouve des compétences associées à cette offre on réalise les étapes suivantes while (itrComps.hasNext()) { //On récupère chaques compétences setIterComps = (Competence) itrComps.next(); // System.out.println("Competence trouve nom : " + setIterComps.getNomComp()); // System.out.println("Competence egale : " + (setIterComps == lstCompsCherche.get(p))); // On vérifie que la compétence saisie soit la même que la compétence cherchée // if (setIterComps.getNomComp().equals(lstCompsCherche.get(p).getNomComp())) { if (this.m_tblComps.containsKey(comp)) { // System.out.println("fffffffffffffffffffffffffffffffffffffffffffff" + this.m_tblComps.get(lstCompsCherche.get(p)).getLibType()); // Si la compétence cherchée est une compétence obligatoire alors on multiplie par 1 tous les mots cléfs associés à cette compétence // if (this.m_tblComps.get(lstCompsCherche.get(p)).getLibType().equals(ComptNoyauFonctionnel.getOblig().getLibType())) { if (this.m_tblComps.get(comp).getLibType().equals(ComptNoyauFonctionnel.getOblig().getLibType())) { poidsMotClef = setIterComps.nbMotClef() * 1; // System.out.println("fffffffffffffffffffffff" + this.m_tblComps.get(lstCompsCherche.get(p)).getLibType()); // System.out.println("fffffffffffffffffffffff" + this.m_tblComps.get(lstCompsCherche.get(p)).getLibType()); // System.out.println("fffffffffffffffff" + setIterComps.nbMotClef()); // System.out.println("v1_poidsMotClef : " + poidsMotClef); } else { // Sinon on multiplie par 0.5 tous les mots cléfs associés à cette compétence poidsMotClef = setIterComps.nbMotClef() * 0.5; // System.out.println("else" + this.m_tblComps.get(lstCompsCherche.get(p)).getLibType()); // System.out.println(setIterComps.nbMotClef()); // System.out.println("v0.5_poidsMotClef : " + poidsMotClef); } } } // System.out.println(" chaque v_poidsMotClef : " + poidsMotClef); // la somme des poids des mots clef est égale à sommePoids + le poid des mots cléfs calculés précédement sommePoids = sommePoids + poidsMotClef; // System.out.println(" chaque v_sommePoids : " + sommePoids); } // le nombre de mot clef total trouvé est égale au nombre de mot clef trouvé int nbMotClefTrouveTotal = nbMotClefTrouve(this); // System.out.println("v_sommePoids : " + sommePoids); // System.out.println("v_nbMotClefTrouveTotal : " + nbMotClefTrouveTotal); // le score de Competence est égale à la somme des poids calculé précédement / par le nombre de mot clef total scoreCompetences = sommePoids / nbMotClefTrouveTotal; // System.out.println("v_scoreCompetencesHash : " + scoreCompetences); // System.out.println(nbMotClefTrouveTotal + "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOffre.java"); return scoreCompetences; }
74fb821b-6888-4b95-89d6-bb2d022d682c
7
public int read(int width) throws IOException { if (width == 0) { return 0; } if (width < 0 || width > 32) { throw new IOException("Bad read width."); } int result = 0; while (width > 0) { if (this.available == 0) { this.unread = this.in.read(); if (this.unread < 0) { throw new IOException("Attempt to read past end."); } this.available = 8; } int take = width; if (take > this.available) { take = this.available; } result |= ((this.unread >>> (this.available - take)) & ((1 << take) - 1)) << (width - take); this.nrBits += take; this.available -= take; width -= take; } return result; }
cf89c32d-a0bf-456c-bfad-d31fe5a9f694
1
private static int factorial(int n){ if(n<2) return 1; return n*factorial(n-1); }
d2dfb54d-e6d8-4310-a980-3fef01220dea
2
public void dumpInstruction(TabbedPrintWriter writer) throws java.io.IOException { writer.println(output[type] + ((count == 1) ? "" : "2") + ((depth == 0) ? "" : "_X" + depth)); }
10604e3f-144b-4eac-88ae-7846f71a6aa5
3
private int jjMoveStringLiteralDfa2_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(0, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(1, active0); return 2; } switch(curChar) { case 108: return jjMoveStringLiteralDfa3_0(active0, 0x80L); default : break; } return jjStartNfa_0(1, active0); }
e622854a-4e36-4417-9f48-54301beefd01
0
public void removeCommand(Command _command) { this.commands.remove(_command); }
28c6b29e-3d9e-442c-8530-432ce5df2c66
0
public String value() { return value; }
c1e45b0c-0552-4448-9ccb-c315cf35d9fc
9
private Object newBuffer(Object template) { if(template instanceof Object[]) return new Object [((Object[]) template).length] ; if(template instanceof byte[]) return new byte [((byte[]) template).length] ; if(template instanceof char[]) return new char [((char[]) template).length] ; if(template instanceof short[]) return new short [((short[]) template).length] ; if(template instanceof boolean[]) return new boolean [((boolean[]) template).length] ; if(template instanceof int[]) return new int [((int[]) template).length] ; if(template instanceof long[]) return new long [((long[]) template).length] ; if(template instanceof float[]) return new float [((float[]) template).length] ; if(template instanceof double[]) return new double [((double[]) template).length] ; return null ; }
cf67e509-5221-41f4-861b-bc9c8dd1923f
8
private String convertLength(int i) { switch(i) { case 1: return "s "; case 2: return "i "; case 3: return "i. "; case 4: return "q "; case 6: return "q. "; case 8: return "h "; case 12: return "h. "; case 16: return "w "; } return ""; }
e242b6e4-56db-4968-888c-729af3d56380
2
@Override public void Play(PlayerResponse response) { deal(); // Send all Users their dealt hand for (PinochlePlayer player : mP.getPlayers()) { PinochleMessage message = new PinochleMessage(); message.setCards(player.getCurrentCards()); player.setMessage(message); } mP.updateAll(); // Check if a user got 5 nines & no meld - redeal if true if(!checkForNines()) { mP.setState(mP.getBid()); ((Bid)mP.getBid()).startBid(); } mP.Play(null); }
aa770173-4572-493e-8a06-d1c0302e0fc1
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PhpposAppConfigEntity that = (PhpposAppConfigEntity) o; if (key != null ? !key.equals(that.key) : that.key != null) return false; if (value != null ? !value.equals(that.value) : that.value != null) return false; return true; }
fb0e5fa2-779e-46a4-8ccc-3c47db470763
9
public static int evalRPN(String[] tokens){ int result=0; Stack<Integer> stack = new Stack<Integer>(); for(int i=0;i<tokens.length;i++){ if(!tokens[i].equals("+") && !tokens[i].equals("-") && !tokens[i].equals("*") && !tokens[i].equals("/")){ stack.push(Integer.parseInt(tokens[i])); } else{ String temp=tokens[i]; int a=0; switch(temp){ case "+": a=stack.pop(); result=stack.pop(); result +=a; break; case "-": a=stack.pop(); result=stack.pop(); result -=a; break; case "*": a=stack.pop(); result=stack.pop(); result *=a; break; case "/": a=stack.pop(); result=stack.pop(); result /=a; break; default: break; } stack.push(result); } } return stack.pop(); }
3cc10768-3c07-4e9b-b81c-8d79dc42a4b9
8
public final boolean isValidMove (final char action) { final char direct = getDirectByAction(action); if (direct == '\0') { // It's a invalid action. return false; } final Point newPos = new Point(minerPos); movePos(newPos, direct); if (!isInBound(newPos)) { // This move is out of bound of map. return false; } final char spot = map[newPos.x][newPos.y]; if (spot == WALL || spot == LIFT) { // Can not go through the wall nor the closed lift. return false; } if (spot == ROCK && (direct == DIRECT_RIGHT || direct == DIRECT_LEFT)) { final Point posBehindRock = new Point(newPos); movePos(posBehindRock, direct); if (!isInBound(newPos)) { /* Rock is at the bound of map, so rock cannot be pushed, so * this move is invalid. */ return false; } else { final char spotBehindRock = map[posBehindRock.x][posBehindRock.y]; /* The spot behind rock is empty, so rock can be pushed, so * this move is valid. Otherwise it's invalid. */ return (spotBehindRock == EMPTY); } } // if (spot == ROCK && (direct == DIRECT_RIGHT || // Other situations is valid. return true; }
b0acf6c4-b69e-48e6-9859-bc38b1d5150d
7
private void updateSimChangeSpeedValues() { //Since this is called many times (the GUI responds to many events...some of which //aren't changes the simulator needs to know about), we compare the current values with //the values the last time this is called...if no change we don't notify the simulator int newdelay = ((Integer) simTimeDelaySpinner.getValue()).intValue(); long newinbetweenperiod = ((Integer) simTimeCycleSpinner.getValue()).longValue(); boolean newiorc; newiorc = !"cycles".equals(simTimeIorCSelect.getSelectedItem()); int neweventtype; int slidervalue = simTimeSlider.getValue(); if (slidervalue == 0) { neweventtype = 1; //run at full speed } else if (slidervalue == 1) { neweventtype = 0; //realtime } else if (slidervalue == 5) { neweventtype = 3; //singlestep } else { neweventtype = 2; //slow it down } if (newdelay == olddelay && newinbetweenperiod == oldinbetweenperiod && oldiorc == newiorc && oldeventtype == neweventtype) { //do nothing, because there has been no change } else { // TODO: change the actual simulation speed olddelay = newdelay; oldinbetweenperiod = newinbetweenperiod; oldiorc = newiorc; oldeventtype = neweventtype; } }
efe97462-b4d1-4426-8381-745d83c5481c
5
public int GetCLPrayer(int ItemID) { if (ItemID == 10716) { return 100; } if (ItemID == 10718) { return 100; } if (ItemID == -1) { return 1; } String ItemName = GetItemName(ItemID); if (ItemName.startsWith("Prayer cape")) { return 100; } if (ItemName.startsWith("Prayer hood")) { return 100; } return 1; }
69c5f54c-a36e-4e12-b650-9419a1948030
8
public void assignMowerTasksByFootprint(LinkedList<FootPrint> footPrint) { for(FootPrint fp:footPrint) { Util.debugPrint(fp.toDebugString(),Util.LOG_DEBUG); Util.debugPrint("Mower Task:"+this.mowerTasks.size()+" "+this.mowerTasks.get(0).getBlocksCount(),Util.LOG_DEBUG); if(this.mowerTasks.size()>0) { if(this.currentMower==null) { if(!fp.getCommand().equals("M"))continue; this.currentMower=new StandardMower(fp.getMowerCoordinate().getCopy()); Util.debugPrint("New Mower Created:"+fp.getMowerCoordinate().getCopy(),Util.LOG_DEBUG); } if(fp.getCommand().equals("M")&&!this.mowerTasks.get(0).assignBlock()) { this.mowerTasks.remove(0); this.mowers.add(this.currentMower); this.currentMower=null; Util.debugPrint("Curent Mower Finished!",Util.LOG_DEBUG); }else { this.currentMower.insertCommand(fp.getCommand()); } } } if(this.currentMower!=null) { this.mowers.add(this.currentMower); this.mowerTasks.remove(0); } //what if there is still task left if(this.mowerTasks.size()==1) { Util.debugPrint("Mower Task Left: "+this.mowerTasks.size(),Util.LOG_DEBUG); this.currentMower=new StandardMower(this.mowers.get(this.mowers.size()-1).getInitPosition().getCopy().action('M')); this.mowers.add(this.currentMower); } }
93f5f89b-94e8-4070-8ffc-66e70b03aff2
6
public static boolean createFunny(ConditionalBlock cb, StructuredBlock last) { if (cb.jump == null || !(cb.getInstruction() instanceof CompareUnaryOperator) || !(last.outer instanceof SequentialBlock) || !(last.outer.getSubBlocks()[0] instanceof IfThenElseBlock)) return false; CompareUnaryOperator compare = (CompareUnaryOperator) cb .getInstruction(); FlowBlock trueDestination; FlowBlock falseDestination; if (compare.getOperatorIndex() == compare.EQUALS_OP) { trueDestination = cb.jump.destination; falseDestination = cb.trueBlock.jump.destination; } else if (compare.getOperatorIndex() == compare.NOTEQUALS_OP) { falseDestination = cb.jump.destination; trueDestination = cb.trueBlock.jump.destination; } else return false; Expression[] e = new Expression[3]; IfThenElseBlock ifBlock; SequentialBlock sequBlock = (SequentialBlock) last.outer; return createFunnyHelper(trueDestination, falseDestination, sequBlock.subBlocks[0]); }
d91ae7e4-146c-4873-9525-638e8009063a
8
public AbstractFace build() { AbstractFace face = null; switch (faceClass.toLowerCase()) { case "black": face = new BlackFace(); break; case "white": default: face = new WhiteFace(); break; } // AbstractEyes eyes = null; switch (eyesClass.toLowerCase()) { case "normal": eyes = new NormalEyes(); break; case "skewed": default: eyes = new SkewedEyes(); break; } // AbstractNose nose = null; switch (noseClass.toLowerCase()) { case "tiny": nose = new TinyNose(); break; case "big": default: nose = new BigNose(); break; } // AbstractMouth mouth = null; switch (mouthClass.toLowerCase()) { case "big": mouth = new BigMouth(); break; case "tiny": default: mouth = new TinyMouth(); } face.setEyes(eyes); face.setNose(nose); face.setMouth(mouth); return face; }
88441ac3-703f-47c0-8ccf-f9cf055d5bc8
7
public void setHome(CommandSender cs, Command cmd, String string, String[] args) { Player player = (Player) cs; if (args.length == 0) { if (player.hasPermission("warpsandports.homes.set.default") || player.isOp()) { Location loc = player.getLocation(); String world = loc.getWorld().getName(); int x = loc.getBlockX(); int y = loc.getBlockY(); int z = loc.getBlockZ(); float yaw = loc.getYaw(); float pitch = loc.getPitch(); MainClass.players.set(player.getUniqueId() + ".Homes.0.world", world); MainClass.players.set(player.getUniqueId() + ".Homes.0.x", x); MainClass.players.set(player.getUniqueId() + ".Homes.0.y", y); MainClass.players.set(player.getUniqueId() + ".Homes.0.z", z); MainClass.players.set(player.getUniqueId() + ".Homes.0.yaw", yaw); MainClass.players.set(player.getUniqueId() + ".Homes.0.pitch", pitch); player.sendMessage(ChatColor.GREEN + "Your home has been set!"); } } else if (args.length == 1) { try { Integer.parseInt(args[0]); } catch (Exception e) { player.sendMessage(ChatColor.RED + "Correct usage " + ChatColor.AQUA + "/setwarp <Number>"); return; } if (player.hasPermission("warpsandports.homes.set." + args[0]) || player.isOp()) { Location loc = player.getLocation(); String world = loc.getWorld().getName(); int x = loc.getBlockX(); int y = loc.getBlockY(); int z = loc.getBlockZ(); float yaw = loc.getYaw(); float pitch = loc.getPitch(); MainClass.players.set(player.getUniqueId() + ".Homes." + args[0] + ".world", world); MainClass.players.set(player.getUniqueId() + ".Homes." + args[0] + ".x", x); MainClass.players.set(player.getUniqueId() + ".Homes." + args[0] + ".y", y); MainClass.players.set(player.getUniqueId() + ".Homes." + args[0] + ".z", z); MainClass.players.set(player.getUniqueId() + ".Homes." + args[0] + ".yaw", yaw); MainClass.players.set(player.getUniqueId() + ".Homes." + args[0] + ".pitch", pitch); player.sendMessage(ChatColor.GREEN + "Home " + ChatColor.AQUA + args[0] + ChatColor.GREEN + " has been set!"); } } else { player.sendMessage(ChatColor.RED + "Correct usage " + ChatColor.AQUA + "/setwarp <Number>"); } }
03b29323-550a-4b3e-8d6c-3bb3217fb98f
0
public editUser() { this.requireLogin = true; this.addParamConstraint("id", ParamCons.INTEGER); this.addParamConstraint("password", true); this.addParamConstraint("username", true); this.addParamConstraint("fullName", true); this.addParamConstraint("email", true); this.addRtnCode(405, "permission denied"); this.addRtnCode(406, "user not found"); this.addRtnCode(201, "already exists"); }
0b2a3f6c-e2b6-4f13-ae03-ef0c376e4e22
5
private List<FBPhoto> processPhotoData(List<Facebook> fbData) throws ParseException { // TODO Auto-generated method stub List<FBPhoto> list=new ArrayList<FBPhoto>(); try { for (Facebook facebook : fbData) { JSONObject photoJson=new JSONObject(facebook.getData()); String dateString=photoJson.getString("created_time"); SimpleDateFormat incomingFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); Date date = incomingFormat.parse(dateString); FBPhoto photo=new FBPhoto(); photo.setUrl(photoJson.getString("source")); if(photoJson.has("place")){ photo.setLocation(photoJson.getJSONObject("place").getString("name")); JSONObject loc=photoJson.getJSONObject("place").getJSONObject("location"); photo.setLat(loc.getDouble("latitude")); photo.setLon(loc.getDouble("longitude")); } ArrayList<String> tags=new ArrayList<>(); if(photoJson.has("tags")){ JSONArray tagArray=photoJson.getJSONObject("tags").getJSONArray("data"); for (int i=0;i<tagArray.length();i++) { tags.add(tagArray.getJSONObject(i).getString("name")); } } photo.setPeople(tags); SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); String time = timeFormat.format(date); photo.setTime(time); list.add(photo); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; }
fd4a8a0d-1465-489b-abed-ac0ca56563c9
0
public String getName() { return name; }
5afac99c-ec79-4f9f-ae61-89d301f81cff
7
private void fixCorrespondingGates(Graph<Vertex,Edge> g) { TreeMap<String, Integer> scoreTallyOut = new TreeMap<String, Integer>(); TreeMap<String, Integer> scoreTallyIn = new TreeMap<String, Integer>(); LinkedList<String> gateways = new LinkedList<String>(); KShortestPaths<Vertex, Edge> sp = new KShortestPaths<Vertex, Edge>(g, g.trueStart, MAX_PATH_LENGTH); for(GraphPath<Vertex, Edge> gp : sp.getPaths(g.trueEnd)){ // Walk along paths keeping score of open and close gateways Vertex start = gp.getStartVertex(); Vertex end = gp.getEndVertex(); Vertex current = start; //System.err.println("Viewing current path " + gp); //System.err.println("Starting with " + start); do{ if(current == null) break; if(current.type == GraphLoader.ParallelGateway){ //scoreTallyIn.put(current.name, 0); if(g.inDegreeOf(current) > 1){ // gatway join scoreTallyIn.put(current.name, g.inDegreeOf(current)); gateways.add(current.name); }else if(g.outDegreeOf(current) > 1){ scoreTallyOut.put(current.name, g.outDegreeOf(current)); gateways.add(current.name); } } current = next(current, gp,g); }while(current != null || current != end); } loopyfix(gateways, scoreTallyIn, scoreTallyOut,g); }
13c5238f-ce2b-43d1-8e25-fa7ae78be197
2
private void compileShader() { glLinkProgram( resource.getProgram() ); if ( glGetProgrami( resource.getProgram(), GL_LINK_STATUS ) == 0 ) { System.err.println( glGetProgramInfoLog( resource.getProgram(), 1024 ) ); System.exit( 1 ); } glValidateProgram( resource.getProgram() ); if ( glGetProgrami( resource.getProgram(), GL_VALIDATE_STATUS ) == 0 ) { System.err.println( glGetProgramInfoLog( resource.getProgram(), 1024 ) ); System.exit( 1 ); } }
666f719e-a176-4579-9971-7bd719dd19cc
3
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); Connection conn; Statement stmt; ResultSet rs; HttpSession hs=request.getSession(true); hs.setAttribute("Que1", 4); try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/chaitanya","root",""); System.out.println("conn succccsss!"); stmt=conn.createStatement(); rs=stmt.executeQuery("select comment,op1,op2,op3,op4 from comment where no=4"); if(rs.next()==true) { out.println("<html>"); out.println("<head>"); out.println("<h2>"); out.println("QUESTION NO 3"); out.println("</h2>"); out.println("</head>"); out.println("<body>"); out.println("<b>"+rs.getString("comment")+"</b>"); out.println("<form method=\"post\" action=\"http://localhost:8080/ExaminationSoftware/SavServlet\">"); out.println("<input type=\"radio\" name=\"option\" value="+rs.getString("op1")+">"+rs.getString("op1")+""); out.println("<br>"); out.println("<input type=\"radio\" name=\"option\" value="+rs.getString("op2")+">"+rs.getString("op2")+""); out.println("<br>"); out.println("<input type=\"radio\" name=\"option\" value="+rs.getString("op3")+">"+rs.getString("op3")+""); out.println("<br>"); out.println("<input type=\"radio\" name=\"option\" value="+rs.getString("op4")+">"+rs.getString("op4")+""); out.println("<br>"); out.println("<input type=\"submit\" value=\"CONFIRM\">"); out.println("</form>"); out.println("</form>"); out.println("<br>"); out.println("<br>"); out.println("<br>"); out.println("<br>"); out.println("<form method=\"post\" action=\"http://localhost:8080/ExaminationSoftware/QueServlet5\">"); out.println("<input type=\"submit\" value=\"NEXT\">"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<head>"); out.println("<h2>"); out.println("QUESTION NOT AVAILABLE!"); out.println("</h2>"); out.println("</head>"); } } catch(SQLException e1) { } catch(ClassNotFoundException e2) { } }
ee7922f0-e6c5-4a69-81bf-a5801895abbf
0
public float getA() { return a; }
89222d09-5c9e-43b4-8360-e39680067caa
4
private void DeleteTopmost() { ConstructEditor deleteMeEditor = mConstructSelector.getSelected(); if(deleteMeEditor.getParent() != null) { int index = deleteMeEditor.construct.parent.children.indexOf(deleteMeEditor.construct); int added = AddChildrenTo(deleteMeEditor.construct, deleteMeEditor.construct.parent, index); // Delete topmost construct (only if we copied some children) if(added > 0) { boolean deleted = deleteMeEditor.delete(); if(deleted == true) { mConstructSelector.getSelected().update(); if(mConstructSelector.SelectAdjacentConstruct(false) == false) mConstructSelector.SelectParentConstruct(); } } } }
221c108d-c5c8-4e0d-9b1d-e839a700851f
6
public void ProcessVulnerabilityXML(javax.swing.JTextField XMLFileName, javax.swing.JTextField XSSAttackName, javax.swing.JTextArea XSSAttackCode, javax.swing.JTextArea XSSAttackDesc, javax.swing.JTextField XSSAttackLabel, javax.swing.JTextArea XSSAttackBrowser, javax.swing.JList XSSAttackNames) { //Adapted from: http://www.developerfusion.co.uk/show/2064/ XSSAttackNameArray.clear(); XSSAttackCodeArray.clear(); XSSAttackDescArray.clear(); XSSAttackLabelArray.clear(); XSSAttackBrowserArray.clear(); try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File(XMLFileName.getText())); // normalize text representation doc.getDocumentElement().normalize(); System.out.println("Root element of the doc is " + doc.getDocumentElement().getNodeName()); NodeList listOfAttacks = doc.getElementsByTagName("attack"); int totalAttacks = listOfAttacks.getLength(); System.out.println("Total no of Attacks : " + totalAttacks); for (int s = 0; s < listOfAttacks.getLength(); s++) { Node firstAttackNode = listOfAttacks.item(s); if (firstAttackNode.getNodeType() == Node.ELEMENT_NODE) { Element firstAttackElement = (Element) firstAttackNode; //------- NodeList nameList = firstAttackElement.getElementsByTagName("name"); Element nameElement = (Element) nameList.item(0); NodeList textFNList = nameElement.getChildNodes(); System.out.println("Name : " + ((Node) textFNList.item(0)).getNodeValue().trim()); XSSAttackNameArray.add(((Node) textFNList.item(0)).getNodeValue().trim()); MyJListModel.addElement(((Node) textFNList.item(0)).getNodeValue().trim()); //------- NodeList codeList = firstAttackElement.getElementsByTagName("code"); Element codeElement = (Element) codeList.item(0); NodeList textCodeList = codeElement.getChildNodes(); System.out.println("Code : " + ((Node) textCodeList.item(0)).getNodeValue().trim()); XSSAttackCodeArray.add(((Node) textCodeList.item(0)).getNodeValue().trim()); //---- NodeList descList = firstAttackElement.getElementsByTagName("desc"); Element descElement = (Element) descList.item(0); NodeList textDescList = descElement.getChildNodes(); System.out.println("Description : " + ((Node) textDescList.item(0)).getNodeValue().trim()); XSSAttackDescArray.add(((Node) textDescList.item(0)).getNodeValue().trim()); //---- NodeList labelList = firstAttackElement.getElementsByTagName("label"); Element labelElement = (Element) labelList.item(0); NodeList textLabelList = labelElement.getChildNodes(); System.out.println("Label : " + ((Node) textLabelList.item(0)).getNodeValue().trim()); XSSAttackLabelArray.add(((Node) textLabelList.item(0)).getNodeValue().trim()); //---- NodeList browserList = firstAttackElement.getElementsByTagName("browser"); Element browserElement = (Element) browserList.item(0); NodeList textBrowserList = browserElement.getChildNodes(); System.out.println("Browser : " + ((Node) textBrowserList.item(0)).getNodeValue().trim()); XSSAttackBrowserArray.add(((Node) textBrowserList.item(0)).getNodeValue().trim()); //------ }//end of if clause }//end of for loop with s var } catch (SAXParseException err) { System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage()); } catch (SAXException e) { Exception x = e.getException(); ((x == null) ? e : x).printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } XSSAttackName.setText(XSSAttackNameArray.get(0).toString()); XSSAttackCode.setText(XSSAttackCodeArray.get(0).toString()); XSSAttackDesc.setText(XSSAttackDescArray.get(0).toString()); XSSAttackLabel.setText(XSSAttackLabelArray.get(0).toString()); XSSAttackBrowser.setText(XSSAttackBrowserArray.get(0).toString()); XSSAttackNames.setSelectedIndex(0); }
59490eb6-7310-4e2c-a193-f5a73c37731a
6
private void save(){ Calendar calendar = Calendar.getInstance(); calendar.set( (Integer)dateReceivedYearField.getSelectedItem(), (Integer)dateReceivedMonthField.getSelectedItem()-1, (Integer)dateReceivedDayField.getSelectedItem(), (Integer)dateReceivedHourField.getSelectedItem(), (Integer)dateReceivedMinuteField.getSelectedItem() ); call.setDateReceived(calendar.getTime()); calendar.set( (Integer)datePassedYearField.getSelectedItem(), (Integer)datePassedMonthField.getSelectedItem()-1, (Integer)datePassedDayField.getSelectedItem(), (Integer)datePassedHourField.getSelectedItem(), (Integer)datePassedMinuteField.getSelectedItem() ); if(call.getDateReceived().before(calendar.getTime())){ call.setDatePassed(calendar.getTime()); }else{ call.setDatePassed(null); } call.setCallerName(callerNameField.getText()); if(call.getWorker() == null){ JOptionPane.showMessageDialog(this, "Не установлен работник принявший вызов!"); return; } Address address = new Address( ((Subject)addressStreetField.getSelectedItem()).getCode(), addressHouseField.getText(), addressAptField.getText() ); call.setAddress(address); if(call.getPatient() == null){ JOptionPane.showMessageDialog(this, "Не выбран пациент!"); return; } call.setComplaints(complaintField.getText()); call.setComments(commentsField.getText()); call.setDiacrisis(diacrisisField.getText()); call.setResult(resultField.getText()); if(call.getCrew() == null){ JOptionPane.showMessageDialog(this, "Не выбрана бригада скорой помощи!"); return; } calendar.set( (Integer)crewStartDateYearField.getSelectedItem(), (Integer)crewStartDateMonthField.getSelectedItem()-1, (Integer)crewStartDateDayField.getSelectedItem(), (Integer)crewStartDateHourField.getSelectedItem(), (Integer)crewStartDateMinuteField.getSelectedItem() ); call.setCrewStartTime(calendar.getTime()); calendar.set( (Integer)crewOffDateYearField.getSelectedItem(), (Integer)crewOffDateMonthField.getSelectedItem()-1, (Integer)crewOffDateDayField.getSelectedItem(), (Integer)crewOffDateHourField.getSelectedItem(), (Integer)crewOffDateMinuteField.getSelectedItem() ); call.setCrewOffTime(calendar.getTime()); calendar.set( (Integer)crewArrivalDateYearField.getSelectedItem(), (Integer)crewArrivalDateMonthField.getSelectedItem()-1, (Integer)crewArrivalDateDayField.getSelectedItem(), (Integer)crewArrivalDateHourField.getSelectedItem(), (Integer)crewArrivalDateMinuteField.getSelectedItem() ); call.setCrewArrivalTime(calendar.getTime()); if(call.getCallReason() == null){ JOptionPane.showMessageDialog( this, "Не указана причина вызова!" ); return; } if(call.getCallType() == null){ JOptionPane.showMessageDialog( this, "Не указан тип вызова!" ); } call.save(); JOptionPane.showMessageDialog(this, "Вызов сохранён!"); this.cancel(); }
f23b369a-e303-4378-ae68-2189353c2185
8
private boolean validateValue(String value) { value = value.toLowerCase(); if (value.lastIndexOf("ms") != -1) { if (Integer.parseInt(value.replaceAll("ms", "")) > 999) { return false; } } else if (value.lastIndexOf("s") != -1) { if (Integer.parseInt(value.replaceAll("s", "")) > 59) { return false; } } else if (value.lastIndexOf("m") != -1) { if (Integer.parseInt(value.replaceAll("m", "")) > 59) { return false; } } else if (value.lastIndexOf("h") != -1) { if (Integer.parseInt(value.replaceAll("h", "")) >= MAX_HOURS) { return false; } } return true; }
7c5f249a-ffce-4a2b-838c-009bcb359614
0
public void setPos(Point2D p) { myBottomLeft = new Point2D.Double(p.getX(), p.getY()); }
c48da208-9b99-45ac-9ad0-41de62f86e67
0
public String getName() { return name; }
d52236eb-57fc-43ed-9938-5fd62b899897
4
private String getSituacao(Integer situacao){ switch(situacao){ case 0: return "Aberto"; case 1: return "Em Julgamento"; case 2: return "Julgado"; case 3: return "Cancelado"; } return null; }
538d3a75-f7a3-452d-8994-2136e237440b
5
public static InputTableModel getModel(Automaton automaton, boolean multipleFile) { InputTableModel model = (InputTableModel) INPUTS_TO_MODELS .get(new Integer(inputsForMachine(automaton))); if (model != null && (model.isMultiple == multipleFile)) { model = new InputTableModel(model); // Clear out the results column. for (int i = 0; i < (model.getRowCount() - 1); i++) model.setResult(i, "", null, null, 0); } else { int add = 0; if(multipleFile) add = 1; model = new InputTableModel(automaton, add); } model.addTableModelListener(LISTENER); if(multipleFile){ model.isMultiple = true; } return model; }
727685ed-c828-4026-ad30-a41b9e4129e4
6
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Token token = (Token) o; if (type != token.type) return false; if (value != null ? !value.equals(token.value) : token.value != null) return false; return true; }
71384d98-d571-45e5-a63b-210f8ed9a206
5
public static HashMap<String, Integer> rankVarianceWeight(LinkedHashMap<String, HashMap<String, Double>> listOfWeightMaps) { HashMap<String, ArrayList<Double>> attributeVals = new HashMap<String, ArrayList<Double>>(); HashMap<String, Double> attributeMeans = new HashMap<String, Double>(); for (HashMap<String, Double> a : listOfWeightMaps.values()) { for (Map.Entry<String, Double> pair : a.entrySet()) { String key = pair.getKey(); Double value = pair.getValue(); if (attributeVals.containsKey(key)) { ArrayList<Double> vals = attributeVals.get(key); vals.add(value); Double sum = attributeMeans.get(key); sum += value; attributeMeans.put(key, sum); } else { ArrayList<Double> vals = new ArrayList<Double>(); vals.add(value); attributeVals.put(key, vals); attributeMeans.put(key, value); } } } HashMap<String, Double> stdevs = new HashMap<String, Double>(); for (Map.Entry<String, Double> pair : attributeMeans.entrySet()) { double var = 0; ArrayList<Double> vals = attributeVals.get(pair.getKey()); double mean = pair.getValue(); mean = mean / vals.size(); for (Double v : vals) { var += Math.pow(v-mean, 2); } var = var / vals.size(); stdevs.put(pair.getKey(), Math.sqrt(var)); } return rankFromStdDev(stdevs); }
f04a9ec6-08ee-4705-ac8a-73c7db7eb2af
8
private boolean isPrimeable(int n) { if (n < 10) { return true; } int[] numbers = Problem30.getNumbers(n); for (int i = 0; i < numbers.length; i++) { int x = numbers[i]; switch (x) { case 1: case 3: case 7: case 9: break; default: return false; } } int mod = n % 6; if (mod == 5 || mod == 1) { return true; } return false; }
5741e467-0dec-4e68-83da-7fd8b0454cd8
5
@Override public User findByEmail(String email) { User user = null; try { connection = getConnection(); ptmt = connection.prepareStatement(QUERY_SELECT + " WHERE email =?;"); ptmt.setString(1, email); resultSet = ptmt.executeQuery(); resultSet.next(); user = new User(); user.setId(resultSet.getInt(ID)); user.setActive(resultSet.getBoolean(ACTIVE)); user.setEmail(resultSet.getString(EMAIL)); user.setLastName(resultSet.getString(LAST_NAME)); user.setLogin(resultSet.getString(LOGIN)); user.setName(resultSet.getString(NAME)); user.setPassword(resultSet.getString(PASSWORD)); user.setBirthday(resultSet.getDate(BIRTHDAY)); user.setDateOfRegistration(resultSet.getDate(DATE_OF_REGISTRATION)); } catch (SQLException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ptmt != null) { ptmt.close(); } if (connection != null) { connection.close(); } if (resultSet != null) { resultSet.close(); } } catch (SQLException ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } } return user; }
4867878f-2140-4d0f-a53b-289e4386c99b
0
private double edgeX(int x, int y, double[][] smoothedGray) { return 1*smoothedGray[x-1][y-1] + 2*smoothedGray[x][y-1] + 1*smoothedGray[x+1][y-1] - 1*smoothedGray[x-1][y+1] - 2*smoothedGray[x][y+1] - 1*smoothedGray[x+1][y+1]; }
c7f836bf-a135-4aa4-a1a9-8d22ae2e3f84
3
public RunGenerator(){ // Makes it look pretty try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { // If Nimbus is not available, you can set the GUI to another look and feel. } // Set up initFrame properties and buttons initFrame = new JFrame("D&D 3.5 Treasure Generator"); initFrame.setLayout(null); initFrame.setSize(350,334); initFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); initFrame.setVisible(true); initFrame.setResizable(false); initFrame.setLocationRelativeTo(null); ButtonListenerI blI = new ButtonListenerI(); generateButton = new JButton("Generate"); generateButton.addActionListener(blI); generateButton.setSize(100,33); initFrame.add(generateButton); generateButton.setLocation(180,10); levelSpinnerLabel = new JLabel("Treasure Level"); levelSpinnerLabel.setSize(100,50); initFrame.add(levelSpinnerLabel); levelSpinnerLabel.setLocation(10,0); SpinnerNumberModel levelModel = new SpinnerNumberModel(1, 1, 30, 1); levelSpinner = new JSpinner(levelModel); levelSpinner.setSize(50,30); initFrame.add(levelSpinner); levelSpinner.setLocation(100,10); treasureListLabel = new JLabel("Treasure"); treasureListLabel.setSize(100,50); initFrame.add(treasureListLabel); treasureListLabel.setLocation(10,50); treasureModel = new DefaultListModel(); treasureList = new JList(treasureModel); treasureList.setSize(313,190); treasureScroll = new JScrollPane(treasureList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); treasureScroll.setSize(323,200); initFrame.add(treasureScroll); treasureScroll.setLocation(10,90); }
99202f39-ff85-4ff1-bcfc-d9f85148baad
2
public void set(Block block,int x,int y,int z){ Block current = blocks[x%16][y%16][z%16]; if(current != null)current.removeFromParent();; if( block != null) block.addToWorld(x, y, z); blocks[x%16][y%16][z%16] = block; }
2fd2d156-a205-4712-8071-b50432cf583f
8
private void interpolate(int iLower, int iUpper) { int dx = xRaster[iUpper] - xRaster[iLower]; if (dx < 0) dx = -dx; int dy = yRaster[iUpper] - yRaster[iLower]; if (dy < 0) dy = -dy; if ((dx + dy) <= 1) return; float tLower = tRaster[iLower]; float tUpper = tRaster[iUpper]; int iMid = allocRaster(false); for (int j = 4; --j >= 0;) { float tMid = (tLower + tUpper) / 2; calcRotatedPoint(tMid, iMid, false); if ((xRaster[iMid] == xRaster[iLower]) && (yRaster[iMid] == yRaster[iLower])) { fp8IntensityUp[iLower] = (fp8IntensityUp[iLower] + fp8IntensityUp[iMid]) / 2; tLower = tMid; } else if ((xRaster[iMid] == xRaster[iUpper]) && (yRaster[iMid] == yRaster[iUpper])) { fp8IntensityUp[iUpper] = (fp8IntensityUp[iUpper] + fp8IntensityUp[iMid]) / 2; tUpper = tMid; } else { interpolate(iLower, iMid); interpolate(iMid, iUpper); return; } } xRaster[iMid] = xRaster[iLower]; yRaster[iMid] = yRaster[iUpper]; }
2f2ebe98-b807-4274-84e7-65ab804ac9ec
6
@Override public void run() { File musicFolder = new File(dir, "music"); File stepsFolder = new File(new File(dir, "newsound"), "step"); File digFolder = new File(new File(dir, "sound3"), "dig"); File randomFolder = new File(new File(dir, "sound3"), "random"); File newMusicFolder = new File(dir, "newmusic"); try { GameSettings.PercentString = "5%"; GameSettings.StatusString = "Downloading music and sounds..."; LogUtil.logInfo("Downloading music and sounds..."); int percent = 5; for (String fileName : resourceFiles) { if (percent >= 80) { percent = 80; } percent += 3; File file = new File(dir, fileName); if (!file.exists()) { GameSettings.PercentString = percent + "%"; GameSettings.StatusString = "Downloading https://s3.amazonaws.com/MinecraftResources/" + fileName + "..."; LogUtil.logInfo("Downloading https://s3.amazonaws.com/MinecraftResources/" + fileName); URL url = new URL("https://s3.amazonaws.com/MinecraftResources/" + fileName); try (InputStream is = url.openStream()) { StreamingUtil.copyStreamToFile(is, file); } GameSettings.StatusString = "Downloaded https://s3.amazonaws.com/MinecraftResources/" + fileName + "!"; LogUtil.logInfo("Downloaded https://s3.amazonaws.com/MinecraftResources/" + fileName); } } GameSettings.PercentString = "85%"; GameSettings.StatusString = "Downloaded music and sounds!"; LogUtil.logInfo("Done downloading music and sounds!"); GameSettings.StatusString = ""; GameSettings.PercentString = ""; done = true; } catch (Exception ex) { LogUtil.logError("Error downloading music and sounds!", ex); } for (int i = 1; i <= 3; i++) { minecraft.sound.registerMusic("calm" + i + ".ogg", new File(musicFolder, "calm" + i + ".ogg")); minecraft.sound.registerSound(new File(randomFolder, "glass" + i + ".ogg"), "random/glass" + i + ".ogg"); } for (int i = 1; i <= 4; i++) { minecraft.sound.registerMusic("calm" + i + ".ogg", new File(newMusicFolder, "hal" + i + ".ogg")); minecraft.sound.registerSound(new File(stepsFolder, "grass" + i + ".ogg"), "step/grass" + i + ".ogg"); minecraft.sound.registerSound(new File(stepsFolder, "gravel" + i + ".ogg"), "step/gravel" + i + ".ogg"); minecraft.sound.registerSound(new File(stepsFolder, "stone" + i + ".ogg"), "step/stone" + i + ".ogg"); minecraft.sound.registerSound(new File(stepsFolder, "wood" + i + ".ogg"), "step/wood" + i + ".ogg"); minecraft.sound.registerSound(new File(stepsFolder, "cloth" + i + ".ogg"), "step/cloth" + i + ".ogg"); minecraft.sound.registerSound(new File(stepsFolder, "sand" + i + ".ogg"), "step/sand" + i + ".ogg"); minecraft.sound.registerSound(new File(stepsFolder, "snow" + i + ".ogg"), "step/snow" + i + ".ogg"); minecraft.sound.registerSound(new File(digFolder, "grass" + i + ".ogg"), "dig/grass" + i + ".ogg"); minecraft.sound.registerSound(new File(digFolder, "gravel" + i + ".ogg"), "dig/gravel" + i + ".ogg"); minecraft.sound.registerSound(new File(digFolder, "stone" + i + ".ogg"), "dig/stone" + i + ".ogg"); minecraft.sound.registerSound(new File(digFolder, "wood" + i + ".ogg"), "dig/wood" + i + ".ogg"); minecraft.sound.registerSound(new File(digFolder, "cloth" + i + ".ogg"), "dig/cloth" + i + ".ogg"); minecraft.sound.registerSound(new File(digFolder, "sand" + i + ".ogg"), "dig/sand" + i + ".ogg"); minecraft.sound.registerSound(new File(digFolder, "snow" + i + ".ogg"), "dig/snow" + i + ".ogg"); } finished = true; }
fa91d85f-12ff-407e-a164-4c2a49e24107
8
private void cliques( List<Vertex> likelyC, List<Vertex> C, List<Vertex> F) { List<Vertex> candidates_array = new ArrayList<Vertex>(C); if (!allEdgesSeen(C, F)) { for (Vertex candidate : candidates_array) { List<Vertex> new_candidates = new ArrayList<Vertex>(); List<Vertex> new_already_found = new ArrayList<Vertex>(); likelyC.add(candidate); C.remove(candidate); for (Vertex new_candidate : C) { if(g.isEdge(candidate,new_candidate)) { new_candidates.add(new_candidate); } } for (Vertex new_found : F) { if (g.isEdge(candidate, new_found)) { new_already_found.add(new_found); } } if (new_candidates.isEmpty() && new_already_found.isEmpty()) { maxCliques.add(new Vector<Vertex>(likelyC)); } else { cliques( likelyC, new_candidates, new_already_found); } F.add(candidate); likelyC.remove(candidate); } } }
d4adcd9d-20a3-4759-83bf-8a21630beaa1
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(BuscaPeca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(BuscaPeca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(BuscaPeca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(BuscaPeca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new BuscaPeca().setVisible(true); } }); }
324e259e-075b-45ca-8c10-6b017641bc40
5
public static void keyReleased(KeyEvent e) { key.clear(e.getKeyCode()); if (!key.get(KeyEvent.VK_SPACE)) { setFire(false); } if (!key.get(KeyEvent.VK_LEFT)) { setX(0); } if (!key.get(KeyEvent.VK_RIGHT)) { setX(0); } if (!key.get(KeyEvent.VK_UP)) { setY(0); } if (!key.get(KeyEvent.VK_DOWN)) { setY(0); } }
debf64f3-80c7-4ce8-b382-959906984a84
7
public void disconnect(){ try { if(input != null) input.close(); } catch(Exception e) {} try { if(output != null) output.close(); } catch(Exception e) {} try{ if(socket != null) socket.close(); } catch(Exception e) {} if (gui != null) gui.connectionFailure(); }
a8b044a9-7bb9-412c-bb6a-27c05d3c330e
3
public void visit_swap(final Instruction inst) { // 0 1 -> 1 0 if (Tree.USE_STACK) { saveStack(); final StackExpr s1 = (StackExpr) stack.pop1(); final StackExpr s0 = (StackExpr) stack.pop1(); final StackExpr[] s = new StackExpr[] { s0, s1 }; manip(s, new int[] { 1, 0 }, StackManipStmt.SWAP); } else { final Expr s1 = stack.pop1(); final Expr s0 = stack.pop1(); final LocalExpr t0 = newStackLocal(stack.height(), s0.type()); final LocalExpr t1 = newStackLocal(stack.height() + 1, s1.type()); if (!t0.equalsExpr(s0)) { addStore(t0, s0); } if (!t1.equalsExpr(s1)) { addStore(t1, s1); } Expr copy = (Expr) t1.clone(); copy.setDef(null); stack.push(copy); copy = (Expr) t0.clone(); copy.setDef(null); stack.push(copy); } }
e7922622-f7b0-4bcd-bf55-6ac5ca8b2dd0
8
public void pintar(int x, int y, int type) { int [] xy = new int [2]; if(type == 5) { xy = buscaType(5); if((xy[0] != -1) && (xy[0] != -1)) { cambiarCasilla(tablero[xy[0]][xy[1]],7); } } if(type == 6) { xy = buscaType(6); if((xy[0] != -1) && (xy[0] != -1)) { cambiarCasilla(tablero[xy[0]][xy[1]],7); } } if(type == 2){ cambiarCasilla(tablero[x][y], 2); if(y+1 < size_tablero_C) cambiarCasilla(tablero[x][y+1], 9); } cambiarCasilla(tablero[x][y],type); }
70c20c1c-b1a5-4a5d-ad87-e3d825baee72
2
public void update (double elapsedTime) { Dimension bounds = myView.getSize(); for (Assembly a : myAssemblies) { a.update(elapsedTime, bounds, myActiveForces); } int lastKey = myView.getLastKeyPressed(); if (myKeyPresses.containsKey(lastKey)) { myKeyPresses.get(lastKey).alter(); } myMouseListener.alter(); myView.clearInput(); }
6559748c-2702-4629-9542-fca00570a857
6
public static EntityMinecart placeCart(GameProfile owner, ItemStack cart, WorldServer world, int x, int y, int z) { if (cart == null) return null; cart = cart.copy(); if (cart.getItem() instanceof IMinecartItem) { IMinecartItem mi = (IMinecartItem) cart.getItem(); return mi.placeCart(owner, cart, world, x, y, z); } else if (cart.getItem() instanceof ItemMinecart) try { boolean placed = cart.getItem().onItemUse(cart, FakePlayerFactory.get(world, railcraftProfile), world, x, y, z , 0, 0, 0, 0); if (placed) { List<EntityMinecart> carts = getMinecartsAt(world, x, y, z, 0.3f); if (carts.size() > 0) { setCartOwner(carts.get(0), owner); return carts.get(0); } } } catch (Exception e) { return null; } return null; }
2cde307b-4d5d-4b3c-8455-6fc064ff9527
3
private void makeCircularStreetList(Street street, ArrayList<FieldCircularList> fieldArrayList) { for(int i = 0; i < fieldArrayList.size(); i++) { if(fieldArrayList.get(i) instanceof Street && ((Street) fieldArrayList.get(i)).isSameColor(street)) { street.setNextGroupElement(((Street) fieldArrayList.get(i))); fieldArrayList.remove(i); i--; } } }
54bc8db9-3ebd-4a25-8c08-86836e58ba07
3
public boolean valideCoord(int x,int y){ return ( x < row && y < col && x > 0 && y > 0); }
977b8d4f-e009-4bc2-b4e7-3d394971a6ab
9
public boolean intersects(S2Polygon b) { // A.intersects(B) if and only if !complement(A).contains(B). However, // implementing a complement() operation is trickier than it sounds, // and in any case it's more efficient to test for intersection directly. // If both polygons have one loop, use the more efficient S2Loop method. // Note that S2Loop.intersects does its own bounding rectangle check. if (numLoops() == 1 && b.numLoops() == 1) { return loop(0).intersects(b.loop(0)); } // Otherwise if neither polygon has holes, we can still use the more // efficient S2Loop.intersects method. The polygons intersect if and // only if some pair of loop regions intersect. if (!bound.intersects(b.getRectBound())) { return false; } if (!hasHoles && !b.hasHoles) { for (int i = 0; i < numLoops(); ++i) { for (int j = 0; j < b.numLoops(); ++j) { if (loop(i).intersects(b.loop(j))) { return true; } } } return false; } // Otherwise if any shell of B is contained by an odd number of loops of A, // or any shell of A is contained by an odd number of loops of B, there is // an intersection. return intersectsAnyShell(b) || b.intersectsAnyShell(this); }
62ac589b-3c85-4cc9-9197-6fed182dd028
8
public ArrayList<Tile> adjacent(int r, int c) { ArrayList<Tile> temp = new ArrayList<Tile>(); if (getTile(r+1,c) != null) {temp.add(getTile(r+1,c));} if (getTile(r-1,c) != null) {temp.add(getTile(r-1,c));} if (getTile(r,c-1) != null) {temp.add(getTile(r,c-1));} if (getTile(r,c+1) != null) {temp.add(getTile(r,c+1));} if (getTile(r+1,c+1) != null) {temp.add(getTile(r+1,c+1));} if (getTile(r+1,c-1) != null) {temp.add(getTile(r+1,c-1));} if (getTile(r-1,c+1) != null) {temp.add(getTile(r-1,c+1));} if (getTile(r-1,c-1) != null) {temp.add(getTile(r-1,c-1));} return temp; }
20928698-12fa-4549-9d17-216dd529bc6b
5
private WarMachine platziereWarMachine(WarMachine newWarMachine) { boolean invalidInput = true; String input = null; Koordinate platzKoordinate = null; Ausrichtung platzAusrichtung = null; while (invalidInput) { try { input = generateRandomKoordinate() + "," + generateRandomAusrichtung(); } catch (Exception e) { e.printStackTrace(); } String[] argumente = input.split(","); if (argumente.length < 3) { continue; } platzKoordinate = eingabe.string2Koord(argumente[0].toString() + "," + argumente[1].toString()); platzAusrichtung = eingabe.string2Ausrichtung(argumente[2]); if (!eingabe.validAusrichtung(platzAusrichtung)) { continue; } try { spielfeld.place(newWarMachine, platzKoordinate, platzAusrichtung); invalidInput = false; } catch (Exception e) { invalidInput = true; } } // while invalid Input return newWarMachine; }
02262dd7-fdad-4a87-882c-41b2a9b54156
3
private Map func_27415_a(File var1, File var2, File var3) { return var1.exists()?this.func_27408_a(var1):(var3.exists()?this.func_27408_a(var3):(var2.exists()?this.func_27408_a(var2):null)); }
11cdc4d8-80fb-4578-ba97-53fe78229cc3
8
@Override public List<OrderDetail> getOrderDetailByID(final Integer id) { Connection conn = null; PreparedStatement stmt=null; List<OrderDetail> OrderDetailList=new ArrayList<>(); ResultSet rs =null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("SELECT ORDER_ID,BOOK_ID,ORDERDETAIL_AMOUNT FROM ORDERDETAIL WHERE ORDER_ID=?"); stmt.setInt(1, id); rs = stmt.executeQuery(); while(rs.next()){//必須要有游標next才取的到值 OrderDetailList.add( new OrderDetail(rs.getInt("ORDER_ID"),rs.getInt("BOOK_ID"),rs.getInt("ORDERDETAIL_AMOUNT"))); } } catch (SQLException ex1) { throw new RuntimeException(ex1); } finally { if (rs != null) { try { rs.close(); } catch (SQLException ex1) { Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex1); } } if (stmt != null) { try { stmt.close(); } catch (SQLException ex1) { Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex1); } } if (conn != null) { try { conn.close(); } catch (SQLException ex1) { Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex1); } } } return OrderDetailList; }
83a4b258-89f9-4143-9d24-926043ba6c42
1
public void test_isoChrononolgy_Chicago() { DateTimeZone zone = DateTimeZone.forID("America/Chicago"); Chronology lenient = ISOChronology.getInstance(zone); try { new DateTime(2007, 3, 11, 2, 30, 0, 0, lenient); fail(); } catch (IllegalArgumentException ex) { // expected } }
b3f87a99-91d0-4014-96dc-62718686fe40
1
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); for(HashBucket bucket : map) { sb.append(bucket.toString()); } sb.append("]"); return sb.toString(); }
7e50a157-ade8-431b-8212-1535d7b6ac21
4
public void listen(int port) { try { server = new ServerSocket(port); listening = true; while (listening) { new TCPClient(server.accept()).start(); } } catch (Exception ex) { if (!ex.getMessage().equals("socket closed") && !server.isClosed()) ex.printStackTrace(); } }
4489e746-d3b2-4c4f-9ee8-175706550aa2
9
public static ToolsRunner getRunnerTool(String actionName) { Preconditions.checkNotNull(actionName, "No Action is set. Please see usage:\n" + getUsageStr()); Preconditions.checkArgument( actionName.equals("sar") || actionName.equals("jobserver") || actionName.equals("schemaserver") || actionName.equals("metadataserver") || actionName.equals("property"), "app:{jobserver/schemaserver/metadataserver/sar/property}"); if ("sar".equals(actionName)) { return new ResultProcessRunner(); } else if ("jobserver".equals(actionName)) { return new JobServerRunner(); } else if ("metadataserver".equals(actionName)) { return new MetaDataServerRunner(); } else if ("schemaserver".equals(actionName)) { return new SchemaServerRunner(); } else if ("property".equals(actionName)) { return new PropertiesRunner(); } return null; }
0d53b06c-a281-4fca-be33-2df20d68f7d3
2
protected void setDirtiness(double dirtiness) { this.dirtiness = dirtiness; if (this.dirtiness < 0) { this.dirtiness = 0; } else if (this.dirtiness > 0.25) { this.dirtiness = 0.25; } }
57d4e087-6c36-4308-b072-95367e98ab2f
8
public static void removeProject(Project project, boolean delete) { int sym = project.getSym(); boolean found = false; ArrayList<Project> projects = new ArrayList<Project>(); if( project.isLocal() ) projects = getProjects(project.getDir()); else projects = getProjects(sym); int i = 0; for (Project cur : projects) { if (cur.getName().equals(project.getName())){ found = true; break; } i++; } if(!found) return; projects.remove(i); if( project.isLocal() ) saveProjects(project.getDir()); else saveProjects(sym); if (delete) for (SymitarFile file : project.getFiles()) if( file.isLocal() ) new File( file.getPath() ).delete(); else RepDevMain.SYMITAR_SESSIONS.get(sym).removeFile(file); }
1db5583e-fb95-44f1-8e85-a32783eca051
6
public byte[] getCode(int bit) { byte[] res; assert ((bit == 0) || (bit == 1)) : "getCode: input isn't a bit!"; if (bit == 0) { if (code0 == null) return(null); res = new byte[code0.length]; for (int i = 0 ; i < code0.length ; i++) res[i] = code0[i]; } else { if (code1 == null) return(null); res = new byte[code1.length]; for (int i = 0 ; i < code1.length ; i++) res[i] = code1[i]; } return (res); }
3ef8f870-916a-4ad1-8c24-a0e00439994f
9
protected void doubleLoop(RasterAccessor src, RasterAccessor dst, int filterSize) { int dwidth = dst.getWidth(); int dheight = dst.getHeight(); int dnumBands = dst.getNumBands(); double dstDataArrays[][] = dst.getDoubleDataArrays(); int dstBandOffsets[] = dst.getBandOffsets(); int dstPixelStride = dst.getPixelStride(); int dstScanlineStride = dst.getScanlineStride(); double srcDataArrays[][] = src.getDoubleDataArrays(); int srcBandOffsets[] = src.getBandOffsets(); int srcPixelStride = src.getPixelStride(); int srcScanlineStride = src.getScanlineStride(); double medianValues[] = new double[filterSize]; double tmpValues[] = new double[filterSize]; int wp = filterSize; double tmpBuffer[] = new double[filterSize*dwidth]; int tmpBufferSize = filterSize*dwidth; for (int k = 0; k < dnumBands; k++) { double dstData[] = dstDataArrays[k]; double srcData[] = srcDataArrays[k]; int srcScanlineOffset = srcBandOffsets[k]; int dstScanlineOffset = dstBandOffsets[k]; int revolver = 0; for (int j = 0; j < filterSize-1; j++) { int srcPixelOffset = srcScanlineOffset; for (int i = 0; i < dwidth; i++) { int imageOffset = srcPixelOffset; for (int v = 0; v < wp; v++) { tmpValues[v] = srcData[imageOffset]; imageOffset += srcPixelStride; } tmpBuffer[revolver+i] = medianFilterDouble(tmpValues); srcPixelOffset += srcPixelStride; } revolver += dwidth; srcScanlineOffset += srcScanlineStride; } // srcScanlineStride already bumped by // filterSize-1*scanlineStride for (int j = 0; j < dheight; j++) { int srcPixelOffset = srcScanlineOffset; int dstPixelOffset = dstScanlineOffset; for (int i = 0; i < dwidth; i++) { int imageOffset = srcPixelOffset; for (int v = 0; v < wp; v++) { tmpValues[v] = srcData[imageOffset]; imageOffset += srcPixelStride; } tmpBuffer[revolver + i] = medianFilterDouble(tmpValues); int a = 0; for (int b = i; b < tmpBufferSize; b += dwidth) { medianValues[a++] = tmpBuffer[b]; } double val = medianFilterDouble(medianValues); dstData[dstPixelOffset] = val; srcPixelOffset += srcPixelStride; dstPixelOffset += dstPixelStride; } revolver += dwidth; if (revolver == tmpBufferSize) { revolver = 0; } srcScanlineOffset += srcScanlineStride; dstScanlineOffset += dstScanlineStride; } } }
90d6116c-b12b-407a-ab28-01b4d539bff0
2
protected void setLineList(List<String> lines) { if ((lines == null) || (lines.size() == 0)) { IllegalArgumentException iae = new IllegalArgumentException("The list must not be null or without entries!"); Main.handleUnhandableProblem(iae); } this.uiFileLines = new ArrayList<String>(lines); }
bac75db7-9a18-4aed-bf77-75d1dabbaeaa
8
private void selectAndPossiblyCenter(JTextComponent component, int start, int end) { component.setSelectionStart(start); component.setSelectionEnd(end); Rectangle r = null; try { r = component.modelToView(start); if (r == null) { // Not yet visible; i.e. JUnit tests return; } if (end != start) { r = r.union(component.modelToView(end)); } } catch (BadLocationException ble) { // Never happens ble.printStackTrace(); component.setSelectionStart(start); component.setSelectionEnd(end); return; } Rectangle visible = component.getVisibleRect(); // If the new selection is already in the view, don't scroll, // as that is visually jarring. if (visible.contains(r)) { component.setSelectionStart(start); component.setSelectionEnd(end); return; } visible.x = r.x - (visible.width - r.width) / 2; visible.y = r.y - (visible.height - r.height) / 2; Rectangle bounds = component.getBounds(); Insets i = component.getInsets(); bounds.x = i.left; bounds.y = i.top; bounds.width -= i.left + i.right; bounds.height -= i.top + i.bottom; if (visible.x < bounds.x) { visible.x = bounds.x; } if (visible.x + visible.width > bounds.x + bounds.width) { visible.x = bounds.x + bounds.width - visible.width; } if (visible.y < bounds.y) { visible.y = bounds.y; } if (visible.y + visible.height > bounds.y + bounds.height) { visible.y = bounds.y + bounds.height - visible.height; } component.scrollRectToVisible(visible); }
19b41712-42c9-438e-82db-5c89f7db460a
1
private static boolean deleteSchedule(Schedule bean, PreparedStatement stmt) throws SQLException{ stmt.setDate(1, bean.getWorkDay()); stmt.setString(2, bean.getUsername()); int affected=stmt.executeUpdate(); if(affected==1){ System.out.println("Employee with username "+bean.getUsername()+" is not working on "+bean.getWorkDay()); } else { System.out.println("unable to delete schedule from database"); return false; } return true; }
753c9112-8161-44d7-98ae-5281b4874570
0
public void teleopPeriodic() { // Runs commands & stuff Scheduler.getInstance().run(); }
90ab1d29-99a9-48e3-9587-e8ee0e6a8d0b
4
public ArrayList<Libros> getById(Libros l){ PreparedStatement ps; ArrayList<Libros> libros = new ArrayList<>(); try { ps = mycon.prepareStatement("SELECT * FROM Libros WHERE codigo=?"); ps.setString(1, l.getCodigolibro()); ResultSet rs = ps.executeQuery(); if(rs!=null){ try { while(rs.next()){ Libros l1 = new Libros( rs.getString("codigo"), rs.getString("nombre"), rs.getString("titulo"), rs.getString("autor"), rs.getInt("cantidad") ); l1.setPrestados(rs.getInt("prestados")); libros.add(l1); } } catch (SQLException ex) { Logger.getLogger(Libros.class.getName()). log(Level.SEVERE, null, ex); } }else{ System.out.println("Total de registros encontrados es: 0"); } } catch (SQLException ex) { Logger.getLogger(LibrosCRUD.class.getName()).log(Level.SEVERE, null, ex); } return libros; }
7f398429-85f4-4c32-99f5-c87d521b86ae
0
public static void FinalBoss() { currentRoomName = "Final Boss"; currentRoom = 9; RoomDescription = "The door swings open and as you take a step in, the lights turn on and confetti falls from the " + "ceiling, a party of giant dancing lobsters come out from hiding and start to boogie.\n\n" + "Congratulations, you have just won Corlanthia"; }
27248bca-217c-4804-a992-28f71a876cb1
8
public static void getServerList() { if (Global.FIRST_IP.equals(Global.NO_FIRST_SERVER)) { Donnees.fillingServers(false); return; // premier serveur } Stockage.Donnees.fillingServers(true); try (SocketChannel clientSocket = SocketChannel.open()) { InetSocketAddress local = new InetSocketAddress(Global.TCP_PORT+3); clientSocket.bind(local); Utilitaires.out("Ack 1.5 " + Global.FIRST_IP + " " + Global.FIRST_PORT); Utilitaires.out("Ack 2 " + (Global.TCP_PORT)); InetSocketAddress remote = new InetSocketAddress(Global.FIRST_IP, Global.FIRST_PORT); clientSocket.connect(remote); clientSocket.write(Utilitaires.stringToBuffer(Message.GET_LIST)); String token; String liste; boolean continuer = true; while (continuer) { liste = Utilitaires.getAFullMessage(Message.END_ENVOI, clientSocket); Scanner sc = new Scanner (liste); while (sc.hasNext()) { token = sc.next(); if (token.equals(Message.END_ENVOI)) { continuer = false; break; } if (token.equals(Message.NEXT_BUFFER)) { break; } if (token.equals(Message.BEGIN)) { try { Donnees.putServer(sc.next(), Integer.parseInt(sc.next())); } catch (Exception e) { // Parsing error - Nobody cares } } } sc.close(); } clientSocket.close(); } catch (Exception e) { Utilitaires.out("Fatal error in getServerList"); e.printStackTrace(); System.exit(-1); } Donnees.printServerList(); Donnees.fillingServers(false); }
737a4e86-75f6-4df2-a455-e46f348ef18b
5
private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed if (txtConclusao.getText().equals("") || txtHoras.getText().equals("")) { JOptionPane.showMessageDialog(null, "Erro ao realizar o Lançamento !!! \n Por Favor Preencha os Campos", "Lançamento de Atividade", JOptionPane.ERROR_MESSAGE); } else { if (cmbAtividade.getSelectedItem().equals("Selecione")) { JOptionPane.showMessageDialog(null, "Erro ao realizar o Lançamento !!! \n Por Favor selecione a atividade", "Lançamento de Atividade", JOptionPane.ERROR_MESSAGE); } else { try { Float Conclusao = Float.parseFloat(txtConclusao.getText()); Float HorasTrabalhadas = Float.parseFloat(txtHoras.getText()); Atividade atividade = new Atividade(); atividade.setConlusao(Conclusao); atividade.setHorasTrabalhadas(HorasTrabalhadas); String AtividadeSelcionada = (String) this.cmbAtividade.getSelectedItem(); AtividadeBO atividadeBO = new AtividadeBO(); atividadeBO.andamentoAtividade(atividade, AtividadeSelcionada); JOptionPane.showMessageDialog(null, "Lançamento realizado com Sucesso!", "Lançamento de Atividade ", JOptionPane.INFORMATION_MESSAGE); logSegurancaDados log = null; log = new logSegurancaDados("INFO", "Lançamento de Horas na Atividade: " + cmbAtividade.getSelectedItem() + "realizada com sucesso pelo " + usuarioLogado.getTipo() + " : " + usuarioLogado.getNome()); txtConclusao.setText(""); txtHoras.setText(""); cmbAtividade.setSelectedItem("Selecione"); } catch (SQLException ex) { } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "Digite somente numeros nos campos !!! \n " + "Formato aceitavel(Hrs.Min) - Ex(10.30)", "Cadastro de Atividade", JOptionPane.ERROR_MESSAGE); } } } }//GEN-LAST:event_btnSalvarActionPerformed
2925de5c-d021-4e41-98ab-46491a57d0b8
4
public RSStub() { String source; try { source = getPageSource(getCodeBase()); Matcher aMatcher = aPattern.matcher(source); if (aMatcher.find()) { Matcher pMatcher = pPattern.matcher(source); while (pMatcher.find()) { String key = pMatcher.group(1); String value = pMatcher.group(2); parameters.put(key, value); } if (source.contains("archive")) { parameters.put("archive", source.substring( source.indexOf("archive=") + 8, source.indexOf(".jar") + 4)); } } } catch (IOException | InterruptedException e) { e.printStackTrace(); } }
87b08ade-d0c1-4a91-940c-6965b8218d3a
5
private static double hue_2_RGB(double v1, double v2, double vH) { if (vH < 0.0) vH += 1; if (vH > 1.0) vH -= 1; if (6 * vH < 1) return ( v1 + (v2-v1) * 6.0 * vH); if (2 * vH < 1) return ( v2 ); if (3 * vH < 2) return v1 + (v2-v1) * ((2.0/3.0) - vH) * 6; return v1; }
ece3f950-4387-46cf-b733-daa6b7f9423a
0
public String getStworz() { return stworz; }
fd207d78-8068-4055-84d7-3b59704852d9
4
private BlankExpression evalExpression(String rawExpression) throws Exception { BlankVar var; // variavel auxiliar para guardar uma BlankVar String[] analysis = rawExpression.split(operationIdentifier.toString()); // Identifica a operação realizada Matcher operationMatcher = operationIdentifier.matcher(rawExpression); operationMatcher.find(); String op = operationMatcher.toMatchResult().group().trim(); String val1 = analysis[0].trim(); String val2 = analysis[1].trim(); // Pega o primeiro valor Matcher paramMatcher = paramIdentifier.matcher(val1); if (paramMatcher.find()) { String opValue1 = paramMatcher.toMatchResult().group(); if (mainScope.hasVariable(opValue1) >= 0) { // verifica se é uma variavel var = mainScope.getVariable(opValue1); val1 = var.getValue(); } else { val1 = opValue1; } } // Encontra o segundo valor paramMatcher = paramIdentifier.matcher(val2); if (paramMatcher.find()) { String opValue2 = paramMatcher.toMatchResult().group(); if (mainScope.hasVariable(opValue2) >= 0) { // verifica se é uma variavel var = mainScope.getVariable(opValue2); val2 = var.getValue(); } else { val2 = opValue2; } } // Cria um novo calculo de expressão return (new BlankExpression(val1, val2, op)); }
c57eb331-c1ca-4a8d-907d-2e485fb3be27
1
public String getSimpleCode(){ String str = ""; if(expression != null){ str += expression.getSimpleCode() + this.printLineNumber(true) + identifier.getNewName() + " := " + expression.place + "\n"; } return str; }
800d26e8-40c4-448c-935b-c2af7084cdd3
3
@Override public Map<String, Integer> getIngressoDisponiveis(Evento evento){ Map<String, Integer> ingresso = new HashMap<>(); try{ conn = ConnectionFactory.getConnection(); String sql = " SELECT secao.nome " + " ,count(ingresso.id) AS ingressos " + " FROM ingresso " + " JOIN secao ON ingresso.idsecao = secao.id " + " JOIN evento ON secao.idevento = evento.id " + " WHERE ingresso.idcompra IS NULL AND evento.nome LIKE ? " + " GROUP BY secao.nome"; ps = conn.prepareStatement(sql); ps.setString(1, evento.getNome()); rs = ps.executeQuery(); while (rs.next()) { String secaolida = rs.getString("nome"); int ingressolido = rs.getInt("ingressos"); ingresso.put(secaolida, ingressolido); } return ingresso; } catch (SQLException e){ throw new RuntimeException("Erro " + e.getSQLState() + " ao atualizar o objeto: " + e.getLocalizedMessage()); } catch (ClassNotFoundException e){ throw new RuntimeException("Erro ao conectar ao banco: " + e.getMessage()); } finally{ close(); } }
d2674720-aebf-48ed-9482-25d09d680f6a
5
public boolean close() { if (!isOpen()) { return true; } Widget close = ctx.widgets.getValidated(new Filter<Widget>() { @Override public boolean accept(Widget element) { return element.getParentId() == WIDGET_ID && element.getId() == CLOE_COMP_ID; } }).get(0); if (close != null) { Point p = getCenter(close.getBounds()); ctx.mouse.click(p.x, p.y); Timer t = new Timer(3000); while (isOpen() && t.isRunning()) { Utils.sleep(Utils.random(100, 200)); } } return !isOpen(); }
dd1ecb7e-e3f2-40ae-9a34-fd746cf25634
5
void jMenuItem_zoom_actionPerformed(ActionEvent e) { int zoomFactor = 0; if (e.getSource() == jMenuItem_zoom1) zoomFactor = 1; else if (e.getSource() == jMenuItem_zoom2) zoomFactor = 2; else if (e.getSource() == jMenuItem_zoom4) zoomFactor = 4; else if (e.getSource() == jMenuItem_zoom8) zoomFactor = 8; if (imagemapPanel.zoom(zoomFactor) == false) jMenuItem_zoom1.setSelected(true); vRule.repaint(); hRule.repaint(); }
a7272516-e208-42ba-99be-4a6af4aaf35e
5
protected static boolean isFlacSpecial(OggPacket packet) { byte[] d = packet.getData(); byte type = d[0]; // Ensure 0x7f then "FLAC" if(type == 0x7f) { if(d[1] == (byte)'F' && d[2] == (byte)'L' && d[3] == (byte)'A' && d[4] == (byte)'C') { return true; } } return false; }
3de726c2-cf36-42bb-9328-4bd5ec487ca8
2
public static List<Utilisateur> selectUtilisateur() throws SQLException { String query = null; List<Utilisateur> util = new ArrayList<Utilisateur>(); ResultSet resultat; try { query = "SELECT * from UTILISATEUR "; PreparedStatement pStatement = (PreparedStatement) ConnectionBDD.getInstance().getPreparedStatement(query); resultat = pStatement.executeQuery(query); while (resultat.next()) { // System.out.println(resultat.getString("PAYS")); Utilisateur uu = new Utilisateur(resultat.getInt("ID_UTILISATEUR"), resultat.getInt("ID_FONCTION"), resultat.getInt("ID_VILLE"), resultat.getString("UTILNOM"), resultat.getString("UTILPRENOM"), resultat.getString("IDENTIFIANT"), resultat.getString("PASSWORD")); util.add(uu); } } catch (SQLException ex) { Logger.getLogger(RequetesUtilisateur.class.getName()).log(Level.SEVERE, null, ex); } return util; }
3008f6f4-10a9-4f93-a2bb-35b346e84e4e
8
private void handleSpecialistQueues() { for (int i = 1; i < 8; i++) { HospitalPart hp = HospitalPart.values()[i]; Sector sec = sectors.get(hp); LinkedBlockingDeque<Patient> q = doc_queues.get(hp); if (sec.hasBusyDoc()) { int[] tmp = sec.getFinishTimes(); for (int j = 0; j < sec.getDocCount(); j++) { if (tmp[j] == clock) { Patient patientOut = sec.goOut(j, hp.toString(), q.size()); // System.out.println(q.size()); if (q.size() > 0) { // for (Patient patient : q) { // System.out.println("@@@@@@@@@@@@@"); // System.out.println(patient.getPatientId()); // if ( sec.isBusy() ) // System.out.println("WtF ?!"); // } } SpecialistWorkType workType = random .getSpecialistWorkType(); if (workType == SpecialistWorkType.HOSPITALIZE) { // HospitalPart hp2 = random.getHospitalizeRoom(); doUrganceStuff(patientOut); // doc_queues.get(hp2).add(patientOut); } } } } // System.out.println("HERE:: " + sec.isBusy() + " " + q.size()); if (q.size() > 0 && !sec.isBusy()) { Patient p = q.poll(); int docId = sec.setPatient(p); // TODO expo sec.setFinish_time((int)Distributions.ExponentialRandomNumber(sec.lamda ), docId); // + clock); // sec.setFinish_time(10 + clock, docId); Hospital.log("biya tooo " + hp, clock, p, hp.toString(), q.size()); } } }
f48878bd-84d0-4bed-a8a9-65ebffc3c386
3
public static void addStock(String uid, String id, int amount) { if(checkUserExistance(uid)) { stocks = UserControl.getUserStock(uid); if (stocks.containsKey(id)) { stocks.put(id, stocks.get(id) + amount); } else { stocks.put(id, amount); } try { Stock currentStock = StockControl.queryStock(id); System.out.println(currentStock); UserStorageAccess xmlAccessor = new UserStorageAccess(); xmlAccessor.addStock(uid,currentStock .getPrice()*amount,stocks); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
d53c1da6-3a6e-4902-97d3-a03c07e45817
9
private void calcG(int choice) { /* calculates the g values. choice parameter is the stage selection */ int index, grstep, i; double d2; switch (choice) { case 1:// initialization for (i = 0; i < ngr; i++) { g[i] = 0.0; } break; case 2: // Compute g of r for (i = 0; i < numberOfParticles - 1; i++) { for (int j = i + 1; j < numberOfParticles; j++) { dx = getParticleX(i) - getParticleX(j); dy = getParticleY(i) - getParticleY(j); // Handle Images for Periodic Boundary Conditions pbclParticles(); // Calculate the 2D distance d2 = Math.sqrt(dx * dx + dy * dy); // Check if outside range if (d2 <= grange) { index = (int) (d2 / dr); g[index] += 2.0; } } } break; case 3: grstep = (numberOfSteps - noneq) / dataDump; double dV; for (i = 1; i < ngr; i++) { r[i] = i * dr; dV = 2.0 * Math.PI * ((r[i] + dr) * (r[i] + dr) - r[i] * r[i]); // generalize g[i] = g[i] / (dV * grstep * numberOfParticles * (numberOfParticles - 1) / (2.0 * volume)); } for (i = 0; i < ngr; i++) { r[i] += 0.5 * dr; } break; default: System.out.println("error in g[r] calculation"); break; } }
b27b6084-f151-4e9a-9d4e-5e1de9c14061
4
/*Update Permissions*/public boolean changePermissions(String username, PermissionsList list){ try{ if(username.length() > 40)return false; select1.setString(1, username); ResultSet rs = select1.executeQuery(); while(rs.next()){ if(rs.getString("username").equals(username)){ updatePermissions.setBytes(1, list.toByteArray()); updatePermissions.setString(2, username); updatePermissions.executeUpdate(); return true; } } }catch(Exception e){e.printStackTrace();} return false; }
7a02c097-70bc-407b-bf7d-70e75fe8d557
1
public String getRoomNames(){ Set<String> keys = chatRooms.keySet(); StringBuffer ret = new StringBuffer(keys.toString().length()+11); ret.append("Chat rooms: ["); for (String key : keys){ ret.append(""+chatRooms.get(key).getName()+", "); } ret.delete(ret.length()-2, ret.length()); ret.append("]"); return ret.toString(); }
7f102be1-db33-4065-a7b5-e6272c16a2c7
9
static private DamageCause[] getTypes() { if (typecache != null) return typecache; List<DamageCause> causes = new ArrayList<DamageCause>(); Field[] materialFields = DamageCause.class.getFields(); for (Field f : materialFields) { try { Object got = f.get(null); if (got instanceof DamageCause) { if (got == DamageCause.CUSTOM || got == DamageCause.MELTING || got == DamageCause.FIRE_TICK || got == DamageCause.VOID || got == DamageCause.SUICIDE) continue; causes.add((DamageCause) f.get(null)); } } catch (Exception ex) {} } typecache = causes.toArray(new DamageCause[0]); return typecache; }
c515e677-170a-4f23-8d5e-a99828da43df
0
public void showPauseMenu(){ pauseMenu.show(); }
64b4078e-73d2-4ad5-a447-989018514503
5
@Override public String toString() { String result = ""; if(useShift) { if(System.getProperty("os.name").toLowerCase().indexOf("mac") >= 0) result+='\u2191'; else result+="SHFT"; } if(useControl) result+="CTRL"; if(useMeta) result += "\u2318"; for(int x : shortcuts) { result += getStringFromID(x); } return result; }