def getOutlierBound(rt): """ Analyzes the results of the 1st partcile analysis. Since the dilation of nuclear perimeter often causes overlap of neighboring neculeus 'terrirories', such nucleus are discarded from the measurements. Small nucelei are already removed, but since rejection of nuclei depends on standard outlier detection method, outliers in both smaller and larger sizes are discarded. """ area = rt.getColumn(rt.getColumnIndex('Area')) circ = rt.getColumn(rt.getColumnIndex("Circ.")) arealist = ArrayList(Arrays.asList(area.tolist())) circlist = ArrayList(Arrays.asList(circ.tolist())) bwc = InstBWC() ans = bwc.calculateBoxAndWhiskerStatistics(arealist) #anscirc = bwc.calculateBoxAndWhiskerStatistics(circlist) if (VERBOSE): print ans.toString() print ans.getOutliers() q1 = ans.getQ1() q3 = ans.getQ3() intrange = q3 - q1 outlier_offset = intrange * 1.5 # circularity better be fixed. #circq1 = anscirc.getQ1() #circq3 = anscirc.getQ3() #circintrange = circq3 - circq1 #circoutlier_offset = circintrange * 1.5 return q1, q3, outlier_offset
def getExtraParametersForStep(self, configurationAttributes, step): print "Passport. getExtraParametersForStep called" if step == 1: return Arrays.asList("selectedProvider", "externalProviders") elif step == 2: return Arrays.asList("passport_user_profile") return None
def getExtraParametersForStep(self, configurationAttributes, step): print "Passport. getExtraParametersForStep called" if step == 1: return Arrays.asList("selectedProvider", "externalProviders") elif step == 2: return Arrays.asList("passport_user_profile") return None
def getExtraParametersForStep(self, configurationAttributes, step): if (step == 1): return Arrays.asList("display_register_action") elif (step == 2): return Arrays.asList("oxpush2_auth_method", "oxpush2_request") return None
def getExtraParametersForStep(self, configurationAttributes, step): if step == 1: return Arrays.asList("CustomAtrributes","PasswordStrength") elif step == 2: return Arrays.asList("code","vufnm","vulnm","vumnm","vumail","vupass") return None
def getExtraParametersForStep(self, configurationAttributes, step): if step == 1: if self.oneStep: return Arrays.asList("super_gluu_request") elif self.twoStep: return Arrays.asList("display_register_action") elif step == 2: return Arrays.asList("super_gluu_auth_method", "super_gluu_request") return None
def run(self, ctx): engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') return projects = engctx.getProjects() if not projects: print('There is no opened project') return # get the first unit available units = RuntimeProjectUtil.findUnitsByType(projects[0], None, False) if not units: print('No unit available') return unit = units[0] print('Unit: %s' % unit) # retrieve the formatter, which is a producer of unit representations formatter = unit.getFormatter() # create a table document columnLabels = Arrays.asList('Key', 'Value', 'Comment') rows = ArrayList() rows.add( TableRow(Arrays.asList(Cell('foo'), Cell('bar'), Cell('none')))) rows.add( TableRow( Arrays.asList(Cell('type'), Cell('integer'), Cell('unset')))) extraDoc = StaticTableDocument(columnLabels, rows) extraPres0 = UnitRepresentationAdapter(101, 'Demo Table', False, extraDoc) # create a tree document columnLabels = Arrays.asList('Key', 'Value') root = KVNode('foo', 'bar') roots = Arrays.asList(root) root.addChild(KVNode('quantified', 'self')) root.addChild(KVNode('galaxy', 'milky way')) node = KVNode('black hole', '42') node.setClassId(ItemClassIdentifiers.INFO_DANGEROUS) root.addChild(node) extraDoc = StaticTreeDocument(roots, columnLabels, -1) extraPres1 = UnitRepresentationAdapter(102, 'Demo Tree', False, extraDoc) # add the newly created presentations to our unit, and notify clients # the second argument indicates that the presentation should be persisted when saving the project formatter.addPresentation(extraPres0, True) formatter.addPresentation(extraPres1, True) unit.notifyListeners(JebEvent(J.UnitChange))
def createMenuItems(self, contextMenuInvocation): context = contextMenuInvocation.getInvocationContext() filterMenu = JMenu("Femida XSS") self._contextMenuData = contextMenuInvocation if (context == 0 or context == 1 or context == 2 or context == 3 or context == 8 or context == 9): filterMenu.add( JMenuItem("Add to Headers", actionPerformed=self.addToHeadersItem)) filterMenu.add( JMenuItem("Add to Parameters", actionPerformed=self.addToParametersItem)) return Arrays.asList(filterMenu) return Arrays.asList([])
def test_vararg(self): from java.util import Arrays self.assertSequenceEqual((), Arrays.asList()) self.assertSequenceEqual(("1"), Arrays.asList("1")) self.assertSequenceEqual(("1","2"), Arrays.asList("1","2")) # Passing a tuple should convert the tuple elemnts to the varargs array. self.assertSequenceEqual(("1","2"), Arrays.asList(("1","2"))) # instance method as opposed to static method above self.assertSequenceEqual(("1","2"), self.test.testAllVarArgs("1","2")) # Multiple varargs goes through a different path then just one vararg so be sure to hit both. self.assertSequenceEqual(("1"), self.test.testAllVarArgs("1")) # mixing normal args with varargs self.assertSequenceEqual(("1","2", "3"), self.test.testMixedVarArgs("1","2", "3")) self.assertSequenceEqual(("1","2", "3", "4"), self.test.testMixedVarArgs("1","2", "3", "4"))
def createLdapExtendedConfigurations(self, authConfiguration): ldapExtendedConfigurations = [] for connectionConfiguration in authConfiguration["ldap_configuration"]: configId = connectionConfiguration["configId"] servers = connectionConfiguration["servers"] bindDN = None bindPassword = None useAnonymousBind = True if (self.containsAttributeString(connectionConfiguration, "bindDN")): useAnonymousBind = False bindDN = connectionConfiguration["bindDN"] bindPassword = CdiUtil.bean(EncryptionService).decrypt( connectionConfiguration["bindPassword"]) useSSL = connectionConfiguration["useSSL"] maxConnections = connectionConfiguration["maxConnections"] baseDNs = connectionConfiguration["baseDNs"] loginAttributes = connectionConfiguration["loginAttributes"] localLoginAttributes = connectionConfiguration[ "localLoginAttributes"] ldapConfiguration = GluuLdapConfiguration() ldapConfiguration.setConfigId(configId) ldapConfiguration.setBindDN(bindDN) ldapConfiguration.setBindPassword(bindPassword) ldapConfiguration.setServers(Arrays.asList(servers)) ldapConfiguration.setMaxConnections(maxConnections) ldapConfiguration.setUseSSL(useSSL) ldapConfiguration.setBaseDNs(Arrays.asList(baseDNs)) ldapConfiguration.setPrimaryKey(loginAttributes[0]) ldapConfiguration.setLocalPrimaryKey(localLoginAttributes[0]) ldapConfiguration.setUseAnonymousBind(useAnonymousBind) ldapExtendedConfigurations.append({ "ldapConfiguration": ldapConfiguration, "connectionConfiguration": connectionConfiguration, "loginAttributes": loginAttributes, "localLoginAttributes": localLoginAttributes }) return ldapExtendedConfigurations
def run(self, ctx): engctx = ctx.getEnginesContext() if not engctx: print('Back-end engines not initialized') return projects = engctx.getProjects() if not projects: print('There is no opened project') return # get the first unit available units = RuntimeProjectUtil.findUnitsByType(projects[0], None, False) if not units: print('No unit available') return unit = units[0] print('Unit: %s' % unit) # retrieve the formatter, which is a producer of unit representations formatter = unit.getFormatter() # create a table document columnLabels = Arrays.asList('Key', 'Value', 'Comment') rows = ArrayList() rows.add(TableRow(Arrays.asList(Cell('foo'), Cell('bar'), Cell('none')))) rows.add(TableRow(Arrays.asList(Cell('type'), Cell('integer'), Cell('unset')))) extraDoc = StaticTableDocument(columnLabels, rows) extraPres0 = UnitRepresentationAdapter(101, 'Demo Table', False, extraDoc) # create a tree document columnLabels = Arrays.asList('Key', 'Value') root = KVNode('foo', 'bar') roots = Arrays.asList(root) root.addChild(KVNode('quantified', 'self')) root.addChild(KVNode('galaxy', 'milky way')) node = KVNode('black hole', '42') node.setClassId(ItemClassIdentifiers.INFO_DANGEROUS) root.addChild(node) extraDoc = StaticTreeDocument(roots, columnLabels, -1) extraPres1 = UnitRepresentationAdapter(102, 'Demo Tree', False, extraDoc) # add the newly created presentations to our unit, and notify clients # the second argument indicates that the presentation should be persisted when saving the project formatter.addPresentation(extraPres0, True) formatter.addPresentation(extraPres1, True) unit.notifyListeners(JebEvent(J.UnitChange));
def searchWithRequestAndQuery(cls, query, indexReader, taxoReader, indexingParams, facetRequest): """ Search an index with facets for given query and facet requests. returns a List<FacetResult> """ # prepare searcher to search against searcher = IndexSearcher(indexReader) # collect matching documents into a collector topDocsCollector = TopScoreDocCollector.create(10, True) if not indexingParams: indexingParams = FacetIndexingParams.DEFAULT # Faceted search parameters indicate which facets are we interested in facetRequests = [facetRequest,] facetRequests = Arrays.asList(facetRequests) # Add the facet request of interest to the search params: facetSearchParams = FacetSearchParams(indexingParams, facetRequests) # and create a FacetsCollector to use in our facetted search: facetsCollector = FacetsCollector.create(facetSearchParams, indexReader, taxoReader) # perform documents search and facets accumulation searcher.search(query, MultiCollector.wrap([topDocsCollector, facetsCollector])) print "\nFound %d Documents for query=%s" % (topDocsCollector.totalHits, query.toString().encode('utf-8')) # Obtain facets results and print them res = facetsCollector.getFacetResults() i = 0 for facetResult in res: print "Result #%d has %d descendants" % (i, facetResult.getNumValidDescendants()) print "Result #%d : %s" % (i, facetResult) i += 1 return res
def run(): global maxDist, minPts ip = IJ.getImage() roi = ip.getRoi() points = roi.getContainedPoints() pointList = Arrays.asList(points) dplist = [] for p in pointList: array = [] array.append(p.x) array.append(p.y) jArray = jarray.array(array, 'd') dp = DoublePoint(jArray) dplist.append(dp) clusterer = DBSCANClusterer(maxDist, minPts) clusters = clusterer.cluster(dplist) RoiManager() roiManager = RoiManager.getRoiManager() for c in clusters: xCoordinates = [] yCoordinates = [] for dp in c.getPoints(): p = dp.getPoint() xCoordinates.append(p[0]) yCoordinates.append(p[1]) roi = PointRoi(xCoordinates, yCoordinates) roiManager.addRoi(roi)
def disjunct(cls, multiplier, *queries, **terms): "Return lucene DisjunctionMaxQuery from queries and terms." self = cls(search.DisjunctionMaxQuery, Arrays.asList(queries), multiplier) for name, values in terms.items(): for value in ([values] if isinstance(values, basestring) else values): self.add(cls.term(name, value)) return self
def __init__(self, searcher, query, field, terms=False, fields=False, tag='', formatter=None, encoder=None): if tag: formatter = highlight.SimpleHTMLFormatter('<{}>'.format(tag), '</{}>'.format(tag)) scorer = (highlight.QueryTermScorer if terms else highlight.QueryScorer)(query, *(searcher.indexReader, field) * (not fields)) highlight.Highlighter.__init__(self, *filter(None, [formatter, encoder, scorer])) self.searcher, self.field = searcher, field self.selector = HashSet(Arrays.asList([field]))
class MyPythonEnglishAnalyzer(PythonEnglishAnalyzer): """ Class of our custom analyzer that uses filters: -StandardTokenizer. -EnglishPossessiveFilter. -LowerCaseFilter. -DiacriticFilter. -StopFilter. -SetKeywordMarkerFilter """ ENGLISH_STOP_WORDS_SET = CharArraySet.unmodifiableSet(CharArraySet(Arrays.asList( ["a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with"]), False)) def __init__(self, stopwords=ENGLISH_STOP_WORDS_SET, stemExclusionSet=CharArraySet.EMPTY_SET): super().__init__(self, stopwords) self.stopwords = stopwords self.stemExclusionSet = stemExclusionSet def createComponents(self, fieldName): source = StandardTokenizer() result = EnglishPossessiveFilter(source) result = LowerCaseFilter(result) result = DiacriticFilter(result) result = StopFilter(result, self.stopwords) if self.stemExclusionSet.isEmpty() is False: result = SetKeywordMarkerFilter(result, self.stemExclusionSet) result = PorterStemFilter(result) return Analyzer.TokenStreamComponents(source, result) def normalize(self, fieldName, input): return LowerCaseFilter(input)
def createLdapExtendedConfigurations(self, authConfiguration): ldapExtendedConfigurations = [] for ldapConfiguration in authConfiguration["ldap_configuration"]: configId = ldapConfiguration["configId"] servers = ldapConfiguration["servers"] bindDN = None bindPassword = None useAnonymousBind = True if (self.containsAttributeString(ldapConfiguration, "bindDN")): useAnonymousBind = False bindDN = ldapConfiguration["bindDN"] bindPassword = ldapConfiguration["bindPassword"] useSSL = ldapConfiguration["useSSL"] maxConnections = ldapConfiguration["maxConnections"] baseDNs = ldapConfiguration["baseDNs"] loginAttributes = ldapConfiguration["loginAttributes"] localLoginAttributes = ldapConfiguration["localLoginAttributes"] ldapConfiguration = GluuLdapConfiguration(configId, bindDN, bindPassword, Arrays.asList(servers), maxConnections, useSSL, Arrays.asList(baseDNs), loginAttributes[0], localLoginAttributes[0], useAnonymousBind) ldapExtendedConfigurations.append({ "ldapConfiguration" : ldapConfiguration, "loginAttributes" : loginAttributes, "localLoginAttributes" : localLoginAttributes }) return ldapExtendedConfigurations
def loadClientConfigurations(self, configurationFile): clientConfiguration = None # Load configuration from file f = open(configurationFile, 'r') try: configurationFileJson = json.loads(f.read()) except: print "Basic (client group). Load configuration from file. Failed to load authentication configuration from file:", configurationFile return None finally: f.close() clientConfigurations = HashMap() for client_key in configurationFileJson.keys(): client_config = configurationFileJson[client_key] client_inum = client_config["client_inum"] user_groups_array = client_config["user_group"] user_groups = Arrays.asList(user_groups_array) clientConfigurations.put(client_inum, user_groups) print "Basic (client group). Load configuration from file. Loaded '%s' configurations" % clientConfigurations.size() print clientConfigurations return clientConfigurations
def createLdapExtendedConfigurations(self, authConfiguration): ldapExtendedConfigurations = [] for ldapConfiguration in authConfiguration["ldap_configuration"]: configId = ldapConfiguration["configId"] servers = ldapConfiguration["servers"] bindDN = None bindPassword = None useAnonymousBind = True if (self.containsAttributeString(ldapConfiguration, "bindDN")): useAnonymousBind = False bindDN = ldapConfiguration["bindDN"] bindPassword = ldapConfiguration["bindPassword"] useSSL = ldapConfiguration["useSSL"] maxConnections = ldapConfiguration["maxConnections"] baseDNs = ldapConfiguration["baseDNs"] loginAttributes = ldapConfiguration["loginAttributes"] localLoginAttributes = ldapConfiguration["localLoginAttributes"] ldapConfiguration = GluuLdapConfiguration(configId, bindDN, bindPassword, Arrays.asList(servers), maxConnections, useSSL, Arrays.asList(baseDNs), loginAttributes[0], localLoginAttributes[0], useAnonymousBind) ldapExtendedConfigurations.append({ "ldapConfiguration" : ldapConfiguration, "loginAttributes" : loginAttributes, "localLoginAttributes" : localLoginAttributes }) return ldapExtendedConfigurations
def update(self, dynamicScopeContext, configurationAttributes): print "Dynamic scope. Update method" userService = CdiUtil.bean(UserService) print "-->userService: " + userService.toString() dynamicScopes = dynamicScopeContext.getDynamicScopes() authorizationGrant = dynamicScopeContext.getAuthorizationGrant() user = dynamicScopeContext.getUser() jsonWebResponse = dynamicScopeContext.getJsonWebResponse() claims = jsonWebResponse.getClaims() member_of_list = userService.getCustomAttribute(user, "memberof") if member_of_list == None: print "-->memberOf: is null" return None else: members_list = member_of_list.getValues() membersArray = [] for members in members_list: group = userService.getUserByDn(members, "displayName") membersArray.append(group.getAttribute("displayName")) claims.setClaim("memberof", Arrays.asList(membersArray)) return True
def outlierDetection(pattern, measA): filtsdevA = [] for ind, sd in enumerate(measA[2]): if not measA[4][ind]: filtsdevA.append(sd) #sdevlist = ArrayList(Arrays.asList(measA[2])) sdevlist = ArrayList(Arrays.asList(filtsdevA)) bwc = InstBWC() ans = bwc.calculateBoxAndWhiskerStatistics(sdevlist) q1 = ans.getQ1() q3 = ans.getQ3() intrange = q3 - q1 outlier_offset = intrange * 1.5 outlow = q1 - outlier_offset outup = q3 + outlier_offset filtersummary = { 'n': len(measA[2]),'Mean': ans.getMean(), 'Median': ans.getMedian(), 'Outlier-Low': outlow, 'Outlier-Up': outup } for i, filep in enumerate(measA[0]): #res = re.search(pattern, filep) if (measA[2][i] < outlow) or (measA[2][i] > outup): #print 'xxxW', res.group(2), measA[2][i] measA[4][i] = 1 # else: #print 'W', res.group(2), measA[2][i] #measA[4].append(0) return filtersummary
def index (cls, indexDir, taxoDir): """Create an index, and adds to it sample documents and facets. indexDir Directory in which the index should be created. taxoDir Directory in which the taxonomy index should be created. """ # create and open an index writer from org.apache.lucene.util import Version config = IndexWriterConfig(Version.LUCENE_42, WhitespaceAnalyzer(Version.LUCENE_42)) config.setOpenMode(IndexWriterConfig.OpenMode.CREATE) iw = IndexWriter(indexDir, config) # create and open a taxonomy writer taxo = DirectoryTaxonomyWriter(taxoDir, IndexWriterConfig.OpenMode.CREATE) # FacetFields is a utility class for adding facet fields to a document: facet_fields = FacetFields(taxo) # loop over sample documents nDocsAdded = 0 nFacetsAdded = 0 for docNum in range(len(docTexts)): # obtain the sample facets for current document facets = categories[docNum] facetList = [CategoryPath(f) for f in facets] # NOTE: setCategoryPaths() requires an Iterable, so need to convert the # Python list in order to to pass a proper argument to setCategoryPaths. # We use java.util.Arrays (via JCC) to create a Java List: facetList = Arrays.asList(facetList) # NOTE: we could use lucene.collections here as well in order to convert our # Python list to a Java based list using the JavaList class (JavaList implements # java.util.List around a Python list instance it wraps): # from lucene.collections import JavaList # facetList = JavaList(facetList) # create a plain Lucene document and add some regular Lucene fields to it doc = Document() doc.add(TextField(TITLE, docTitles[docNum], Field.Store.YES)) doc.add(TextField(TEXT, docTexts[docNum], Field.Store.NO)) # use the FacetFields utility class for adding facet fields (i.e. the categories) # to the document (and, as required, to the taxonomy index) facet_fields.addFields(doc, facetList) # finally add the document to the index iw.addDocument(doc) nDocsAdded +=1 nFacetsAdded += facetList.size() # end for # commit changes. # we commit changes to the taxonomy index prior to committing them to the search index. # this is important, so that all facets referred to by documents in the search index # will indeed exist in the taxonomy index. taxo.commit() iw.commit() # close the taxonomy index and the index - all modifications are # now safely in the provided directories: indexDir and taxoDir. taxo.close() iw.close() print "Indexed %d documents with overall %d facets." % (nDocsAdded,nFacetsAdded)
def disjunct(cls, multiplier, *queries, **terms): """Return lucene DisjunctionMaxQuery from queries and terms.""" queries = list(queries) for name, values in terms.items(): queries += (cls.term(name, value) for value in ( [values] if isinstance(values, str) else values)) return cls(search.DisjunctionMaxQuery, Arrays.asList(queries), multiplier)
def getExtraParametersForStep(self, configurationAttributes, step): print "Casa. getExtraParametersForStep %s" % str(step) if step > 1: list = ArrayList() acr = CdiUtil.bean(Identity).getWorkingParameter("ACR") if acr in self.authenticators: module = self.authenticators[acr] params = module.getExtraParametersForStep(module.configAttrs, step) if params != None: list.addAll(params) list.addAll(Arrays.asList("ACR", "methods", "trustedDevicesInfo")) print "extras are %s" % list return list return Arrays.asList("externalProviders")
def getExtraParametersForStep(self, configurationAttributes, step): print "Casa. getExtraParametersForStep %s" % str(step) list = ArrayList() if step > 1: acr = CdiUtil.bean(Identity).getWorkingParameter("ACR") if acr in self.authenticators: module = self.authenticators[acr] params = module.getExtraParametersForStep(module.configAttrs, step) if params != None: list.addAll(params) list.addAll(Arrays.asList("ACR", "methods", "trustedDevicesInfo")) list.addAll(Arrays.asList("casa_contextPath", "casa_prefix", "casa_faviconUrl", "casa_extraCss", "casa_logoUrl")) print "extras are %s" % list return list
def test_vararg(self): from java.util import Arrays self.assertSequenceEqual((), Arrays.asList()) self.assertSequenceEqual(("1"), Arrays.asList("1")) self.assertSequenceEqual(("1", "2"), Arrays.asList("1", "2")) # Passing a tuple should convert the tuple elemnts to the varargs array. self.assertSequenceEqual(("1", "2"), Arrays.asList(("1", "2"))) # instance method as opposed to static method above self.assertSequenceEqual(("1", "2"), self.test.testAllVarArgs("1", "2")) # Multiple varargs goes through a different path then just one vararg so be sure to hit both. self.assertSequenceEqual(("1"), self.test.testAllVarArgs("1")) # mixing normal args with varargs self.assertSequenceEqual(("1", "2", "3"), self.test.testMixedVarArgs("1", "2", "3")) self.assertSequenceEqual( ("1", "2", "3", "4"), self.test.testMixedVarArgs("1", "2", "3", "4"))
def getExtraParametersForStep(self, configurationAttributes, step): return Arrays.asList( "stepCount", # Used to complete the workflow "provider", # The 1FA provider chosen by the user "abort", # Used to trigger error abort back to the RP "forceAuthn", # Used to force authentication when prompt=login "userId", # Used to keep track of the user across multiple requests "mfaId", # Used to bind a 2nd factor credential into the session "mfaFallback") # Used to bypass Fido authnetication
def getUniqueSrcIps(self, protocol=6): uniqueIps = HashSet() srcAddrSqlBuilder = SelectSqlBuilder('Agg_V5', 'srcAddr as ip', distinct=1) srcAddrSqlBuilder.where('prot=%d' % protocol) srcIps = self._sqlClient.execute(srcAddrSqlBuilder) if srcIps: uniqueIps.addAll(Arrays.asList([ipEntry.ip for ipEntry in srcIps])) return uniqueIps.toArray()
def addCommentsToDoc(self, unit): notes = unit.getNotes() # Get the notes of unit if isinstance( unit, IInteractiveUnit ): # If the type of unit is IInteractiveUnit, which means it my has comments and we can use getComments() totalComments = unit.getComments() # Get all comments flag = True # If flag is true, we will add the unit name in the first column, and after that, it will be set to false, which means other rows of this unit will not be added the unit name. # So only the first row of the unit have the unit name if totalComments: for address in totalComments: if (totalComments[address] != None and totalComments[address] != ''): if (flag): self.rows.add( TableRow( Arrays.asList( Cell(unit.getName()), Cell(address), Cell(totalComments[address])))) flag = False else: self.rows.add( TableRow( Arrays.asList( Cell(''), Cell(address), Cell(totalComments[address])))) if totalComments and notes: self.rows.add( TableRow( Arrays.asList(Cell(''), Cell('Notes:'), Cell(unit.getNotes())))) return if notes: self.rows.add( TableRow( Arrays.asList(Cell(unit.getName()), Cell('Notes:'), Cell(unit.getNotes())))) return return if notes: self.rows.add( TableRow( Arrays.asList(Cell(unit.getName()), Cell('Notes:'), Cell(unit.getNotes()))))
def getUniqueSrcIps(self, protocol=6): uniqueIps = HashSet() srcAddrSqlBuilder = SelectSqlBuilder('Agg_V5', 'srcAddr as ip', distinct=1) srcAddrSqlBuilder.where('prot=%d' % protocol) srcIps = self._sqlClient.execute(srcAddrSqlBuilder) if srcIps: uniqueIps.addAll(Arrays.asList([ipEntry.ip for ipEntry in srcIps])) return uniqueIps.toArray()
def initialize_executors_holder(servers): server_names= [] for server in servers: server_name = server.getProperty("serverName") server_names.append(server_name) if executors_holder.RUNNING_EXECUTORS.containsKey(server_name): print "DEBUG: server name already in RUNNING EXECUTORS [%s]" % server_name current_size = executors_holder.RUNNING_EXECUTORS.get(server_name).maxSize() if current_size != server.getProperty("nrExecutors"): fixed = FixedSizeList.decorate(Arrays.asList(String[server.getProperty("nrExecutors")])); executors_holder.RUNNING_EXECUTORS.replace(server_name, fixed) else: print "DEBUG: server name not in RUNNING EXECUTORS [%s]" % server_name fixed = FixedSizeList.decorate(Arrays.asList(["available"] * server.getProperty("nrExecutors"))); executors_holder.RUNNING_EXECUTORS.put(server_name, fixed) # Remove any RUNNING_EXECUTORS that are not in servers for key in executors_holder.RUNNING_EXECUTORS.keySet(): if key not in server_names: print "DEBUG: Removing obsolete executors server [%s]" % key executors_holder.RUNNING_EXECUTORS.remove(key)
def run(self, ctx): prj = ctx.getMainProject() unit = prj.findUnit(IInteractiveUnit) print('Unit: %s' % unit) # retrieve the formatter, which is a producer of unit representations formatter = unit.getFormatter() # create a table document columnLabels = Arrays.asList('Key', 'Value', 'Comment') rows = ArrayList() rows.add( TableRow(Arrays.asList(Cell('foo'), Cell('bar'), Cell('none')))) rows.add( TableRow( Arrays.asList(Cell('type'), Cell('integer'), Cell('unset')))) extraDoc = StaticTableDocument(columnLabels, rows) extraPres0 = UnitRepresentationAdapter(101, 'Demo Table', False, extraDoc) # create a tree document columnLabels = Arrays.asList('Key', 'Value') root = KVNode('foo', 'bar') roots = Arrays.asList(root) root.addChild(KVNode('quantified', 'self')) root.addChild(KVNode('galaxy', 'milky way')) node = KVNode('black hole', '42') node.setClassId(ItemClassIdentifiers.INFO_DANGEROUS) root.addChild(node) extraDoc = StaticTreeDocument(roots, columnLabels, -1) extraPres1 = UnitRepresentationAdapter(102, 'Demo Tree', False, extraDoc) # add the newly created presentations to our unit, and notify clients # the second argument indicates that the presentation should be persisted when saving the project formatter.addPresentation(extraPres0, True) formatter.addPresentation(extraPres1, True) UnitUtil.notifyGenericChange(unit)
def addCommentsToDoc(self, unit): notes = unit.getNotes() # Get the notes of unit if isinstance(unit, IInteractiveUnit): # If the type of unit is IInteractiveUnit, which means it my has comments and we can use getComments() totalComments = unit.getComments() # Get all comments flag = True # If flag is true, we will add the unit name in the first column, and after that, it will be set to false, which means other rows of this unit will not be added the unit name. # So only the first row of the unit have the unit name if totalComments: for address in totalComments: if (totalComments[address] != None and totalComments[address] != ''): if (flag): self.rows.add(TableRow(Arrays.asList(Cell(unit.getName()), Cell(address), Cell(totalComments[address])))) flag = False else: self.rows.add(TableRow(Arrays.asList(Cell(''), Cell(address), Cell(totalComments[address])))) if totalComments and notes: self.rows.add(TableRow(Arrays.asList(Cell(''), Cell('Notes:'), Cell(unit.getNotes())))) return if notes: self.rows.add(TableRow(Arrays.asList(Cell(unit.getName()), Cell('Notes:'), Cell(unit.getNotes())))) return return if notes: self.rows.add(TableRow(Arrays.asList(Cell(unit.getName()), Cell('Notes:'), Cell(unit.getNotes()))))
def getExtraParametersForStep(self, configurationAttributes, step): print "MFA. getExtraParametersForStep called for step '%s'" % step # Inject dependencies identity = CdiUtil.bean(Identity) flow = identity.getWorkingParameter("flow") authenticatorType = identity.getWorkingParameter("authenticatorType") # General Parameters parameters = ArrayList(Arrays.asList("userId", "flow", "authenticatorType", "nextStep", "rpShortName.en", "rpShortName.fr", "rpContent")) # Registration Parameters if (flow == "Register"): parameters.add("recoveryCode") if (authenticatorType == "TOTP" and step == 3): parameters.addAll(Arrays.asList("totpEnrollmentRequest", "totpSecretKey", "qrLabel", "qrOptions")) if (authenticatorType == "FIDO" and step == 2): parameters.add("fido_u2f_registration_request") if (flow == "Authenticate" and authenticatorType == "FIDO" and step == 2): parameters.add("fido_u2f_authentication_request") return parameters
def getExtraParametersForStep(self, configurationAttributes, step): print "Casa. getExtraParametersForStep %s" % str(step) if step > 1: list = ArrayList() acr = CdiUtil.bean(Identity).getWorkingParameter("ACR") if acr in self.authenticators: module = self.authenticators[acr] params = module.getExtraParametersForStep(module.configAttrs, step) if params != None: list.addAll(params) list.addAll(Arrays.asList("ACR", "methods", "trustedDevicesInfo")) print "extras are %s" % list return list return None
def updateAttributes(self, context, configurationAttributes): print "Idp extension. Method: updateAttributes" attributeContext = context.getAttributeContext() customAttributes = HashMap() customAttributes.putAll(attributeContext.getIdPAttributes()) # Remove givenName attribute customAttributes.remove("givenName") # Update surname attribute if customAttributes.containsKey("sn"): customAttributes.get("sn").setValues( ArrayList(Arrays.asList(StringAttributeValue("Dummy")))) # Set updated attributes attributeContext.setIdPAttributes(customAttributes.values()) return True
def getSupportedClaims(self, configurationAttributes): return Arrays.asList("role")
def getExtraParametersForStep(self, configurationAttributes, step): if step > 1: return Arrays.asList("randCode", "numbers", "choppedNos") return None
def doInit(self): self.client = MemcachedClient(ConnectionFactoryBiggerTimeout(), Arrays.asList([InetSocketAddress("127.0.0.1", 11211)]))
def select(self, *fields): "Only load selected fields." self.fields = HashSet(Arrays.asList(fields))
def getExtraParametersForStep(self, configurationAttributes, step): return Arrays.asList("code", "mobile_number")
def getOr(cls, disjuncts): """ generated source for method getOr """ return cls.getOr(Arrays.asList(disjuncts))
def getExtraParametersForStep(self, configurationAttributes, step): return Arrays.asList("uaf_auth_method", "uaf_obb_auth_method", "uaf_obb_server_uri", "uaf_obb_start_response")
def getExtraParametersForStep(self, configurationAttributes, step): if step == 2: return Arrays.asList("duo_count_login_steps", "cas2_user_uid") return None
def ident(self): return FunctionIdent(self.name(), Arrays.asList(DataTypes.LONG, DataTypes.LONG))
def assertAsList(self, a, b): self.assertEqual(Arrays.asList(a), b)
def getExtraParametersForStep(self, configurationAttributes, step): return Arrays.asList("cert_selected", "cert_valid", "cert_x509", "cert_x509_fingerprint", "cert_count_login_steps", "cert_user_external_uid")
def getExtraParametersForStep(self, configurationAttributes, step): if (step in [2, 3]): return Arrays.asList("oxpush_user_uid", "oxpush_pairing_uid") return None
def getExtraParametersForStep(self, configurationAttributes, step): if step == 2: return Arrays.asList("code") return None
def getExtraParametersForStep(self, configurationAttributes, step): if (step == 2): return Arrays.asList("saml_user_uid") return None
#ConsoleUtil.write("Error: There is no Key for \""+str(node)+"\" in NodeIndex[]") node="B" if not node.find("_"): if n==1: drawing=1 parent=node shortnode=node else: if n < len(node.split("_")): drawing=1 shortnode = node.split("_")[n] parent = node.split("_"+node.split("_")[n])[0] if drawing==1: ConsoleUtil.writeInfo("n="+str(n)+", parent="+parent) widget.setPropertyValue("visible","true") pindex = int(nodeLoader.NodeIndex[parent]) siblings = nodeLoader.SubNodeNames[pindex].rstrip("'").lstrip("'").split(",") siblings.sort() ConsoleUtil.writeInfo("subnodes="+nodeLoader.SubNodeNames[pindex]) subnodes = nodeLoader.SubNodeNames[pindex].rstrip("'").lstrip("'").split(",") widget.setPropertyValue("items",Arrays.asList(subnodes) ) widget.setPropertyValue("height",24*len(subnodes) ) selectedPV = pvArray[1] selectedPV.setValue(shortnode)
def getExtraParametersForStep(self, configurationAttributes, step): if step == 2: return Arrays.asList("duo_count_login_steps", "cas2_user_uid") return None
def getRule_0(cls, head, body): """ generated source for method getRule_0 """ return cls.getRule(head, Arrays.asList(body))
def getExtraParametersForStep(self, configurationAttributes, step): return Arrays.asList("cert_selected", "cert_valid", "cert_x509", "cert_x509_fingerprint", "cert_count_login_steps", "cert_user_external_uid")
def ident(self): return FunctionIdent(self.name(), Arrays.asList(DataTypes.INTEGER))
def getExtraParametersForStep(self, configurationAttributes, step): if (step == 2): return Arrays.asList("oneid_user_uid") return None
def getRelation_0(cls, name, body): """ generated source for method getRelation_0 """ return cls.getRelation(name, Arrays.asList(body))
String destinationName = "Destination"; UUID destinationId = authoringClient.models().addEntity() .withAppId(appId) .withVersionId(versionId) .withName(destinationName) .execute(); System.out.println("Created simple entity " + destinationName + " with ID " + destinationId.toString()); String className = "Class"; UUID classId = authoringClient.models().addHierarchicalEntity(appId, versionId, new HierarchicalEntityModel() .withName(className) .withChildren(Arrays.asList("First", "Business", "Economy"))); System.out.println("Created hierarchical entity " + className + " with ID " + classId.toString()); //============================================================= // This will create the "Flight" composite entity including "Class" and "Destination" System.out.println("Creating the \"Flight\" composite entity including \"Class\" and \"Destination\"."); String flightName = "Flight"; UUID flightId = authoringClient.models().addCompositeEntity(appId, versionId, new CompositeEntityModel() .withName(flightName) .withChildren(Arrays.asList(className, destinationName))); System.out.println("Created composite entity " + flightName + "with ID " + flightId.toString());
def getExtraParametersForStep(self, configurationAttributes, step): return Arrays.asList("uaf_auth_method", "uaf_obb_auth_method", "uaf_obb_server_uri", "uaf_obb_start_response")