@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); }
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(); } }
@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); }
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; }
@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 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; }
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; }
/** Get the names of parameters - one ocurrence */ public List<String> names() { List<String> names = new ArrayList<>(); for (Pair pair : paramList) { String s = pair.getName(); if (names.contains(s)) continue; names.add(s); } return names; }
public void remove(String name) { // Absolute record for (Iterator<Pair> iter = paramList.iterator(); iter.hasNext(); ) { Pair p = iter.next(); if (p.getName().equals(name)) iter.remove(); } // Map params.remove(name); }
public int getAlignedTarget(int sourcePosition) { for (Pair<Integer, Integer> alignment : sureAlignments) { if (alignment.getSecond() == sourcePosition) { return alignment.getFirst(); } } System.err.println("nothing aligned with " + sourcePosition); return -999; }
public Set<Integer> getAlignedSources(int targetPosition) { Set<Integer> sources = new HashSet<Integer>(); for (Pair<Integer, Integer> alignment : sureAlignments) { if (alignment.getFirst() == targetPosition) { sources.add(alignment.getSecond()); } } return sources; }
public Pair decode() { Pair ret; if (cursor < output.size()) { ret = (Pair) output.get(cursor++); ret.setValid(true); } else { ret = new Pair(0, 'a', false); } return ret; }
@Test(expected = TransformException.class) public void verifyBad() throws RuleBaseException, TransformException { SortByValueBlock block = define("<sort by='ascending'>@name</sort>"); SortByValueBlock.SortByValueSeg seg = (SortByValueBlock.SortByValueSeg) block.createSeg(mod); setModData( "(<sort-value refid='m1'>start</sort-value>, <sort-value refid='m2'>foo</sort-value>)"); seg.values = new ArrayList<Pair<String, Item>>(); seg.values.add(Pair.of("m1", content.query().single("/id('m1')/@name").toAtomicItem())); seg.values.add(Pair.of("m2", content.query().single("/id('m2')/@name").toAtomicItem())); seg.verify(); }
public static void main(String[] args) { GregorianCalendar[] birthdays = { new GregorianCalendar(1906, Calendar.DECEMBER, 9), // G.Hopper new GregorianCalendar(1815, Calendar.DECEMBER, 10), // A.Lovelace new GregorianCalendar(1903, Calendar.DECEMBER, 3), // J.von Neumann new GregorianCalendar(1910, Calendar.JUNE, 22), // K.Zuse }; Pair<GregorianCalendar> mm = ArrayAlg.minmax(birthdays); System.out.println("min = " + mm.getFirst().getTime()); System.out.println("max = " + mm.getSecond().getTime()); }
@NotNull private static <T extends PsiMember> List<T> getAllByMap( @NotNull PsiClass aClass, @NotNull MemberType type) { List<Pair<T, PsiSubstitutor>> pairs = getAllWithSubstitutorsByMap(aClass, type); final List<T> ret = new ArrayList<T>(pairs.size()); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < pairs.size(); i++) { Pair<T, PsiSubstitutor> pair = pairs.get(i); T t = pair.getFirst(); LOG.assertTrue(t != null, aClass); ret.add(t); } return ret; }
private boolean handleBackspace(String filter) { boolean clicked = false; final Iterator<Pair<String, JCheckBox>> iterator = myTriggeredCheckboxes.iterator(); while (iterator.hasNext()) { final Pair<String, JCheckBox> next = iterator.next(); if (next.getFirst().length() < filter.length()) break; if (next.getFirst().length() >= filter.length()) { iterator.remove(); next.getSecond().doClick(); clicked = true; } } return clicked; }
private Pair<AbstractUrl, String> createPairForNode(AbstractTreeNode node) { final String className = node.getClass().getName(); final Object value = node.getValue(); final AbstractUrl url = createUrlByElement(value, myProject); if (url == null) return null; return Pair.create(url, className); }
/** * Get Result String * * @return result string */ public String printComparableResults(boolean newline) { if (!(resultVector != null)) log.error("Attempted to access null vector."); String outString = ""; int i = 0; for (TypeQ question : sortedQuestions) { Double tempResult = resultVector.get(i); // if(tempResult.intValue() == 0) // continue; if (groundTruthVector != null) { Double evalInd = groundTruthVector.getSecond().get(i); if (evalInd.intValue() == 0) { ++i; continue; } } ++i; if (!newline) outString += "\n"; outString += question + " " + tempResult.intValue(); newline = false; } if (log.isDebugEnabled()) { log.debug(outString); } return outString; }
@NotNull private VirtualFilePointer create( @Nullable("null means the pointer will be created from the (not null) url") VirtualFile file, @Nullable("null means url has to be computed from the (not-null) file path") String url, @NotNull Disposable parentDisposable, @Nullable VirtualFilePointerListener listener) { VirtualFileSystem fileSystem; String protocol; String path; if (file == null) { int protocolEnd = url.indexOf(URLUtil.SCHEME_SEPARATOR); if (protocolEnd == -1) { protocol = null; fileSystem = null; } else { protocol = url.substring(0, protocolEnd); fileSystem = myVirtualFileManager.getFileSystem(protocol); } path = url.substring(protocolEnd + URLUtil.SCHEME_SEPARATOR.length()); } else { fileSystem = file.getFileSystem(); protocol = fileSystem.getProtocol(); path = file.getPath(); url = VirtualFileManager.constructUrl(protocol, path); } if (fileSystem == TEMP_FILE_SYSTEM) { // for tests, recreate always VirtualFile found = file == null ? VirtualFileManager.getInstance().findFileByUrl(url) : file; return new IdentityVirtualFilePointer(found, url); } boolean isJar = fileSystem == JAR_FILE_SYSTEM; if (fileSystem != LOCAL_FILE_SYSTEM && !isJar) { // we are unable to track alien file systems for now VirtualFile found = fileSystem == null ? null : file != null ? file : VirtualFileManager.getInstance().findFileByUrl(url); // if file is null, this pointer will never be alive return getOrCreateIdentity(url, found); } if (file == null) { String cleanPath = cleanupPath(path, isJar); // if newly created path is the same as substringed from url one then the url did not change, // we can reuse it //noinspection StringEquality if (cleanPath != path) { url = VirtualFileManager.constructUrl(protocol, cleanPath); path = cleanPath; } } // else url has come from VirtualFile.getPath() and is good enough VirtualFilePointerImpl pointer = getOrCreate(parentDisposable, listener, path, Pair.create(file, url)); DelegatingDisposable.registerDisposable(parentDisposable, pointer); return pointer; }
private static void addScopesToList( final List<Pair<NamedScope, NamedScopesHolder>> scopeList, final NamedScopesHolder holder) { NamedScope[] scopes = holder.getScopes(); for (NamedScope scope : scopes) { scopeList.add(Pair.create(scope, holder)); } }
@NotNull private static Map<String, List<Pair<PsiMember, PsiSubstitutor>>> generateMapByList( @NotNull final List<Pair<PsiMember, PsiSubstitutor>> list) { Map<String, List<Pair<PsiMember, PsiSubstitutor>>> map = new THashMap<String, List<Pair<PsiMember, PsiSubstitutor>>>(); map.put(ALL, list); for (final Pair<PsiMember, PsiSubstitutor> info : list) { PsiMember element = info.getFirst(); String currentName = element.getName(); List<Pair<PsiMember, PsiSubstitutor>> listByName = map.get(currentName); if (listByName == null) { listByName = new ArrayList<Pair<PsiMember, PsiSubstitutor>>(1); map.put(currentName, listByName); } listByName.add(info); } return map; }
@Override public void restore() throws TransformException { List<Node> references = mod.references(); ItemList targets = mod.nearest(NodeTarget.class).targets(); proxies = new ArrayList<Pair<String, Node>>(references.size()); for (int i = 0; i < references.size(); i++) { proxies.add(Pair.of(targets.get(i).query().single("@xml:id").value(), references.get(i))); } }
@Test public void sortDescending() throws RuleBaseException { SortByValueBlock block = define("<sort by='descending'>@name</sort>"); SortByValueBlock.SortByValueSeg seg1 = (SortByValueBlock.SortByValueSeg) block.createSeg(mod); SortByValueBlock.SortByValueSeg seg2 = (SortByValueBlock.SortByValueSeg) block.createSeg(mod); seg1.values = new ArrayList<Pair<String, Item>>(); seg1.values.add(Pair.of("m1", content.query().single("/id('m1')/@name").toAtomicItem())); seg2.values = new ArrayList<Pair<String, Item>>(); seg2.values.add(Pair.of("m2", content.query().single("/id('m2')/@name").toAtomicItem())); final OrderGraph graph = mockery.mock(OrderGraph.class); mockery.checking( new Expectations() { { one(graph).order("m1", "m2", 0); } }); block.sort(Arrays.asList(seg1, seg2), graph); }
@SuppressWarnings("unchecked") @Test(expected = TransformException.class) public void verifyMismatch() throws RuleBaseException, TransformException { Node uc1 = content.query().single("/id('uc1')").node(); Node comp1 = content.query().single("/id('comp1')").node(); Node comp2 = content.query().single("/id('comp2')").node(); Node cname = content.query().single("/id('cname')").node(); setModScope(uc1.query()); SortBySiblingBlock block = define("<sort before='sibling'>uml:name</sort>"); SortBySiblingBlock.SortBySiblingSeg seg = (SortBySiblingBlock.SortBySiblingSeg) block.createSeg(mod); seg.siblingsByTarget = Arrays.<Pair<Node, List<Node>>>asList( new Pair[] { Pair.of(comp1, Arrays.asList(comp2)), Pair.of(comp2, Arrays.asList(cname)) }); seg.verify(); }
static String isitpossible(int a, int b, int c, int d) { Pair source = new Pair(a, b); Pair dest = new Pair(c, d); list.add(source); while (!list.isEmpty()) { Pair pair = list.poll(); if (pair.getX() == dest.getX() && pair.getY() == dest.getY()) return "Yes"; else { int sum = pair.getX() + pair.getY(); if (sum <= Math.max(c, d)) { list.add(new Pair(sum, pair.getY())); list.add(new Pair(pair.getX(), sum)); } } } return "No"; }
@NotNull private Pair<Boolean, GroovyResolveResult[]> resolveByShape( final boolean allVariants, @Nullable final GrExpression upToArgument) { LOG.assertTrue(allVariants || upToArgument == null); final Trinity key = Trinity.create( TypeInferenceHelper.getCurrentContext(), this, Pair.create(allVariants, upToArgument)); final Pair<Boolean, GroovyResolveResult[]> result = RecursionManager.doPreventingRecursion( key, true, new Computable<Pair<Boolean, GroovyResolveResult[]>>() { @Override public Pair<Boolean, GroovyResolveResult[]> compute() { return doResolveByShape(allVariants, upToArgument); } }); return result == null ? Pair.create(false, GroovyResolveResult.EMPTY_ARRAY) : result; }
/* * This is somewhat of a hack, to change the position of the goal we * first save all of the non-empty nodes on the map, clear the map, move the * goal and add re-add all of the non-empty cells. Since most of these cells * are not between the start and goal this does not seem to hurt performance * too much. Also, it frees up a good deal of memory we are probably not * going to use. */ public void updateGoal(int x, int y) { List<Pair<ipoint2, Double>> toAdd = new ArrayList<Pair<ipoint2, Double>>(); Pair<ipoint2, Double> tempPoint; for (Map.Entry<State, CellInfo> entry : cellHash.entrySet()) { if (!close(entry.getValue().cost, C1)) { tempPoint = new Pair(new ipoint2(entry.getKey().x, entry.getKey().y), entry.getValue().cost); toAdd.add(tempPoint); } } cellHash.clear(); openHash.clear(); while (!openList.isEmpty()) openList.poll(); k_m = 0; s_goal.x = x; s_goal.y = y; CellInfo tmp = new CellInfo(); tmp.g = tmp.rhs = 0; tmp.cost = C1; cellHash.put(s_goal, tmp); tmp = new CellInfo(); tmp.g = tmp.rhs = heuristic(s_start, s_goal); tmp.cost = C1; cellHash.put(s_start, tmp); s_start = calculateKey(s_start); s_last = s_start; Iterator<Pair<ipoint2, Double>> iterator = toAdd.iterator(); while (iterator.hasNext()) { tempPoint = iterator.next(); updateCell(tempPoint.first().x, tempPoint.first().y, tempPoint.second()); } }
@Override public void setConf(org.apache.hadoop.conf.Configuration conf) { if (conf == null) return; // you first get a null configuration - ignore that String mos = conf.get(AvroJob.MAP_OUTPUT_SCHEMA); Schema schema = Schema.parse(mos); pair = new Pair<Object, Object>(schema); Schema keySchema = Pair.getKeySchema(schema); final List<Field> fields = keySchema.getFields(); final GenericRecord key = new GenericData.Record(keySchema); projector = new Projector(key, fields); }
private List<Object> getList(List<Pair<String, Object>> values, String tag) { for (Pair<String, Object> value : values) { if (value.left.equals(tag)) { //noinspection unchecked return (List<Object>) value.right; } } final List<Object> list = new ArrayList<Object>(); values.add(Pair.of(tag, (Object) list)); return list; }
/** * Resolves the component name in each of the couplings in the given set to its devs component, * and returns a new list of resolved such couplings. * * @param couplings The set of couplings, each containing an unresolved component name. * @param modelToSimMap A mapping of (names of) components to their simulators. * @param rootSim The root simulator (or coordinator) of the simulator making this call (if any). * @return A new list of couplings, corresponding to the given one, except each coupling contains * the actual destination component, rather than just that component's name. */ protected static List resolveCouplings( Set couplings, Function modelToSimMap, atomicSimulator rootSim) { // for each of the couplings to the source port List resolvedCouplings = new ArrayList(); Iterator i = couplings.iterator(); while (i.hasNext()) { Pair coupling = (Pair) i.next(); // resolve the destination component name to its actual component EntityInterface component = getComponentWithName((String) coupling.getKey(), modelToSimMap, rootSim); // package the destination component with the destination // port-name, and add the result to our list of resolved // couplings resolvedCouplings.add(new Pair(component, coupling.getValue())); } return resolvedCouplings; }