java.util.HashSet Java Examples

The following examples show how to use java.util.HashSet. 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: SearchEngine.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
public String[] listModules(String org) {
    Set<String> entries = new HashSet<>();

    Map<String, Object> tokenValues = new HashMap<>();
    tokenValues.put(IvyPatternHelper.ORGANISATION_KEY, org);

    for (DependencyResolver resolver : settings.getResolvers()) {
        Map<String, String>[] modules = resolver.listTokenValues(
            new String[] {IvyPatternHelper.MODULE_KEY}, tokenValues);
        for (Map<String, String> module : modules) {
            entries.add(module.get(IvyPatternHelper.MODULE_KEY));
        }
    }

    return entries.toArray(new String[entries.size()]);
}
 
Example #2
Source File: ProjectResourceTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void configuration(final WebTarget target) {
    final FactoryConfiguration config = target
            .path("project/configuration")
            .request(MediaType.APPLICATION_JSON_TYPE)
            .get(FactoryConfiguration.class);
    final String debug = config.toString();
    assertEquals(new HashSet<>(asList("Gradle", "Maven")), new HashSet<>(config.getBuildTypes()), debug);
    assertEquals(new HashMap<String, List<FactoryConfiguration.Facet>>() {

        {
            put("Test", singletonList(new FactoryConfiguration.Facet("Talend Component Kit Testing",
                    "Generates test(s) for each component.")));
            put("Runtime", singletonList(new FactoryConfiguration.Facet("Apache Beam",
                    "Generates some tests using beam runtime instead of Talend Component Kit Testing framework.")));
            put("Libraries", singletonList(new FactoryConfiguration.Facet("WADL Client Generation",
                    "Generates a HTTP client from a WADL.")));
            put("Tool",
                    asList(new FactoryConfiguration.Facet("Codenvy",
                            "Pre-configures the project to be usable with Codenvy."),
                            new FactoryConfiguration.Facet("Travis CI",
                                    "Creates a .travis.yml pre-configured for a component build.")));
        }
    }, new HashMap<>(config.getFacets()), debug);
}
 
Example #3
Source File: ArrivalBoundDispatch.java    From DNC with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static Set<ArrivalCurve> getPermutations(Set<ArrivalCurve> arrival_curves_1,
		Set<ArrivalCurve> arrival_curves_2) {
	if (arrival_curves_1.isEmpty()) {
		return new HashSet<ArrivalCurve>(arrival_curves_2);
	}
	if (arrival_curves_2.isEmpty()) {
		return new HashSet<ArrivalCurve>(arrival_curves_1);
	}

	Set<ArrivalCurve> arrival_bounds_merged = new HashSet<ArrivalCurve>();

	for (ArrivalCurve alpha_1 : arrival_curves_1) {
		for (ArrivalCurve alpha_2 : arrival_curves_2) {
			arrival_bounds_merged.add(Curve.getUtils().add(alpha_1, alpha_2));
		}
	}

	return arrival_bounds_merged;
}
 
Example #4
Source File: JumpI.java    From securify with Apache License 2.0 6 votes vote down vote up
private Set<Instruction> getAllReachableInstructions(Instruction start) {
	Set<Instruction> reachable = new HashSet<>();
	reachable.add(start);
	Queue<Instruction> bfs = new LinkedList<>();
	bfs.add(start);
	while (!bfs.isEmpty()) {
		Instruction i = bfs.poll();
		// add next instruction
		Instruction next = i.getNext();
		if (next != null && !reachable.contains(next)) {
			reachable.add(next);
			bfs.add(next);
		}
		// check for additional jump destinations
		if (i instanceof BranchInstruction && !(i instanceof _VirtualInstruction)) {
			((BranchInstruction)i).getOutgoingBranches().forEach(jdest -> {
				if (!reachable.contains(jdest)) {
					reachable.add(jdest);
					bfs.add(jdest);
				}
			});
		}
	}
	return reachable;
}
 
Example #5
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private GraphQLSchema generateGraphQLSchema() {
    GraphQLSchema.Builder schemaBuilder = GraphQLSchema.newSchema();

    createGraphQLEnumTypes();
    createGraphQLInterfaceTypes();
    createGraphQLObjectTypes();
    createGraphQLInputObjectTypes();

    addQueries(schemaBuilder);
    addMutations(schemaBuilder);

    schemaBuilder.additionalTypes(new HashSet<>(enumMap.values()));
    schemaBuilder.additionalTypes(new HashSet<>(interfaceMap.values()));
    schemaBuilder.additionalTypes(new HashSet<>(typeMap.values()));
    schemaBuilder.additionalTypes(new HashSet<>(inputMap.values()));

    codeRegistryBuilder.fieldVisibility(getGraphqlFieldVisibility());
    schemaBuilder = schemaBuilder.codeRegistry(codeRegistryBuilder.build());

    // register error info
    ErrorInfoMap.register(schema.getErrors());

    return schemaBuilder.build();
}
 
Example #6
Source File: ProgramParentUidsHelper.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static Set<String> getAssignedTrackedEntityAttributeUids(List<Program> programs, List<TrackedEntityType> types) {
    Set<String> attributeUids = new HashSet<>();

    for (Program program : programs) {
        List<ProgramTrackedEntityAttribute> attributes =
                ProgramInternalAccessor.accessProgramTrackedEntityAttributes(program);
        if (attributes != null) {
            for (ProgramTrackedEntityAttribute programAttribute : attributes) {
                attributeUids.add(programAttribute.trackedEntityAttribute().uid());
            }
        }
    }

    for (TrackedEntityType type : types) {
        if (type.trackedEntityTypeAttributes() != null) {
            for (TrackedEntityTypeAttribute attribute : type.trackedEntityTypeAttributes()) {
                attributeUids.add(attribute.trackedEntityAttribute().uid());
            }
        }
    }

    return attributeUids;
}
 
Example #7
Source File: PythonArchiveAnalyzer.java    From steady with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public Set<FileAnalyzer> getChilds(boolean _recursive) {
	final Set<FileAnalyzer> nested_fa = new HashSet<FileAnalyzer>();
	if(!_recursive) {
		nested_fa.addAll(this.nestedAnalyzers);
	}
	else {
		for(FileAnalyzer fa: this.nestedAnalyzers) {
			nested_fa.add(fa);
			final Set<FileAnalyzer> nfas = fa.getChilds(true);
			if(nfas!=null && !nfas.isEmpty())
				nested_fa.addAll(nfas);
		}
	}
	return nested_fa;
}
 
Example #8
Source File: SimpleUploadDataStoreTest.java    From RxUploader with Apache License 2.0 6 votes vote down vote up
@SuppressLint("ApplySharedPref")
@Test
public void testGetInvalidJobId() throws Exception {
    final Job test = createTestJob();
    final String json = gson.toJson(test);
    final String key = SimpleUploadDataStore.jobIdKey(test.id());
    final Set<String> keys = new HashSet<>();
    keys.add(key);

    final SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putStringSet(SimpleUploadDataStore.KEY_JOB_IDS, keys);
    editor.putString(key, json);
    editor.commit();

    final TestSubscriber<Job> ts = TestSubscriber.create();
    dataStore.get("bad_id").subscribe(ts);

    ts.awaitTerminalEvent(1, TimeUnit.SECONDS);
    ts.assertNoErrors();
    ts.assertValueCount(1);
    ts.assertValue(Job.INVALID_JOB);
}
 
Example #9
Source File: SitePermsService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * @return a list of all valid roles names
 */
public List<String> getValidRoles() {
    HashSet<String> roleIds = new HashSet<String>();
    for (String templateRef : getTemplateRoles()) {
        AuthzGroup ag;
        try {
            ag = authzGroupService.getAuthzGroup(templateRef);
            Set<Role> agRoles = ag.getRoles();
            for (Role role : agRoles) {
                roleIds.add(role.getId());
            }
        } catch (GroupNotDefinedException e) {
            // nothing to do here but continue really
        }
    }
    ArrayList<String> roles = new ArrayList<String>(roleIds);
    Collections.sort(roles);
    return roles;
}
 
Example #10
Source File: DataModelDesc.java    From kylin with Apache License 2.0 6 votes vote down vote up
private boolean validate() {

        // ensure no dup between dimensions/metrics
        for (ModelDimensionDesc dim : dimensions) {
            String table = dim.getTable();
            for (String c : dim.getColumns()) {
                TblColRef dcol = findColumn(table, c);
                metrics = ArrayUtils.removeElement(metrics, dcol.getIdentity());
            }
        }

        Set<TblColRef> mcols = new HashSet<>();
        for (String m : metrics) {
            mcols.add(findColumn(m));
        }

        // validate PK/FK are in dimensions
        boolean pkfkDimAmended = false;
        for (Chain chain : joinsTree.getTableChains().values()) {
            pkfkDimAmended = validatePkFkDim(chain.join, mcols) || pkfkDimAmended;
        }
        return pkfkDimAmended;
    }
 
Example #11
Source File: GeneralKnockout.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void checkCompletionDoesntContainHtmlItems(CompletionJListOperator jlist, String[] invalidList) {
    try {
        List items = jlist.getCompletionItems();
        HashSet<String> completion = new HashSet<>();
        for (Object item : items) {
            if (item instanceof HtmlCompletionItem) {
                completion.add(((HtmlCompletionItem) item).getItemText());
            } else {
                completion.add(item.toString());
            }
        }
            for (String sCode : invalidList) {
            if (completion.contains(sCode)) {
                fail("Completion list contains invalid item:" + sCode);
            }
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example #12
Source File: NodeSelection.java    From onos with Apache License 2.0 6 votes vote down vote up
private Set<String> findHosts(Set<String> ids) {
    Set<String> unmatched = new HashSet<>();
    Host host;

    for (String id : ids) {
        try {
            host = hostService.getHost(hostId(id));
            if (host != null) {
                hosts.add(host);
            } else {
                unmatched.add(id);
            }
        } catch (Exception e) {
            unmatched.add(id);
        }
    }
    return unmatched;
}
 
Example #13
Source File: Utils.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * A small implementation of UNIX find.
 * @param matchRegex Only collect paths that match this regex.
 * @param pruneRegex Don't recurse down a path that matches this regex. May be null.
 * @throws IOException if File.getCanonicalPath() fails.
 */
public static List<File> find(final File startpath, final String matchRegex, final String pruneRegex) throws IOException{
    final Pattern matchPattern = Pattern.compile(matchRegex, Pattern.CASE_INSENSITIVE);
    final Pattern prunePattern = pruneRegex == null ? null : Pattern.compile(pruneRegex, Pattern.CASE_INSENSITIVE);
    final Set<String> visited = new HashSet<String>();
    final List<File> found = new ArrayList<File>();
    class Search{
        void search(final File path) throws IOException{
            if(prunePattern != null && prunePattern.matcher(path.getAbsolutePath()).matches()) return;
            String cpath = path.getCanonicalPath();
            if(!visited.add(cpath))  return;
            if(matchPattern.matcher(path.getAbsolutePath()).matches())
                found.add(path);
            if(path.isDirectory())
                for(File sub : path.listFiles())
                    search(sub);
        }
    }
    new Search().search(startpath);
    return found;
}
 
Example #14
Source File: CsvBlurDriver.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
private static Set<Path> recurisvelyGetPathesContainingFiles(Path path, Configuration configuration)
    throws IOException {
  Set<Path> pathSet = new HashSet<Path>();
  FileSystem fileSystem = path.getFileSystem(configuration);
  if (!fileSystem.exists(path)) {
    LOG.warn("Path not found [{0}]", path);
    return pathSet;
  }
  FileStatus[] listStatus = fileSystem.listStatus(path);
  for (FileStatus status : listStatus) {
    if (status.isDir()) {
      pathSet.addAll(recurisvelyGetPathesContainingFiles(status.getPath(), configuration));
    } else {
      pathSet.add(status.getPath().getParent());
    }
  }
  return pathSet;
}
 
Example #15
Source File: PathSimilarity.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * <p>groupPathsByJointNode.</p>
 */
public void groupPathsByJointNode () {
	this.groupedPaths = new HashMap<String, HashSet<Integer>>();
	for (int i = 0; i < this.paths.size(); i++) {
		LinkedList<String> p = this.paths.get(i);
		for(String s : p) {
			if(!this.groupedPaths.containsKey(s)) {
				HashSet<Integer> tmp = new HashSet<Integer>();
				tmp.add(i);
				this.groupedPaths.put(s, tmp);
			} else {
				this.groupedPaths.get(s).add(i);
			}
		}
	}
}
 
Example #16
Source File: ConditionalSpecialCasing.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static char[] lookUpTable(String src, int index, Locale locale, boolean bLowerCasing) {
    HashSet<Entry> set = entryTable.get(new Integer(src.codePointAt(index)));
    char[] ret = null;

    if (set != null) {
        Iterator<Entry> iter = set.iterator();
        String currentLang = locale.getLanguage();
        while (iter.hasNext()) {
            Entry entry = iter.next();
            String conditionLang = entry.getLanguage();
            if (((conditionLang == null) || (conditionLang.equals(currentLang))) &&
                    isConditionMet(src, index, locale, entry.getCondition())) {
                ret = bLowerCasing ? entry.getLowerCase() : entry.getUpperCase();
                if (conditionLang != null) {
                    break;
                }
            }
        }
    }

    return ret;
}
 
Example #17
Source File: JarRefactoringDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void buttonPressed(final int buttonId) {
	if (buttonId == IDialogConstants.OK_ID) {
		fData.setRefactoringAware(true);
		final RefactoringDescriptorProxy[] descriptors= fHistoryControl.getCheckedDescriptors();
		Set<IProject> set= new HashSet<IProject>();
		IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
		for (int index= 0; index < descriptors.length; index++) {
			final String project= descriptors[index].getProject();
			if (project != null && !"".equals(project)) //$NON-NLS-1$
				set.add(root.getProject(project));
		}
		fData.setRefactoringProjects(set.toArray(new IProject[set.size()]));
		fData.setRefactoringDescriptors(descriptors);
		fData.setExportStructuralOnly(fExportStructural.getSelection());
		final IDialogSettings settings= fSettings;
		if (settings != null)
			settings.put(SETTING_SORT, fHistoryControl.isSortByProjects());
	}
	super.buttonPressed(buttonId);
}
 
Example #18
Source File: SelfDecompiler.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Print the formula to create a unique instance of it.
 */
public Vertex createUniqueTemplate(Vertex formula, Network network) {
	try {
		StringWriter writer = new StringWriter();
		printTemplate(formula, writer, "", new ArrayList<Vertex>(), new ArrayList<Vertex>(), new HashSet<Vertex>(), network);
		String source = writer.toString();
		if (source.length() > AbstractNetwork.MAX_TEXT) {
			return formula;
		}
		// Maintain identity on formulas through printing them.
		Vertex existingFormula = network.createVertex(source);
		if (!existingFormula.instanceOf(Primitive.FORMULA)) {
			for (Iterator<Relationship> iterator = formula.orderedAllRelationships(); iterator.hasNext(); ) {
				Relationship relationship = iterator.next();
				existingFormula.addRelationship(relationship.getType(), relationship.getTarget(), relationship.getIndex());
			}
		}
		return existingFormula;
	} catch (IOException ignore) {
		throw new BotException(ignore);
	}
}
 
Example #19
Source File: EventTypeChangeListener.java    From nakadi with MIT License 6 votes vote down vote up
private void onEventTypeInvalidated(final String eventType) {
    final Optional<Set<InternalListener>> toNotify;
    readWriteLock.readLock().lock();
    try {
        toNotify = Optional.ofNullable(eventTypeToListeners.get(eventType))
                .map(HashSet<InternalListener>::new);
    } finally {
        readWriteLock.readLock().unlock();
    }
    if (toNotify.isPresent()) {
        for (final InternalListener listener : toNotify.get()) {
            try {
                listener.authorizationChangeListener.accept(eventType);
            } catch (RuntimeException ex) {
                LOG.error("Failed to notify listener " + listener, ex);
            }
        }
    }
}
 
Example #20
Source File: ConfigureWorkingSetAssignementAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void recalculateCheckedState(List<IWorkingSet> addedWorkingSets) {
	Set<IWorkingSet> checkedWorkingSets= new HashSet<IWorkingSet>();
	GrayedCheckedModelElement[] elements= fModel.getChecked();
	for (int i= 0; i < elements.length; i++)
		checkedWorkingSets.add(elements[i].getWorkingSet());

	if (addedWorkingSets != null)
		checkedWorkingSets.addAll(addedWorkingSets);

	fModel= createGrayedCheckedModel(fElements, getAllWorkingSets(), checkedWorkingSets);

	fTableViewer.setInput(fModel);
	fTableViewer.refresh();
	fTableViewer.setCheckedElements(fModel.getChecked());
	fTableViewer.setGrayedElements(fModel.getGrayed());
}
 
Example #21
Source File: ProxyClassPerformanceTest.java    From JGiven with Apache License 2.0 6 votes vote down vote up
@Test
public void test_creation_of_proxy_classes(){
    Set<Long> results = new HashSet<>();
    for( int i = 0; i < 1000; i++ ) {
        ScenarioBase scenario = new ScenarioBase();
        TestStage testStage = scenario.addStage( TestStage.class );
        testStage.something();
        if( i % 100 == 0 ) {
            System.gc();
            long usedMemory = ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) / ( 1024 * 1024 );
            System.out.println( "Used memory: " + usedMemory );
            results.add( usedMemory );
        }
    }

    assertThat( results )
            .describedAs( "Only should contains 1 or 2 items, as first iteration might use more memory might contain 2 items" )
            .hasSizeBetween( 1, 2 );
}
 
Example #22
Source File: RemotePreferencesTest.java    From RemotePreferences with MIT License 6 votes vote down vote up
@Test
public void testStringSetRead() {
    HashSet<String> set = new HashSet<>();
    set.add("Chocola");
    set.add("Vanilla");
    set.add("Coconut");
    set.add("Azuki");
    set.add("Maple");
    set.add("Cinnamon");

    getSharedPreferences()
        .edit()
        .putStringSet("pref", set)
        .apply();

    RemotePreferences remotePrefs = getRemotePreferences(true);
    Assert.assertEquals(set, remotePrefs.getStringSet("pref", null));
}
 
Example #23
Source File: FlattenedOptional.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param vars
 *            - set of {@link Var} names, possibly contained constants
 */
private Set<String> setWithOutConstants(Set<String> vars) {
    Set<String> copy = new HashSet<>();
    for (String s : vars) {
        if (!VarNameUtils.isConstant(s)) {
            copy.add(s);
        }
    }

    return copy;
}
 
Example #24
Source File: DefaultControllerTest.java    From yarg with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonExtractionForBand() throws IOException, URISyntaxException {
    ReportBand band = YmlDataUtil.bandFrom(FileLoader.load("extraction/fixture/default_json_report_band.yml"));

    BandData rootBand = new BandData(BandData.ROOT_BAND_NAME);
    rootBand.setData(new HashMap<>());
    rootBand.setFirstLevelBandDefinitionNames(new HashSet<>());

    Multimap<String, BandData> reportBandMap = HashMultimap.create();

    for (ReportBand definition : band.getChildren()) {
        List<BandData> data = controllerFactory.controllerBy(definition.getBandOrientation())
                .extract(contextFactory.context(definition, rootBand, ExtractionUtils.getParams(definition)));

        Assert.assertNotNull(data);

        data.forEach(b-> {
            Assert.assertNotNull(b);
            Assert.assertTrue(StringUtils.isNotEmpty(b.getName()));

            reportBandMap.put(b.getName(), b);
        });

        rootBand.addChildren(data);
        rootBand.getFirstLevelBandDefinitionNames().add(definition.getName());
    }

    checkHeader(reportBandMap.get("header"), 2, "name", "id");
    checkMasterData(reportBandMap.get("master_data"), 2, 2,
            "id", "name", "value", "user_id");
}
 
Example #25
Source File: InsituSource.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a collection of in-situ positions, where data for the given parameter name are given.
 * @param parameterName the parameter name which is needed at the position
 * @return a collection of in-situ positions
 */
public Collection<GeoPos> getInsituPositionsFor(String parameterName) {
    Set<GeoPos> result = new HashSet<>();
    final int columnIndex = getIndexForParameter(parameterName);
    final Iterable<Record> records = recordSource.getRecords();
    for (Record record : records) {
        final Double value = (Double) record.getAttributeValues()[columnIndex];
        if (value == null) {
            continue;
        }
        result.add(record.getLocation());
    }
    return result;
}
 
Example #26
Source File: ProgramStageDataElementServiceTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void setUpTest()
{
    organisationUnit = createOrganisationUnit( 'A' );
    organisationUnitService.addOrganisationUnit( organisationUnit );

    Program program = createProgram( 'A', new HashSet<>(), organisationUnit );
    programService.addProgram( program );

    stageA = new ProgramStage( "A", program );
    stageA.setSortOrder( 1 );
    stageA.setUid( "StageA" );
    programStageService.saveProgramStage( stageA );

    stageB = new ProgramStage( "B", program );
    stageB.setSortOrder( 2 );
    programStageService.saveProgramStage( stageB );

    Set<ProgramStage> programStages = new HashSet<>();
    programStages.add( stageA );
    programStages.add( stageB );
    program.setProgramStages( programStages );
    programService.updateProgram( program );

    dataElementA = createDataElement( 'A' );
    dataElementB = createDataElement( 'B' );

    dataElementService.addDataElement( dataElementA );
    dataElementService.addDataElement( dataElementB );

    stageDataElementA = new ProgramStageDataElement( stageA, dataElementA, false, 1 );

    stageDataElementB = new ProgramStageDataElement( stageA, dataElementB, false, 2 );
}
 
Example #27
Source File: ParsePush.java    From parse4cn1 with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the collection of channels on which this push notification will be sent.
 * <p>
 * A push can either have channels or a query so setting this will unset the query.
 * <p>
 * Note that only devices subscribed to at least one of these channel will receive the push
 * notification. Subscription to channels is handled via the {@link ParseInstallation} class.
 * @param channels The channels to be set (possibly null). Replace any previously set channels. 
 */
public void setChannels(final Collection<String> channels) {
    if (channels != null) {
        this.channels = new HashSet<String>();
        this.channels.addAll(channels);
    } else {
        this.channels = null;
    }
    query = null;
}
 
Example #28
Source File: ResourceHelper.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * If node is an element of modules, it does nothing.  If it is then it
 * adds to <code>modules</code> all modules imported (directly or indirectly)
 * by module <code>node</code> by an EXTENDS statement or by an unnamed
 * INSTANCE occurring before Location <code>loc</code>.  It adds to 
 * <code>symbols</code> all symbols sym that occur in a
 * 
 *    sym == INSTANCE ...
 *    
 * statement that occurs in module <code>node</code> before location 
 * <code>loc</code> or anywhere in one of the modules added to <code>modules</code>.
 * 
 * This procedure is called by declaredSymbolsInScope and by itself, the
 * latter calls always with loc a Location beyond the end of any module.
 * 
 * @param modules
 * @param symbols
 * @param loc
 * @param node
 */
public static void addImportedModulesSet(HashSet<ModuleNode> modules, StringSet symbols, 
                               Location loc, ModuleNode node) {
    if (modules.contains(node)) {
        return ;
    }
    modules.add(node) ;
    
    HashSet<ModuleNode> extendees = node.getExtendedModuleSet();
    Iterator<ModuleNode> iter = extendees.iterator() ;
    while (iter.hasNext()) {
        ModuleNode modNode = iter.next() ;
        addImportedModulesSet(modules, symbols, infiniteLoc, modNode) ;
    }
    
    InstanceNode[] instances = node.getInstances() ;
    for (int i = 0; i < instances.length; i++) {
        // We add the instance only if its comes before loc.
        // For a LOCAL instance, we add the module to `module' or its name to `symbols'
        // only if this is the initial call, which is the case iff  loc # infiniteLoc
        if ( earlierLine(instances[i].stn.getLocation(), loc)
             && (   ! instances[i].getLocal()
                 || earlierLine(loc, infiniteLoc))){
           if (instances[i].getName() != null) {
               symbols.add(instances[i].getName().toString()) ;
           } else {
              // Testing on 9 Oct 2014 revealed that the following is unnecessary because
              // the defined operators imported into a module M without renaming by an INSTANCE
              // are contained in M.getOpDefs().  Imported named theorems are similarly
              // contained in M.getThmOrAssDefs().
              
              addImportedModulesSet(modules, symbols, infiniteLoc, instances[i].getModule()) ; 
           }
        }
    }     

}
 
Example #29
Source File: AuthKit.java    From HongsCORE with MIT License 5 votes vote down vote up
/**
 * 获取分组拥有的权限
 * @param gid
 * @return
 * @throws HongsException
 */
public static Set getDeptRoles(String gid) throws HongsException {
    Table rel = DB.getInstance("master").getTable("dept_role");
    List<Map> lst = rel.fetchCase()
        .filter("dept_id = ?", gid)
        .select("role"    )
        .getAll();
    Set set = new HashSet();
    for(Map row : lst) {
        set.add(row.get("role"));
    }
    return set;
}
 
Example #30
Source File: ZLMaxentHypertagger.java    From openccg with GNU Lesser General Public License v2.1 5 votes vote down vote up
private HashSet<Pair<String,Double>> betaSearch(ArrayList<ProbIndexPair> probList, double beta) {
	double maxProb = probList.get(0).prob;	
	HashSet<Pair<String,Double>> names = new HashSet<Pair<String, Double>>();
	for(int i = 0; i < probList.size(); i++) {
		if(probList.get(i).prob >= beta * maxProb) {
			names.add(new Pair<String, Double>(protoHTModel.getOutcome(probList.get(i).index), probList.get(i).prob));
		} else {
			break;
		}
	}
	return names;
}