/* * Similar to makeSureValInRange function except it is meant to return * more than one values of valid user input via LinkedList and it will * not return unless all of the input is valid * @param1 scanner object * @param2 lowerbound int * @param3 upperbound int * @param4 String that represents the entity we are entering the values for */ public static LinkedList<Integer> makeSureValInRange2( Scanner scan, int lowerbound, int upperbound, String inputFor) { assert (lowerbound <= upperbound); LinkedList<Integer> list = new LinkedList<Integer>(); System.out.println( SearchCriteria.prioritySetUpString( SearchCriteria.StringEnum.SELECT_CRITERIA, inputFor)); // prints the options to the user int value = scan.nextInt(); if (valInRange(lowerbound, upperbound, value)) { list.add(value); // If the first inputted is in range then we add more values boolean done = false; int i = lowerbound; while (!done && i < upperbound) { // keep looking for input until user enters a duplicate value // or the LinkedList of input is full value = scan.nextInt(); if (!list.contains(value) && valInRange(lowerbound, upperbound, value)) list.add(value); else done = true; i++; } return list; } else { // If the first value intered is not valid, then we return a null, which means that // we use default values (all values within range) System.out.println( SearchCriteria.prioritySetUpString(SearchCriteria.StringEnum.DEFAULT, inputFor)); return null; } }
/** * On créé le paquet de cartes Kokus * * @return */ public LinkedList<Kokus> initialisationPaquetKokus() { LinkedList<Kokus> llk = new LinkedList<Kokus>(); for (Kokus k : this.hashKokus) { // 12 cartes kokus de 1 unité if (k.getNbkoku() == 1) { for (int i = 0; i < 12; i++) { llk.add(k); } } // 8 cartes kokus de 2 unités if (k.getNbkoku() == 2) { for (int i = 0; i < 8; i++) { llk.add(k); } } // 4 cartes kokus de 3 unités if (k.getNbkoku() == 3) { for (int i = 0; i < 4; i++) { llk.add(k); } } } Collections.shuffle(llk); return llk; }
/** * Helper function: update the "old" RM group with the "next" group provided. * * @param old * @param next */ private void updateRMGroup(LinkedList<MemberInfo> old, LinkedList<MemberInfo> next) { if (next == null || next.isEmpty()) { System.out.println("empty or null next MemberInfo sent in updated."); return; } // Add to our old list the memberInfo objects that were not previously there. for (MemberInfo m : next) { if (old == null) { System.out.println("OLD NULL"); } if (m == null) { System.out.println("M NULL"); } if (!old.contains(m)) { old.add(m); } } // Remove from our old list the memberInfo objects that are absent in next. LinkedList<MemberInfo> toRemove = new LinkedList<MemberInfo>(); for (MemberInfo m : old) { if (!next.contains(m)) { toRemove.add(m); } } for (MemberInfo m : toRemove) { old.remove(m); } }
public void solve() { n = ni(); m = ni(); map = new char[n][m]; for (int i = 0; i < n; i++) { map[i] = nwrd().toCharArray(); } boolean use[][] = new boolean[n][m]; long ans = 0; LinkedList<Integer> ls = new LinkedList<Integer>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == '#') { ls.add(i * 10000 + j); while (ls.size() != 0) { int t = ls.pollFirst(); int jx = t % 10000; int ix = t / 10000; use[ix][jx] = true; map[ix][jx] = '.'; for (int k = 0; k < 4; k++) { if (is(ix + dx[k], jx + dy[k]) && !use[ix + dx[k]][jx + dy[k]] && map[ix + dx[k]][jx + dy[k]] == '#') { ls.add((ix + dx[k]) * 10000 + jx + dy[k]); use[ix + dx[k]][jx + dy[k]] = true; } } } ans++; } else use[i][j] = true; } } pw.print(ans); }
private static LinkedList<Coords> polarSort(LinkedList<Coords> list) { // find point with lowest x-coord int i = 0; double lowest = 9999999999.0; int lowIndex = 0; Coords tmp; while (i < list.size()) { tmp = list.get(i); if (tmp.getX() < lowest) { lowest = tmp.getX(); lowIndex = i; } else if (tmp.getX() == lowest) { if (tmp.getY() < list.get(lowIndex).getY()) { lowIndex = i; } } i++; } Coords lowestCoord = list.remove(lowIndex); LinkedList<Coords> sorted = new LinkedList<Coords>(); sorted.add(list.poll()); while (list.size() > 0) { tmp = list.poll(); i = sorted.size(); while (i > 0 && compVect(lowestCoord, sorted.get(i - 1), tmp) < 0.0) { i--; } sorted.add(i, tmp); } sorted.add(0, lowestCoord); return sorted; }
protected void add(Object value) { File f = null; FileOutputStream fos = null; try { f = createTempFile("S", dir); fos = new FileOutputStream(f); ObjectOutputStream fout = new ObjectOutputStream(new BufferedOutputStream(fos)); fout.writeObject(value); fout.flush(); fos.getFD().sync(); } catch (Exception e) { throw new SpaceError(e); } finally { if (fos != null) { try { fos.close(); } catch (Exception e) { throw new SpaceError(e); } } } stored.add(f.getAbsolutePath()); /* fill cache */ if (cacheSize > data.size()) if ((data.size() + 1) == stored.size()) data.add(value); }
private <T> Collection<T> generatePoints( TreeSet<Integer> grids_x, TreeSet<Integer> grids_y, PointFactory<T> factory, boolean collectExtremity) throws PointFactory.PFException { TreeMap<ViewComponentInfo, Collection<T>> map = new TreeMap<ViewComponentInfo, Collection<T>>(); ViewComponentInfo hit; for (Integer x : grids_x) { for (Integer y : grids_y) { // System.out.println("("+x+","+y+")"); hit = this.projectAbsoluteCoordinateRecursively(x, y); if (hit != null) { // Collection<T> iter = factory.get(x,y,hit); map.put(hit, factory.get(x, y, hit)); } } } LinkedList<T> lst = new LinkedList<T>(); for (Map.Entry<ViewComponentInfo, Collection<T>> entry : map.entrySet()) { for (T t : entry.getValue()) { if (collectExtremity) { if (entry.getKey().children == null || entry.getKey().isCollectionMember || entry.getKey().isSpinner || entry.getKey().hasOnClickListener()) { lst.add(t); } } else lst.add(t); } } return lst; }
protected Data(Object name) { super(); data = new LinkedList(); stored = new LinkedList(); listeners = null; String n = "space" + File.separatorChar; if (name instanceof String) n += name; else n += "H" + Integer.toString(name.hashCode()); dir = new File(n); dir.mkdirs(); FilenameFilter filter = new FilenameFilter() { public boolean accept(File f, String name) { return name.toUpperCase().startsWith("S"); } }; File file[] = dir.listFiles(filter); Arrays.sort(file); for (int i = 0; file.length > i; i++) { if (cacheSize > data.size()) { Object value = readValue(file[i].getAbsolutePath()); if (value == null) { (new File(file[i].getAbsolutePath())).delete(); } else { stored.add(file[i].getAbsolutePath()); data.add(value); } } else stored.add(file[i].getAbsolutePath()); } }
private synchronized void addRRset(Name name, RRset rrset) { if (!hasWild && name.isWild()) hasWild = true; Object types = data.get(name); if (types == null) { data.put(name, rrset); return; } int rtype = rrset.getType(); if (types instanceof List) { List list = (List) types; for (int i = 0; i < list.size(); i++) { RRset set = (RRset) list.get(i); if (set.getType() == rtype) { list.set(i, rrset); return; } } list.add(rrset); } else { RRset set = (RRset) types; if (set.getType() == rtype) data.put(name, rrset); else { LinkedList list = new LinkedList(); list.add(set); list.add(rrset); data.put(name, list); } } }
/** * On créé la paquet de carte Troupes * * @return */ public LinkedList<CarteTroupe> initialisationPaquetTroupe() { LinkedList<CarteTroupe> llct = new LinkedList<CarteTroupe>(); int i = 1; for (Troupes t : hashTroupes) { CarteTroupe ct = new CarteTroupe(t); // On met 6 fois la même carte dans la liste for (int k = 0; k < 6; k++) { llct.add(ct); } // il faut également mettre un carte avec deux troupes (en tout 6 cartes) int j = 1; for (Troupes t2 : hashTroupes) { // On ne reprend pas les cartes précédentes (elles ont déjà ét traitées) if (i == j || i < j) { CarteTroupe ct2 = new CarteTroupe(t, t2); llct.add(ct2); } j++; } i++; } // On mélange le paquet Collections.shuffle(llct); return llct; }
public static String normalizePath(String path) { if (!path.contains("./")) { return path; } boolean absolute = path.startsWith("/"); String[] elements = path.split(Repository.SEPARATOR); LinkedList<String> list = new LinkedList<String>(); for (String e : elements) { if ("..".equals(e)) { if (list.isEmpty() || "..".equals(list.getLast())) { list.add(e); } else { list.removeLast(); } } else if (!".".equals(e) && e.length() > 0) { list.add(e); } } StringBuilder sb = new StringBuilder(path.length()); if (absolute) { sb.append("/"); } int count = 0, last = list.size() - 1; for (String e : list) { sb.append(e); if (count++ < last) sb.append("/"); } return sb.toString(); }
/** @return the list of the data flavors */ public Collection<DataFlavor> getColorDataFlavors() { LinkedList<DataFlavor> dataFlavors = new LinkedList<DataFlavor>(); dataFlavors.add(colorFlavor); dataFlavors.add(w3cSVGColorFlavor); return dataFlavors; }
private void index() throws IOException { Enumeration entries = _jar.entries(); _nameToEntryMap = new HashMap(); _crcToEntryMap = new HashMap(); _entries = new ArrayList(); if (_debug) { System.out.println("indexing: " + _jar.getName()); } if (entries != null) { while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); long crc = entry.getCrc(); Long crcL = new Long(crc); if (_debug) { System.out.println("\t" + entry.getName() + " CRC " + crc); } _nameToEntryMap.put(entry.getName(), entry); _entries.add(entry); // generate the CRC to entries map if (_crcToEntryMap.containsKey(crcL)) { // key exist, add the entry to the correcponding // linked list // get the linked list LinkedList ll = (LinkedList) _crcToEntryMap.get(crcL); // put in the new entry ll.add(entry); // put it back in the hash map _crcToEntryMap.put(crcL, ll); } else { // create a new entry in the hashmap for the new key // first create the linked list and put in the new // entry LinkedList ll = new LinkedList(); ll.add(entry); // create the new entry in the hashmap _crcToEntryMap.put(crcL, ll); } } } }
/** Generate a sentence that includes (if possible) the specified word. */ public String getSentence(String word) { LinkedList parts = new LinkedList(); Quad[] quads; if (words.containsKey(word)) { quads = (Quad[]) ((HashSet) words.get(word)).toArray(new Quad[0]); } else { quads = (Quad[]) this.quads.keySet().toArray(new Quad[0]); } if (quads.length == 0) { return ""; } Quad middleQuad = quads[rand.nextInt(quads.length)]; Quad quad = middleQuad; for (int i = 0; i < 4; i++) { parts.add(quad.getToken(i)); } while (quad.canEnd() == false) { String[] nextTokens = (String[]) ((HashSet) next.get(quad)).toArray(new String[0]); String nextToken = nextTokens[rand.nextInt(nextTokens.length)]; quad = (Quad) this.quads.get( new Quad(quad.getToken(1), quad.getToken(2), quad.getToken(3), nextToken)); parts.add(nextToken); } quad = middleQuad; while (quad.canStart() == false) { String[] previousTokens = (String[]) ((HashSet) previous.get(quad)).toArray(new String[0]); String previousToken = previousTokens[rand.nextInt(previousTokens.length)]; quad = (Quad) this.quads.get( new Quad(previousToken, quad.getToken(0), quad.getToken(1), quad.getToken(2))); parts.addFirst(previousToken); } StringBuffer sentence = new StringBuffer(); Iterator it = parts.iterator(); while (it.hasNext()) { String token = (String) it.next(); sentence.append(token); } return sentence.toString(); }
Node() { v = chars[max]; max++; if (v >= 'A' && v <= 'Z') dim[0] = dim[1] = 2; else { c = new LinkedList<Node>(); v = (char) (v == '|' ? 1 : 0); for (int j = 0; j < 2; j++) { Node child = new Node(); dim[v] += child.dim[v]; dim[1 - v] = dim[1 - v] > child.dim[1 - v] ? dim[1 - v] : child.dim[1 - v]; if (child.v == v) for (Node cc : child.c) c.add(cc); else c.add(child); } } }
/** * The read admin list reads in admin objects from a readfile * * @return * @throws FileNotFoundException */ public LinkedList<Admin> readAdminList() throws FileNotFoundException { FileInputStream fstream = new FileInputStream("adminList.csv"); LinkedList<Admin> adminList = new LinkedList<Admin>(); Scanner input = new Scanner(fstream); input.useDelimiter(","); try { // reads file while (input.hasNext()) { String firstName = input.next(); String lastName = input.next(); String userName = input.next(); String password = input.next(); String email = input.next(); String office = input.next(); String phoneNumber = input.nextLine(); // creates admin Admin newAdmin = new Admin(userName, password, email, firstName, lastName, office, phoneNumber); adminList.add(newAdmin); } fstream.close(); } catch (Exception e) { adminList = null; } Collections.sort(adminList); return adminList; }
/** * reads faculty list file * * @return LinkedList<Faculty> * @throws FileNotFoundException */ public LinkedList<Faculty> readFacultyList() throws FileNotFoundException { FileInputStream fstream = new FileInputStream("facultyList.csv"); LinkedList<Faculty> facultyList = new LinkedList<Faculty>(); Scanner input = new Scanner(fstream); input.useDelimiter(","); try { // reads file while (input.hasNext()) { String firstName = input.next(); String lastName = input.next(); String userName = input.next(); String password = input.next(); String email = input.next(); String office = input.next(); String phoneNumber = input.nextLine(); // creates faculty member Faculty newFaculty = new Faculty(userName, password, email, firstName, lastName, office, phoneNumber); facultyList.add(newFaculty); } fstream.close(); } catch (Exception e) { facultyList = null; } Collections.sort(facultyList); return facultyList; }
// Test method public LinkedList<Integer> getLiveAuctionsIds() throws RemoteException { LinkedList<Integer> ll = new LinkedList<Integer>(); for (AuctionItem t : liveAuctionItems.values()) { ll.add(t.getAuctionId()); } return ll; }
void add(Target t) { SocketChannel sc = null; try { sc = SocketChannel.open(); sc.configureBlocking(false); boolean connected = sc.connect(t.address); t.channel = sc; t.connectStart = System.currentTimeMillis(); if (connected) { t.connectFinish = t.connectStart; sc.close(); printer.add(t); } else { synchronized (pending) { pending.add(t); } sel.wakeup(); } } catch (IOException x) { if (sc != null) { try { sc.close(); } catch (IOException xx) { } } t.failure = x; printer.add(t); } }
public void addTarget(Target target) { // 向targets队列中加入一个任务 SocketChannel socketChannel = null; try { socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(target.address); target.channel = socketChannel; target.connectStart = System.currentTimeMillis(); synchronized (targets) { targets.add(target); } selector.wakeup(); } catch (Exception x) { if (socketChannel != null) { try { socketChannel.close(); } catch (IOException xx) { } } target.failure = x; addFinishedTarget(target); } }
private static <T> Iterator<T> reverse(Iterable<T> values) { LinkedList<T> reversed = new LinkedList<>(); for (T value : values) { reversed.add(value); } return reversed.descendingIterator(); }
private List getMatchingPatterns(char[] chars, int startingIdx) { Node cur = head; LinkedList matchingPatterns = new LinkedList(); if (cur.pattern != null) { matchingPatterns.add(cur.pattern); } for (int c = startingIdx; cur != null && c < chars.length; ++c) { Character curchar = new Character(chars[c]); Node next = (Node) cur.children.get(curchar); cur = next; if (cur != null && cur.pattern != null) { matchingPatterns.add(cur.pattern); } } return matchingPatterns; }
public String get_item_ids() { String jsonarry; try { krypton_database_get_my_tokens getxt = new krypton_database_get_my_tokens(); String token_array[] = new String[network.listing_size]; token_array = getxt.get_tokens(network.base58_id); LinkedList<String> list = new LinkedList<String>(); for (int loop = 0; loop < token_array.length; loop++) { // ************ if (!token_array[loop].contains("-")) { list.add(token_array[loop]); } } // ***************************************************************** jsonarry = JSONValue.toJSONString(list); } catch (Exception e) { statex = "0"; jsonarry = "Error"; } // ***************** return jsonarry; } // *************************************
/** * Run all jobs in the work list (and any children they have) to completion. This method returns * <code>true</code> if all jobs were successfully completed. If all jobs were successfully * completed, then the worklist will be empty. * * <p>The scheduling of <code>Job</code>s uses two methods to maintain scheduling invariants: * <code>selectJobFromWorklist</code> selects a <code>SourceJob</code> from <code>worklist</code> * (a list of jobs that still need to be processed); <code>enforceInvariants</code> is called * before a pass is performed on a <code>SourceJob</code> and is responsible for ensuring all * dependencies are satisfied before the pass proceeds, i.e. enforcing any scheduling invariants. */ public boolean runToCompletion() { boolean okay = true; while (okay && !worklist.isEmpty()) { SourceJob job = selectJobFromWorklist(); if (Report.should_report(Report.frontend, 1)) { Report.report(1, "Running job " + job); } okay &= runAllPasses(job); if (job.completed()) { // the job has finished. Let's remove it from the map so it // can be garbage collected, and free up the AST. jobs.put(job.source(), COMPLETED_JOB); if (Report.should_report(Report.frontend, 1)) { Report.report(1, "Completed job " + job); } } else { // the job is not yet completed (although, it really // should be...) if (Report.should_report(Report.frontend, 1)) { Report.report(1, "Failed to complete job " + job); } worklist.add(job); } } if (Report.should_report(Report.frontend, 1)) Report.report(1, "Finished all passes -- " + (okay ? "okay" : "failed")); return okay; }
public Conversation insertNewConversation(long rmt_ip, int lcl_port, int rmt_port) { gc(); Conversation conv = new Conversation(rmt_ip, lcl_port, rmt_port); modLong.setLong(rmt_ip); modInt.setInt((lcl_port << 16) | (rmt_port & 0xFFFF)); ModInteger mInt = new ModInteger(); mInt.setInt((lcl_port << 16) | (rmt_port & 0xFFFF)); HashMap portsMap = (HashMap) hostsMap.get(modLong); if (portsMap == null) { ModLong mLong = new ModLong(); mLong.setLong(rmt_ip); portsMap = new HashMap(); hostsMap.put(mLong, portsMap); } portsMap.put(mInt, conv); allConversations.add(conv); hasChanged = true; return conv; }
public void addFinishedTarget(Target target) { // 向finishedTargets队列中加入一个任务 synchronized (finishedTargets) { finishedTargets.notify(); finishedTargets.add(target); } }
/** * Find mod files in the "mods" folder * * @param modFolder Folder to search * @param modFiles List of mod files to load */ protected void findModFiles(File modFolder, LinkedList<File> modFiles) { List<String> supportedVerions = Arrays.asList(SUPPORTED_VERSIONS); for (File modFile : modFolder.listFiles(this)) { try { // Check for a version file ZipFile modZip = new ZipFile(modFile); ZipEntry version = modZip.getEntry("version.txt"); if (version != null) { // Read the version string InputStream versionStream = modZip.getInputStream(version); BufferedReader versionReader = new BufferedReader(new InputStreamReader(versionStream)); String strVersion = versionReader.readLine(); versionReader.close(); // Only add the mod if the version matches and we were able to successfully add it to the // class path if (supportedVerions.contains(strVersion) && addURLToClassPath(modFile.toURI().toURL())) { modFiles.add(modFile); } } modZip.close(); } catch (Exception ex) { logger.warning( "Error enumerating '" + modFile.getAbsolutePath() + "': Invalid zip file or error reading file"); } } }
public MayaAnimBuildAction() { super( "MayaAnimBuild", new VersionID("2.4.1"), "Temerity", "Extends the MayaBuild Action to now allow for the referencing of Maya files " + "that only contain curves, which are then hooked up to models which have either " + "been Imported or Referenced."); addUnitsParams(); addStartFrameParam(); addEndFrameParam(); addInitalMELParam(); addAnimMELParam(); addModelMELParam(); addFinalMELParam(); { LayoutGroup layout = new LayoutGroup(true); addUnitsParamsToLayout(layout); layout.addSeparator(); layout.addEntry(aStartFrame); layout.addEntry(aEndFrame); layout.addSeparator(); layout.addEntry(aInitialMEL); layout.addEntry(aModelMEL); layout.addEntry(aAnimMEL); layout.addEntry(aFinalMEL); setSingleLayout(layout); } { LinkedList<String> layout = new LinkedList<String>(); layout.add(aSceneType); layout.add(aBuildType); layout.add(aNameSpace); layout.add(aPrefixName); setSourceLayout(layout); } addSupport(OsType.MacOS); addSupport(OsType.Windows); }
/** * Translates the link structure into the cell structure depending on healthy detector locations */ public void createCellStructure() { int i = 0; while (i < mainlineLinks.size() - 1) { if (mainlineLinks.get(i).isHasDetector() & mainlineLinks.get(i).getDetectorML().getHealthStatus() == 100) { Cell c = new Cell((int) totalTimeInHours * 60 / 5); c.addLink(mainlineLinks.get(i)); c.setDetectorML(mainlineLinks.get(i).getDetectorML()); c.setDetectorHOV(mainlineLinks.get(i).getDetectorHOV()); while (!mainlineLinks.get(i + 1).isHasDetector() & i < mainlineLinks.size() - 2 | (mainlineLinks.get(i + 1).isHasDetector() & mainlineLinks.get(i + 1).getDetectorML().getHealthStatus() != 100)) { c.addLink(mainlineLinks.get(i + 1)); i++; } // Onramps and Offramps in the Cell for (Link l : c.getLinks()) { c.addToOnrampPerLink(l.getUpNode().getInLinks().size() - 1); c.addToOfframpPerLink(l.getDownNode().getOutLinks().size() - 1); for (int linkID : l.getUpNode().getInLinks()) { if (links.get(linkID).getLinkType().equals("onramp")) { if (links.get(linkID).getDetectorML().getFlowData().isEmpty() | links.get(linkID).getDetectorML().getHealthStatus() != 100) { c.addToImputeOR(true); c.appendZeroColumnToMeasuredOnrampFlow(); } else { c.appendColumnToMeasuredOnrampFlow( links.get(linkID).getDetectorML().getFlowDataArray()); c.addToImputeOR(false); } } } for (int linkID : l.getDownNode().getOutLinks()) { if (links.get(linkID).getLinkType().equals("offramp")) { if (links.get(linkID).getDetectorML().getFlowData().isEmpty() | links.get(linkID).getDetectorML().getHealthStatus() != 100) { c.addToImputeFR(true); c.appendZeroColumnToMeasuredOfframpFlow(); } else { c.appendColumnToMeasuredOfframpFlow( links.get(linkID).getDetectorML().getFlowDataArray()); c.addToImputeFR(false); } } } } cells.add(c); } i++; } i = 0; }
public void caseAElem(final AElem elem) { blist = false; if ((elem.getUnOp() != null) && ((elem.getUnOp() instanceof AStarUnOp) || (elem.getUnOp() instanceof APlusUnOp))) { blist = true; } String elem_name = (elem.getElemName() != null ? elem.getElemName().getText() : elem.getId().getText()); if (!blist) { listElems.add(elem_name); } else { listElemslist.add(elem_name); } listElemsGlobal.add(elem_name); }