public static void main(String[] args) { int n = 10000; if (args.length > 0) n = Integer.parseInt(args[0]); List<Integer> sorted = new ArrayList<Integer>(n); for (int i = 0; i < n; i++) sorted.add(new Integer(i)); List<Integer> shuffled = new ArrayList<Integer>(sorted); Collections.shuffle(shuffled); Queue<Integer> pq = new PriorityQueue<Integer>(n, new MyComparator()); for (Iterator<Integer> i = shuffled.iterator(); i.hasNext(); ) pq.add(i.next()); List<Integer> recons = new ArrayList<Integer>(); while (!pq.isEmpty()) recons.add(pq.remove()); if (!recons.equals(sorted)) throw new RuntimeException("Sort test failed"); recons.clear(); pq = new PriorityQueue<Integer>(shuffled); while (!pq.isEmpty()) recons.add(pq.remove()); if (!recons.equals(sorted)) throw new RuntimeException("Sort test failed"); // Remove all odd elements from queue pq = new PriorityQueue<Integer>(shuffled); for (Iterator<Integer> i = pq.iterator(); i.hasNext(); ) if ((i.next().intValue() & 1) == 1) i.remove(); recons.clear(); while (!pq.isEmpty()) recons.add(pq.remove()); for (Iterator<Integer> i = sorted.iterator(); i.hasNext(); ) if ((i.next().intValue() & 1) == 1) i.remove(); if (!recons.equals(sorted)) throw new RuntimeException("Iterator remove test failed."); }
/* * Returns list of sensors currently loaded in the system * */ public static String getListOfSensors() { StringBuilder s = new StringBuilder(); Iterator iter = Mappings.getAllVSensorConfigs(); sensors.clear(); coordinates.clear(); while (iter.hasNext()) { VSensorConfig sensorConfig = (VSensorConfig) iter.next(); Double longitude = sensorConfig.getLongitude(); Double latitude = sensorConfig.getLatitude(); Double altitude = sensorConfig.getAltitude(); String sensor = sensorConfig.getName(); if ((latitude != null) && (longitude != null) && (altitude != null)) { Point point = new Point(latitude, longitude, altitude); coordinates.add(point); sensors.add(sensor); s.append(sensor) .append(" => ") .append(longitude) .append(" : ") .append(latitude) .append("\n"); } } return s.toString(); }
public synchronized void dispose() { List<SchedulerListener> l = listeners; listeners = null; if (l != null) { boolean cont = true; while (cont) { synchronized (l) { int queueSize = getQueueSize(); if (queueSize == 0) { cont = false; } else { try { l.wait(); } catch (InterruptedException ex) { // Ignore! } } } } synchronized (l) { l.clear(); } } }
private void load() { chestItemList.clear(); File chestFile = new File(SkyWarsReloaded.get().getDataFolder(), "chest.yml"); if (!chestFile.exists()) { SkyWarsReloaded.get().saveResource("chest.yml", false); } if (chestFile.exists()) { loadChest(chestFile); } opChestItemList.clear(); File opChestFile = new File(SkyWarsReloaded.get().getDataFolder(), "opchest.yml"); if (!opChestFile.exists()) { SkyWarsReloaded.get().saveResource("opchest.yml", false); } if (opChestFile.exists()) { loadChest(opChestFile); } basicChestItemList.clear(); File basicChestFile = new File(SkyWarsReloaded.get().getDataFolder(), "basicchest.yml"); if (!basicChestFile.exists()) { SkyWarsReloaded.get().saveResource("basicchest.yml", false); } if (basicChestFile.exists()) { loadChest(basicChestFile); } }
private void dumpSurvivalData(Map<String, List<SurvivalData>> survivalData) { List<String> daysToDeath = new ArrayList<String>(); List<String> lastFollowUp = new ArrayList<String>(); List<String> lastKnownAlive = new ArrayList<String>(); List<String> vitalStatus = new ArrayList<String>(); for (String patientId : new TreeSet<String>(survivalData.keySet())) { for (SurvivalData sd : survivalData.get(patientId)) { daysToDeath.add(sd.daysToDeath); lastFollowUp.add(sd.lastFollowUp); lastKnownAlive.add(sd.lastKnownAlive); vitalStatus.add(sd.vitalStatus); } System.out.print(patientId + "\t\t"); printList(daysToDeath); printList(lastFollowUp); printList(lastKnownAlive); printList(vitalStatus); System.out.println(); daysToDeath.clear(); lastFollowUp.clear(); lastKnownAlive.clear(); vitalStatus.clear(); } }
private void purgeQueue() { final ReferenceContext refContext = queue.getFirst().ref; // divide them up by source while (!queue.isEmpty()) { VCcontext context = queue.removeFirst(); for (final VariantContext vc : context.vcs) { if (vc.getSource().equals(source1)) sourceVCs1.add(vc); else sourceVCs2.add(vc); } } writeAndPurgeAllEqualVariants(sourceVCs1, sourceVCs2, SAME_STATUS); if (sourceVCs1.isEmpty()) { writeAll(sourceVCs2, source2, null); } else if (sourceVCs2.isEmpty()) { writeAll(sourceVCs1, source1, null); } else { resolveByHaplotype(refContext); } // allow for GC of the data sourceVCs1.clear(); sourceVCs2.clear(); }
private void makeClumpGoldStandard() throws EvalError { switch (testFileType) { case WSJ: clumpGoldStandard = CorpusUtil.wsjClumpGoldStandard(alpha, corpusFiles); break; case NEGRA: clumpGoldStandard = CorpusUtil.negraClumpGoldStandard(alpha, corpusFiles); break; case CTB: clumpGoldStandard = CorpusUtil.ctbClumpGoldStandard(alpha, corpusFiles); break; case SPL: evalTypes.clear(); evalTypes.add(OutputType.NONE); evals.clear(); evals.add(NullEval.instance()); break; default: throw new EvalError("Unexpected file type for clumping gold standard: " + corpusFiles); } if (filterLength > 0) clumpGoldStandard = clumpGoldStandard.filterBySentenceLength(filterLength); }
/** Create a random Json document with random values */ public String getRandomJson(int nbNodes) { // init sb.setLength(0); sb.append("{"); states.clear(); states.add(OBJECT_ATT); images.clear(); nodes.clear(); incr.clear(); datatypes.clear(); types.clear(); curNodePath.length = 1; curNodePath.offset = 0; Arrays.fill(curNodePath.ints, -1); shouldFail = false; nestedObjs = 0; // <= so that when nbNodes == 1, the json is still valid /* * the generated json might be uncomplete, if states is not empty, and * the maximum number of nodes has been reached. */ for (final int i = 0; i <= nbNodes && !states.empty(); nbNodes++) { sb.append(this.getWhitespace()).append(this.getNextNode()).append(this.getWhitespace()); } shouldFail = shouldFail ? true : !states.empty(); return sb.toString(); }
public void saveDataItems() { if (shouldLogData()) { try { if (ps == null) { synchronized (this) { if (ps == null) { String timestampString = LogTimestamp.getTimestampString(); if (timestampString != null) { File logFile = new File(parentDirectory, timestampString + ".csv"); ps = new PrintStream(new FileOutputStream(logFile)); ps.print("time,timeSinceStart"); writelist(ps, dataNames); startTime = System.currentTimeMillis(); } } } } if (ps != null) { timeUpdated = (System.currentTimeMillis() - startTime); ps.print(getDate()); ps.print(','); ps.print(timeUpdated); writelist(ps, dataValues); ps.flush(); timeSinceLog = System.currentTimeMillis(); } } catch (IOException e) { e.printStackTrace(); } } dataValues.clear(); dataNames.clear(); }
@Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { if (!super.isAvailable(project, editor, file) || !(file instanceof JetFile)) { return false; } // When running single test 'isAvailable()' is invoked multiple times, so we need to clear // lists. overriddenNonOverridableMembers.clear(); containingDeclarationsNames.clear(); DeclarationDescriptor descriptor = ResolvePackage.resolveToDescriptor(element); if (!(descriptor instanceof CallableMemberDescriptor)) return false; for (CallableMemberDescriptor overriddenDescriptor : getAllDeclaredNonOverridableOverriddenDescriptors((CallableMemberDescriptor) descriptor)) { assert overriddenDescriptor.getKind() == DECLARATION : "Can only be applied to declarations."; PsiElement overriddenMember = descriptorToDeclaration(overriddenDescriptor); if (overriddenMember == null || !QuickFixUtil.canModifyElement(overriddenMember) || !(overriddenMember instanceof JetCallableDeclaration)) { return false; } String containingDeclarationName = overriddenDescriptor.getContainingDeclaration().getName().asString(); overriddenNonOverridableMembers.add((JetCallableDeclaration) overriddenMember); containingDeclarationsNames.add(containingDeclarationName); } return overriddenNonOverridableMembers.size() > 0; }
public void copyFrom(TypeToNameMap from) { assert from != this; myPatterns.clear(); myPatterns.addAll(from.myPatterns); myNames.clear(); myNames.addAll(from.myNames); }
// look up and apply coarts for given rels to each sign in result private void applyCoarts(List<String> coartRels, Collection<Sign> result) { List<Sign> inputSigns = new ArrayList<Sign>(result); result.clear(); List<Sign> outputSigns = new ArrayList<Sign>(inputSigns.size()); // for each rel, lookup coarts and apply to input signs, storing results in output signs for (Iterator<String> it = coartRels.iterator(); it.hasNext(); ) { String rel = it.next(); Collection<String> preds = (Collection<String>) _coartRelsToPreds.get(rel); if (preds == null) continue; // not expected Collection<Sign> coartResult = getSignsFromRelAndPreds(rel, preds); if (coartResult == null) continue; for (Iterator<Sign> it2 = coartResult.iterator(); it2.hasNext(); ) { Sign coartSign = it2.next(); // apply to each input for (int j = 0; j < inputSigns.size(); j++) { Sign sign = inputSigns.get(j); grammar.rules.applyCoart(sign, coartSign, outputSigns); } } // switch output to input for next iteration inputSigns.clear(); inputSigns.addAll(outputSigns); outputSigns.clear(); } // add results back result.addAll(inputSigns); }
// look up and apply coarts for w to each sign in result @SuppressWarnings("unchecked") private void applyCoarts(Word w, SignHash result) throws LexException { List<Sign> inputSigns = new ArrayList<Sign>(result.asSignSet()); result.clear(); List<Sign> outputSigns = new ArrayList<Sign>(inputSigns.size()); // for each surface attr, lookup coarts and apply to input signs, storing results in output // signs for (Iterator<Pair<String, String>> it = w.getSurfaceAttrValPairs(); it.hasNext(); ) { Pair<String, String> p = it.next(); String attr = (String) p.a; if (!_indexedCoartAttrs.contains(attr)) continue; String val = (String) p.b; Word coartWord = Word.createWord(attr, val); SignHash coartResult = getSignsFromWord(coartWord, null, null, null); for (Iterator<Sign> it2 = coartResult.iterator(); it2.hasNext(); ) { Sign coartSign = it2.next(); // apply to each input for (int j = 0; j < inputSigns.size(); j++) { Sign sign = inputSigns.get(j); grammar.rules.applyCoart(sign, coartSign, outputSigns); } } // switch output to input for next iteration inputSigns.clear(); inputSigns.addAll(outputSigns); outputSigns.clear(); } // add results back result.addAll(inputSigns); }
public FunDef getDef(Exp[] args, String funName, Syntax syntax) { // Compute signature first. It makes debugging easier. final String signature = syntax.getSignature(funName, Category.Unknown, ExpBase.getTypes(args)); // Resolve function by its upper-case name first. If there is only one // function with that name, stop immediately. If there is more than // function, use some custom method, which generally involves looking // at the type of one of its arguments. List<Resolver> resolvers = funTable.getResolvers(funName, syntax); assert resolvers != null; final List<Resolver.Conversion> conversionList = new ArrayList<Resolver.Conversion>(); int minConversionCost = Integer.MAX_VALUE; List<FunDef> matchDefs = new ArrayList<FunDef>(); List<Resolver.Conversion> matchConversionList = null; for (Resolver resolver : resolvers) { conversionList.clear(); FunDef def = resolver.resolve(args, this, conversionList); if (def != null) { int conversionCost = sumConversionCost(conversionList); if (conversionCost < minConversionCost) { minConversionCost = conversionCost; matchDefs.clear(); matchDefs.add(def); matchConversionList = new ArrayList<Resolver.Conversion>(conversionList); } else if (conversionCost == minConversionCost) { matchDefs.add(def); } else { // ignore this match -- it required more coercions than // other overloadings we've seen } } } switch (matchDefs.size()) { case 0: throw MondrianResource.instance().NoFunctionMatchesSignature.ex(signature); case 1: break; default: final StringBuilder buf = new StringBuilder(); for (FunDef matchDef : matchDefs) { if (buf.length() > 0) { buf.append(", "); } buf.append(matchDef.getSignature()); } throw MondrianResource.instance() .MoreThanOneFunctionMatchesSignature .ex(signature, buf.toString()); } final FunDef matchDef = matchDefs.get(0); for (Resolver.Conversion conversion : matchConversionList) { conversion.checkValid(); conversion.apply(this, Arrays.asList(args)); } return matchDef; }
private static List<Integer> largestDivisibleSubset(int[] nums) { if (nums == null || nums.length == 0) return new LinkedList<>(); List<Integer> subset = new LinkedList<>(); List<Integer> finalset = new LinkedList<>(); Arrays.sort(nums); // iterate through each number so they can be compared for (int i = 0; i < nums.length; i++) { subset.clear(); if (nums[i] == 0) continue; subset.add(nums[i]); // System.out.println(subset); // if(nums[i] == 3) System.out.println(nums[i]); // iterate through the rest of the numbers for (int k = 0; k < nums.length; k++) { if (subset.contains(nums[k]) || nums[k] == 0) continue; boolean isDivisible = false; int itrNum = nums[k]; // if(nums[k] % 3 == 0) System.out.println("k == " + nums[k]); // System.out.println(subset); // iterate through the numbers in the subset and check against nums[k] for (int o = 0; o < subset.size(); o++) { // System.out.println(subset.get(o)); int subsetNum = subset.get(o); // if(nums[o] % 3 == 0) System.out.println("~~ o == " + n); if (subsetNum % itrNum == 0 || itrNum % subsetNum == 0) isDivisible = true; else { isDivisible = false; break; } } // if(itrNum % 3 == 0) System.out.println(itrNum); // System.out.println(subset); // if nums[k] is divisible by all numbers in the subset, add it to the subset // and increase the largestSubsetSize variable if (isDivisible) subset.add(itrNum); } // check if we found a larger subset if (subset.size() > finalset.size()) { finalset.clear(); finalset.addAll(subset); } // if(nums[i] % 3 == 0) System.out.println(subset); } Collections.sort(finalset); return finalset; }
void clear() { myPsiElements.clear(); for (RangeMarker marker : myRangeMarkers) { if (!(marker instanceof FoldRegion)) marker.dispose(); } myRangeMarkers.clear(); mySerializedElements.clear(); }
private void clearOldSelections() { for (MonthCellDescriptor selectedCell : selectedCells) { // De-select the currently-selected cell. selectedCell.setSelected(false); } selectedCells.clear(); selectedCals.clear(); }
public MmAccordionPanel() { super(); mainPanelWidth = 300; this.componentsPanel = new JPanel(); this.showButtons = false; checkBox.clear(); labels.clear(); panelLayout(); }
public void clearMessages() { messages.clear(); getRootStyleNode().removeChildrenAll(); rootMessageStyleNodes.clear(); endMarginNode = null; newMessageSeparatorNode = null; }
private void initializeTest() { symbols.clear(); scenarios.clear(); testSummary.clear(); allExpectations.clear(); allInstructionResults.clear(); allInstructions.clear(); allTables.clear(); exceptions.resetForNewTest(); }
protected void cleanupBuffers() { // Delete the capture buffers for (int i = 0; i < m_CaptureBuffers.size(); ++i) { FrameBuffer buffer = m_CaptureBuffers.get(i); buffer.free(); } m_FreeBufferList.clear(); m_CaptureBuffers.clear(); }
public void close() { for (ClassDataCollector cd : delegates) try { if (cd instanceof Closeable) ((Closeable) cd).close(); } catch (Exception e) { reporter.error("Fail to call close on %s", cd); } delegates.clear(); shortlist.clear(); }
private void updateListWidgets(boolean roots) { _directories.clear(); _files.clear(); if (!roots) { fillListWidgets(getCurrentDirectory()); } else { fillDirectoriesWidgetWithRoots(); } _directories.paint(); _files.paint(); }
@Override public void recycleInvitationCode(Integer pageSize) { IConfigService configService = ServiceManager.getService(IConfigService.class); if (pageSize == null) { pageSize = PAGE_SIZE; } long id = 0; List<InvitationCode> codeList; List<InvitationCodeRecycle> recycles = new ArrayList<InvitationCodeRecycle>(); List<InvitationCode> codes = new ArrayList<InvitationCode>(); InvitationCodeRecycle recycle; while (true) { NotificationWriter writer = notificationDaoManager.getWriter(); codeList = writer.getInvitationCode(pageSize, id); // 得到将要reindex的orderId if (CollectionUtils.isEmpty(codeList)) break; Object status = writer.begin(); try { for (InvitationCode code : codeList) { // 过期 无效 if (InvitationCodeStatus.isRecycle( code.getExpirationTime(), configService.getConfig("INVITATION_CODE_OVERDUE_DATE", ShopConstant.BC_SHOP_ID), code.getStatus())) { recycle = new InvitationCodeRecycle(); if (code.getExpirationTime() < System.currentTimeMillis()) { recycle = recycle.fromInvitationCode(code); } recycle.setStatus(InvitationCodeStatus.INVALID_OVERDUE); recycles.add(recycle); codes.add(code); } else if (InvitationCodeStatus.isOverdue( code.getExpirationTime(), configService.getConfig("INVITATION_CODE_EFFECTIVE_DATE", ShopConstant.BC_SHOP_ID))) { // 过期 code.setStatus(InvitationCodeStatus.OVERDUE); writer.update(code); } } id = codeList.get(codeList.size() - 1).getId(); if (CollectionUtils.isNotEmpty(recycles)) { for (int i = 0, max = recycles.size(); i < max; i++) { writer.save(recycles.get(i)); writer.delete(InvitationCode.class, codes.get(i).getId()); } } writer.commit(status); } finally { writer.rollback(status); recycles.clear(); codes.clear(); } } }
public void clear() { lock.lock(); try { graph.clear(); entryTasks.clear(); executionPlan.clear(); failures.clear(); runningProjects.clear(); } finally { lock.unlock(); } }
@NotNull private static GitCommandResult run(@NotNull Computable<GitLineHandler> handlerConstructor) { final List<String> errorOutput = new ArrayList<String>(); final List<String> output = new ArrayList<String>(); final AtomicInteger exitCode = new AtomicInteger(); final AtomicBoolean startFailed = new AtomicBoolean(); final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); int authAttempt = 0; boolean authFailed; boolean success; do { errorOutput.clear(); output.clear(); exitCode.set(0); startFailed.set(false); exception.set(null); GitLineHandler handler = handlerConstructor.compute(); handler.addLineListener( new GitLineHandlerListener() { @Override public void onLineAvailable(String line, Key outputType) { if (isError(line)) { errorOutput.add(line); } else { output.add(line); } } @Override public void processTerminated(int code) { exitCode.set(code); } @Override public void startFailed(Throwable t) { startFailed.set(true); errorOutput.add("Failed to start Git process"); exception.set(t); } }); handler.runInCurrentThread(null); authFailed = handler.hasHttpAuthFailed(); success = !startFailed.get() && errorOutput.isEmpty() && (handler.isIgnoredErrorCode(exitCode.get()) || exitCode.get() == 0); } while (authFailed && authAttempt++ < 2); return new GitCommandResult(success, exitCode.get(), errorOutput, output, null); }
private RNode[] makePartition(RNode n) throws DimensionalException { numOfPartitions++; numOfNodes += 2; RNode[] parts = new RNode[] {n, new RNode(n.getMbr(), n.isLeaf(), M_order)}; parts[1].setParent(n.getParent()); if (parts[1].getParent() != null) { parts[1].getParent().children().add(parts[1]); } List<RNode> cpyc = new LinkedList<RNode>(n.children()); n.children().clear(); RNode[] seeds = getSeeds(cpyc); parts[0].children().add(seeds[0]); parts[1].children().add(seeds[1]); update(parts[0]); update(parts[1]); while (!cpyc.isEmpty()) { if (parts[0].missingEntries(m_order) == 0 && parts[1].missingEntries(m_order) + cpyc.size() == m_order) { parts[1].children().addAll(cpyc); cpyc.clear(); update(parts[0]); update(parts[1]); return parts; } else if (parts[1].missingEntries(m_order) == 0 && parts[0].missingEntries(m_order) + cpyc.size() == m_order) { parts[0].children().addAll(cpyc); cpyc.clear(); update(parts[0]); update(parts[1]); return parts; } RNode next = chooseNext(cpyc, seeds), chosen; double enl1 = getEnlargement(parts[0], next); double enl2 = getEnlargement(parts[1], next); if (enl1 < enl2) chosen = parts[0]; else if (enl2 < enl1) chosen = parts[1]; else { double ar1 = parts[0].getMbr().getArea(); double ar2 = parts[1].getMbr().getArea(); if (ar1 < ar2) chosen = parts[0]; else if (ar2 < ar1) chosen = parts[1]; else { if (parts[0].children().size() < parts[1].children().size()) chosen = parts[0]; else if (parts[0].children().size() > parts[1].children().size()) chosen = parts[1]; else chosen = parts[new Random().nextInt(2)]; } } chosen.children().add(next); update(chosen); } return parts; }
public void testSelect() throws Exception { EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(new Bar()); em.persist(new Bar()); em.getTransaction().commit(); em.getTransaction().begin(); em.persist(new Foo("foo", Calendar.getInstance())); Foo foo = new Foo("bar", Calendar.getInstance()); foo.setBar(em.find(Bar.class, 1L)); em.persist(foo); Foo2 foo2 = new Foo2(); foo2.setBars(Arrays.asList(em.find(Bar.class, 1L), em.find(Bar.class, 2L))); em.persist(foo2); em.persist(new Foo2()); em.getTransaction().commit(); em.close(); output_value.clear(); lifeCycle.bind("consume_command_value", consume_command_value); assertOk("jpa open testEmf"); assertOk("jpa select f FROM Foo f order by f.id | consume_command_value"); assertEquals(2, output_value.size()); assertEquals("1", output_value.get(0).get("*id").toString()); assertEquals("foo", output_value.get(0).get("name")); assertEquals("<null>", output_value.get(0).get("bar")); assertNotNull(output_value.get(0).get("created")); assertEquals("2", output_value.get(1).get("*id").toString()); assertEquals("bar", output_value.get(1).get("name")); assertNotNull(output_value.get(1).get("created")); assertNotNull(output_value.get(1).get("bar")); assertEquals(Bar.class.getName() + "[id=1]", output_value.get(1).get("bar")); output_value.clear(); assertOk("jpa select f FROM Foo2 f order by f.id | consume_command_value"); assertEquals(2, output_value.size()); assertEquals("1", output_value.get(0).get("*id".toString())); assertEquals( "{" + Bar.class.getName() + "[id=1]," + Bar.class.getName() + "[id=2]}", output_value.get(0).get("bars")); assertEquals("2", output_value.get(1).get("*id".toString())); assertEquals("{}", output_value.get(1).get("bars")); assertOk("jpa close"); }
public void clearItems() { synchronized (lock) { myItems.clear(); mySortedItems.clear(); myRelevanceClassifier = myArranger.createRelevanceClassifier(); } }
/** * A single file, single time point ViewSetup to the data set * * @param filePath absolute file system path to file of this ViewSetup * @return the newly added ViewSetup or null if its configuration failed for any reason, e.g. * file does not exist */ public boolean setSingleFile(final String filePath) { KLB.Header header = null; try { header = klb.readHeader(filePath); } catch (IOException ex) { return false; } headers.clear(); headers.add(header); filePathTemplate = filePath; indexTag = tagMatch = tagFormat = null; timePoints = null; setPixelSpacing(header.pixelSpacing); final int t = 0; int level = 0; while (true) { try { headers.add(klb.readHeader(getFilePath(t, ++level))); } catch (IOException ex) { break; } } return true; }