• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python DictUtils.DictUtils类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: _writeError

    def _writeError(self, data):
        """ Writes import error data to the logger, formatting it for human readable display. """
        source = {}

        if 'data' in data:
            for n,v in DictUtils.iter(data['data']):
                source[' '.join(n.split('_')).title()] = v

        indexPrefix = ''
        if 'index' in data:
            indexPrefix = ' [INDEX: %s]:' % data.get('index', 'Unknown')

        result  = [
            'IMPORT ERROR%s: %s' % (indexPrefix, data['message']),
            'DATA: ' + DictUtils.prettyPrint(source)]

        if 'existing' in data:
            source = {}
            snapshot = data['existing'].snapshot
            if snapshot:
                snapshot = JSON.fromString(snapshot)
            if snapshot:
                for n,v in DictUtils.iter(snapshot):
                    source[' '.join(n.split('_')).title()] = v
            result.append('CONFLICT: ' + DictUtils.prettyPrint(source))

        if 'error' in data:
            self._logger.writeError(result, data['error'])
        else:
            self._logger.write(result)
开发者ID:sernst,项目名称:Cadence,代码行数:30,代码来源:TrackCsvImporter.py


示例2: __call__

    def __call__(self):
        super(ZigguratDataView, self).__call__()
        if isinstance(self._response, Response) or StringUtils.isStringType(self._response):
            return self._response

        DictUtils.cleanBytesToText(self._response, inPlace=True)
        return render_to_response('json', self._response, self._request)
开发者ID:sernst,项目名称:Ziggurat,代码行数:7,代码来源:ZigguratDataView.py


示例3: test_closestPointOnLine

    def test_closestPointOnLine(self):
        """ doc... """
        count = 5000
        bound = 10000.0

        for i in range(count):
            start = PositionValue2D(
                x=random.uniform(-bound, bound),
                y=random.uniform(-bound, bound),
                xUnc=0.1,
                yUnc=0.1)

            end = PositionValue2D(
                x=random.uniform(-bound, bound) + start.x,
                y=random.uniform(-bound, bound) + start.y,
                xUnc=0.1,
                yUnc=0.1)

            line = LineSegment2D(start, end)
            if not line.isValid:
                continue

            target = line.getParametricPosition(random.uniform(0.0, 1.0))
            offset = random.uniform(1.0, bound)
            point  = line.adjustPointAlongLine(target, offset, inPlace=False)

            debug  = {
                'POINT':point,      'TARGET':target,
                'OFFSET':offset,    'DISTANCE':point.distanceTo(target) }

            self.assertAlmostEqual(
                offset, point.distanceTo(target).raw,
                msg='Invalid offset distance:\n'
                    + DictUtils.prettyPrint(debug, delimiter='\n'))

            point.rotate(Angle(degrees=90.0*random.choice([1.0, -1.0])), target)

            self.assertAlmostEqual(
                offset, point.distanceTo(target).raw,
                msg='Invalid rotated offset distance:\n'
                    + DictUtils.prettyPrint(debug, delimiter='\n'))

            pointOnLine = line.closestPointOnLine(point)
            xUnc = math.sqrt(pointOnLine.xUnc*pointOnLine.xUnc + target.xUnc*target.xUnc)
            yUnc = math.sqrt(pointOnLine.yUnc*pointOnLine.yUnc + target.yUnc*target.yUnc)
            debug = {
                'POINT':point,  'RESULT':pointOnLine,
                'INDEX':i,      'TARGET':target,
                'START':start,  'END':end,
                'X_UNC':xUnc,   'Y_UNC':yUnc }

            self.assertAlmostEqual(
                pointOnLine.x, target.x, delta=2.0*xUnc,
                msg='BAD RESULT [X]:\n' + DictUtils.prettyPrint(debug, delimiter='\n'))

            self.assertAlmostEqual(
                pointOnLine.y, target.y, delta=2.0*yUnc,
                msg='BAD RESULT [Y]:\n' + DictUtils.prettyPrint(debug, delimiter='\n'))
开发者ID:sernst,项目名称:Cadence,代码行数:58,代码来源:test_LineSegment2D.py


示例4: _postAnalyze

    def _postAnalyze(self):
        self.logger.write('TRACKWAY COUNT: %s' % self._weightedStats.count)
        self._weightedStats.save()
        self._unweightedStats.save()

        for key, csv in DictUtils.iter(self._quartileStats):
            csv.save()

        for label, paths in DictUtils.iter(self._densityPlots):
            self.mergePdfs(paths, '%s-Densities.pdf' % label.replace(' ', '-'))
开发者ID:sernst,项目名称:Cadence,代码行数:10,代码来源:TrackwayStatsStage.py


示例5: _postAnalyze

    def _postAnalyze(self):
        """_postAnalyze doc..."""

        ratios = []

        for name, curve in DictUtils.iter(self.data):
            segments = curve.segments

            for i in ListUtils.rangeOn(segments):
                segment = segments[i]
                segmentLine = segment.line

                # If this is an extrapolated segment, use the length from the neighboring segment
                # instead of the artificial length of this segment.
                if segment == segments[0]:
                    segmentLine = segments[i + 1].line
                elif segment == segments[-1]:
                    segmentLine = segments[i - 1].line

                for pairData in segment.pairs:
                    projectionLine = pairData["line"]
                    ratios.append(100.0 * projectionLine.length.raw / segmentLine.length.raw)

        h = Histogram(
            data=ratios,
            binCount=50,
            xLabel="Projection/Stride Ratio (%)",
            title="Relative Stride to Projection Length Ratios",
        )
        h.shaveDataToXLimits()
        self._paths.append(h.save(path=self.getTempFilePath(extension="pdf")))

        self.mergePdfs(self._paths, "Curve-Projection.pdf")
开发者ID:sernst,项目名称:Cadence,代码行数:33,代码来源:CurveProjectionStage.py


示例6: echo

 def echo(self):
     print('TARGET:',self.target)
     print('GAIT PHASE OFFSET:',self._phaseOffset)
     print('DUTY FACTOR:',self._dutyFactor)
     print('CHANNELS:')
     for n,v in DictUtils.iter(self._channels):
         print(v.toString())
开发者ID:sernst,项目名称:Cadence,代码行数:7,代码来源:TargetData.py


示例7: save

    def save(self, path =None):
        """ Saves the CSV file data to the specified path """
        if path is None:
            path = self.path

        if self.removeIfSavedEmpty and not self.rows:
            self.remove()
            return

        index = 0
        names = self.fieldNames
        if self.autoIndexFieldName:
            names.insert(0, self.autoIndexFieldName)

        try:
            with open(path, 'wb') as f:
                writer = csv.DictWriter(f, fieldnames=names, dialect=csv.excel)
                writer.writeheader()
                for row in self.rows:
                    result = dict()

                    if self.autoIndexFieldName:
                        index += 1
                        result[self.autoIndexFieldName] = index

                    for key, spec in DictUtils.iter(self._fields):
                        value = row.get(key, spec.get('empty', ''))
                        name = spec.get('name', key)
                        if StringUtils.isTextType(value):
                            value = value.encode('latin-1')
                        result[name] = value
                    writer.writerow(result)
            return True
        except Exception:
            return False
开发者ID:sernst,项目名称:Cadence,代码行数:35,代码来源:CsvWriter.py


示例8: __init__

    def __init__(self, **kwargs):
        """Creates a new instance of ConfigReader."""
        self._configs     = ArgsUtils.get('configs', dict(), kwargs)
        self._filenames   = ArgsUtils.get('filenames', None, kwargs)
        self._configPath  = ArgsUtils.get(
            'rootConfigPath',
            CadenceEnvironment.getConfigPath(),
            kwargs
        )

        if self._filenames:
            for n,v in DictUtils.iter(self._filenames):
                if not v:
                    continue

                path = os.path.join(self._configPath, v)
                if not path.endswith('.cfg'):
                    path += '.cfg'

                parser = ConfigParser.ConfigParser()
                if os.path.exists(path):
                    parser.read(path)
                else:
                    raise Exception(path + ' config file does not exist!')

                self._configs[n] = self._configParserToDict(parser)

        self._overrides = dict()
        self.setOverrides(ArgsUtils.get('overrides', None, kwargs))
开发者ID:sernst,项目名称:Cadence,代码行数:29,代码来源:ConfigReader.py


示例9: echoModel

    def echoModel(self):
        """ An example using a Ziggurat database model. Here a new entry of the ZigguratTest_Test
            model is created and added to the database and its index in differing radices is
            returned in the response.

            NOTE: The model class is imported in-line in this example simply to allow use of the
                Hello Ziggurat examples without model support for those not in an environment
                without the required database support. """

        try:
            from ziggHello.models.zigguratTest.ZigguratTest_Test import ZigguratTest_Test
            model = ZigguratTest_Test.MASTER

            out = dict()
            for name, value in DictUtils.iter(self._router.ziggurat.environ):
                if name.upper() == name:
                    out[name] = StringUtils.toUnicode(value)

            entry = model()
            entry.infoData = out
            model.session.add(entry)
            model.session.flush()
        except Exception as err:
            self._router.response['error'] = str(err)
            self._router.logger.writeError(u'MODEL ERROR', err)
            return

        self._router.response['index'] = [entry.i, entry.i16, entry.i36, entry.i64]
开发者ID:sernst,项目名称:Ziggurat,代码行数:28,代码来源:HelloController.py


示例10: _handleResponseReady

    def _handleResponseReady(self, request, response):
        """Event handler for the response object being ready for use."""

        if self._cacheControlPublic:
            response.cache_control = "public"

        # -------------------------------------------------------------------------------------------
        # Cache Expiration: Set the caching values according to the _expires property
        rep = self._explicitResponse
        if rep is None or (isinstance(rep, ViewResponse) and rep.allowCaching):
            response.cache_control.max_age = self.expires if not self.expires is None else 0
        else:
            response.cache_control.max_age = 0

        # -------------------------------------------------------------------------------------------
        # Cache Validators
        if self._etag is not None:
            response.etag = StringUtils.toUnicode(self._etag)

        if self._lastModified is not None:
            response.last_modified = self._lastModified

        # If required encode the response headers as strings to prevent unicode errors. This is
        # necessary for certain WSGI server applications, e.g. flup.
        if self.ziggurat.strEncodeEnviron:
            for n, v in DictUtils.iter(response.headers):
                if StringUtils.isStringType(v):
                    response.headers[n] = StringUtils.toStr2(v)

        # Clean up per-thread sessions.
        ConcreteModelsMeta.cleanupSessions()
开发者ID:sernst,项目名称:Ziggurat,代码行数:31,代码来源:ZigguratBaseView.py


示例11: getColorNameAndValue

    def getColorNameAndValue(self):
        """ Finds the nearest named color by comparing all named colors """
        if self._rawColor == 0:
            return {
                'name':'Black',
                'value':0,
                'key':'black',
                'residual':0.0 }

        maxRange = 560.0
        nearestValue = None
        nearestName  = None
        range   = 360
        myColor = self.asHsl(output=list)
        poolColor = self.__class__(0)
        for name, value in DictUtils.iter(ColorNames.NAMES):
            poolColor.load(value)
            color = poolColor.asHsl(output=list)

            test = (myColor[0] - color[0])*(myColor[0] - color[0]) \
                + (myColor[1] - color[1])*(myColor[1] - color[1]) \
                + (myColor[2] - color[2])*(myColor[2] - color[2])
            if test < range:
                nearestValue = value
                nearestName  = name
                range        = test
            if range < 1:
                break

        return {
            'name':StringUtils.capitalizeWords(nearestName.replace('_', ' ')),
            'value':nearestValue,
            'key':nearestName,
            'residual':100.0*range/maxRange }
开发者ID:sernst,项目名称:PyAid,代码行数:34,代码来源:ColorValue.py


示例12: currentChildWidgetID

 def currentChildWidgetID(self):
     if not self._currentWidget:
         return None
     for key, widget in DictUtils.iter(self._widgets):
         if widget == self._currentWidget:
             return key
     return None
开发者ID:sernst,项目名称:PyGlass,代码行数:7,代码来源:PyGlassWidget.py


示例13: getChannel

    def getChannel(self, kind):
        """Doc..."""
        for n,v in DictUtils.iter(self._channels):
            if n == kind:
                return v

        return None
开发者ID:sernst,项目名称:Cadence,代码行数:7,代码来源:TargetData.py


示例14: compileAllOnPath

    def compileAllOnPath(path, rootPath=None, recursive=False, debug=False, trace=False, force=False, compress=False):

        CoffeescriptBuilder._results = ""
        CoffeescriptBuilder._missing = {}
        if recursive:
            print("RECURSIVE COMPILE AT: " + path)

            def walker(paths, dirName, names):
                out = CoffeescriptBuilder._compileAllInDirectory(
                    os.path.join(paths[0], dirName), paths[1], debug=debug, trace=trace, force=force, compress=compress
                )
                CoffeescriptBuilder._results += out["res"]
                for n, v in DictUtils.iter(out["missing"]):
                    if n in CoffeescriptBuilder._missing:
                        continue
                    CoffeescriptBuilder._missing[n] = v

            FileUtils.walkPath(path, walker, [path, rootPath])
            print("\n\nCOMPILATION RESULTS:" + CoffeescriptBuilder._results)

            if CoffeescriptBuilder._missing:
                print("\n\nMISSING IMPORTS:" + "\n\n")
                for n, v in DictUtils.iter(CoffeescriptBuilder._missing):
                    print(v["class"] + " [LINE: #" + str(v["line"]) + " | " + v["package"] + "]")
        else:
            print("COMPILING DIRECTORY: " + path)
            CoffeescriptBuilder._compileAllInDirectory(
                path, rootPath, debug=debug, trace=trace, force=force, compress=compress
            )
开发者ID:sernst,项目名称:PyAid,代码行数:29,代码来源:CoffeescriptBuilder.py


示例15: addChannels

 def addChannels(self, channels):
     if isinstance(channels, list):
         for v in channels:
             self.addChannel(v)
     elif isinstance(channels, dict):
         for n, v in DictUtils.iter(channels):
             self.addChannel(v)
开发者ID:sernst,项目名称:Cadence,代码行数:7,代码来源:CadenceData.py


示例16: fromMessage

    def fromMessage(cls, message):
        if not message:
            return None

        try:
            if NimbleEnvironment.ENABLE_COMPRESSION:
                message = zlib.decompress(message)
            data = json.loads(message.replace(NimbleData._NEWLINE_ESCAPE, '\n').strip())
        except Exception as err:
            print('Corrupt Nimble Data:')
            print(str(message))
            print(err)
            return None

        data      = DictUtils.cleanDictKeys(data)
        className = data['class']
        if className == cls.__name__:
            return NimbleData(**data)

        module = ''
        try:
            module  = '.'.join(cls.__module__.split('.')[:-1]) + '.' + className
            res     = __import__(module, globals(), locals(), [className])
            Source  = getattr(res, className)
            return Source(**data)
        except Exception as err:
            print('Invalid Nimble data:')
            print('ERROR: ', err)
            print('MESSAGE:', message)
            print('DATA:', data)
            print('CLASS:', className)
            print('MODULE:', module)

        return None
开发者ID:sernst,项目名称:Nimble,代码行数:34,代码来源:NimbleData.py


示例17: print_track

def print_track(track, aSession):
    """

    @param track:
    @param aSession:
    @return:
    """

    limb_id = "{}{}".format("l" if track.left else "r", "p" if track.pes else "m")

    print(track.echoForVerification())
    print(
        "        size: (%s, %s) | field (%s, %s)"
        % (track.width, track.length, track.widthMeasured, track.lengthMeasured)
    )

    aTrack = track.getAnalysisPair(aSession)
    print(
        "        curve[#%s -> %s]: %s (%s)"
        % (
            aTrack.curveIndex,
            aTrack.curveSegment,
            NumericUtils.roundToSigFigs(aTrack.segmentPosition, 4),
            NumericUtils.roundToSigFigs(aTrack.curvePosition, 4),
        )
    )
    print("        snapshot: {}\n".format(DictUtils.prettyPrint(track.snapshotData)))

    return dict(limb_id=limb_id, track=track, aTrack=aTrack)
开发者ID:sernst,项目名称:Cadence,代码行数:29,代码来源:trackwayPrinter.py


示例18: setFromDict

    def setFromDict(self, keysAndValues):
        if not keysAndValues:
            return

        self._loadSettings()
        for key, value in DictUtils.iter(keysAndValues):
            self._updateSetting(key, value)
        self._saveSettings()
开发者ID:sernst,项目名称:PyAid,代码行数:8,代码来源:SettingsConfig.py


示例19: _instantiateClass

    def _instantiateClass(self, Target, command):
        k       = 'constructorArgs'
        conArgs = command[k] if k in command else None

        k         = 'constructorKwargs'
        conKwargs = command[k] if k in command else None

        if conArgs and conKwargs:
            targetObject = Target(*conArgs, **DictUtils.cleanDictKeys(conKwargs))
        elif conArgs:
            targetObject = Target(*conArgs)
        elif conKwargs:
            targetObject = Target(**DictUtils.cleanDictKeys(conKwargs))
        else:
            targetObject = Target()

        return targetObject
开发者ID:Gorfaal,项目名称:Nimble,代码行数:17,代码来源:MayaRouter.py


示例20: echoImportFlags

 def echoImportFlags(self, separator =' | '):
     """echoImportFlags doc..."""
     out = []
     d = Reflection.getReflectionDict(ImportFlagsEnum)
     for key, value in DictUtils.iter(d):
         if value & self.importFlags:
             out.append(key)
     return ('[%s]' % separator.join(out)) if out else '--'
开发者ID:sernst,项目名称:Cadence,代码行数:8,代码来源:TracksTrackDefault.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python FileUtils.FileUtils类代码示例发布时间:2022-05-25
下一篇:
Python Logger.Logger类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap