当前位置: 首页>>代码示例>>Python>>正文


Python util.Collections类代码示例

本文整理汇总了Python中java.util.Collections的典型用法代码示例。如果您正苦于以下问题:Python Collections类的具体用法?Python Collections怎么用?Python Collections使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Collections类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: append_to_errors

    def append_to_errors(self, errorsList, check):
        """Clean errors list from duplicate errors and ids that must be
           ignored
        """
        if errorsList[0][0] == "":
            #osmId == "", this tool doesn't give id of OSM objects
            check.errors = [Error(check, e) for e in errorsList]
        else:
            if check.ignoreIds != []:
                #remove OSM objects that the user wants to ignore
                check.errors = [Error(check, e) for e in errorsList if e[0] not in check.ignoreIds]

                #remove duplicate ids
                #check.errors = dict((e.osmId, e) for e in check.errors).values()
            else:
                #copy all errors and remove duplicate ids
                #check.errors = dict((e[0], Error(e)) for e in errorsList).values()
                check.errors = [Error(check, e) for e in errorsList]

            #Remove from the list of errors those that have been reviewed yet
            #while clicking the "Next" button
            check.errors = [e for e in check.errors if e.osmId not in check.reviewedIds]

        #print "\n- errors of selected check in current zone:", [e.osmId for e in check.errors]

        #Randomize the errors so that different users don't start
        #correcting the same errors
        Collections.shuffle(check.errors)

        #Filter errors in favourite zone
        if self.app.favouriteZoneStatus and self.app.favZone.zType != "rectangle":
            #not rectangular favourite area, use jts
            from com.vividsolutions.jts.geom import Coordinate, GeometryFactory
            polygon = self.app.favZone.wktGeom
            errorsInPolygon = []
            for error in check.errors:
                (lat, lon) = error.coords
                point = GeometryFactory().createPoint(Coordinate(lon, lat))
                if polygon.contains(point):
                    if error not in errorsInPolygon:
                        errorsInPolygon.append(error)
            check.errors = errorsInPolygon

        #Apply limits from preferences
        #max number of errors
        limits = []
        if self.app.maxErrorsNumber != "":
            limits.append(self.app.maxErrorsNumber)
        try:
            if self.tool.prefs["limit"] != "":
                limits.append(int(self.tool.prefs["limit"]))
        except:
            pass
        if limits != []:
            check.errors = check.errors[:min(limits)]

        #Reset index of current error
        check.currentErrorIndex = -1
        check.toDo = len(check.errors)
开发者ID:alex85k,项目名称:qat_script,代码行数:59,代码来源:download_and_parse.py

示例2: exportAll

def exportAll(exportConfigFile, generalConfigFile):
    try:
        print "Loading export config from :", exportConfigFile
        exportConfigProp = loadProps(exportConfigFile,generalConfigFile)
        adminUrl = exportConfigProp.get("adminUrl")
        user = exportConfigProp.get("user")
        passwd = exportConfigProp.get("password")

        jarFileName = exportConfigProp.get("jarFileName")
        customFile = exportConfigProp.get("customizationFile")

        passphrase = exportConfigProp.get("passphrase")
        project = exportConfigProp.get("project")

        connectToServer(user, passwd, adminUrl)
        print 'connected'

        ALSBConfigurationMBean = findService("ALSBConfiguration", "com.bea.wli.sb.management.configuration.ALSBConfigurationMBean")
        print "ALSBConfiguration MBean found"

        print project
        if project == None :
            ref = Ref.DOMAIN
            collection = Collections.singleton(ref)
            if passphrase == None :
                print "Export the config"
                theBytes = ALSBConfigurationMBean.export(collection, true, None)
            else :
                print "Export and encrypt the config"
                theBytes = ALSBConfigurationMBean.export(collection, true, passphrase)
        else :
            ref = Ref.makeProjectRef(project);
            print "Export the project", project
            collection = Collections.singleton(ref)
            theBytes = ALSBConfigurationMBean.exportProjects(collection, passphrase)
        print 'fileName',jarFileName
        aFile = File(jarFileName)
        print 'file',aFile
        out = FileOutputStream(aFile)
        out.write(theBytes)
        out.close()
        print "ALSB Configuration file: "+ jarFileName + " has been exported"

        if customFile != None:
            print collection
            query = EnvValueQuery(None, Collections.singleton(EnvValueTypes.WORK_MANAGER), collection, false, None, false)
            customEnv = FindAndReplaceCustomization('Set the right Work Manager', query, 'Production System Work Manager')
            print 'EnvValueCustomization created'
            customList = ArrayList()
            customList.add(customEnv)
            print customList
            aFile = File(customFile)
            out = FileOutputStream(aFile)
            Customization.toXML(customList, out)
            out.close()

#        print "ALSB Dummy Customization file: "+ customFile + " has been created"
    except:
        raise
开发者ID:robertoporfiro,项目名称:guavatools,代码行数:59,代码来源:export.py

示例3: getRandomWord

 def getRandomWord(self):
     """ generated source for method getRandomWord """
     if self.scrambledTokens.isEmpty():
         for word in WordList.words:
             self.scrambledTokens.add(word + self.scrambledPrefix)
         Collections.shuffle(self.scrambledTokens, self.random)
         self.scrambledPrefix += 1
     return self.scrambledTokens.pop()
开发者ID:hobson,项目名称:ggpy,代码行数:8,代码来源:MappingGdlScrambler.py

示例4: __init__

 def __init__(self, theRandom):
     """ generated source for method __init__ """
     super(MappingGdlScrambler, self).__init__()
     self.random = theRandom
     self.scrambleMapping = HashMap()
     self.unscrambleMapping = HashMap()
     self.scrambledPrefix = 0
     self.scrambledTokens = Stack()
     for word in WordList.words:
         self.scrambledTokens.add(word)
     Collections.shuffle(self.scrambledTokens, self.random)
开发者ID:hobson,项目名称:ggpy,代码行数:11,代码来源:MappingGdlScrambler.py

示例5: main

 def main(cls, args):
     """ generated source for method main """
     description = GameRepository.getDefaultRepository().getGame("conn4").getRules()
     flattener = PropNetFlattener(description)
     flattened = flattener.flatten()
     print "Flattened description for connect four contains: \n" + len(flattened) + "\n\n"
     strings = ArrayList()
     for rule in flattened:
         strings.add(rule.__str__())
     Collections.sort(strings)
     for s in strings:
         print s
开发者ID:hobson,项目名称:ggpy,代码行数:12,代码来源:PropNetFlattener.py

示例6: run

    def run(self):
        # sanity check:
        if len(self.sources) == 0: raise Exception("No sources defined")
        if len(self.sinks) == 0: raise Exception("No sinks defined")

        # create a plan:
        specs = []
        pipemap = {}
        for sink in self.sinks:
            spec = JobSpec(self._jobid(), self.workpath)
            spec.outputpath = sink.sinkpath
            spec.outputformat = sink.outputformat
            spec.outputJson = sink.json
            spec.compressoutput = sink.compressoutput
            spec.compressiontype = sink.compressiontype
            specs.append(spec)
            if len(sink.sources) != 1: raise Exception("Sinks can only have one source: " + sink)
            self._walkPipe(spec, sink.sources[0], specs, pipemap)

        # sort out paths for jobs:
        self._configureJobs(specs)

        # run jobs:
        _log.info("Working directory is " + self.workpath)
        _log.info(str(len(specs)) + " job(s) found from " + str(len(self.pipes)) + " pipe action(s)")
        happy.dfs.delete(self.workpath)
        jobsDone = Collections.synchronizedSet(HashSet())
        jobResults = Collections.synchronizedList(ArrayList())
        jobsStarted = sets.Set()
        while jobsDone.size() < len(specs):
            # only keep 3 jobs in flight:
            for spec in specs:
                id = spec.id
                if id not in jobsStarted:
                    parentIds = [parent.id for parent in spec.parents]
                    if jobsDone.containsAll(parentIds):
                        thread = threading.Thread(name="Cloud Job " + str(id), target=self._runJob, args=(spec.getJob(), id, jobsDone, jobResults))
                        thread.setDaemon(True)
                        thread.start()
                        jobsStarted.add(id)
                if len(jobsStarted) - jobsDone.size() >= 3: break
            time.sleep(1)
        # compile results:
        results = {}
        for result in jobResults:
            for key, value in result.iteritems():
                results.setdefault(key, []).extend(value)
        # check for errors:
        if self.hasErrors():
            totalErrors = sum(results["happy.cloud.dataerrors"])
            _log.error("*** " + str(totalErrors) + " DataException errors were caught during this run, look in " + \
                self.workpath + "/errors to see details ***")
        return results
开发者ID:tristanbuckner,项目名称:happy,代码行数:53,代码来源:impl.py

示例7: _GetCurrentASTPath

def _GetCurrentASTPath(context, reverse=False):
    '''
    @return: ArrayList(SimpleNode)
    '''
    from org.python.pydev.parser.fastparser import FastParser
    selection = _CreateSelection(context)
    ret = FastParser.parseToKnowGloballyAccessiblePath(
        context.getDocument(), selection.getStartLineIndex())
    if reverse:
        from java.util import Collections
        Collections.reverse(ret)
        
    return ret
开发者ID:,项目名称:,代码行数:13,代码来源:

示例8: repopulateGameList

 def repopulateGameList(self):
     """ generated source for method repopulateGameList """
     theRepository = self.getSelectedGameRepository()
     theKeyList = ArrayList(theRepository.getGameKeys())
     Collections.sort(theKeyList)
     self.theGameList.removeAllItems()
     for theKey in theKeyList:
         if theGame == None:
             continue
         if theName == None:
             theName = theKey
         if 24 > len(theName):
             theName = theName.substring(0, 24) + "..."
         self.theGameList.addItem(self.NamedItem(theKey, theName))
开发者ID:hobson,项目名称:ggpy,代码行数:14,代码来源:GameSelector.py

示例9: run

def run(config):
    """Display the config as a fully resolved set of properties"""
    print '\nConfiguration properties are:'
    v = Vector(config.keySet())
    Collections.sort(v)
    it = v.iterator()
    while (it.hasNext()):
       element = it.next();
       if (String(element.lower()).endsWith('.password')):
           printValue = '****'
       else:
           printValue = config.get(element)

       print '   ' + element + "=" + printValue
    print '\n'
开发者ID:Integral-Technology-Solutions,项目名称:ConfigNOW,代码行数:15,代码来源:show_config.py

示例10: checkForJob

    def checkForJob(self,workDir):
        jobFile = os.path.join(workDir,'sentinel')

        if os.path.exists(jobFile):
            partId = int(os.path.basename(workDir))
            mc = ManagementContainer.getInstance()
            pm = mc.getPartitionManager()
            partition = pm.getPartition(partId)
            log('Found a purge job for partition',partId)
            if self.processJob(partition,workDir,jobFile):
                log('Purge succeeded. Clearing jobs directory (',workDir,')to signal dispatcher that a partition is completed')
                self.clearJobDirectory(workDir)
                pm.refreshFreeSpaceInfo(Collections.singletonList(partition))
            else:
                log('Purge failed. Not clearing job directory(',workDir,'). Will retry with current batch later')
                count = 1
                if partId in self.failuresByPartId:
                    count = self.failuresByPartId[partId]
                    count = count + 1
                    if count >= self.maxFailures:
                        log('Purge: failed purge',count,'times for partition',partId,'. Clearing job')
                        self.clearJobDirectory(workDir)
                        count = 0
                self.failuresByPartId[partId] = count

            return True

        return False
开发者ID:,项目名称:,代码行数:28,代码来源:

示例11: getCondensationSet

 def getCondensationSet(cls, rule, model, checker, sentenceNameSource):
     """ generated source for method getCondensationSet """
     varsInRule = GdlUtils.getVariables(rule)
     varsInHead = GdlUtils.getVariables(rule.getHead())
     varsNotInHead = ArrayList(varsInRule)
     varsNotInHead.removeAll(varsInHead)
     for var in varsNotInHead:
         ConcurrencyUtils.checkForInterruption()
         for literal in rule.getBody():
             if GdlUtils.getVariables(literal).contains(var):
                 minSet.add(literal)
         for literal in minSet:
             if isinstance(literal, (GdlRelation, )):
                 varsSupplied.addAll(GdlUtils.getVariables(literal))
             elif isinstance(literal, (GdlDistinct, )) or isinstance(literal, (GdlNot, )):
                 varsNeeded.addAll(GdlUtils.getVariables(literal))
         varsNeeded.removeAll(varsSupplied)
         if not varsNeeded.isEmpty():
             continue 
         for varNeeded in varsNeeded:
             for literal in rule.getBody():
                 if isinstance(literal, (GdlRelation, )):
                     if GdlUtils.getVariables(literal).contains(varNeeded):
                         suppliers.add(literal)
             candidateSuppliersList.add(suppliers)
         for suppliers in candidateSuppliersList:
             if Collections.disjoint(suppliers, literalsToAdd):
                 literalsToAdd.add(suppliers.iterator().next())
         minSet.addAll(literalsToAdd)
         if goodCondensationSetByHeuristic(minSet, rule, model, checker, sentenceNameSource):
             return minSet
     return None
开发者ID:hobson,项目名称:ggpy,代码行数:32,代码来源:CondensationIsolator.py

示例12: makeNextAssignmentValid

 def makeNextAssignmentValid(self):
     """ generated source for method makeNextAssignmentValid """
     if self.nextAssignment == None:
         return
     # Something new that can pop up with functional constants...
     i = 0
     while i < len(self.nextAssignment):
         if self.nextAssignment.get(i) == None:
             # Some function doesn't agree with the answer here
             # So what do we increment?
             incrementIndex(self.plan.getIndicesToChangeWhenNull().get(i))
             if self.nextAssignment == None:
                 return
             i = -1
         i += 1
     # Find all the unsatisfied distincts
     # Find the pair with the earliest var. that needs to be changed
     varsToChange = ArrayList()
     d = 0
     while d < self.plan.getDistincts().size():
         # The assignments must use the assignments implied by nextAssignment
         if term1 == term2:
             # need to change one of these
             varsToChange.add(self.plan.getVarsToChangePerDistinct().get(d))
         d += 1
     if not varsToChange.isEmpty():
         # We want just the one, as it is a full restriction on its
         # own behalf
         changeOneInNext(Collections.singleton(varToChange))
开发者ID:hobson,项目名称:ggpy,代码行数:29,代码来源:AssignmentIteratorImpl.py

示例13: getPassportRedirectUrl

    def getPassportRedirectUrl(self, provider):

        # provider is assumed to exist in self.registeredProviders
        url = None
        try:
            facesContext = CdiUtil.bean(FacesContext)
            tokenEndpoint = "https://%s/passport/token" % facesContext.getExternalContext().getRequest().getServerName()

            httpService = CdiUtil.bean(HttpService)
            httpclient = httpService.getHttpsClient()

            print "Passport. getPassportRedirectUrl. Obtaining token from passport at %s" % tokenEndpoint
            resultResponse = httpService.executeGet(httpclient, tokenEndpoint, Collections.singletonMap("Accept", "text/json"))
            httpResponse = resultResponse.getHttpResponse()
            bytes = httpService.getResponseContent(httpResponse)

            response = httpService.convertEntityToString(bytes)
            print "Passport. getPassportRedirectUrl. Response was %s" % httpResponse.getStatusLine().getStatusCode()

            tokenObj = json.loads(response)
            url = "/passport/auth/%s/%s" % (provider, tokenObj["token_"])
        except:
            print "Passport. getPassportRedirectUrl. Error building redirect URL: ", sys.exc_info()[1]

        return url
开发者ID:GluuFederation,项目名称:community-edition-setup,代码行数:25,代码来源:PassportExternalAuthenticator.py

示例14: pyValToJavaObj

def pyValToJavaObj(val):
    retObj = val   
    valtype = type(val) 
    if valtype is int:
        retObj = Integer(val)
    elif valtype is float:
        retObj = Float(val)
    elif valtype is long:
        retObj = Long(val)
    elif valtype is bool:
        retObj = Boolean(val)
    elif valtype is list:
        retObj = ArrayList()
        for i in val:
            retObj.add(pyValToJavaObj(i))
    elif valtype is tuple:
        tempList = ArrayList()
        for i in val:
            tempList.add(pyValToJavaObj(i))
        retObj = Collections.unmodifiableList(tempList)
    elif issubclass(valtype, dict):
        retObj = pyDictToJavaMap(val)
    elif issubclass(valtype, JavaWrapperClass):
        retObj = val.toJavaObj()
    return retObj
开发者ID:KeithLatteri,项目名称:awips2,代码行数:25,代码来源:JUtil.py

示例15: mergeBaseRelations

 def mergeBaseRelations(self, rels):
     """ generated source for method mergeBaseRelations """
     merges = HashMap()
     for rel in rels:
         if not merges.containsKey(name):
             merges.put(name, ArrayList())
         addRelToMerge(rel, merge)
     rval = HashSet()
     valConst = GdlPool.getConstant("val")
     for c in merges.keySet():
         body.add(c)
         for mergeSet in merge:
             Collections.sort(ms2, SortTerms())
             body.add(GdlPool.getFunction(valConst, ms2))
         rval.add(toAdd)
     return rval
开发者ID:hobson,项目名称:ggpy,代码行数:16,代码来源:PropNetAnnotater.py


注:本文中的java.util.Collections类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。