method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
e3b1606a-8a93-4485-907c-ac9d5234356f
5
public void newPacket(DataPacket packet) { if(monitor != null || client != null) { if(packet.getData().length > 0) System.out.println(packet.getSource() + "-" + new String(packet.getData())); if (packet.isKeepAlive()) { this.monitor.messageReceived(packet); } else if (packet.isRouting()) { this.router.packetReceived(packet); } else { this.client.packetReceived(packet); } } else { return; } }
a93f16d0-02ba-4f05-9281-4472756719b7
0
@BeforeTest public void setup() { addressBookData = "src/test/resources/address_book.csv"; data = Data.getDataAsList(addressBookData); addressBook = new AddressBook(data); }
032f1caa-57a3-4759-98d8-21dabc0bc6d5
2
private void setConfigs(Matrix new_m, int[] start, int[] vector, int[] start_vector) { assert start.length == 2; assert vector.length == 2; assert start_vector.length == 2; m = new_m; starting_point[0] = (start[0] < 0) ? m.width-start[0] : start[0]; starting_point[1] = (start[1] < 0) ? m.height-start[1] : start[1]; point_vector = vector; starting_point_vector = start_vector; calculateNext(); }
70f14a42-fa7f-412f-963b-593444b3f3b3
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Node<?> other = (Node<?>) obj; if (data == null) { if (other.data != null) return false; } else if (!data.equals(other.data)) return false; return true; }
67183684-5816-4856-8b79-f751b8d10a6b
7
public static boolean isMuted(String player){ if (player == null) return false; else { Double mute = config.getDouble("mute.".concat(player.toLowerCase()).concat(".time"), 0); if (mute == -1){ return true; } else if (mute == 0){ deleteMute(player); return false; } else { mute *= 1000; Long start; try { start = (Long) config.get("mute.".concat(player).concat(".start")); } catch (Exception e){ return true; } if (start == null) { return true; } Long mutems = Long.parseLong(Integer.toString(mute.intValue())); if (mutems == null) return false; mutems += start; if (System.currentTimeMillis() < mutems){ return true; } else { deleteMute(player); return false; } } } }
d68a54a4-5c87-4202-a276-e2eba229ade2
8
public void copyResource(DocPath resource, boolean overwrite, boolean replaceNewLine) { if (exists() && !overwrite) return; try { InputStream in = Configuration.class.getResourceAsStream(resource.getPath()); if (in == null) return; OutputStream out = openOutputStream(); try { if (!replaceNewLine) { byte[] buf = new byte[2048]; int n; while((n = in.read(buf))>0) out.write(buf,0,n); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); BufferedWriter writer; if (configuration.docencoding == null) { writer = new BufferedWriter(new OutputStreamWriter(out)); } else { writer = new BufferedWriter(new OutputStreamWriter(out, configuration.docencoding)); } try { String line; while ((line = reader.readLine()) != null) { writer.write(line); writer.write(DocletConstants.NL); } } finally { reader.close(); writer.close(); } } } finally { in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(System.err); throw new DocletAbortException(e); } }
085d3eb4-fa87-4a38-b851-d907e15fcbef
8
static final boolean method2510(IndexLoader class45, Class348_Sub16_Sub3 class348_sub16_sub3, IndexLoader class45_5_, boolean bool, Class279 class279, IndexLoader class45_6_) { try { Class318_Sub1_Sub4.aClass279_8764 = class279; Class98.aClass348_Sub16_Sub3_1564 = class348_sub16_sub3; Class43.aClass45_611 = class45; Class367_Sub9.aClass45_7371 = class45_6_; Class333.aClass45_4147 = class45_5_; Class367_Sub3.anIntArray7299 = new int[16]; if (bool != false) anInt6451 = 71; anInt6442++; for (int i = 0; i < 16; i++) Class367_Sub3.anIntArray7299[i] = 255; return true; } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929 (runtimeexception, ("rba.G(" + (class45 != null ? "{...}" : "null") + ',' + (class348_sub16_sub3 != null ? "{...}" : "null") + ',' + (class45_5_ != null ? "{...}" : "null") + ',' + bool + ',' + (class279 != null ? "{...}" : "null") + ',' + (class45_6_ != null ? "{...}" : "null") + ')')); } }
d7bfee50-ad90-43e6-b01d-2636ae0fd5e3
4
public int minusDILookback( int optInTimePeriod ) { if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) ) optInTimePeriod = 14; else if( ((int)optInTimePeriod < 1) || ((int)optInTimePeriod > 100000) ) return -1; if( optInTimePeriod > 1 ) return optInTimePeriod + (this.unstablePeriod[FuncUnstId.MinusDI.ordinal()]) ; else return 1; }
db21fa90-6268-4f3d-8431-c3ec04bca953
6
public void onAction(String binding, boolean isPressed, float tpf) { if (binding.equals(KeyMapper.MOVE_LEFT)) { left = isPressed; } else if (binding.equals(KeyMapper.MOVE_RIGHT)) { right = isPressed; } else if (binding.equals(KeyMapper.MOVE_FORWARD)) { up = isPressed; } else if (binding.equals(KeyMapper.MOVE_BACKWARD)) { down = isPressed; } else if (binding.equals(KeyMapper.PLAYER_JUMP)) { jumping = isPressed; } else if (binding.equals(KeyMapper.MOVE_FAST)) { fast = isPressed; } }
f60ca004-d92f-4f8d-babf-6c71523db47b
8
public static Program parseASM(String text, String defaultLabel) throws ParserException{ // break into lines String[] lines = text.split("\n"); // Create an alias map to keep track of redundant labels AliasMap aliasMap = new AliasMap(); // Create a new program Program prog = new Program(); // Create new segment, "" String label = defaultLabel; Segment segment = new Segment(); // Prepare pattern for recognizing comments Pattern pattern_comment = Pattern.compile("\\s*\\#.*", Pattern.CASE_INSENSITIVE); // Prepare pattern for recognizing labels Pattern pattern_label = Pattern.compile("\\s*(@[\\._\\~A-Z]+)", Pattern.CASE_INSENSITIVE); // for each line: for (int lineNumber=0; lineNumber<lines.length; lineNumber++){ // remove leading and trailing whitespace String line = lines[lineNumber].trim(); // Ignore empty lines if (line.length() == 0){ // done handling this line continue; } // Ignore comments Matcher REComment = pattern_comment.matcher(line); if (REComment.matches()){ // done handling this line continue; } // Handle labels Matcher RELabel = pattern_label.matcher(line); if (RELabel.matches()){ // handle label String newLabel = RELabel.group(1); // if current segment is empty: if (segment.isEmpty()){ // Unless the label currently has no name, if (label == ""){ // (in which case we populate the name with the new label) label = newLabel; } else { // the new label is an alias aliasMap.add(newLabel, label); } } else { // otherwise it begins a new segment, // so we record the old segment prog.addSegment(label, segment); // and initialize a new one label = newLabel; segment = new Segment(); } // done handling this line continue; } // If it isn't any of the above, it must be an instruction (or an illegal statement) try { Instruction instruction = Instruction.disassemble(line); // If no exception has occurred, this is indeed an instruction. // add it to the current segment segment.add(instruction); } catch (ParserException e) { throw e; } } // close current segment if (!segment.isEmpty()){ prog.addSegment(label, segment); } // resolve aliases! prog.deAlias(aliasMap); // done! return prog; }
63c08e69-a693-4731-ba37-bd1dc65909ad
8
public static List<Edge> dijkstraShortestPath(Graph g, int sourceVertex, int destinationVertex) { Set<Integer> mould = new HashSet<>(); Set<Integer> universe = new HashSet<>(); universe.addAll(g.getAllVertex()); Map<Integer,List<Edge>> shortestPath = new HashMap<>(); final Map<Integer,Integer> shortestCost = new HashMap<>(); mould.add(sourceVertex); universe.remove(sourceVertex); shortestPath.put(sourceVertex,new ArrayList<Edge>()); shortestCost.put(sourceVertex,0); PriorityQueue<Edge> heap = new PriorityQueue<>(universe.size(),new Comparator<Edge>(){ @Override public int compare(Edge e1, Edge e2) { return Integer.compare(e1.weight+shortestCost.get(e1.from), e2.weight+shortestCost.get(e2.from)); } }); while(!universe.isEmpty()) { // go through all the vertices of the mould for(int vertex: mould){ // check all outgoing edges for(Edge edge: g.getEdges(vertex)) { // add the edge which is not targetting to a edge present in the mould if(!mould.contains(edge.to) && !heap.contains(edge)){ heap.add(edge); } } } //this will find the next edge to be included which has minimum shortest Cost till origin +weight //remove it from the heap Edge target = null; //get the edge which has minimum cost and which goes to a destination not already in mould. while(true) { //special case : if the supplied graph is a disconnected graph if(heap.isEmpty()) { return shortestPath.get(destinationVertex); } target = heap.remove(); if(!mould.contains(target.to)){ break; } } // remove the target vertex from universe universe.remove(target.to); // add it to mould mould.add(target.to); //update the shortest path List<Edge> shortestPathForTarget = new ArrayList<>(); shortestPathForTarget.addAll(shortestPath.get(target.from)); shortestPathForTarget.add(target); shortestPath.put(target.to,shortestPathForTarget); // update the shortest cost shortestCost.put(target.to, shortestCost.get(target.from) + target.weight ); } return shortestPath.get(destinationVertex); }
18d90a5b-14f3-4e0e-b668-34b7f28dc246
8
private void generateCallMethod(ClassFileWriter cfw) { cfw.startMethod("call", "(Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "Lorg/mozilla/javascript/Scriptable;" + "[Ljava/lang/Object;)Ljava/lang/Object;", (short)(ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); // Generate code for: // if (!ScriptRuntime.hasTopCall(cx)) { // return ScriptRuntime.doTopCall(this, cx, scope, thisObj, args); // } int nonTopCallLabel = cfw.acquireLabel(); cfw.addALoad(1); //cx cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/ScriptRuntime", "hasTopCall", "(Lorg/mozilla/javascript/Context;" +")Z"); cfw.add(ByteCode.IFNE, nonTopCallLabel); cfw.addALoad(0); cfw.addALoad(1); cfw.addALoad(2); cfw.addALoad(3); cfw.addALoad(4); cfw.addInvoke(ByteCode.INVOKESTATIC, "org/mozilla/javascript/ScriptRuntime", "doTopCall", "(Lorg/mozilla/javascript/Callable;" +"Lorg/mozilla/javascript/Context;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +")Ljava/lang/Object;"); cfw.add(ByteCode.ARETURN); cfw.markLabel(nonTopCallLabel); // No generate switch to call the real methods cfw.addALoad(0); cfw.addALoad(1); cfw.addALoad(2); cfw.addALoad(3); cfw.addALoad(4); int end = scriptOrFnNodes.length; boolean generateSwitch = (2 <= end); int switchStart = 0; int switchStackTop = 0; if (generateSwitch) { cfw.addLoadThis(); cfw.add(ByteCode.GETFIELD, cfw.getClassName(), ID_FIELD_NAME, "I"); // do switch from (1, end - 1) mapping 0 to // the default case switchStart = cfw.addTableSwitch(1, end - 1); } for (int i = 0; i != end; ++i) { ScriptOrFnNode n = scriptOrFnNodes[i]; if (generateSwitch) { if (i == 0) { cfw.markTableSwitchDefault(switchStart); switchStackTop = cfw.getStackTop(); } else { cfw.markTableSwitchCase(switchStart, i - 1, switchStackTop); } } if (n.getType() == Token.FUNCTION) { OptFunctionNode ofn = OptFunctionNode.get(n); if (ofn.isTargetOfDirectCall()) { int pcount = ofn.fnode.getParamCount(); if (pcount != 0) { // loop invariant: // stack top == arguments array from addALoad4() for (int p = 0; p != pcount; ++p) { cfw.add(ByteCode.ARRAYLENGTH); cfw.addPush(p); int undefArg = cfw.acquireLabel(); int beyond = cfw.acquireLabel(); cfw.add(ByteCode.IF_ICMPLE, undefArg); // get array[p] cfw.addALoad(4); cfw.addPush(p); cfw.add(ByteCode.AALOAD); cfw.add(ByteCode.GOTO, beyond); cfw.markLabel(undefArg); pushUndefined(cfw); cfw.markLabel(beyond); // Only one push cfw.adjustStackTop(-1); cfw.addPush(0.0); // restore invariant cfw.addALoad(4); } } } } cfw.addInvoke(ByteCode.INVOKESTATIC, mainClassName, getBodyMethodName(n), getBodyMethodSignature(n)); cfw.add(ByteCode.ARETURN); } cfw.stopMethod((short)5); // 5: this, cx, scope, js this, args[] }
107b32c8-f576-451e-abe8-f25d9d47a92c
2
public static boolean propertyEqualsAsInt(PropertyContainer container, String key, int test_value) { if (container != null) { try { int value = getPropertyAsInt(container, key); return value == test_value; } catch (NullPointerException npe) { return false; } } else { throw new IllegalArgumentException("Provided PropertyContainer was null."); } }
7a5809fc-3a63-499d-b6c7-a706adc980f8
6
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onDropLockedItemOnDeath(PlayerDeathEvent event) { if (event.getEntity().getWorld().isGameRule("keepInventory")) { return; } final Player player = event.getEntity(); if (player.hasPermission("disable.slot.locking")) { return; } List<ItemStack> drops = event.getDrops(); drops.clear(); PlayerInventory inv = player.getInventory(); final Map<Integer, ItemStack> toKeep = new TreeMap<>(); for (int index = 0; index < 40; index++) { if (player.hasPermission("cyom.slot.lock." + index)) { toKeep.put(index, inv.getItem(index)); } else { drops.add(inv.getItem(index)); } } if (!toKeep.isEmpty()) { new BukkitRunnable() { @Override public void run() { PlayerInventory inv = player.getInventory(); for (Map.Entry<Integer, ItemStack> entry : toKeep.entrySet()) { inv.setItem(entry.getKey(), entry.getValue()); } } }.runTask(plugin); } }
52bdc822-1d10-4bef-b3f8-30a9decbb081
7
public HashMap<String, Vector<Vector<Integer>>> generateSocaialFeature(String fileName){ String[] handPickRelevantUser = null; if(fileName.equalsIgnoreCase("NUS1")){ handPickRelevantUser = new String[] { "NUSingapore", "NUSLibraries", "nusmba", "NUS_MENA", "NUSCFA", "nusosa", "yalenus", "NUSHistSoc", "NUScomcentre", "NUSCaretalyst", "fakeNUS", "nushackers", "ActivateUrLife", "NUSSDE", "NUS_Press", "AIESECinNUS", "nuscit", "nuscc", "kr_nus", "NUSBizSchool", "nusfp", "cnmsoc", "USStage", "nusjss", "NUS_IIE", "Mac_NUS", "nusbba", "realFASS", "teamNUS", "RadioPulze", "nusms", "NESociety", "FASSNews" }; } else if(fileName.equalsIgnoreCase("NUS2")){ handPickRelevantUser = new String[] { "NUSnatcon", "The_SA_Blog", "NUS_President", "NUSPhilippines", "nusextra", "nusuk", "thinkposNUS", "NUS_LGBT", "nusScotland", "nusconnect" }; } else if(fileName.equalsIgnoreCase("DBS1")){ handPickRelevantUser = new String[] { "dbsbank", "DBSNUS" }; } else if(fileName.equalsIgnoreCase("DBS2")){ handPickRelevantUser = new String[] { "DBScollege", "DBSLibraryTwits", }; } else if(fileName.equalsIgnoreCase("STARHUB")){ handPickRelevantUser = new String[] { "StarHub", "StarHubExcites", "StarHubCares", "SH_MobiTweet", "StarHubGee", "StarHubNews", "Starhub_R" }; } File baseDirectoryToTrainingFolder = new File("TRAIN"); File[] trainingFiles = baseDirectoryToTrainingFolder.listFiles(); HashMap<String, Vector<Vector<Integer>>> trainingSocialFeatureVectors = new HashMap<String, Vector<Vector<Integer>>>(); for(int i = 0; i < trainingFiles.length; i ++){ Vector<Vector<Integer>> tweetsUserRelevancy = generateSocialFeatureVectorForOneClass(handPickRelevantUser, trainingFiles[i]); String mapName = trainingFiles[i].getName().replace(".txt", ""); if(mapName.equalsIgnoreCase("STARHUB")) mapName = "Starhub"; trainingSocialFeatureVectors.put(mapName, tweetsUserRelevancy); } return trainingSocialFeatureVectors; }
beddd371-4935-4364-a82d-cf233e4b05ec
1
@Override public void addMessageToDB() { try { String statement = new String("INSERT INTO " + DBTable + " (uid1, uid2, time, isConfirmed, isRejected) VALUES (?, ?, NOW(), ?, ?)"); PreparedStatement stmt = DBConnection.con.prepareStatement(statement); stmt.setInt(1, fromUser); stmt.setInt(2, toUser); stmt.setBoolean(3, isConfirmed); stmt.setBoolean(4, isRejected); DBConnection.DBUpdate(stmt); } catch (SQLException e1) { e1.printStackTrace(); } }
5b9e03f2-7c12-4af2-8039-55d1fdc252be
6
private void moveElevator() { if ((elevator.wasTargetOfLastCollision()&&elevatorCountdown--<=0)|| (elevatorPosition!=-90f&&elevatorPosition!=-180f)) { float tempElevator=elevatorPosition+elevatorOffset; float tempOffset=elevatorOffset; if (tempElevator<-180f) { tempOffset=-180f-elevatorPosition; elevatorCountdown=50; elevatorOffset*=-1f; } else { if (tempElevator>-90f) { tempOffset=-90f-elevatorPosition; elevatorCountdown=50; elevatorOffset*=-1f; } } elevatorPosition+=tempOffset; elevator.translate(0, tempOffset, 0); } }
35a12c71-01bd-4402-8996-de526596ee39
3
public void writeToFile() throws IOException { String path = "C:\\Users\\lenovo\\Desktop\\1.txt"; File f = new File(path); if (f.exists()) { f.delete(); f = new File(path); } if (f.createNewFile()) { BufferedWriter output = new BufferedWriter(new FileWriter(f)); while (current != null) { System.out.println(current.toString()); output.write(current.toString()); output.write('\n'); current = lexer.nextToken(); } output.close(); } else System.out.println("fail to create the file"); }
bbee0482-fe78-4fe8-8c1d-987a75130c0f
3
public static int searchInsert(int[] A, int target) { // Note: The Solution object is instantiated only once and is reused by each test case. int ss=0, ee=A.length-1; int middle; while(ss<=ee) { middle=(ss+ee)/2; if(A[middle]==target) return middle; else if(A[middle]>target) ee=middle-1; else ss=middle+1; } return ee+1; }
b42c28c2-5cbc-44e4-8f2f-8d8fb5a0d4c4
8
public static List<TradFile> readTransitive(InputStream in) throws FileNotFoundException{ List<TradFile> list=new ArrayList<>(); Scanner scanner=new Scanner(in); TradFile tFile=null; while(scanner.hasNextLine()){ String line=scanner.nextLine(); if(line.startsWith(FILE_DELIMITER)){ if(tFile!=null) list.add(tFile); tFile=new TradFile(); tFile.setFile(line.substring(FILE_DELIMITER.length(), line.length())); } else if(tFile!=null){ String[] parts=line.split("="); if(parts.length<2){ tFile.getList().add(new Line(null, null)); } else{ String left=parts[0].trim(); String right=parts[1].trim(); switch (right) { case "": throw new RuntimeException(parts[0]+" right hand is empty"); case "?": System.out.println("Ignore : "+left); break; default: tFile.getList().add(new Line(left, right)); break; } } } } if(tFile!=null) list.add(tFile); scanner.close(); return list; }
8a2a9110-f9f2-4c68-b8f0-00cf4750d1a4
5
@Override public void executeInternal(int minValue) { seqUnbounded(new EflTextSegment(Move.A)); // player mon uses attack // System.out.println("EflHitMetricSegment: size=" + sb.size()); seq(new CheckMetricSegment(new EflCheckMoveDamage(isCrit, effectMiss, 0, minDamage, maxDamage, false),GREATER_EQUAL, minDamage, null)); if (numEndTexts == 0 && !noCheckAdditionalTexts) // check for additional texts seqMetric(new StateResettingMetric() { @Override public int getMetricInternal() { EflUtil.runFor(5, 0, 0); return new EflCheckAdditionalTexts().getMetricInternal(); } }); seq(new EflSkipTextsSegment(numEndTexts - 1)); // skip critical hit! messages if(numEndTexts > 0) // skip last message if any seq(new EflTextSegment()); // critical hit! or very/not effective message seq(new Segment() { @Override public StateBuffer execute(StateBuffer sb) { for(State s : sb.getStates()) s.setAttributeInt(player ? KillEnemyMonSegment.PLAYER_ATTRIBUTE : KillEnemyMonSegment.ENEMY_ATTRIBUTE, 0); // set 0 damage return sb; } }); }
8b02c821-5dd4-4513-8e71-5b7c97d9cfe0
9
public boolean isBalanced(String input){ Stack<Character> stack = new Stack<Character>(); for(int i=0;i<input.length();i++){ // push if(LEFT_BRACES.indexOf(input.charAt(i) ) != -1){ stack.push(input.charAt(i)); } // pop & validate else{ Character lastElement = stack.pop(); if( lastElement == null || lastElement == '(' && input.charAt(i) != ')' || lastElement == '{' && input.charAt(i) != '}' || lastElement == '[' && input.charAt(i) != ']' ){ return false; } } } return true; }
ce42c6f5-83d6-4161-9446-8b434bf5d58b
6
public int deserialize(BinarySearchTree<String, String, String> tree) { Properties prop = new Properties(); InputStream istream = getClass().getClassLoader().getResourceAsStream("com/file/resources/additionalsearchtree.properties"); List<BinaryNode<String, String,String>> li = null; try { prop.load(istream); String pathLocation = prop.getProperty("path"); BufferedReader br = new BufferedReader(new FileReader(pathLocation)); String line = br.readLine(); int count=1; while(line!=null){ for(int i=0;i<count;i++){ String[] parts = line.split("\\|"); if(parts[i].equals("name") && parts[i+1].equals("rollnumber") && parts[i+2].equals("address")){ continue; }else{ tree.add(parts[i], parts[i+1], parts[i+2]); } } line=br.readLine(); } System.out.println("Inorder traverse:"); li = tree.inOrder(tree.returnRoot()); br.close(); } catch (Exception e) { e.printStackTrace(); } return li.size(); }
a5a400e6-136f-4f40-8b3e-3a7ed81f0f6c
1
public DbScoreboard() { try { Class.forName("org.sqlite.JDBC"); ensureStructure(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
2db120ff-8aa0-4d74-8f0f-a4881a1b4919
0
@Override public String toString(){ return "id= "+this.getId()+", " +this.getName()+"\n"+ getTime()+"\n"+ "Ребро: "+this.getHig()+"\n"+ "Сумма рёбер: "+this.getSum()+"\n"+ "Длина диагонали: "+this.getDiag()+"\n"+ "S=: "+this.getArea()+ " V=: "+this.getVolume()+"\n"; }
dc6683dc-2716-4f61-846c-f04857be97d9
1
public Key min() { if (isEmpty()) throw new java.util.NoSuchElementException(); return pq[1]; }
a9900b30-1262-458b-b234-c3029b80f7e2
8
@Override public void createPreview(JTextArea ContentBox) { String nLine = String.format("%n"); ContentBox.setText(""); boolean toolsInitFlag = false; boolean pointsFlag = false; for (int i = 0; i < fileLength; i++) { if (tools_init[i] != null) { if (!toolsInitFlag) { toolsInitFlag = true; ContentBox.append("Defined tools : " + nLine); ContentBox.append(nLine); } Tool t = tools_init[i]; String toolnumber = ""; if (t.getIndex() < 10) { toolnumber = "0" + String.valueOf(t.getIndex()); } else { toolnumber = String.valueOf(t.getIndex()); } float size = Float.parseFloat(t.getSize()) * 1000; ContentBox.append("T" + toolnumber + " , size : " + size + format + nLine); } else if (points.get(i) != null) { if (!pointsFlag) { pointsFlag = true; ContentBox.append(nLine); ContentBox.append("Drill points : " + nLine); ContentBox.append(nLine); } Point p = points.get(i); if (p.getX() == -1) { ContentBox.append("Y" + checkNullsPoint(p.getY(), 2) + nLine); } else if (p.getY() == -1) { ContentBox.append("X" + checkNullsPoint(p.getX(), 2) + nLine); } else { ContentBox.append("X" + checkNullsPoint(p.getX(), 2) + "Y" + checkNullsPoint(p.getY(), 2) + nLine); } } } }
83cbb360-8f93-4c93-9d63-ae203c644169
5
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TransactionEntity)) return false; TransactionEntity that = (TransactionEntity) o; if (identificationCode != that.identificationCode) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; return true; }
4bc98171-aa65-453f-8c01-e122593db914
9
private void parseRegex(String regex) //a-z, ^0, A-Z { int strLen = regex.length(); if(regex.startsWith("^")) //is a not { for(int i = 1; i < strLen; i++) { if(regex.length() > i + 2 && regex.charAt(i+1) == '-') //fits a-z pattern { for(int j = regex.charAt(i); j <= regex.charAt(i+2); j++) //ignore - char { legal.remove(String.valueOf((char)j)); } i += 2; //account for extra char's used in pattern. } else //single char { char toRemove = regex.charAt(i); String strToRemove = String.valueOf(toRemove); legal.remove(strToRemove); } } } else // normal regex, not a not. { for(int i = 0; i < strLen; i++) { if(regex.length() > i + 2 && regex.charAt(i+1) == '-') //fits a-z pattern { for(int j = regex.charAt(i); j <= regex.charAt(i+2); j++) //ignore - char { legal.add(String.valueOf((char)j)); } i += 2; //account for extra char's used in pattern. } else //single char { legal.add(String.valueOf(regex.charAt((char)i))); } } } }
9fcf593a-1b2d-49c5-8b1e-2e14c91436e7
3
public static void main(String args[]) { //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EditarEquipo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { EditarEquipo dialog = new EditarEquipo(new javax.swing.JFrame(), true, new Piloto(), new Piloto()); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
2caaf604-84a8-485d-bc4f-86eceb9912d4
9
int insertKeyRehash(long val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
218622b9-c324-4201-8ac7-35827a429b07
3
public PanelOptions() { JPanel content = new JPanel(); content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); lblGeneration = new JLabel("Génération #0,00"); content.add(lblGeneration); content.add(new JLabel()); content.add(new JLabel("Algorithme utilisé")); cmbAlgorithme = new JComboBox(); cmbAlgorithme.addItem("Conway"); cmbAlgorithme.addItem("High Life"); cmbAlgorithme.addItem("Random"); cmbAlgorithme.addItem("Personnalisé"); cmbAlgorithme.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ControllerGrille.setRules(getRule(), getGrid(), lblGeneration, btnProchaineGeneration); vTxtRule.setEnabled(cmbAlgorithme.getSelectedIndex() == 3); } }); content.add(cmbAlgorithme); vTxtRule = new JValidTextField(Color.white, Color.pink); vTxtRule.setText("23/3"); vTxtRule.setRegex("[0-8]{0,9}/[0-8]{0,9}"); vTxtRule.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { btnProchaineGeneration.setEnabled(isInputValid()); if (vTxtRule.isInputValid()) { ControllerGrille.setRules(getRule(), getGrid(), lblGeneration, btnProchaineGeneration); } } }); vTxtRule.setEnabled(false); content.add(vTxtRule); content.add(new JLabel()); chkPacManMode = new JCheckBox("Pac-man mode"); chkPacManMode.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { ControllerGrille.setWrap(chkPacManMode.isSelected(), getGrid(), lblGeneration, btnProchaineGeneration); } }); content.add(chkPacManMode); chkPartyMode = new JCheckBox("Party mode"); chkPartyMode.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { JCellule[][] grid = getGrid(); for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { grid[i][j].setParty(((JCheckBox) e.getSource()).isSelected()); } } ControllerGrille.synchroniser(getGrid(), lblGeneration, btnProchaineGeneration); } }); content.add(chkPartyMode); content.add(new JLabel()); content.add(new JLabel("Bonds de :")); vTxtGeneration = new JValidTextField(Color.white, Color.pink); vTxtGeneration.setMaxValue(2000.0); vTxtGeneration.setMinValue(0.0); vTxtGeneration.setNumericOnly(true); vTxtGeneration.setText("0.5"); vTxtGeneration.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { //btnProchaineGeneration.setEnabled(isInputValid()); } }); content.add(vTxtGeneration); content.add(new JLabel("générations")); content.add(new JLabel(" ")); content.setName("content"); btnRandomize = new JButton("Randomizer"); btnRandomize.setName("rnd"); btnRandomize.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ControllerGrille.randomize(getGrid(), lblGeneration, btnProchaineGeneration); } }); content.add(btnRandomize); content.add(new JLabel(" ")); btnProchaineGeneration = new JButton("Prochaine Génération"); btnProchaineGeneration.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ControllerGrille.prochaineGeneration(getGrid(), getSautDeGeneration(), lblGeneration, btnProchaineGeneration); } }); btnProchaineGeneration.setBackground(Color.pink); content.add(btnProchaineGeneration); content.add(new JLabel(" ")); btnAide = new JButton("Aide"); btnAide.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ControllerFenetres.apropos(); } }); content.add(btnAide); this.add(content); this.setVisible(true); }
607ac27d-591b-4714-9e9b-3cbf036e90ec
1
@Override public String toString() { String toString = "[\n"; for (Rule rule : this.rules) { toString += rule.toString() + "\n"; } toString += "]"; return toString; }
47fa56c6-d41e-4802-96c3-3c9672ae12ae
3
public static List<Zaposlenik> dajZaposlenike(String pretraga) { Session session = HibernateUtil.getSessionFactory().openSession(); Query q = session.createQuery("from " + Zaposlenik.class.getName()); List<Zaposlenik> sviZaposlenici = (List<Zaposlenik>)q.list(); List<Zaposlenik> zaposlenici = new ArrayList<Zaposlenik>(); pretraga = pretraga.toLowerCase(); for(Zaposlenik zaposlenik : sviZaposlenici) { if(zaposlenik.getOsoba() != null && zaposlenik.getOsoba().getImePrezime().toLowerCase().contains(pretraga)) { zaposlenici.add(zaposlenik); } } return zaposlenici; }
e23cb465-633b-4d37-a4be-f07ec8d94ff0
0
private void createPanelStructure() { JPanel mainPanel = new JPanel(); //Set main panel layout mainPanel.setLayout(gridBagLayout); GridBagConstraints constraints = new GridBagConstraints(); //Add groupboxes equationParametersPanel.setBorder(BorderFactory.createTitledBorder("Equation parameters")); integrationParametersPanel.setBorder(BorderFactory.createTitledBorder("Integration parameters")); initialConditionsPanel.setBorder(BorderFactory.createTitledBorder("Initial conditions (in fractions of Pi)")); interpolationParametersPanel.setBorder(BorderFactory.createTitledBorder("Interpolation parameters")); //Set GridBagConstraints constraints.anchor = GridBagConstraints.NORTHWEST; constraints.insets = DEFAULT_INSETS; constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 1; constraints.weighty = 1; constraints.fill = GridBagConstraints.BOTH; //Apply constraints to all internal panels gridBagLayout.setConstraints(equationParametersPanel, constraints); constraints.gridy++; gridBagLayout.setConstraints(integrationParametersPanel, constraints); constraints.gridy++; gridBagLayout.setConstraints(initialConditionsPanel, constraints); constraints.gridy++; gridBagLayout.setConstraints(interpolationParametersPanel, constraints); constraints.gridy++; gridBagLayout.setConstraints(buttonsPanel, constraints); //Add all internal panels to main panel mainPanel.add(equationParametersPanel); mainPanel.add(integrationParametersPanel); mainPanel.add(interpolationParametersPanel); mainPanel.add(initialConditionsPanel); mainPanel.add(buttonsPanel); //Add main panel to window frame.getContentPane().add(mainPanel); }
9ab825b8-abbe-4893-b803-b402d8a79884
1
public void validate(){ if( key == null ){ throw new IllegalStateException( "key is null" ); } }
2d1db1c1-2fae-4dda-baa7-20cf9933ad0f
4
@Test public void test3() { System.out.println("Test avec l'init avec 2 arguments et tous les états possibles"); System.out.println("Tests de couverture des post-conditions d'init"); for(BlocType b : BlocType.values()) { for(PowerUpType p : PowerUpType.values()) { bloc3.init(b,p); assertTrue("type initial Fail",bloc3.getType()==b); assertTrue("power-up initial Fail",bloc3.getPowerUpType() == p); } } System.out.println("Tests de couverture des postconditions des operators"); for(BlocType b : BlocType.values()) { bloc3.setType(b); assertTrue("changement de type Fail",bloc3.getType() == b); for(PowerUpType p : PowerUpType.values()) { bloc3.setPowerUpType(p); assertTrue("changement de power-up Fail",bloc3.getPowerUpType() == p); } } }
3f6d231c-b3ab-4527-8590-dad79960f5d5
4
@Test public void testBatchBuy() throws EasyPostException, InterruptedException { List<Map<String, Object>> shipments = new ArrayList<Map<String, Object>>(); Map<String, Object> shipmentMap = new HashMap<String, Object>(); shipmentMap.put("to_address", defaultToAddress); shipmentMap.put("from_address", defaultFromAddress); shipmentMap.put("parcel", defaultParcel); shipmentMap.put("carrier", "USPS"); shipmentMap.put("service", "Priority"); shipments.add(shipmentMap); // create batch and wait until ready Map<String, Object> batchMap = new HashMap<String, Object>(); batchMap.put("shipments", shipments); Batch batch = Batch.create(batchMap); while(true) { batch = batch.refresh(); if ("created".equals(batch.getState())) { break; } Thread.sleep(3000); } batch.buy(); while(true) { batch = batch.refresh(); if ("purchased".equals(batch.getState())) { break; } Thread.sleep(3000); } assertEquals("Batch state is not purchased.", batch.getState(), "purchased"); }
aae2552b-2b79-4f94-9016-0c09ea0422a7
4
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed int index = estrategyT.getSelectedRow(); if(index>=0){ String nombre = (String)estrategyT.getModel().getValueAt(index,0); for(int i=0;i<contenedorEstrategia.getEstrategias().size();i++){ if(contenedorEstrategia.getEstrategias().get(i).getNombre().equals(nombre)){ boolean status = contenedorEstrategia.getEstrategias().get(i).isEstatus(); if(status){ contenedorEstrategia.getEstrategias().get(i).setEstatus(false); estrategyT.getModel().setValueAt("Inactive", index, 4); } else{ contenedorEstrategia.getEstrategias().get(i).setEstatus(true); estrategyT.getModel().setValueAt("Active", index, 4); } guardarArchivo(principal.getCurrentServer()+"_strategies.txt"); break; } } } else{ JOptionPane.showMessageDialog(this, "Select a strategy", "Error", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_jButton4ActionPerformed
61acd7ab-8f53-4264-8752-248e10c79747
8
private ArrayList<CardPattern> hasBomb(ArrayList<Card> cards){ ArrayList<CardPattern> bombCardPatterns = new ArrayList<CardPattern>(); CardPatternFactory factory = new CardPatternFactory(); Collections.sort(cards); int i=0; int sameCardsCounter=0; int size = cards.size(); int value=0; while(i<size){ if(value==cards.get(i).getValue()){ sameCardsCounter++; if(sameCardsCounter==4){ ArrayList<Card> bombCards = new ArrayList<Card>(); bombCards.add(cards.get(i-3)); bombCards.add(cards.get(i-2)); bombCards.add(cards.get(i-1)); bombCards.add(cards.get(i)); bombCardPatterns.add(factory.createCardPattern(bombCards)); sameCardsCounter=0; } }else{ value=cards.get(i).getValue(); sameCardsCounter=0; } i++; } Collections.sort(cards, new CardComparatorPerColorPerVal()); i=0; size = cards.size(); int cardsCount=0; int color=0; value=0; while(i<size){ if((cards.get(i).getColor()==color) && (cards.get(i).getValue()==value+1)){ value=cards.get(i).getValue(); cardsCount++; if(cardsCount>=4){ ArrayList<Card> bombCards = new ArrayList<Card>(); for(int j=0;j<=cardsCount;j++){ bombCards.add(cards.get(i-j)); } bombCardPatterns.add(factory.createCardPattern(bombCards)); } }else{ value=cards.get(i).getValue(); color = cards.get(i).getColor(); cardsCount=0; } i++; } return bombCardPatterns; }
1cb2dfc9-f5de-40a7-b96e-a29f5aecfb1f
4
public void EliminaMedio (int Posicion) { if ( VaciaLista()) System.out.println( "Nada"); else { NodosProcesos Aux =null; NodosProcesos Actual = PrimerNodo; int i =1; while (( i != Posicion) & (Actual.siguiente != PrimerNodo)) { i++; Aux =Actual; Actual =Actual.siguiente; } if (i ==Posicion) { if (Aux == null) { Actual = PrimerNodo; PrimerNodo = PrimerNodo.siguiente; } else Aux.siguiente = Actual.siguiente; } } }
aaad9563-292d-4cb3-9b60-102046241161
8
private int readValidityPeriodInt() { // this will convert the VP to #MINUTES int validity = readByte(); int minutes = 0; if ((validity > 0) && (validity <= 143)) { // groups of 5 min minutes = (validity + 1) * 5; } else if ((validity > 143) && (validity <= 167)) { // groups of 30 min + 12 hrs minutes = (12 * 60) + (validity - 143) * 30; } else if ((validity > 167) && (validity <= 196)) { // days minutes = (validity - 166) * 24 * 60; } else if ((validity > 197) && (validity <= 255)) { // weeks minutes = (validity - 192) * 7 * 24 * 60; } return minutes; }
48439f83-a6ae-44c1-a7b3-e958dac38f1b
1
protected void setBufferManager( BufMgr mgrArg ) { mgr = mgrArg; int numBuffers = mgr.getNumBuffers(); // These are the C++ code which we ignored //char *Sh_StateArr = MINIBASE_SHMEM->malloc((numBuffers * sizeof(STATE))); //state_bit = new(Sh_StateArr) STATE[numBuffers]; for ( int index=0; index < numBuffers; ++index ) { state_bit[index].state = Available; } head = -1; // maintain the head of the clock. }
1e1e249c-e1d1-4ea3-a834-719b86326c86
1
private void init() { for (int i = 0; i < CAPACITY; i++) { arr[i] = null; } }
2e5734aa-237d-48ee-9cf8-0267fad3f603
1
private boolean empate(int numero1,int numero2){ if(numero1 == numero2){ return true; }else{ return false; } }
8aca4a47-43c8-4bca-a095-81d153a3d13d
7
public int edmons_karp(int s, int t) { int u, e; this.s = s; mf = 0; Arrays.fill(p, -1); while (true) { f = 0; Queue<Integer> q = new LinkedList<Integer>(); int[] dist = new int[V]; Arrays.fill(dist, INF); dist[s] = 0; q.offer(s); Arrays.fill(p, -1); while (!q.isEmpty()) { u = q.poll(); if (u == t) break; for (int i = 0; i < ady[u].size(); i++) { e = ady[u].get(i); if (g[u][e] > 0 && dist[e] == INF) { dist[e] = dist[u] + 1; q.offer(e); p[e] = u;// parent of vertex e is vertex u } } } augment(t, INF); if (f == 0) break; mf += f; } return mf; }
5c97f397-3572-463e-818d-2a44c739c1f1
7
@Override public void layoutContainer(Container parent) { int cardOverflow = fieldCardComponents.size() % 4; int cardsPerSide = fieldCardComponents.size() / 4; boolean even = true; Dimension point = new Dimension(); //calculates where to start drawing the the field cards if(cardOverflow != 0) { point.width = cardsPerSide * FieldCard.widthCard + FieldCard.heightCard; even = false; } else { point.width = (cardsPerSide - 1) * FieldCard.widthCard + FieldCard.heightCard; } point.height = point.width; int currentCardIndex = 0; for(int i = 0; i < 4; i++) { if(cardOverflow > 0) { for(int j = 0; j < (cardsPerSide + 1); j++, currentCardIndex++) { setBoundaries(i, j, point, currentCardIndex, FieldCard.widthCard, cardsPerSide + 1); } } else { for(int j = 0; j < cardsPerSide; j++, currentCardIndex++) { if(even) { setBoundaries(i, j, point, currentCardIndex, FieldCard.widthCard, cardsPerSide); } else { //calculates the width of the card when it is needed to stretch it int widthCard = (FieldCard.widthCard * cardsPerSide - 1) / (cardsPerSide - 1); setBoundaries(i, j, point, currentCardIndex, widthCard, cardsPerSide); } } } if(cardOverflow != 0) { cardOverflow--; } } }
25692cf1-d329-4866-8ddf-962b2fba1520
2
public static void saveConfig() throws IOException { File current = new File(System.getProperty("user.dir") + "/config"); if(current.exists()) { current.delete(); } current.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(current)); writer.write("<AUDIO>"); writer.newLine(); writer.write("volume=" + Ensemble.get().getMasterVolume()); writer.newLine(); writer.newLine(); writer.write("<KEYS>"); writer.newLine(); for(int x = 0; x<Keybinds.values().length; x++) { writer.write(Keybinds.values()[x].name() + "=" + Keybinds.values()[x].getKey()); writer.newLine(); } writer.close(); }
17716259-7d5e-429f-939c-f65f70b11162
9
public void tick() { ticksleft--; if (pressedUp) { pressedUp = false; currentblock.tryRotate(); } if (pressedRight) { pressedRight = false; currentblock.tryMoveRight(); } if (pressedLeft) { pressedLeft = false; currentblock.tryMoveLeft(); } if (ticksleft <= 0) { if (currentblock == null) { currentblock = new TetrisBlock(this, TetrisBlock.Shape.random()); } ticksleft = tickTime; if (currentblock.canMoveDown()) { currentblock.moveDown(); } else { System.out.println("Solidized"); currentblock.solidize(); currentblock = null; } } //Render part for (int x=0; x<solidblocks.length; x++) { for (int y=0; y<solidblocks[x].length; y++) { screen[x][y] = solidblocks[x][y]; } } if (currentblock != null) currentblock.render(); updateScreen(); }
7c5dd16f-d816-4b94-aab0-1af89f291d1f
6
protected String InferLangFromReferralUrl(HttpServletRequest httpRequest, String parseLangQueryParams) { // Examine the referer header that came with this request to see if we can infer the user's language. // If we find a query string paramater that matches the list provided, return the content of that param. try { String referrer = httpRequest.getHeader("referer"); if (referrer != null && !parseLangQueryParams.isEmpty()) { // These are the params we will look for String[] langParams = parseLangQueryParams.split(";"); // Now parse the referrer URL URL referrerUrl = new URL(referrer); String[] params = referrerUrl.getQuery().split("&"); for (String param : params) { int splitPos = param.indexOf("="); String paramName = URLDecoder.decode(param.substring(0, splitPos), "UTF-8"); // If we find a matching lang param, return its value for (int i = 0; i < langParams.length; i++) if (paramName.equalsIgnoreCase(langParams[i])) { String lang = URLDecoder.decode(param.substring(splitPos + 1), "UTF-8"); log.debug("Found language preference in referral URL: " + lang); return lang; } } } } catch (Exception ex) { log.error("Unable to infer a lang parameter from referral URL: " + ex.getMessage()); } return null; }
d2184d7e-5aab-49f1-925a-f5c4ab1e4502
8
private void volume_slide() { int up, down; up = ( volume_slide_param & 0xF0 ) >> 4; down = volume_slide_param & 0x0F; if( down == 0x0F && up > 0 ) { /* Fine slide up.*/ if( effect_tick == 0 ) { set_volume( volume + up ); } } else if( up == 0x0F && down > 0 ) { /* Fine slide down.*/ if( effect_tick == 0 ) { set_volume( volume - down ); } } else { /* Normal slide.*/ if( effect_tick > 0 || fast_volume_slides ) { set_volume( volume + up - down ); } } }
f8fa6289-d852-44a5-99c0-db0bc219641a
2
public void idToValue() { int valueList[] = { 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 }; for (int i = 0; i < 52; i++) { if (id == i) { value = valueList[i]; break; } } }
3a2a23a2-cb1f-4a0c-bbb1-aeaf8219b4c9
1
public long[] decodeLongs() { long[] res = new long[decodeInt()]; for (int i = 0; i < res.length; i++) { res[i] = decodeLong(); } return res; }
96c84a6e-590a-4885-92b5-af7b882ddc53
7
public double calculateDistance() throws IllegalStateException, ArithmeticException { double U1, U2, w, sigma, ssig, csig, salp, c2alp, c2sigm; double u, A, B, C, dsig, b; double lambda, dlam = 0.0, lastdlam = 0.0; double p, q; int nIters = 0, nMaxIters = 10; double a = ellipsoid.getSemiMajorAxis(); double f = ellipsoid.getFlattening(); if (!havePositionA) throw new IllegalStateException("positionA is not defined"); if (!havePositionB) throw new IllegalStateException("positionB is not defined"); b = a * (1.0 - f); U1 = Math.atan((1.0 - f) * Math.tan(latitudeA)); U2 = Math.atan((1.0 - f) * Math.tan(latitudeB)); w = longitudeB - longitudeA; if (w < -Math.PI) w += TwoPi; if (w > Math.PI) w -= TwoPi; lambda = w; do { lastdlam = dlam; p = Math.cos(U2) * Math.sin(lambda); q = Math.cos(U1) * Math.sin(U2) - Math.sin(U1) * Math.cos(U2) * Math.cos(lambda); ssig = Math.sqrt(p * p + q * q); csig = Math.sin(U1) * Math.sin(U2) + Math.cos(U1) * Math.cos(U2) * Math.cos(lambda); sigma = Math.atan2(ssig, csig); salp = Math.cos(U1) * Math.cos(U2) * Math.sin(lambda) / ssig; c2alp = 1.0 - salp * salp; c2sigm = csig - 2.0 * Math.sin(U1) * Math.sin(U2) / c2alp; C = (f / 16.0) * c2alp * (4.0 + f * (4.0 - 3.0 * c2alp)); dlam = (1.0 - C) * f * salp * (sigma + C * ssig * (c2sigm + C * csig * (2.0 * c2sigm * c2sigm - 1.0))); lambda = w + dlam; nIters += 1; } while ((Math.abs(dlam - lastdlam) > EPSILON) && (nIters <= nMaxIters)); if (nIters > nMaxIters) throw new ArithmeticException("Exceeded iteration limit"); u = (1.0 - salp * salp) * (a * a - b * b) / (b * b); A = 1.0 + (u / 16384.0) * (4096.0 + u * (-768.0 + u * (320.0 - 175.0 * u))); B = (u / 1024.0) * (256.0 + u * (-128.0 + u * (74.0 - 47.0 * u))); dsig = B * ssig * (c2sigm + (B / 4.0) * (csig * (2.0 * c2sigm * c2sigm - 1.0) - (B / 6.0) * c2sigm * (4.0 * ssig * ssig - 3.0) * (4.0 * c2sigm * c2sigm - 3.0))); p = Math.cos(U2) * Math.sin(lambda); q = Math.cos(U1) * Math.sin(U2) - Math.sin(U1) * Math.cos(U2) * Math.cos(lambda); azimuthA = Math.atan2(p, q); haveAzimuthA = true; p = -Math.cos(U1) * Math.sin(lambda); q = Math.cos(U2) * Math.sin(U1) - Math.sin(U2) * Math.cos(U1) * Math.cos(lambda); azimuthB = Math.atan2(p, q); haveAzimuthB = true; geodesicDistance = b * A * (sigma - dsig); haveDistance = true; return geodesicDistance; }
8e6dfd4c-ccd5-4265-865a-6249c2d9daf0
0
boolean isObjectAlreadyInDB() { return objectAlreadyInDB; }//isObjectAlreadyInDB
0289a902-0dd8-47ff-a08b-634d00e646d0
3
@Override public void deleteMedicine(MedicineDTO medicine) throws SQLException { Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.delete(medicine); session.getTransaction().commit(); } catch (Exception e) { System.err.println("Error while deleting a medicine!"); } finally { if (session != null && session.isOpen()) session.close(); } }
4c914e9f-9cd0-4af4-b893-2e89f2bafcd3
3
private synchronized void deuce (String v) throws JMSException { QueueConnection qc =null; QueueSession qs =null; ///prova mess try { qc = qcf.createQueueConnection(); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { qs = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { this.sender = qs.createSender( altro); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); }//manda al rivale CreateMessage Mess = new CreateMessage(this.name, this.room, this.name, 3); //STEP Message ObjectMessage j = qs.createObjectMessage(Mess); j.setBooleanProperty("multy", true); j.setJMSReplyTo(que); qc.start(); System.out.println("Invio messaggio deuce " + altro.toString()); this.sender = this.senderSession.createSender(altro); this.sender.send(j); qc.close(); //manda in topic via House CreateMessage creMess = new CreateMessage(this.name, this.room, this.name, 3); // winner ObjectMessage roomObjectMess = this.senderSession.createObjectMessage(creMess); roomObjectMess.setBooleanProperty("multy", true); roomObjectMess.setJMSReplyTo(que); this.sender = this.senderSession.createSender(queue); this.sender.send(roomObjectMess); }
956bb43a-688f-4322-ac5c-a54bb81972cf
5
private void build_function_structure() { if(log_level >= 4) log.log(4, key, "build_function_structure called.", "\n"); TreeMap<Integer,Variable> temp = new TreeMap<>(); HashMap<Integer,Variable> helper; int count = 0; for (String context : function_startpoint.keySet()) { for (Variable variable : context_varname_var.get(context).values()) { if (variable.get_var_type().equals("VAR_INPUT")){ temp.put(new Integer(variable.get_id()), variable); } } for (Variable variable_sorted : temp.values()) { helper = new HashMap<>(); helper.put(new Integer(count), variable_sorted); functioname_inputid_var.put(context, helper); } count = 0; temp = new TreeMap<>(); } }
ee663806-4751-4974-91c2-2b1e998fa0b5
4
public List<ItemType> getAllRandomItems(){ List<ItemType> itemsToReturn = new ArrayList<>(); for(ItemType item : items.keySet()){ double d = new Random().nextDouble(); if(d < items.get(item)){ itemsToReturn.add(item); } } for(ExclusiveItems exclusive : exclusiveItems){ ItemType exclusiveItem = exclusive.getRandomItem(); if(exclusiveItem != null){ itemsToReturn.add(exclusiveItem); } } return itemsToReturn; }
6009d42c-ad08-4db3-b8ac-a9c9b3c0ef89
1
public void testConstructor_RI_RP8() throws Throwable { DateTime dt = new DateTime(TEST_TIME_NOW); Period dur = new Period(0, 0, 0, 0, 0, 0, 0, -1); try { new MutableInterval(dt, dur); fail(); } catch (IllegalArgumentException ex) {} }
03e02764-6077-42d5-9692-c1a894304218
5
@Override public void execute() { if (Game.getClientState() != Game.INDEX_MAP_LOADED) { ItemCombiner.stop = 1000; } if (Game.getClientState() != Game.INDEX_MAP_LOADED && ItemCombiner.stop == 1000) { ItemCombiner.stop = 50; } if (ItemCombiner.client != Bot.client()) { WidgetCache.purge(); Bot.context().getEventManager().addListener(this); ItemCombiner.client = Bot.client(); } if (Widgets.get(640, 30).isOnScreen()) { Widgets.get(640, 30).click(true); } }
1927c871-3f9e-4177-9a28-6c079befbed5
5
public void addCard(String s) { // Correspondance entier-carte : 0 = chevalier ; 1 = monopole ; 2 = route ; 3 = decouverte ; 4 = victoire. if (s.equals("chevalier")) cards[0]++; else if (s.equals("monopole")) cards[1]++; else if (s.equals("route")) cards[2]++; else if (s.equals("decouverte")) cards[3]++; else if (s.equals("victoire")) cards[4]++; totalCards++; }
640f208c-13ad-4b5c-9d3b-c6759b1d2219
2
public String log() throws Exception { ArrayList<LogItem> toLog = new ArrayList<LogItem>(data.length); LogItem toAdd; for (int i = 0; i < data.length; ++i) { if (dataSwitch[i]) { toAdd = new LogItem(); toAdd.barID = AutoAppro.products.get(data[i].supplierID).barID; toAdd.price = data[i].price; toAdd.quantity = data[i].quantity; toLog.add(toAdd); } } return AutoAppro.logger.log(toLog); }
766441dd-c290-4e92-9407-cc1faf84fbed
8
private void setMatrixArray(int[] readBuffer) { //1st report if (readBuffer[0] == 0x1a) { oldMatrix[4] = matrix[4]; oldMatrix[5] = matrix[5]; oldMatrix[6] = matrix[6]; oldMatrix[7] = matrix[7]; /*deb*/ System.out.println("setting matrix[4...7]"); matrix[4] = readBuffer[1]; matrix[5] = readBuffer[2]; matrix[6] = readBuffer[3]; matrix[7] = readBuffer[4]; } //2nd report else if (readBuffer[0] == 0x19) { oldMatrix[0] = matrix[0]; oldMatrix[1] = matrix[1]; oldMatrix[2] = matrix[2]; oldMatrix[3] = matrix[3]; /*deb*/ System.out.println("setting matrix[0...3]"); matrix[0] = readBuffer[1]; matrix[1] = readBuffer[2]; matrix[2] = readBuffer[3]; matrix[3] = readBuffer[4]; } //3rd report else if (readBuffer[0] == 0x1b) { oldMatrix[8] = matrix[8]; oldMatrix[9] = matrix[9]; oldMatrix[10] = matrix[10]; oldMatrix[11] = matrix[11]; /*deb*/ System.out.println("setting matrix[8...11]"); matrix[8] = readBuffer[1]; matrix[9] = readBuffer[2]; matrix[10] = readBuffer[3]; matrix[11] = readBuffer[4]; } //4th report else if (readBuffer[0] == 0x1c) { oldMatrix[12] = matrix[12]; oldMatrix[13] = matrix[13]; oldMatrix[14] = matrix[14]; oldMatrix[15] = matrix[15]; /*deb*/ System.out.println("setting matrix[12...15]"); matrix[12] = readBuffer[1]; matrix[13] = readBuffer[2]; matrix[14] = readBuffer[3]; matrix[15] = readBuffer[4]; } //create event if (!doScan) { if (iow.getId() == AbstractIowDevice.IOW40ID && readBuffer[0] == 0x19) { SwitchMatrixEvent event = new SwitchMatrixEvent(matrix, oldMatrix); for (int i = 0; i < listeners.size(); i++) { SwitchMatrixChangeListener smcl = (SwitchMatrixChangeListener) listeners.get(i); (new NotifierThread(event, smcl)).start(); } } } }
1ac70385-ae0e-448f-bad0-610a910c52f3
3
@Override public void handleMessages(Inbox inbox) { // TODO Auto-generated method stub while (inbox.hasNext()) { Message msg = inbox.next(); if (msg instanceof PackHelloOldBetHop) { PackHelloOldBetHop a = (PackHelloOldBetHop) msg; handlePackHello(a); }else if (msg instanceof PackReplyOldBetHop) { PackReplyOldBetHop b = (PackReplyOldBetHop) msg; handlePackReply(b); } } }
1c09f94b-7f2b-4323-b142-a83e88d040d8
8
public Spit(String dir, TileMap tm){ super(tm); if(dir.equals("right")){ facingRight = true; facingUp = false; facingDown = false; } else if(dir.equals("up")){ facingRight = false; facingUp = true; facingDown = false; } else if(dir.equals("down")){ facingRight = false; facingUp = false; facingDown = true; }else{ facingRight = false; facingUp = false; facingDown = false; } moveSpeed = 3.8; if(dir.equals("right")){ dx = moveSpeed; dy = 0; }else if(dir.equals("left")){ dx = -moveSpeed; dy = 0; }else if(dir.equals("up")){ dy = -moveSpeed; dx = 0; }else{ dy = moveSpeed; dx = 0; } width = 28; height = 30; cwidth = 28; cheight = 30; try{ BufferedImage spritesheet = ImageIO.read( getClass().getResourceAsStream( "/Sprites/Enemies/SpitterBall.png")); sprites = new BufferedImage[4]; for(int i = 0; i < sprites.length; i++){ sprites[i] = spritesheet.getSubimage(width * i, 0, width, height); } animation = new Animation(); animation.setFrames(sprites); animation.setDelay(70); }catch(Exception e){ e.printStackTrace(); } }
69949df7-5320-442a-a89d-5bb7b4844750
7
public void storeSMS(HttpServletRequest req) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); String msg=""; String disease, age, location, riskgroup, vaccine; disease=age=location=riskgroup=vaccine=null; Entity en=new Entity("inboundSMS"); en.setProperty("number", req.getParameter("msisdn")); msg=req.getParameter("text").toLowerCase(); String[] tokens= msg.split(","); if(tokens.length>1) { for(int x=0;x<tokens.length;x++) { //if we find age in the token, we can extract the age if(tokens[x].lastIndexOf("age")!=-1) { age=tokens[x].substring(3); age=age.trim(); } if(tokens[x].lastIndexOf("riskgroup")!=-1) { riskgroup=tokens[x].substring(9); riskgroup=riskgroup.trim(); } if(tokens[x].lastIndexOf("location")!=-1) { location=tokens[x].substring(8); location=location.trim(); } if(tokens[x].lastIndexOf("vaccine")!=-1) { vaccine=tokens[x].substring(7); vaccine=vaccine.trim(); } if(tokens[x].lastIndexOf("disease")!=-1) { disease=tokens[x].substring(7); disease=disease.trim(); } } en.setProperty("riskGroup", riskgroup); en.setProperty("disease", disease); en.setProperty("location", location); en.setProperty("age", age); en.setProperty("vaccine", vaccine); } datastore.put(en); }
27f69151-6fd2-46dc-b332-1f858a69c388
9
public static String display(Object object) { if (object == null) { return null; } try { // Invoke toString if declared in the class. If not found, the // NoSuchMethodException is caught and handled object.getClass().getDeclaredMethod("toString"); return object.toString(); } catch (NoSuchMethodException noMethodEx) { try { for (Field field : object.getClass().getDeclaredFields()) { // Find the primary key field and display it if (field.getAnnotation(Id.class) != null) { // Find a matching getter and invoke it to display the // key for (Method method : object.getClass().getDeclaredMethods()) { if (method.equals(new PropertyDescriptor(field.getName(), object.getClass()) .getReadMethod())) { return method.invoke(object).toString(); } } } } for (Method method : object.getClass().getDeclaredMethods()) { // Find the primary key as a property instead of a field, // and display it if (method.getAnnotation(Id.class) != null) { return method.invoke(object).toString(); } } } catch (Exception ex) { // Unlikely, but abort and stop view generation if any exception // is thrown throw new RuntimeException(ex); } } return null; }
a30843eb-28de-44d0-9bdc-26ab0633509c
9
private String makeCode(){ String c=((ComboText)command.getSelectedItem()).getValue(); if(c.equals("MAKE")){ String code=objName.getText()+"=addons.canvas2d("+makeW.getValue()+","+makeH.getValue()+");\n"; code+=objName.getText()+".autoUpdate="+makeUpdate.isSelected()+"\n"; code+=objName.getText()+".setAA("+makeAA.isSelected()+")"; return code; } else if(c.equals("drawMap")){ String code=objName.getText()+".drawMap(\""; String m[]=map.getText().split("\n"); int i=0; for(String line:m){ code+=line; if(i++ < m.length)code+="\\n"; } code+="\")"; return code; } else if(c.equals("drawPixel")||c.equals("lineFrom")||c.equals("lineTo")){ return objName.getText()+"."+c+"("+ "("+drawX.getText()+")," +"("+drawY.getText()+"))"; } else if(c.equals("drawLine")){ return objName.getText()+"."+c+"("+ "("+lineFromX.getText()+"),"+ "("+lineFromY.getText()+"),"+ "("+lineToX.getText()+"),"+ "("+lineToY.getText()+")"+ ")"; } else if(c.equals("setColor")){ return objName.getText()+"."+c+"(\""+colorHEX.getText()+"\")"; } return objName.getText()+"."+c+"();"; }
bd3adbc7-19c5-4216-b533-fbb9a3be728f
9
public static Map<String, Vector<String>> getCuratedCategories() throws PluginNotFoundException { final Map<String, Vector<String>> identities = new HashMap<String, Vector<String>>(); final SimpleFieldSet sfs = new SimpleFieldSet(true); sfs.putOverwrite("Message", "GetOwnIdentities"); SyncPluginTalker spt = new SyncPluginTalker(new ReceptorCore() { public void onReply(String pluginname, String indentifier, SimpleFieldSet params, Bucket data) { try { if (params.getString("Message").equals("OwnIdentities")) { Map<String,String> identifiers = new HashMap<String,String>(); String currentId = null; Iterator<String> it = params.toplevelKeyIterator(); while (it.hasNext()) { String key = it.next(); if (key.startsWith(IDENTITY_KEY_PREFIX)) { currentId = params.get(key); String id = key.split(IDENTITY_KEY_PREFIX)[1]; identifiers.put(id,currentId); } } for(String idNum : identifiers.keySet()) { int count = 0; Vector<String> categories = new Vector<String>(); while(true) { String name = params.get("Properties"+idNum+".Property"+count+".Name"); if(name == null) break; count++; if (name.startsWith(IDENTITY_CATEGORY_NAME_PREFIX)) { categories.add(name.split(IDENTITY_CATEGORY_NAME_PREFIX)[1]); } } if (!categories.isEmpty()) { identities.put(identifiers.get(idNum), categories); } } } else { Logger.error(this, "Unexpected message : " + params.getString("Message")); } } catch (FSParseException ex) { Logger.error(this, "WoTIdentity : Parse error !"); } } }, sfs, null); spt.run(); return identities; }
06cdba48-add9-4b3e-b5bc-0ec913dd77a0
1
public ArrayList<Integer> getValidMoves(int player) { ArrayList<Integer> playerPieces = findPlayerPieces(player); ArrayList<Integer> legalMoves = new ArrayList<Integer>(); for (Integer playerPiece : playerPieces) legalMoves = findLegalMoves(playerPiece, player, legalMoves); Collections.sort(legalMoves); return legalMoves; }
ac318519-53bd-4b61-b41d-2dc2864c927a
0
public int getValidRxCount() { return validRxPackets; }
09ca3a78-7edf-4f0f-958d-4a14a11ebaf1
5
public void setFullScreen(DisplayMode displayMode) { final JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setUndecorated(true); frame.setIgnoreRepaint(true); frame.setResizable(false); device.setFullScreenWindow(frame); if (displayMode != null && device.isDisplayChangeSupported()) { try { device.setDisplayMode(displayMode); } catch (IllegalArgumentException ex) { } // fix for mac os x frame.setSize(displayMode.getWidth(), displayMode.getHeight()); } // avoid potential deadlock in 1.4.1_02 try { EventQueue.invokeAndWait(new Runnable() { public void run() { frame.createBufferStrategy(2); } }); } catch (InterruptedException ex) { // ignore } catch (InvocationTargetException ex) { // ignore } }
ba959924-ee67-44d4-9970-01474cb8531a
4
@Override public void keyReleased(KeyEvent e) { //only checks for user input if the game has started if(gameFrame.gameStarted()){ // if the user presses W if (KeyEvent.getKeyText(e.getKeyCode()).equals("W")) { // attempt to move the player forwards player.moveForward(); } else if (KeyEvent.getKeyText(e.getKeyCode()).equals("D")) { // turn the player right player.turnRight(); } else if (KeyEvent.getKeyText(e.getKeyCode()).equals("A")) { // turn the player left player.turnLeft(); } } //resets descriptiontext gameFrame.setDescriptionText("",1000,1000); gamePanel.update(); }
9c4c8863-fccb-4474-9212-437b185383bc
5
private Result _evaluate(EvaluationCtx context) { // evaluate Result result = combiningAlg.combine(context, parameters, childElements); // if we have no obligations, we're done if (obligations.size() == 0) return result; // now, see if we should add any obligations to the set int effect = result.getDecision(); if ((effect == Result.DECISION_INDETERMINATE) || (effect == Result.DECISION_NOT_APPLICABLE)) { // we didn't permit/deny, so we never return obligations return result; } Iterator it = obligations.iterator(); while (it.hasNext()) { Obligation obligation = (Obligation)(it.next()); if (obligation.getFulfillOn() == effect) result.addObligation(obligation); } // finally, return the result return result; }
aadc11f4-e7ce-4018-89e9-1f7d02f163b3
8
public static Iterator<Position> get8NeighborhoodIterator(Position center) { ArrayList<Position> list = new ArrayList<Position>(); int row = center.getRow(); int col = center.getColumn(); int r,c; for (int dr = -1; dr <= +1; dr++) { for (int dc = -1; dc <= +1; dc++) { r = row+dr; c = col+dc; // avoid positions outside the world if ( r >= 0 && r < GameConstants.WORLDSIZE && c >= 0 && c < GameConstants.WORLDSIZE ) { // avoid center position if ( r != row || c != col ){ list.add( new Position(r,c)); } } } } return list.iterator(); }
912a1cb3-42f9-4184-bd25-f18b131e3af1
3
@WebMethod(operationName = "ReadProduct") public ArrayList<Product> ReadProduct(@WebParam(name = "prod_id") String prod_id) { Product prod = new Product(); ArrayList<Product> prods = new ArrayList<Product>(); ArrayList<QueryCriteria> qc = new ArrayList<QueryCriteria>(); if(!prod_id.equals("-1")){ qc.add(new QueryCriteria("prod_id", prod_id, Operand.EQUALS)); } ArrayList<String> fields = new ArrayList<String>(); ArrayList<QueryOrder> order = new ArrayList<QueryOrder>(); try { prods = prod.Read(qc, fields, order); } catch (SQLException ex) { Logger.getLogger(JAX_WS.class.getName()).log(Level.SEVERE, null, ex); } if(prods.isEmpty()){ return null; } return prods; }
7bdd8abc-1f12-4093-bdcf-fea9abdbfb89
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (hashCode() == o.hashCode()) return true; Asteroid asteroid = (Asteroid) o; if (dangerousToMankind != asteroid.dangerousToMankind) return false; if (target != null ? !target.equals(asteroid.target) : asteroid.target != null) return false; return true; }
5c9d8e00-a41c-4887-8b3a-60100971c1ea
8
public static boolean argumentMatchesListHelperP(Stella_Object argument, List theList) { { Surrogate testValue000 = Stella_Object.safePrimaryType(argument); if (Surrogate.subtypeOfP(testValue000, Units.SGT_LOGIC_PATTERN_VARIABLE)) { { PatternVariable argument000 = ((PatternVariable)(argument)); { Stella_Object value = (((QueryIterator)(Logic.$QUERYITERATOR$.get())).currentPatternRecord.variableBindings.theArray)[(argument000.boundToOffset)]; if (value != null) { return (Units.argumentMatchesListHelperP(value, theList)); } else { return (true); } } } } else if (Surrogate.subtypeOfP(testValue000, Units.SGT_LOGIC_SKOLEM)) { { Skolem argument000 = ((Skolem)(argument)); { Proposition prop = argument000.definingProposition; Vector args = ((prop != null) ? prop.arguments : ((Vector)(null))); int listLength = theList.length(); if (args == null) { return (false); } else if (args.length() == (listLength + 1)) { { Stella_Object item = null; Cons iter000 = theList.theConsList; int i = Stella.NULL_INTEGER; int iter001 = 0; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest, iter001 = iter001 + 1) { item = iter000.value; i = iter001; if (!(Stella_Object.eqlP(item, (args.theArray)[i]))) { return (false); } } } return (true); } else { return (false); } } } } else { return (false); } } }
ab973675-12ed-435f-a02e-279f05386d93
2
private void activate() { if (isActive()) throw new IllegalArgumentException("Forcefield was already active, something went wrong"); this.active = true; for (Element e : getGrid().getElementsOnPosition(getGrid().getElementPosition(this))) collideWith(e); }
f84bb352-d43b-43bb-95c6-ed28605310d7
3
public void mightyMode(boolean isOn){ this.player= new MightyPacman(this.player.getX(), this.player.getY(), this, this.player.getFacing(), this.player.getSavedDir()); this.playerStateTimer.stop(); this.playerStateTimer.start(); for (int i=0; i < 4; i++) if (this.ghosts[i].getIsAlive()) if (i%2 == 0) this.ghosts[i].setIsWeak(false); else this.ghosts[i].setIsWeak(isOn); }
95d7af89-46db-445b-ae15-d4064182cf7e
8
public int compare(String o1, String o2) { String s1 = (String)o1; String s2 = (String)o2; int thisMarker = 0; int thatMarker = 0; int s1Length = s1.length(); int s2Length = s2.length(); while (thisMarker < s1Length && thatMarker < s2Length) { String thisChunk = getChunk(s1, s1Length, thisMarker); thisMarker += thisChunk.length(); String thatChunk = getChunk(s2, s2Length, thatMarker); thatMarker += thatChunk.length(); // If both chunks contain numeric characters, sort them numerically int result = 0; if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // Simple chunk comparison by length. int thisChunkLength = thisChunk.length(); result = thisChunkLength - thatChunk.length(); // If equal, the first different number counts if (result == 0) { for (int i = 0; i < thisChunkLength; i++) { result = thisChunk.charAt(i) - thatChunk.charAt(i); if (result != 0) { return result; } } } } else { result = thisChunk.compareTo(thatChunk); } if (result != 0) return result; } return s1Length - s2Length; }
cb7bed96-db3b-415a-8962-065cc790c788
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(AdminView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AdminView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AdminView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AdminView.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 AdminView().setVisible(true); } }); }
49c54db3-d650-4161-aebc-aa6e82d1873c
8
@Override public void option() { int cores = Runtime.getRuntime().availableProcessors(); BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); if (this.operand.equals("random")) { Random r = new Random(new Date().getTime()); int tasks = r.nextInt(15) + 1; Config.getInstance().threads(tasks); System.out.println("Running with " + tasks + " worker threads"); return; } if (this.operand.equals("cores")) { System.out.println("Running with " + cores + " worker treads"); Config.getInstance().threads(cores); return; } try { int tasks = Integer.parseInt(this.operand); if (tasks == 0) tasks = 1; else if (tasks > cores * max_factor) { System.out.println("You are attempting to run " + max_factor + " times more threads than you have cores available"); System.out.println("Are you certain you don't want to scale down to " + (cores * max_factor) + " threads? (y/N)"); String ret = input.readLine().toLowerCase(); if (!(ret.equals("y") || ret.equals("yes"))) { System.out.println("Setting the number of tasks to " + (cores * max_factor)); tasks = cores * max_factor; } } Config.getInstance().threads(tasks); } catch (NumberFormatException e) { System.err.println("Operand " + this.operand + " to -t or --tasks is not a valid number!"); System.exit(ErrorCode.OPTION_UNSPECIFIED); } catch (IOException e) { System.err.println("System input broke somehow ..."); System.exit(ErrorCode.GENERIC); } }
738ca03f-f450-4d51-a0ce-dbf4c8e48072
1
public double[] meanColumns() { int nRows = getRowDimension(); int nCols = getColumnDimension(); double[] result = sumColumns(); for (int c = 0; c < nCols; c++) { result[c] = result[c] / nRows; } return result; }
b0b0199a-911f-4cc4-8160-fbfc506c4824
7
public LinkedList<FaultsStore> getFaults(){ LinkedList<FaultsStore> psl = new LinkedList<FaultsStore>(); Connection Conn; FaultsStore ps = null; ResultSet rs = null; try { Conn = _ds.getConnection(); } catch (Exception et) { System.out.println("No Connection in Faults Model"); return null; } PreparedStatement pmst = null; Statement stmt = null; String sqlQuery = "select summary,idfault from fault"; System.out.println("Faults Query " + sqlQuery); try { try { // pmst = Conn.prepareStatement(sqlQuery); stmt = Conn.createStatement(); } catch (Exception et) { System.out.println("Can't create prepare statement"); return null; } System.out.println("Created prepare"); try { // rs=pmst.executeQuery(); rs = stmt.executeQuery(sqlQuery); } catch (Exception et) { System.out.println("Can not execut query here " + et); return null; } System.out.println("Statement executed"); if (rs.wasNull()) { System.out.println("result set was null"); } else { System.out.println("Well it wasn't null"); } while (rs.next()) { System.out.println("Getting RS"); ps = new FaultsStore(); ps.setFaultid(rs.getString("idfault")); ps.setFaultSummary(rs.getString("summary")); psl.add(ps); } } catch (Exception ex) { System.out.println("Opps, error in query " + ex); return null; } try { Conn.close(); } catch (Exception ex) { return null; } return psl; }
0009b59c-be52-492f-9bde-a03e2b9d1312
7
private void printString(TypeList list1, TypeList list2) { String inputedType = list1.type(); if (list2 != null) { inputedType = inputedType + "/" + list2.type(); TypeNode current2 = list2.head(); while (current2 != null) { list1.modType(current2.type(), current2.multiplier()); current2 = current2.next; } } System.out.println("Inputed type(s): " + inputedType); System.out.println("Weak against:"); TypeNode current = list1.head(); while(current != null) { if (current.multiplier() > 1) { System.out.println(current.type() + " - " + current.multiplier() + "x damage against " + inputedType); } current.restore(); current = current.next; } System.out.println("Resistant to:"); current = list1.head(); while(current != null) { if (current.multiplier() < 1) { if (current.multiplier() == 0) { System.out.println(inputedType + " is immune against " + current.type()); } else { System.out.println(current.type() + " - " + current.multiplier() + "x damage against " + inputedType); } } current = current.next; } System.out.println(""); }
f9aab11f-12ed-410a-971e-6b3c92f2c33c
1
public static void main(String args[]){ System.out.println("The value of 12 is"); R1Dot9IsOdd r=new R1Dot9IsOdd(); if(r.isOdd(12)){ System.out.println("Odd"); }else{ System.out.println("Even"); } }
44873bec-7f46-4007-958f-707e810f8746
4
private boolean isFourCardBadugi() { if (isColour() || isStreet() || isThree() || isPair()) { return false; } else { return true; } }
d7ee0f16-7c9d-4647-9a69-7cb0fe447569
5
public boolean postMortem(PostMortem pm) { JSONzip that = (JSONzip) pm; return this.namehuff.postMortem(that.namehuff) && this.namekeep.postMortem(that.namekeep) && this.stringkeep.postMortem(that.stringkeep) && this.substringhuff.postMortem(that.substringhuff) && this.substringkeep.postMortem(that.substringkeep) && this.values.postMortem(that.values); }
80e22b34-c090-44ed-86de-b630574c2adc
9
public void reinit(){ switch(loadingCount){ case 0: updateMapProgress(0.10f, "Reloading"); break; case 1: this.setPaused(true); // ensure it's paused //stateManager = new AppStateManager(this); bulletAppState.cleanup(); initStates(); updateMapProgress(0.10f, "Create Ship"); break; case 2: // remove ship rootNode.detachChild(ship.getNode()); //ship.detach(); // create new ship //stateManager = new AppStateManager(this); // TODO: make this work if (ship == null) { ship = new Ship(stateManager); } updateMapProgress(0.10f, "Loading Map"); break; case 3: //ship.stopAllForces(); Vector3f loc = mapObjectExtractor.warp.getNode().getLocalTranslation(); ship.setStartingPosition(loc.x,loc.y,0f); rootNode.attachChild(ship.getNode()); updateMapProgress(0.10f, "Setup Keyboard Input"); break; case 4: // create keybinder KeyBinder keyBinder = new KeyBinder(inputManager,ship); updateMapProgress(0.10f, "Setup Camera"); break; case 5: // setup camera chaseCam.setEnabled(false); chaseCam = new ChaseCamera(cam, ship.getNode(), inputManager); chaseCam.setDefaultHorizontalRotation((float)(Math.PI/-2.0f)); chaseCam.setDefaultVerticalRotation((float)(Math.PI/1f)); chaseCam.setInvertHorizontalAxis(true); chaseCam.setInvertVerticalAxis(true); chaseCam.setToggleRotationTrigger(new KeyTrigger(KeyInput.KEY_M)); updateMapProgress(0.10f, "Reading Game"); break; case 6: updateMapProgress(0.10f, "Finished"); ship.stopAllForces(); bulletAppState.setSpeed(0); break; case 7: updateMapProgress(0.00f, "Done"); break; } loadingCount++; }
888ab46f-487e-4ae6-b9a3-1f344869f7af
7
@Override public void delScript(ScriptingEngine S) { if(scripts!=null) { if(scripts.remove(S)) { if(scripts.size()==0) scripts=new SVector<ScriptingEngine>(1); if(((behaviors==null)||(behaviors.size()==0))&&((scripts==null)||(scripts.size()==0))) CMLib.threads().deleteTick(this,Tickable.TICKID_EXIT_BEHAVIOR); } } }
b4d2dcc6-06ff-4ca5-87df-435fd97c7347
9
public void checkHit(){ setBounds((int)x, (int)y, 20, 20); for(Enemy enemy : board.getEnemies()){ if(this.intersects(enemy) && enemy.inGame()){ if(ammoAbility != null && ammoAbility.equals("glue")) enemy.slowDownEnemy(); enemy.setLives(damage); // add splash damage to missiles if(ammoType.equals("Missile")){ Sound.playSound("explosion.wav"); setBounds((int)x-60, (int)y-60, 100, 100); Board.hitMarkers.add(new HitMarker((int)x-60, (int)y-60, 1)); for(int i = 0; i < board.getEnemies().length; i++){ Enemy enemyNearby = board.getEnemies()[i]; if(enemyNearby.intersects(this) && enemy.inGame()){ enemy.setLives(damage/2); } } } else Board.hitMarkers.add(new HitMarker((int)enemy.getX()+15, (int)enemy.getY()+15,0)); tower.removeFiredAmmo(this); break; } } }
775e9e9c-d9d0-4e8a-9885-a7f408e02a53
7
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Rectangle other = (Rectangle) obj; if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) return false; if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) return false; if (Float.floatToIntBits(height) != Float.floatToIntBits(other.height)) return false; if (Float.floatToIntBits(width) != Float.floatToIntBits(other.width)) return false; return true; }
5b656d10-d588-46ce-8f0f-3437b7315b12
0
@Override public String getCity() { return super.getCity(); }
cd3dbb17-4653-473b-93b9-49ad4eddb20f
3
boolean isAttackPlaceDiagonallyBelowRightNotHarming(int position, char[] boardElements, int dimension, int attackPlacesOnTheRight) { int positionRightBelow = 1; while (attackPlacesOnTheRight > 0) { if (isPossibleToPlaceDiagRightBelow(boardElements.length, position, dimension, positionRightBelow) && isBoardElementAnotherFigure(boardElements[elementDiagonallyRightBelow(dimension, position, positionRightBelow)])) { return false; } positionRightBelow++; attackPlacesOnTheRight--; } return true; }
8ff5970e-3215-49f3-b336-8c8b839d51b1
7
public boolean setInputFormat(Instances instanceInfo) throws Exception { if ((instanceInfo.classIndex() > 0) && (!getFillWithMissing())) { throw new IllegalArgumentException("TimeSeriesDelta: Need to fill in missing values " + "using appropriate option when class index is set."); } super.setInputFormat(instanceInfo); // Create the output buffer Instances outputFormat = new Instances(instanceInfo, 0); for(int i = 0; i < instanceInfo.numAttributes(); i++) { if (i != instanceInfo.classIndex()) { if (m_SelectedCols.isInRange(i)) { if (outputFormat.attribute(i).isNumeric()) { outputFormat.renameAttribute(i, outputFormat.attribute(i).name() + " d" + (m_InstanceRange < 0 ? '-' : '+') + Math.abs(m_InstanceRange)); } else { throw new UnsupportedAttributeTypeException("Time delta attributes must be numeric!"); } } } } outputFormat.setClassIndex(instanceInfo.classIndex()); setOutputFormat(outputFormat); return true; }
fe6e2ea5-1388-47e0-844e-be490be4552c
3
public PassengerCarChoice(Frame owner, DepartingTrain theTrain) { super(owner, true); this.theTrain = theTrain; setBounds(100, 100, 270, 203); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); { JLabel lblNewLabel = new JLabel("Gross Weight:"); lblNewLabel.setBounds(21, 25, 87, 23); contentPanel.add(lblNewLabel); } { JLabel lblSeats = new JLabel("Seats:"); lblSeats.setBounds(21, 58, 81, 23); contentPanel.add(lblSeats); } { grossWeightModel.setMinimum(0); txfGwPassengerCar = new JSpinner(grossWeightModel); txfGwPassengerCar.setBounds(107, 26, 137, 22); contentPanel.add(txfGwPassengerCar); } { seatsModel.setMinimum(0); txfSeatsPassengerCar = new JSpinner(seatsModel); txfSeatsPassengerCar.setBounds(107, 58, 137, 22); contentPanel.add(txfSeatsPassengerCar); } { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(txfGwPassengerCar.getValue().equals("") || txfSeatsPassengerCar.getValue().equals("")) JOptionPane.showMessageDialog(null, "Please fill in the required field(s)", "Warning",JOptionPane.WARNING_MESSAGE); else{ PassengerCar p; try { p = new PassengerCar(Integer.parseInt(txfGwPassengerCar.getValue().toString()), Integer.parseInt(txfSeatsPassengerCar.getValue().toString())); PassengerCarChoice.this.theTrain.addCarriage(p); dispose(); } catch (NumberFormatException | TrainException e1) { JOptionPane.showMessageDialog(null, "Please input legal value(s)", "Warning",JOptionPane.WARNING_MESSAGE); } } } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.setActionCommand("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); buttonPane.add(cancelButton); } } }
06a12dd8-0bfe-4e36-bdef-2c4984b4a65e
6
private static String write(int c, String l) { switch (c) { case 0: return "NAME:" + NAME; case 1: return "MONEY:" + MONEY; case 2: return "POS:" + POS; case 3: return "MAP:" + MAP; case 4: return "GENDER:" + GENDER; case 5: return "MUSIC:" + MUSIC; } return null; }
b27a94c0-1ea6-473b-8ba4-7c6ad8386974
6
public static CategoryDataset timeCreateDataset2(String t0, String t1, String t2, String t3, Map<String,Integer> timemap, String user_name) { DefaultCategoryDataset dataset=new DefaultCategoryDataset(); //System.out.println(t0+t1+t2+t3); int a0 = Integer.parseInt(t0); int a1 = Integer.parseInt(t1); int a2 = Integer.parseInt(t2); int a3 = Integer.parseInt(t3); int index = 0; for(int i=a0; i<=a2; i++) { int l=1, r=12; if(i==a0) l = a1; if(i==a2) r = a3; for(int j=l; j<=r; j++) { String ss = ""; ss = ss + String.valueOf(i); if(j<10) ss = ss + "0" + String.valueOf(j); else ss = ss + String.valueOf(j); if(timemap.containsKey(ss)) { dataset.setValue(timemap.get(ss), user_name, ss); index++; } } } return dataset; }