public static void main(String args[]) { Pair p; p = new Pair(2, new Pair(88, null)); System.out.println(p.car()); System.out.println(p.cdr().car()); System.out.println(p.ww); System.out.println(p.yy); System.out.println(p.car); System.out.println(p.cdr.car); System.out.println(p.V4[0]); System.out.println(p.V4[1]); System.out.println(p.V3[0]); System.out.println(p.V3[1]); System.out.println(SpecialPair.w); System.out.println(SpecialPair.x); System.out.println(SpecialPair.V1[0]); System.out.println(SpecialPair.V1.length); System.out.println(A.fa()); A a = new A(); A[] va = new A[2]; System.out.println(a.fb()); System.out.println(a.w); // A strange case, should we generate code for va[0]? // System.out.println(va[0].w); }
public Value matchPositions(Value str) { PatternMatcher matcher = getMatcher(); // Do the matching PatternMatcherInput jStr = new PatternMatcherInput(string(str)); Pair result = null; Pair prev = null; boolean found = false; while (matcher.contains(jStr, pattern)) { found = true; MatchResult matchResult = matcher.getMatch(); for (int i = 0, length = matchResult.groups(); i < length; i++) { Pair m = new Pair( Quantity.valueOf(matchResult.beginOffset(i)), Quantity.valueOf(matchResult.endOffset(i))); Pair elem = new Pair(m, EMPTYLIST); if (result == null) result = prev = elem; else { prev.setCdr(elem); prev = elem; } } } if (!found) return FALSE; else return result; }
@Test public void restore() throws RuleBaseException, TransformException { Node comp1 = content.query().single("/id('comp1')").node(); Node comp2 = content.query().single("/id('comp2')").node(); Node cname = content.query().single("/id('cname')").node(); setModNearestAncestorImplementing( NodeTarget.class, new NodeTarget() { public ItemList targets() throws TransformException { return content.query().all("/id('comp1 comp2')"); } }); setModData("(<sort-siblings run-length='2'/>, <sort-siblings run-length='1'/>)"); setModReferences(cname, comp2, cname); SortBySiblingBlock block = define("<sort before='sibling'>uml:name</sort>"); SortBySiblingBlock.SortBySiblingSeg seg = (SortBySiblingBlock.SortBySiblingSeg) block.createSeg(mod); seg.restore(); assertEquals( Arrays.asList( new Pair[] { Pair.of(comp1, Arrays.asList(cname, comp2)), Pair.of(comp2, Arrays.asList(cname)) }), seg.siblingsByTarget); }
/** * Method to find all frequent items in a projected sequence database * * @param sequences the set of sequences * @return A list of pairs, where a pair is an item with (1) a boolean indicating if it is in an * itemset that is "cut" and (2) the sequence IDs where it occurs. */ protected Set<Pair> findAllFrequentPairs( SequentialPattern prefix, List<PseudoSequence> sequences) { // We use a Map the store the pairs. Map<Pair, Pair> mapPairs = new HashMap<Pair, Pair>(); // for each sequence for (PseudoSequence sequence : sequences) { // for each itemset for (int i = 0; i < sequence.size(); i++) { // for each item for (int j = 0; j < sequence.getSizeOfItemsetAt(i); j++) { String item = sequence.getItemAtInItemsetAt(j, i); // create the pair corresponding to this item Pair paire = new Pair(sequence.isPostfix(i), item); // false is ok? // get the pair object store in the map if there is one already Pair oldPaire = mapPairs.get(paire); // if there is no pair object yet if (oldPaire == null) { // store the pair object that we created mapPairs.put(paire, paire); } else { // otherwise use the old one paire = oldPaire; } // record the current sequence id for that pair paire.getSequencesID().add(sequence.getId()); } } } MemoryLogger.getInstance().checkMemory(); // check the memory for statistics. // return the map of pairs return mapPairs.keySet(); }
@Test public void totalOrder() throws RuleBaseException { SortBlock block = define("<sort by='ascending' priority='5'>@foo</sort>"); final OrderGraph graph = mockery.mock(OrderGraph.class); mockery.checking( new Expectations() { { one(graph).order("x2", "x1", 5); one(graph).order("x2", "x3", 5); one(graph).order("x2", "x4", 5); one(graph).order("x1", "x4", 5); one(graph).order("x3", "x4", 5); } }); List<Pair<String, Integer>> list = new ArrayList<Pair<String, Integer>>(); list.add(Pair.of("x1", 23)); list.add(Pair.of("x2", 18)); list.add(Pair.of("x3", 23)); list.add(Pair.of("x4", 35)); Comparator<Pair<String, Integer>> comparator = new Comparator<Pair<String, Integer>>() { public int compare(Pair<String, Integer> o1, Pair<String, Integer> o2) { return o1.second.compareTo(o2.second); } }; block.totalOrder(list, comparator, graph); }
public static void main(String[] args) { int[] test = {9, 3, 6, 5, 5, 7, -1, 13, 14, -2, 12, 0}; ArrayList<Pair> pairs = printPairSums(test, 12); for (Pair p : pairs) { System.out.println(p.toString()); } }
/** * resolves n to node of type R or S, via declaration returns null if n's declaration can't be * cast to R/S */ private Pair<R, S> resolve(IdentNode n) { if (n instanceof PackageIdentNode) { if (!resolveOwner((PackageIdentNode) n)) { return null; } } Pair<R, S> pair = new Pair<R, S>(); DeclNode resolved = n.getDecl(); if (clsR.isInstance(resolved)) { pair.fst = clsR.cast(resolved); } if (clsS.isInstance(resolved)) { pair.snd = clsS.cast(resolved); } if (pair.fst != null || pair.snd != null) { return pair; } n.reportError( "\"" + n + "\" is a " + resolved.getUseString() + " but a " + Util.getStrListWithOr(classes, BaseNode.class, "getUseStr") + " is expected"); return null; }
/** * resolves n to node of type R, via declaration if n is an identifier, via simple cast otherwise * returns null if n's declaration or n can't be cast to R or S */ public Pair<R, S> resolve(BaseNode n, BaseNode parent) { if (n instanceof IdentNode) { Pair<R, S> pair = resolve((IdentNode) n); if (pair != null) { assert pair.fst == null || pair.snd == null; parent.becomeParent(pair.fst); parent.becomeParent(pair.snd); } return pair; } Pair<R, S> pair = new Pair<R, S>(); if (clsR.isInstance(n)) { pair.fst = clsR.cast(n); } if (clsS.isInstance(n)) { pair.snd = clsS.cast(n); } if (pair.fst != null || pair.snd != null) { assert pair.fst == null || pair.snd == null; return pair; } n.reportError( "\"" + n + "\" is a " + n.getUseString() + " but a " + Util.getStrListWithOr(classes, BaseNode.class, "getUseStr") + " is expected"); return null; }
@SuppressWarnings("unchecked") @Test public void sortAfter() throws RuleBaseException { final Node comp1 = content.query().single("/id('comp1')").node(); final Node comp2 = content.query().single("/id('comp2')").node(); final Node cname = content.query().single("/id('cname')").node(); SortBySiblingBlock block = define("<sort after='sibling'>uml:name</sort>"); SortBySiblingBlock.SortBySiblingSeg seg1 = (SortBySiblingBlock.SortBySiblingSeg) block.createSeg(mod); SortBySiblingBlock.SortBySiblingSeg seg2 = (SortBySiblingBlock.SortBySiblingSeg) block.createSeg(mod); seg1.siblingsByTarget = Arrays.<Pair<Node, List<Node>>>asList( new Pair[] { Pair.of(comp1, Arrays.asList(cname, comp2)), Pair.of(comp2, Arrays.asList(cname)) }); seg2.siblingsByTarget = Arrays.<Pair<Node, List<Node>>>asList(new Pair[] {Pair.of(cname, Arrays.asList(comp2))}); final OrderGraph graph = mockery.mock(OrderGraph.class); mockery.checking( new Expectations() { { one(graph).order(cname, comp1, 0); one(graph).order(comp2, comp1, 0); one(graph).order(cname, comp2, 0); one(graph).order(comp2, cname, 0); } }); block.sort(Arrays.asList(seg1, seg2), graph); }
public boolean addRoots(final String name, final Collection<AbstractTreeNode> nodes) { final Collection<TreeItem<Pair<AbstractUrl, String>>> list = getFavoritesListRootUrls(name); final HashSet<AbstractUrl> set = new HashSet<AbstractUrl>( ObjectsConvertor.convert( list, new Convertor<TreeItem<Pair<AbstractUrl, String>>, AbstractUrl>() { @Override public AbstractUrl convert(TreeItem<Pair<AbstractUrl, String>> o) { return o.getData().getFirst(); } })); for (AbstractTreeNode node : nodes) { final Pair<AbstractUrl, String> pair = createPairForNode(node); if (pair != null) { if (set.contains(pair.getFirst())) continue; final TreeItem<Pair<AbstractUrl, String>> treeItem = new TreeItem<Pair<AbstractUrl, String>>(pair); list.add(treeItem); set.add(pair.getFirst()); appendChildNodes(node, treeItem); } } fireListeners.rootsChanged(name); return true; }
public static final int optionsFromScheme(Value value, Value type) { if (value instanceof Symbol) { if (value == CASE_INSENSITIVE) { if (type == REGEX_PERL5) return Perl5Compiler.CASE_INSENSITIVE_MASK; else if (type == REGEX_GLOB) return GlobCompiler.CASE_INSENSITIVE_MASK; else if (type == REGEX_AWK) return AwkCompiler.CASE_INSENSITIVE_MASK; else throw new RuntimeException("Unknown compiler " + type); } else if (value == EXTENDED) { if (type == REGEX_PERL5) return Perl5Compiler.EXTENDED_MASK; else throw new RuntimeException("The extended mask is supported only by Perl5 regexps"); } else if (value == SINGLELINE) { if (type == REGEX_PERL5) return Perl5Compiler.SINGLELINE_MASK; else throw new RuntimeException("The singleline mask is supported only by Perl5 regexps"); } else if (value == MULTILINE) { if (type == REGEX_PERL5) return Perl5Compiler.MULTILINE_MASK; else if (type == REGEX_GLOB) throw new RuntimeException("Glob compiler doesn't support this option: " + value); else if (type == REGEX_AWK) return AwkCompiler.MULTILINE_MASK; } else throw new RuntimeException("Unsupported regexp option " + value); } else if (value instanceof Pair) { int options = 0; Pair pv = (Pair) value; while (pv != EMPTYLIST) { options |= optionsFromScheme(pv.car(), type); pv = (Pair) pv.cdr(); } return options; } else throw new RuntimeException("Invalid format for options " + value); // Not reached, but keeps the Java compiler happy return 0; }
// Gestiona la reacción de la colisión de los dos shoots pasados por parámetro public static void manageCollisionWithShoot(Pair<Shoot, Shoot> shootToShoot) { Shoot shoot1 = shootToShoot.getFirst(); Shoot shoot2 = shootToShoot.getSecond(); shoot1.collideWithShoot(shoot2); shoot2.collideWithShoot(shoot1); }
public void swap(int i1, int i2, int j1, int j2) { int ilength = i2 - i1 + 1; int jlength = j2 - j1 + 1; int diff = jlength - ilength; Set<Pair<Integer, Integer>> newAlignments = new HashSet<Pair<Integer, Integer>>(); for (Pair<Integer, Integer> alignment : sureAlignments) { int pos = alignment.getFirst(); if (pos < i1 || pos > j2) { newAlignments.add(alignment); } else if (pos >= i1 && pos <= i2) { newAlignments.add(new Pair<Integer, Integer>(pos + j2 - i2, alignment.getSecond())); } else if (pos > i2 && pos < j1) { newAlignments.add(new Pair<Integer, Integer>(pos + diff, alignment.getSecond())); } else if (pos >= j1 && pos <= j2) { newAlignments.add(new Pair<Integer, Integer>(pos - j1 + i1, alignment.getSecond())); } else { System.err.println("Error in Alignment.swap()"); System.exit(1); } } sureAlignments = newAlignments; }
public boolean equals(Pair one, Pair two) { if ((one.getFirst() == two.getFirst()) && (one.getSecond() == two.getSecond())) { return true; } else { return false; } }
public static Provider url2Provider(Pair<Long, URL> pair) { if (pair == null) { return null; } Long id = pair.getKey(); URL url = pair.getValue(); if (url == null) return null; Provider p = new Provider(); p.setId(id); p.setService(url.getServiceKey()); p.setAddress(url.getAddress()); p.setApplication(url.getParameter(Constants.APPLICATION_KEY)); p.setUrl(url.toIdentityString()); p.setParameters(url.toParameterString()); p.setDynamic(url.getParameter("dynamic", true)); p.setEnabled(url.getParameter(Constants.ENABLED_KEY, true)); p.setWeight(url.getParameter(Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT)); p.setUsername(url.getParameter("owner")); return p; }
@Override public boolean picksplit( HSPLeafNode<WritableString, R> leaf, int level, ArrayList<ArrayList<Pair<WritableString, R>>> childrenData, ArrayList<Predicate> childrenPredicates) { if (level == 1) { initializePredicates(childrenPredicates); for (Pair<WritableString, R> p : leaf.getKeyRecords()) { WritableString str = p.getFirst(); int idx = charToInt(str.getString().charAt(0)); childrenData.get(idx).add(p); } for (int i = 0; i < childrenData.size(); i++) { if (childrenData.get(i).size() > 1) { return true; } } return false; } WritableChar predic = (WritableChar) leaf.getPredicate(); if (predic == null) return false; initializePredicates(childrenPredicates); for (Pair<WritableString, R> p : leaf.getKeyRecords()) { WritableString str = p.getFirst(); int idx = charToInt(str.getString().charAt(level - 1)); childrenData.get(idx).add(p); } for (int i = 0; i < childrenData.size(); i++) { if (childrenData.get(i).size() > 1) { return true; } } return false; }
Pair Calculate(int u) { BigInteger ans; Pair temp; temp = new Pair(); if (g[u].size() == 0) { temp.x = BigInteger.ONE; temp.n = 1; return temp; } if (g[u].size() == 1) { temp = Calculate((int) g[u].get(0)); temp.n++; return temp; } int p, q; temp = Calculate((int) g[u].get(0)); ans = temp.x; p = temp.n; temp = Calculate((int) g[u].get(1)); ans = ans.multiply(temp.x); q = temp.n; ans = ans.multiply(C[p + q][p]); temp.x = ans; temp.n = p + q + 1; return temp; }
public List<X> getNextCombination() { List<X> result = new ArrayList<X>(); Iterator<Pair> currentCombinationIterator = this.getCurrentCombination().iterator(); Iterator<List<X>> uncombinedListIterator = this.listOfLists.iterator(); while (currentCombinationIterator.hasNext() && uncombinedListIterator.hasNext()) { Pair currentPair = currentCombinationIterator.next(); List<X> currentSublist = uncombinedListIterator.next(); result.add(currentSublist.get(currentPair.getCurrentValue() - 1)); } int overflow = 1; Iterator<Pair> iter = this.getCurrentCombination().iterator(); while (iter.hasNext()) { Pair currentPair = iter.next(); if ((currentPair.getCurrentValue() + overflow) > currentPair.getMaxValue()) { overflow = (currentPair.getCurrentValue() + overflow) - currentPair.getMaxValue(); currentPair.setCurrentValue(1); } else { currentPair.setCurrentValue(currentPair.getCurrentValue() + 1); overflow = 0; break; } } if (overflow != 0) { this.setHasMoreCombinations(false); } return result; }
/** the drawing method displays 0/1 values by dedicated colors */ protected void drawMatrixEntry(PrintWriter out, Pair xy, FullDomain list, FullDomain removed) { out.println("<!-- index " + xy.getX() + " " + xy.getY() + " domain " + list + " -->"); unitSquareSVG(out, posX(xy), posY(xy), booleanColor(list, removed)); if (list.isFixed()) { textSVG(out, posX(xy), posY(xy), list.getIntValue(), Colors.ASSIGNED_TEXT_COLOR); } }
public Value match(Value str) { PatternMatcher matcher = getMatcher(); // Do the matching PatternMatcherInput jStr = new PatternMatcherInput(string(str)); Pair result = null; Pair prev = null; boolean found = false; while (matcher.contains(jStr, pattern)) { found = true; MatchResult matchResult = matcher.getMatch(); for (int i = 0, length = matchResult.groups(); i < length; i++) { Pair m = new Pair(new SchemeString(matchResult.group(i)), EMPTYLIST); if (result == null) result = prev = m; else { prev.setCdr(m); prev = m; } } } if (!found) return FALSE; else return result; }
private boolean tryToReloadApplication() { try { final Application app = ApplicationManager.getApplication(); if (app.isDisposed()) return false; final HashSet<Pair<VirtualFile, StateStorage>> causes = new HashSet<Pair<VirtualFile, StateStorage>>(myChangedApplicationFiles); if (causes.isEmpty()) return true; final boolean[] reloadOk = {false}; final LinkedHashSet<String> components = new LinkedHashSet<String>(); ApplicationManager.getApplication() .runWriteAction( new Runnable() { @Override public void run() { try { reloadOk[0] = ((ApplicationImpl) app).getStateStore().reload(causes, components); } catch (StateStorageException e) { Messages.showWarningDialog( ProjectBundle.message("project.reload.failed", e.getMessage()), ProjectBundle.message("project.reload.failed.title")); } catch (IOException e) { Messages.showWarningDialog( ProjectBundle.message("project.reload.failed", e.getMessage()), ProjectBundle.message("project.reload.failed.title")); } } }); if (!reloadOk[0] && !components.isEmpty()) { String message = "Application components were changed externally and cannot be reloaded:\n"; for (String component : components) { message += component + "\n"; } final boolean canRestart = ApplicationManager.getApplication().isRestartCapable(); message += "Would you like to " + (canRestart ? "restart " : "shutdown "); message += ApplicationNamesInfo.getInstance().getProductName() + "?"; if (Messages.showYesNoDialog( message, "Application Configuration Reload", Messages.getQuestionIcon()) == Messages.YES) { for (Pair<VirtualFile, StateStorage> cause : causes) { StateStorage stateStorage = cause.getSecond(); if (stateStorage instanceof XmlElementStorage) { ((XmlElementStorage) stateStorage).disableSaving(); } } ApplicationManagerEx.getApplicationEx().restart(true); } } return reloadOk[0]; } finally { myChangedApplicationFiles.clear(); } }
public String render(String renderId, Map<String, Object> httpParams) { Pair<Script, Template> pair = renders.get(renderId); if (pair == null) { pair = new Pair<Script, Template>(); Map<String, Object> map = rentationDAO.getRentation(renderId); if (map == null) { return "the render does not exist"; } if (map.get("js") != null) { try { Script script = scriptExecService.compile((String) map.get("js"), renderId); pair.setJs(script); } catch (Exception e) { throw new HttpStatusExceptionImpl(433, e.getMessage()); } } if (map.get("ftl") != null) {} renders.put(renderId, pair); } Object wsresult; if (pair.getJs() != null) { wsresult = scriptExecService.executeScript(pair.getJs(), httpParams, false); httpParams.put("model", wsresult); } return renderId; }
@Override public void postPacket(StyxMessage message, ClientDetails target) { Pair pair = new Pair(); pair.mMessage = message; pair.mTransmitter = target; mQueue.offer(pair); }
public void run() { _isDone = false; _results = new FindResults(_searchText.length()); switch (_requestCode) { case ProgressSource.FIND: _results.foundOffset = FINDER.wrappedFind(_src, _searchText, _start, _isCaseSensitive, _isWholeWord); notifyComplete(_results); break; case ProgressSource.FIND_BACKWARDS: _results.foundOffset = FINDER.wrappedFindBackwards(_src, _searchText, _start, _isCaseSensitive, _isWholeWord); notifyComplete(_results); break; case ProgressSource.REPLACE_ALL: Pair replaceResult = FINDER.replaceAll( _src, _searchText, _replacementText, _start, _isCaseSensitive, _isWholeWord); _results.replacementCount = replaceResult.getFirst(); _results.newStartPosition = replaceResult.getSecond(); notifyComplete(_results); break; default: TextWarriorException.assertVerbose(false, "Invalid request code for FindThread"); break; } }
@Override public Condition[] multiple(Dataset dataset, Instance[] instances, int attribute, int target) { Pair[] candidates = new Pair[dataset.size()]; double[] frequency = new double[dataset.classLength()]; int index = 0; double size = 0; for (int i = 0; i < dataset.size(); i++) { // the dynamc discretisation only considers the instances covered // by the current rule if (instances[i].flag == RULE_COVERED) { double v = dataset.value(i, attribute); if (!Double.isNaN(v)) { Pair pair = new Pair(); pair.value = v; pair.classValue = (dataset.value(i, dataset.classIndex()) == target) ? 1 // positive (target) : 0; // negative pair.weight = instances[i].weight; candidates[index] = pair; size += pair.weight; index++; } } } if (index == 0) { // there are no candidate threshold values return null; } candidates = Arrays.copyOf(candidates, index); Arrays.sort(candidates); Condition[] conditions = create( candidates, 0, candidates.length, frequency, size, IntervalBuilder.minimumCases(dataset, size)); if (conditions == null) { // no interval was created return null; } else { for (Condition c : conditions) { c.attribute = attribute; } return conditions; } }
public static void main(String[] args) { Pair first = new Pair(2.4); Pair second = new Pair(2.5); System.out.println(second.pair(first)); System.out.println(first.equals(second)); }
/** * @name lookup * @about takes a key and finds its value * @param T1 key - the key whose value is sought * @return returns the value if found */ public T2 lookUp(T1 key) { for (Pair<T1, T2> p : keyValues) { if (p.equals(new Pair<T1, T2>(key))) return p.getValue(); } // -end for System.out.println("nothing found"); return null; } // --end method lookup
@Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Pair<?, ?>)) { return false; } Pair<?, ?> otherPair = (Pair<?, ?>) obj; return otherPair.getFirst().equals(e1) && otherPair.getSecond().equals(e2); }
@Override public Long getValue(final Pair<String, String> current_friend) { return DB.getHumanCrudWallLocal(false) .readWallId( new HumanId(current_friend.getValue()), new Obj<String>(current_friend.getKey())) .returnValueBadly(); }
private final void add(ListChangeIndex<T> change) { if (this.recordChanges()) this.changes.add(change); // must change bounded lists first, otherwise listeners couldn't access them for (final Pair<?> p : this.boundLists.values()) { p.apply(change); } for (final IClosure<? super ListChangeIndex<T>> l : this.listeners) l.executeChecked(change); }