Java Code Examples for java.util.HashSet#contains()
The following examples show how to use
java.util.HashSet#contains() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Dissector.java From TrakEM2 with GNU General Public License v3.0 | 6 votes |
/** Retain the data within the layer range, and through out all the rest. */ @Override synchronized public boolean crop(final List<Layer> range) { final HashSet<Long> lids = new HashSet<Long>(); for (final Layer l : range) { lids.add(l.getId()); } for (final Item item : al_items) { for (int i=0; i<item.n_points; i++) { if (!lids.contains(item.p_layer[i])) { item.remove(i); i--; } } } calculateBoundingBox(null); return true; }
Example 2
Source File: SynthesisChainResultHandlingMonitor.java From workcraft with MIT License | 6 votes |
private void setComponentsRenderStyle(final VisualCircuit visualCircuit, final RenderType renderType) { HashSet<String> mutexNames = new HashSet<>(); for (Mutex me: mutexes) { mutexNames.add(me.name); } for (final VisualFunctionComponent component: visualCircuit.getVisualFunctionComponents()) { if (mutexNames.contains(visualCircuit.getMathReference(component))) { component.setRenderType(RenderType.BOX); } else { component.setRenderType(renderType); } } // Redo layout as component shape may have changed. AbstractLayoutCommand layoutCommand = visualCircuit.getBestLayouter(); if (layoutCommand != null) { layoutCommand.layout(visualCircuit); } }
Example 3
Source File: Solution_021.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
public static void main(final String[] args) { HashSet<Integer> result = CollectionLiterals.<Integer>newHashSet(); final int max = 10000; IntegerRange _upTo = new IntegerRange(1, max); for (final Integer i : _upTo) { boolean _contains = result.contains(i); boolean _not = (!_contains); if (_not) { final Integer sumOfDivisors = Solution_021.sumOfDivisors((i).intValue()); if (((!Objects.equal(sumOfDivisors, i)) && ((sumOfDivisors).intValue() <= max))) { final Integer otherSumOfDivisors = Solution_021.sumOfDivisors((sumOfDivisors).intValue()); boolean _equals = Objects.equal(otherSumOfDivisors, i); if (_equals) { result.add(i); result.add(sumOfDivisors); } } } } final Function2<Integer, Integer, Integer> _function = (Integer i1, Integer i2) -> { return Integer.valueOf(((i1).intValue() + (i2).intValue())); }; InputOutput.<Integer>println(IterableExtensions.<Integer>reduce(result, _function)); }
Example 4
Source File: InstructionComparator.java From NOVA-Core with GNU Lesser General Public License v3.0 | 6 votes |
private static InsnListSection insnListMatchesL(InsnList haystack, InsnList needle, int start, HashSet<LabelNode> controlFlowLabels) { int h = start, n = 0; for (; h < haystack.size() && n < needle.size(); h++) { AbstractInsnNode insn = haystack.get(h); if (insn.getType() == 15) { continue; } if (insn.getType() == 8 && !controlFlowLabels.contains(insn)) { continue; } if (!insnEqual(haystack.get(h), needle.get(n))) { return null; } n++; } if (n != needle.size()) { return null; } return new InsnListSection(haystack, start, h - 1); }
Example 5
Source File: OpenTracingAdapter.java From java-specialagent with Apache License 2.0 | 6 votes |
/** * Returns the {@code JarFile} referencing the Trace Exporter by the given * {@code name} in the specified {@code ClassLoader}. * * @param classLoader The {@code ClassLoader} in which to find the Tracer * Plugin. * @param name The short name of the Trace Exporter. * @return The {@code URL} referencing the Trace Exporter by the given * {@code name} in the specified {@code ClassLoader}, or {@code null} * if one was not found. */ private static URL findTracer(final ClassLoader classLoader, final String name) throws IOException { final Enumeration<URL> enumeration = classLoader.getResources(TRACER_FACTORY); final HashSet<URL> urls = new HashSet<>(); while (enumeration.hasMoreElements()) { final URL url = enumeration.nextElement(); if (urls.contains(url)) continue; urls.add(url); if (logger.isLoggable(Level.FINEST)) logger.finest("Found " + TRACER_FACTORY + ": <" + AssembleUtil.getNameId(url) + ">" + url); final String jarPath = AssembleUtil.getSourceLocation(url, TRACER_FACTORY).getPath(); final String fileName = AssembleUtil.getName(jarPath); final String tracerName = fileName.substring(0, fileName.lastIndexOf('.')); if (name.equals(tracerName)) return new URL("file", null, jarPath); } return null; }
Example 6
Source File: EndNode.java From iBioSim with Apache License 2.0 | 6 votes |
public static List<DecomposedGraphNode> getMatchingEndNodes(DecomposedGraphNode specNode, DecomposedGraphNode libNode) { List<DecomposedGraphNode> endNodes = new ArrayList<>(); Queue<EndNode> queue = new LinkedList<>(); HashSet<DecomposedGraphNode> visited = new HashSet<>(); queue.add(new EndNode(specNode, libNode)); while(!queue.isEmpty()) { EndNode node = queue.poll(); if(node.libNode.getChildrenNodeList().size() == 0) { endNodes.add(node.specNode); } else { for(int i=0; i<node.libNode.getChildrenNodeList().size(); i++) { if(!visited.contains(node.specNode.getChildrenNodeList().get(i))) { visited.add(node.specNode.getChildrenNodeList().get(i)); queue.add(new EndNode(node.specNode.getChildrenNodeList().get(i), node.libNode.getChildrenNodeList().get(i))); } } } } return endNodes; }
Example 7
Source File: JobSubmissionTaskHandler.java From swift-k with Apache License 2.0 | 5 votes |
private void setOtherAttributes(JobSpecification spec, RslNode rsl) throws IllegalSpecException { HashSet<String> RSLAttributes = new HashSet<String>( Arrays.asList("directory", "executable", "arguments", "stdin", "stdout", "stderr", "count", "environment", "maxtime", "maxwalltime", "maxcputime", "jobtype", "grammyjob", "queue", "project", "hostcount", "dryrun", "minmemory", "maxmemory", "save_state", "two_phase", "restart", "stdout_position", "stderr_position", "remote_io_url") ); for (String key : spec.getAttributeNames()) { try { String value = String.valueOf(spec.getAttribute(key)); if (key.equals("condor_requirements")) { continue; } if (key.equalsIgnoreCase("maxwalltime")) { value = WallTime.normalize(value, jobManager); } if(RSLAttributes.contains(key.toLowerCase())) { rsl.add(new NameOpValue(key, NameOpValue.EQ, value)); } } catch (Exception e) { throw new IllegalSpecException( "Cannot parse the user defined attributes", e); } } }
Example 8
Source File: EdgeDefinitionConfigurationHelper.java From datawave with Apache License 2.0 | 5 votes |
private boolean validateEdgeNode(EdgeNode node, HashSet<String> edgeRelationships, HashSet<String> collectionType) { if (edgeRelationships.contains(node.getRelationship()) && collectionType.contains(node.getCollection())) { return true; } else { log.error("Edge Definition in config file does not have a matching edge relationship and collection type for Relationship: " + node.getRelationship() + " and Collection: " + node.getCollection()); return false; } }
Example 9
Source File: CacheWriterClient.java From cache2k with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override public Map<K, V> onInvoke(ObjectInputStream ois, ObjectOutputStream oos) throws IOException, ClassNotFoundException { // send the entries to write for (Cache.Entry<? extends K, ? extends V> entry : entries) { oos.writeObject(entry.getKey()); oos.writeObject(entry.getValue()); } oos.writeObject(null); Object o = ois.readObject(); if (o instanceof RuntimeException) { // Partial Success processsing, read in keys that failed to be written HashSet<K> failedToWriteKeys = new HashSet<>(); K key = (K) ois.readObject(); while (key != null) { failedToWriteKeys.add(key); key = (K) ois.readObject(); } Iterator<Cache.Entry<? extends K, ? extends V>> iter = entries.iterator(); while (iter.hasNext()) { if (!failedToWriteKeys.contains(iter.next().getKey())) { iter.remove(); } } throw(RuntimeException) o; } else { entries.clear(); return null; } }
Example 10
Source File: Editor.java From Rel with Apache License 2.0 | 5 votes |
private String getKeySelectionExpression(int rownum) { HashSet<String> key; if (keys.size() == 0) { key = new HashSet<String>(); for (int column = 0; column < heading.length; column++) key.add(heading[column].getName()); } else key = keys.get(0); Row originalValues = rows.get(rownum); String keyspec = ""; for (int column = 0; column < heading.length; column++) { String attributeName = heading[column].getName(); if (key.contains(attributeName)) { if (keyspec.length() > 0) keyspec += " AND "; String attributeType = heading[column].getType().toString(); Object attributeValueRaw = originalValues.getOriginalColumnValue(column); String attributeValue = ""; if (attributeValueRaw != null) attributeValue = attributeValueRaw.toString(); if (attributeType.equals("CHARACTER")) attributeValue = "'" + StringUtils.quote(attributeValue) + "'"; keyspec += attributeName + " = " + attributeValue; } } return keyspec; }
Example 11
Source File: XMLServerLoader.java From heisenberg with Apache License 2.0 | 5 votes |
private void loadQuarantine(Element root) { NodeList list = root.getElementsByTagName("host"); for (int i = 0, n = list.getLength(); i < n; i++) { Node node = list.item(i); if (node instanceof Element) { Element e = (Element) node; String host = e.getAttribute("name").trim(); if (quarantine.getHosts().containsKey(host)) { throw new ConfigException("host duplicated : " + host); } Map<String, Object> props = ConfigUtil.loadElements(e); String[] users = SplitUtil.split((String) props.get("user"), ',', true); HashSet<String> set = new HashSet<String>(); if (null != users) { for (String user : users) { UserConfig uc = this.users.get(user); if (null == uc) { throw new ConfigException("[user: " + user + "] doesn't exist in [host: " + host + "]"); } if (null == uc.getSchemas() || uc.getSchemas().size() == 0) { throw new ConfigException("[host: " + host + "] contains one root privileges user: " + user); } if (set.contains(user)) { throw new ConfigException("[host: " + host + "] contains duplicate user: " + user); } else { set.add(user); } } } quarantine.getHosts().put(host, set); } } }
Example 12
Source File: SectorRefactor.java From ramus with GNU General Public License v3.0 | 5 votes |
/** * Додає в масив сектори відображення, які пов’язані між собою одним потоком * і знаходяться на одному функціональному блоці. * * @param sector - сектор, для якого будуть знайдені пов’язані. * @param v Вектор в який будуть додані сектори відображення. */ public void getStreamedSectors(final PaintSector sector, final HashSet v) { getStreamedSectors(sector.getSector(), sector.getStart(), v, true); getStreamedSectors(sector.getSector(), sector.getEnd(), v, true); if (!v.contains(sector)) v.add(sector); }
Example 13
Source File: MysqlSlave.java From antsdb with GNU Lesser General Public License v3.0 | 5 votes |
private Parameters toParameters(TableMeta meta, Row row) { List<Column> columns = row.getColumns(); Object[] pureValues; PrimaryKeyMeta keyMeta = meta.getPrimaryKey(); if (keyMeta!=null) { List<ColumnMeta> primaryKeys = keyMeta.getColumns(meta); HashSet<Integer> pkNum = new HashSet<>(); for (ColumnMeta key: primaryKeys) { pkNum.add(key.getColumnId()); } pureValues = new Object[pkNum.size()]; for (int i=0; i<columns.size(); i++) { // col id starts with 1 if (pkNum.contains(i+1)) { pureValues[i] = toParameter(columns.get(i)); } } } else { pureValues = new Object[columns.size()]; for (int i=0; i<columns.size(); i++) { pureValues[i] = toParameter(columns.get(i)); } } return new Parameters(pureValues); }
Example 14
Source File: RMContainerAllocator.java From hadoop with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private void handleUpdatedNodes(AllocateResponse response) { // send event to the job about on updated nodes List<NodeReport> updatedNodes = response.getUpdatedNodes(); if (!updatedNodes.isEmpty()) { // send event to the job to act upon completed tasks eventHandler.handle(new JobUpdatedNodesEvent(getJob().getID(), updatedNodes)); // act upon running tasks HashSet<NodeId> unusableNodes = new HashSet<NodeId>(); for (NodeReport nr : updatedNodes) { NodeState nodeState = nr.getNodeState(); if (nodeState.isUnusable()) { unusableNodes.add(nr.getNodeId()); } } for (int i = 0; i < 2; ++i) { HashMap<TaskAttemptId, Container> taskSet = i == 0 ? assignedRequests.maps : assignedRequests.reduces; // kill running containers for (Map.Entry<TaskAttemptId, Container> entry : taskSet.entrySet()) { TaskAttemptId tid = entry.getKey(); NodeId taskAttemptNodeId = entry.getValue().getNodeId(); if (unusableNodes.contains(taskAttemptNodeId)) { LOG.info("Killing taskAttempt:" + tid + " because it is running on unusable node:" + taskAttemptNodeId); eventHandler.handle(new TaskAttemptKillEvent(tid, "TaskAttempt killed because it ran on unusable node" + taskAttemptNodeId)); } } } } }
Example 15
Source File: LevelDBToMCAFile.java From FastAsyncWorldedit with GNU General Public License v3.0 | 4 votes |
public static void copyLevelDat(File folderTo, File in) throws IOException { File levelDat = new File(folderTo, "level.dat"); if (!levelDat.exists()) { folderTo.mkdirs(); levelDat.createNewFile(); } try (LittleEndianDataInputStream ledis = new LittleEndianDataInputStream(new FileInputStream(in))) { int version = ledis.readInt(); // Ignored int length = ledis.readInt(); // Ignored NBTInputStream nis = new NBTInputStream((DataInput) ledis); NamedTag named = nis.readNamedTag(); com.sk89q.jnbt.CompoundTag tag = (CompoundTag) named.getTag(); Map<String, com.sk89q.jnbt.Tag> map = ReflectionUtils.getMap(tag.getValue()); Map<String, String> gameRules = new HashMap<>(); gameRules.put("firedamage", "firedamage"); gameRules.put("falldamage", "falldamage"); gameRules.put("dofiretick", "doFireTick"); gameRules.put("drowningdamage", "drowningdamage"); gameRules.put("doentitydrops", "doEntityDrops"); gameRules.put("keepinventory", "keepInventory"); gameRules.put("sendcommandfeedback", "sendCommandFeedback"); gameRules.put("dodaylightcycle", "doDaylightCycle"); gameRules.put("commandblockoutput", "commandBlockOutput"); gameRules.put("domobloot", "doMobLoot"); gameRules.put("domobspawning", "doMobSpawning"); gameRules.put("doweathercycle", "doWeatherCycle"); gameRules.put("mobgriefing", "mobGriefing"); gameRules.put("dotiledrops", "doTileDrops"); HashMap<String, com.sk89q.jnbt.Tag> ruleTagValue = new HashMap<>(); for (Map.Entry<String, String> rule : gameRules.entrySet()) { com.sk89q.jnbt.Tag value = map.remove(rule.getKey()); if (value instanceof ByteTag) { value = new StringTag((Byte) value.getValue() == 1 ? "true" : "false"); } if (value != null) { ruleTagValue.put(rule.getValue(), value); } } HashSet<String> allowed = new HashSet<>(Arrays.asList( "lightningTime", "pvp", "LevelName", "Difficulty", "GameType", "Generator", "LastPlayed", "RandomSeed", "StorageVersion", "Time", "commandsEnabled", "currentTick", "rainTime", "SpawnX", "SpawnY", "SpawnZ", "SizeOnDisk" )); Iterator<Map.Entry<String, com.sk89q.jnbt.Tag>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, com.sk89q.jnbt.Tag> entry = iterator.next(); if (!allowed.contains(entry.getKey())) { iterator.remove(); } } { map.put("GameRules", new CompoundTag(ruleTagValue)); map.put("version", new IntTag(19133)); map.put("DataVersion", new IntTag(1343)); map.put("initialized", new ByteTag((byte) 1)); map.putIfAbsent("SizeOnDisk", new LongTag(0)); // generator int generator = tag.getInt("Generator"); String name; switch (generator) { default: case 1: name = "default"; break; case 2: name = "flat"; break; } map.put("generatorName", new StringTag(name)); map.put("generatorOptions", new StringTag("")); map.put("generatorVersion", new IntTag(1)); map.put("Difficulty", new ByteTag((byte) tag.getInt("Difficulty"))); map.put("DifficultyLocked", new ByteTag((byte) 0)); map.put("MapFeatures", new ByteTag((byte) 1)); map.put("allowCommands", new ByteTag(tag.getByte("commandsEnabled"))); long time = tag.getLong("Time"); if (time == 0) time = tag.getLong("CurrentTick"); map.put("Time", new LongTag(time)); map.put("spawnMobs", new ByteTag((byte) 1)); Long lastPlayed = tag.getLong("LastPlayed"); if (lastPlayed != null && lastPlayed < Integer.MAX_VALUE) { lastPlayed = lastPlayed * 1000; map.put("LastPlayed", new LongTag(lastPlayed)); } HashMap<String, com.sk89q.jnbt.Tag> data = new HashMap<>(); data.put("Data", new CompoundTag(map)); CompoundTag root = new CompoundTag(data); try (NBTOutputStream nos = new NBTOutputStream(new PGZIPOutputStream(new FileOutputStream(levelDat)))) { nos.writeNamedTag("level.dat", root); } } } }
Example 16
Source File: TestEQTLDatasetForInteractions.java From systemsgenetics with GNU General Public License v3.0 | 4 votes |
private void correctDosageDirectionForQtl(File snpsToSwapFile, ExpressionDataset datasetGenotypes, ExpressionDataset datasetExpression) throws IOException { //double[] mainEQTLCorr = new double[datasetGenotypes.nrProbes]; if (snpsToSwapFile != null) { System.out.println("Enforcing for every eQTL that the genotype dosage is swapped based on: " + snpsToSwapFile.getAbsolutePath()); HashSet<String> snpsToSwap = new HashSet<String>(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(snpsToSwapFile), "UTF-8")); String line; while ((line = reader.readLine()) != null) { snpsToSwap.add(line); } reader.close(); for (int snp = 0; snp < datasetGenotypes.nrProbes; snp++) { if (snpsToSwap.contains(datasetGenotypes.probeNames[snp])) { for (int s = 0; s < datasetGenotypes.nrSamples; s++) { datasetGenotypes.rawData[snp][s] = 2 - datasetGenotypes.rawData[snp][s]; } } //mainEQTLCorr[snp] = corr; } } else { System.out.println("Enforcing for every eQTL that the genotype dosage positively correlated with gene expression levels:"); Writer writer = new BufferedWriter(new FileWriter(outputDir + "/swappedDosages.txt")); for (int snp = 0; snp < datasetGenotypes.nrProbes; snp++) { double corr = JSci.maths.ArrayMath.correlation(datasetGenotypes.rawData[snp], datasetExpression.rawData[snp]); //System.out.println(datasetExpression.probeNames[snp] + "\t" + snp + "\t" + corr); if (corr < 0) { corr = -corr; for (int s = 0; s < datasetGenotypes.nrSamples; s++) { datasetGenotypes.rawData[snp][s] = 2 - datasetGenotypes.rawData[snp][s]; } writer.append(datasetGenotypes.probeNames[snp]); writer.append('\n'); } //mainEQTLCorr[snp] = corr; } writer.close(); } }
Example 17
Source File: XWindowPeer.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
private void lowerOverrideRedirect() { // // make new hash of toplevels of all windows from 'windows' hash. // FIXME: do not call them "toplevel" as it is misleading. // HashSet toplevels = new HashSet(); long topl = 0, mytopl = 0; for (XWindowPeer xp : windows) { topl = getToplevelWindow( xp.getWindow() ); if( xp.equals( this ) ) { mytopl = topl; } if( topl > 0 ) toplevels.add( Long.valueOf( topl ) ); } // // find in the root's tree: // (1) my toplevel, (2) lowest java toplevel, (3) desktop // We must enforce (3), (1), (2) order, upward; // note that nautilus on the next restacking will do (1),(3),(2). // long laux, wDesktop = -1, wBottom = -1; int iMy = -1, iDesktop = -1, iBottom = -1; int i = 0; XQueryTree xqt = new XQueryTree(XToolkit.getDefaultRootWindow()); try { if( xqt.execute() > 0 ) { int nchildren = xqt.get_nchildren(); long children = xqt.get_children(); for(i = 0; i < nchildren; i++) { laux = Native.getWindow(children, i); if( laux == mytopl ) { iMy = i; }else if( isDesktopWindow( laux ) ) { // we need topmost desktop of them all. iDesktop = i; wDesktop = laux; }else if(iBottom < 0 && toplevels.contains( Long.valueOf(laux) ) && laux != mytopl) { iBottom = i; wBottom = laux; } } } if( (iMy < iBottom || iBottom < 0 )&& iDesktop < iMy) return; // no action necessary long to_restack = Native.allocateLongArray(2); Native.putLong(to_restack, 0, wBottom); Native.putLong(to_restack, 1, mytopl); XlibWrapper.XRestackWindows(XToolkit.getDisplay(), to_restack, 2); XlibWrapper.unsafe.freeMemory(to_restack); if( !mustControlStackPosition ) { mustControlStackPosition = true; // add root window property listener: // somebody (eg nautilus desktop) may obscure us addRootPropertyEventDispatcher(); } } finally { xqt.dispose(); } }
Example 18
Source File: BDDAlgebraLearner.java From symbolicautomata with Apache License 2.0 | 4 votes |
public List <Boolean> verifySFAisBDD(SFA <HashSet <Boolean>, Boolean> sfa, BinaryBooleanAlgebra ba) throws TimeoutException { /* Verify that SFA computation graph is a tree */ HashSet <Integer> visited = new HashSet<>(); List <List<Boolean>> paths = new LinkedList <>(); List <Boolean> curPath, errorPath = null; List <Integer> stack = new LinkedList <>(); Integer curState, errorState=0; // Assumes that unreachable and dead states are removed; if (sfa.stateCount() <= 1) { return null; } if (sfa.getFinalStates().size() > 1) { throw new AssertionError("More than one final state, this shouldn't happen"); } if ((errorPath = hasSmallAccepting(sfa, ba)) != null) { return errorPath; } if ((errorPath = hasLargeAccepting(sfa, ba)) != null) { return errorPath; } stack.add(sfa.getInitialState()); paths.add(new LinkedList <Boolean>()); while (stack.size() > 0) { curState = stack.remove(0); curPath = paths.remove(0); visited.add(curState); for (SFAMove <HashSet<Boolean>, Boolean> t : sfa.getInputMovesFrom(curState)) { if (visited.contains(t.to) && !sfa.getFinalStates().contains(t.to)) { errorState = t.to; errorPath = curPath; errorPath.add(t.getWitness(ba)); break; } stack.add(t.to); curPath.add(t.getWitness(ba)); paths.add(new LinkedList <Boolean>(curPath)); curPath.remove(curPath.size()-1); } if (errorPath != null) { break; } } if (errorPath != null) { errorPath.addAll(generateWitness(sfa, ba, errorState)); return errorPath; } return null; }
Example 19
Source File: 10150 Doublets.java From UVA with GNU General Public License v3.0 | 4 votes |
public static void main (String [] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s; HashSet<String> dictionary=new HashSet<>(); HashMap<String, char []> dictionaryChars=new HashMap<>(); while ((s=br.readLine()).length()>0) { dictionary.add(s); dictionaryChars.put(s,s.toCharArray()); } boolean isFirst=true; while ((s=br.readLine())!=null) { if (s.trim().length()==0) break; StringTokenizer st=new StringTokenizer(s); String start=st.nextToken(); String end=st.nextToken(); Edge solution=null; if (dictionary.contains(start) && dictionary.contains(end) && start.length()==end.length()) { HashSet<String> visited=new HashSet<>(); LinkedList<Edge> queue=new LinkedList<>(); queue.add(new Edge(null, start)); visited.add(start); while (!queue.isEmpty()) { Edge e=queue.removeFirst(); if (e.dest.equals(end)) { solution = e; break; } //For the given test data, this is faster than iterating through all the words (TLE) / precomputing the edges (~90% slower). char [] tempChars=Arrays.copyOf(dictionaryChars.get(e.dest), dictionaryChars.get(e.dest).length); for (int i=0;i<tempChars.length;i++) { for (int i2=0;i2<26;i2++) { tempChars[i]=(char)((((tempChars[i]-'a')+1)%26)+'a'); String next=new String(tempChars); if (dictionary.contains(next) && !visited.contains(next)) { visited.add(next); queue.addLast(new Edge(e, next)); } } } } } if (!isFirst) System.out.println(); else isFirst=false; if (solution==null) System.out.println("No solution."); else { LinkedList<String> stk=new LinkedList<>(); while (solution!=null) { stk.addFirst(solution.dest); solution=solution.prev; } StringBuilder sb=new StringBuilder(); for (String word : stk) { sb.append(word); sb.append('\n'); } System.out.print(sb.toString()); } } }
Example 20
Source File: DiseaseGeneHpoData.java From systemsgenetics with GNU General Public License v3.0 | 4 votes |
public DiseaseGeneHpoData(final File diseaseGeneHpoFile, HashMap<String, ArrayList<String>> ncbiToEnsgMap, HashMap<String, ArrayList<String>> hgncToEnsgMap, HashSet<String> exludedHpo, HashSet<String> includeGenes, String diseasePrefix) throws FileNotFoundException, IOException { geneToHpos = new HashMap<>(); diseaseToGenes = new HashMap<>(); diseaseGeneToHpos = new HashMap<>(); Predicate<String> diseasePattern; if(diseasePrefix != null){ diseasePattern = Pattern.compile("^" + diseasePrefix).asPredicate(); } else { diseasePattern = null; } final CSVParser hpoParser = new CSVParserBuilder().withSeparator('\t').withIgnoreQuotations(true).build(); final CSVReader hpoReader = new CSVReaderBuilder(new BufferedReader(new FileReader(diseaseGeneHpoFile))).withSkipLines(1).withCSVParser(hpoParser).build(); String[] nextLine; while ((nextLine = hpoReader.readNext()) != null) { String disease = nextLine[0]; String hgcnId = nextLine[1]; String ncbiId = nextLine[2]; String hpo = nextLine[3]; if(diseasePattern != null && !diseasePattern.test(disease)){ continue; } if (exludedHpo != null && exludedHpo.contains(hpo)) { continue; } ArrayList<String> ensgIds = ncbiToEnsgMap.get(ncbiId); if (ensgIds == null) { ensgIds = hgncToEnsgMap.get(hgcnId); } if (ensgIds == null) { System.err.println("Missing mapping for gene: " + ncbiId + " " + hgcnId); } else if (ensgIds.size() > 1) { System.err.println("Skipping becasue multiple ENSG IDs for gene: " + ncbiId + " " + hgcnId); } else if (!includeGenes.contains(ensgIds.get(0))) { System.err.println("Skipping becasue gene not in include list: " + ncbiId + " " + hgcnId); } else { String ensgId = ensgIds.get(0); HashSet<String> geneHpos = geneToHpos.get(ensgId); if (geneHpos == null) { geneHpos = new HashSet<>(); geneToHpos.put(ensgId, geneHpos); } geneHpos.add(hpo); HashSet<String> diseaseGenes = diseaseToGenes.get(disease); if (diseaseGenes == null) { diseaseGenes = new HashSet<>(); diseaseToGenes.put(disease, diseaseGenes); } diseaseGenes.add(ensgId); DiseaseGene diseaseGene = new DiseaseGene(disease, ensgId); HashSet<String> diseaseGeneHpos = diseaseGeneToHpos.get(diseaseGene); if (diseaseGeneHpos == null) { diseaseGeneHpos = new HashSet<>(); diseaseGeneToHpos.put(diseaseGene, diseaseGeneHpos); } diseaseGeneHpos.add(hpo); } } }