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


Python dict函数代码示例

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


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

示例1: __init__

    def __init__(self, session: Session, config, loop=None):
        self.logger = logging.getLogger(__name__)
        self.session = session
        self.config = config
        if loop is None:
            self._loop = asyncio.get_event_loop()
        else:
            self._loop = loop
        self._reader_task = None
        self._writer_task = None
        self._inflight_task = None
        self._reader_ready = asyncio.Event(loop=self._loop)
        self._writer_ready = asyncio.Event(loop=self._loop)
        self._inflight_ready = asyncio.Event(loop=self._loop)
        self._inflight_changed = asyncio.Condition(loop=self._loop)

        self._running = False

        self.session.local_address, self.session.local_port = self.session.writer.get_extra_info("sockname")

        self.incoming_queues = dict()
        for p in PacketType:
            self.incoming_queues[p] = asyncio.Queue()
        self.outgoing_queue = asyncio.Queue()
        self.inflight_messages = dict()
开发者ID:gitter-badger,项目名称:hbmqtt,代码行数:25,代码来源:protocol.py

示例2: test_mode_full_timeout

 def test_mode_full_timeout(self):
     self.setupStep(
         bzr.Bzr(repourl='http://bzr.squid-cache.org/bzr/squid3/trunk',
                 mode='full', method='fresh', timeout=1))
     self.expectCommands(
         ExpectShell(workdir='wkdir',
                     timeout=1,
                     command=['bzr', '--version'])
         + 0,
         Expect('stat', dict(file='wkdir/.buildbot-patched',
                             logEnviron=True))
         + 1,
         Expect('stat', dict(file='wkdir/.bzr',
                             logEnviron=True))
         + 0,
         ExpectShell(workdir='wkdir',
                     timeout=1,
                     command=['bzr', 'clean-tree', '--force'])
         + 0,
         ExpectShell(workdir='wkdir',
                     timeout=1,
                     command=['bzr', 'update'])
         + 0,
         ExpectShell(workdir='wkdir',
                     timeout=1,
                     command=['bzr', 'version-info', '--custom', "--template='{revno}"])
         + ExpectShell.log('stdio',
                           stdout='100')
         + 0,
     )
     self.expectOutcome(result=SUCCESS, status_text=["update"])
     self.expectProperty('got_revision', '100', 'Bzr')
     return self.runStep()
开发者ID:DamnWidget,项目名称:buildbot,代码行数:33,代码来源:test_steps_source_bzr.py

示例3: create_filetree

def create_filetree(path=None, depth=0, max_depth=0):

    tree = None

    if max_depth == 0 or depth < max_depth:
        if path is None:
            path = os.getcwd()

        tree = dict(name=os.path.basename(path), children=[])

        try:
            lst = os.listdir(path)
        except OSError:
            pass  # ignore errors
        else:
            for name in lst:
                fn = os.path.join(path, name)
                if (os.path.isdir(fn) and
                        re.match('^.*(Compiled)$', fn) is None):
                    child = create_filetree(fn, depth + 1, max_depth)
                    if child is not None:
                        tree['children'].append(child)
                elif re.match('^.*\.(m|def|txt|csv)$', fn) is not None:
                    tree['children'].append(dict(name=fn.replace(
                        os.getcwd() + os.path.sep, "")))

    return tree
开发者ID:Data2Dynamics,项目名称:d2d,代码行数:27,代码来源:d2d_presenter_plotly.py

示例4: site

def site():
    """ Site handler """

    myversion = request.env.web2py_version

    # Shortcut to make the elif statements more legible
    file_or_appurl = 'file' in request.vars or 'appurl' in request.vars

    if DEMO_MODE:
        pass

    elif request.vars.filename and not 'file' in request.vars:
        # create a new application
        appname = cleanpath(request.vars.filename).replace('.', '_')
        if app_create(appname, request):
            if MULTI_USER_MODE:
                db.app.insert(name=appname,owner=auth.user.id)
            session.flash = T('new application "%s" created', appname)
            redirect(URL('design',args=appname))
        else:
            session.flash = \
                T('unable to create application "%s" (it may exist already)', request.vars.filename)
        redirect(URL(r=request))

    elif file_or_appurl and not request.vars.filename:
        # can't do anything without an app name
        msg = 'you must specify a name for the uploaded application'
        response.flash = T(msg)

    elif file_or_appurl and request.vars.filename:
        # fetch an application via URL or file upload
        f = None
        if request.vars.appurl is not '':
            try:
                f = urllib.urlopen(request.vars.appurl)
            except Exception, e:
                session.flash = DIV(T('Unable to download app because:'),PRE(str(e)))
                redirect(URL(r=request))
            fname = request.vars.appurl
        elif request.vars.file is not '':
            f = request.vars.file.file
            fname = request.vars.file.filename

        if f:
            appname = cleanpath(request.vars.filename).replace('.', '_')
            installed = app_install(appname, f, request, fname,
                                    overwrite=request.vars.overwrite_check)
        if f and installed:
            msg = 'application %(appname)s installed with md5sum: %(digest)s'
            session.flash = T(msg, dict(appname=appname,
                                        digest=md5_hash(installed)))
        elif f and request.vars.overwrite_check:
            msg = 'unable to install application "%(appname)s"'
            session.flash = T(msg, dict(appname=request.vars.filename))

        else:
            msg = 'unable to install application "%(appname)s"'
            session.flash = T(msg, dict(appname=request.vars.filename))

        redirect(URL(r=request))
开发者ID:markbree,项目名称:web2py,代码行数:60,代码来源:default.py

示例5: _sourcedirIsUpdatable

    def _sourcedirIsUpdatable(self):
        myFileWriter = StringFileWriter()
        args = {
                'workdir': self.build.path_module.join(self.workdir, 'CVS'),
                'writer': myFileWriter,
                'maxsize': None,
                'blocksize': 32*1024,
                }

        cmd = buildstep.RemoteCommand('uploadFile',
                dict(slavesrc='Root', **args),
                ignore_updates=True)
        yield self.runCommand(cmd)
        if cmd.rc is not None and cmd.rc != 0:
            defer.returnValue(False)
            return
        if myFileWriter.buffer.strip() != self.cvsroot:
            defer.returnValue(False)
            return

        myFileWriter.buffer = ""
        cmd = buildstep.RemoteCommand('uploadFile',
                dict(slavesrc='Repository', **args),
                ignore_updates=True)
        yield self.runCommand(cmd)
        if cmd.rc is not None and cmd.rc != 0:
            defer.returnValue(False)
            return
        if myFileWriter.buffer.strip() != self.cvsmodule:
            defer.returnValue(False)
            return

        defer.returnValue(True)
开发者ID:davidag,项目名称:buildbot,代码行数:33,代码来源:cvs.py

示例6: check

def check(cmd, mf):
    m = mf.findNode('PyQt5')
    if m and not isinstance(m, MissingModule):
        try:
            # PyQt5 with sipconfig module, handled
            # by sip recipe
            import sipconfig
            return None

        except ImportError:
            pass

        # All imports are done from C code, hence not visible
        # for modulegraph
        # 1. Use of 'sip'
        # 2. Use of other modules, datafiles and C libraries
        #    in the PyQt5 package.
        mf.import_hook('sip', m)
        if sys.version[0] != 2:
            return dict(packages=['PyQt5'],
                        expected_missing_imports=set(['copy_reg', 'cStringIO', 'StringIO']))
        else:
            return dict(packages=['PyQt5'])

    return None
开发者ID:asuc-octo,项目名称:tabulator,代码行数:25,代码来源:qt5.py

示例7: __compute_alternative_params

    def __compute_alternative_params(self):
        # Copied directly from skopt
        transformed_bounds = np.array(self.__opt.space.transformed_bounds)
        est = clone(self.__opt.base_estimator)

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            est.fit(self.__opt.space.transform(self.__opt.Xi), self.__opt.yi)

        X = self.__opt.space.transform(self.__opt.space.rvs(
            n_samples=self.__opt.n_points, random_state=self.__opt.rng))

        values = _gaussian_acquisition(X=X, model=est, y_opt=np.min(self.__opt.yi),
                                       acq_func='EI',
                                       acq_func_kwargs=dict(n_points=10000))

        print('original point ei: %s' % np.min(values))
        discount_width = .5
        values = self.__discount_leased_params(X, values, discount_width)
        while np.min(values) > -1e-5 and discount_width > 1e-2:
            discount_width *= .9
            values = _gaussian_acquisition(X=X, model=est, y_opt=np.min(self.__opt.yi),
                                           acq_func='EI',
                                           acq_func_kwargs=dict(n_points=10000))
            values = self.__discount_leased_params(X, values, discount_width)
        next_x = X[np.argmin(values)]
        print('new point ei: %s' % np.min(values))

        if not self.__opt.space.is_categorical:
            next_x = np.clip(next_x, transformed_bounds[:, 0], transformed_bounds[:, 1])

        return self.__opt.space.inverse_transform(next_x.reshape((1, -1)))[0]
开发者ID:mallamanis,项目名称:resultslogger,代码行数:32,代码来源:bayesoptqueue.py

示例8: parse

    def parse(self, basefile):
        # Find out possible skeleton entries by loading the entire
        # graph of resource references, and find resources that only
        # exist as objects.
        #
        # Note: if we used download_from_triplestore we know that this list
        #       is clean -- we could just iterate the graph w/o filtering
        g = Graph()
        self.log.info("Parsing %s" % basefile)
        g.parse(self.store.downloaded_path(basefile), format="nt")
        self.log.info("Compiling object set")
        # create a uri -> True dict mapping -- maybe?
        objects = dict(zip([str(o).split("#")[0] for (s, p, o) in g], True))
        self.log.info("Compiling subject set")
        subjects = dict(zip([str(s).split("#")[0] for (s, p, o) in g], True))
        self.log.info("%s objects, %s subjects. Iterating through existing objects" %
                      (len(objects), len(subjects)))

        for o in objects:
            if not o.startswith(self.config.url):
                continue
            if '9999:999' in o:
                continue
            if o in subjects:
                continue
            for repo in otherrepos:
                skelbase = repo.basefile_from_uri(repo)
                if skelbase:
                    skel = repo.triples_from_uri(o)  # need to impl
                    with self.store.open_distilled(skelbase, "wb") as fp:
                        fp.write(skel.serialize(format="pretty-xml"))

                    self.log.info("Created skel for %s" % o)
开发者ID:h4ck3rm1k3,项目名称:ferenda,代码行数:33,代码来源:skeleton.py

示例9: close

    def close(self):
        """
        Shut down the UnitManager, and all umgr components.
        """

        # we do not cancel units at this point, in case any component or pilot
        # wants to continue to progress unit states, which should indeed be
        # independent from the umgr life cycle.

        if self._closed:
            return

        self._terminate.set()
        self.stop()

        self._rep.info('<<close unit manager')

        # we don't want any callback invokations during shutdown
        # FIXME: really?
        with self._cb_lock:
            self._callbacks = dict()
            for m in rpt.UMGR_METRICS:
                self._callbacks[m] = dict()

        self._log.info("Closed UnitManager %s." % self._uid)

        self._closed = True
        self._rep.ok('>>ok\n')
开发者ID:radical-cybertools,项目名称:radical.pilot,代码行数:28,代码来源:unit_manager.py

示例10: testGetSetProperties

    def testGetSetProperties(self):
        self.addEngine(4)
        dikt = dict(a=5, b='asdf', c=True, d=None, e=list(range(5)))
        d= self.multiengine.set_properties(dikt)
        d.addCallback(lambda r: self.multiengine.get_properties())
        d.addCallback(lambda r: self.assertEquals(r, 4*[dikt]))
        d.addCallback(lambda r: self.multiengine.get_properties(('c',)))
        d.addCallback(lambda r: self.assertEquals(r, 4*[{'c': dikt['c']}]))
        d.addCallback(lambda r: self.multiengine.set_properties(dict(c=False)))
        d.addCallback(lambda r: self.multiengine.get_properties(('c', 'd')))
        d.addCallback(lambda r: self.assertEquals(r, 4*[dict(c=False, d=None)]))

        #Non-blocking
        d.addCallback(lambda r: self.multiengine.set_properties(dikt, block=False))
        d.addCallback(lambda did: self.multiengine.get_pending_deferred(did, True))
        d.addCallback(lambda r: self.multiengine.get_properties(block=False))
        d.addCallback(lambda did: self.multiengine.get_pending_deferred(did, True))
        d.addCallback(lambda r: self.assertEquals(r, 4*[dikt]))
        d.addCallback(lambda r: self.multiengine.get_properties(('c',), block=False))
        d.addCallback(lambda did: self.multiengine.get_pending_deferred(did, True))
        d.addCallback(lambda r: self.assertEquals(r, 4*[{'c': dikt['c']}]))
        d.addCallback(lambda r: self.multiengine.set_properties(dict(c=False), block=False))
        d.addCallback(lambda did: self.multiengine.get_pending_deferred(did, True))
        d.addCallback(lambda r: self.multiengine.get_properties(('c', 'd'), block=False))
        d.addCallback(lambda did: self.multiengine.get_pending_deferred(did, True))
        d.addCallback(lambda r: self.assertEquals(r, 4*[dict(c=False, d=None)]))
        return d
开发者ID:sunqiang,项目名称:ipython-py3k,代码行数:27,代码来源:multienginetest.py

示例11: test_existing_lcd_partial

 def test_existing_lcd_partial(self):
     commit1 = self._add_commit('Commit 1', ['file1'])
     commit2 = self._add_commit('Commit 2', ['file1', 'file2'], ['file2'], [commit1])
     commit3 = self._add_commit('Commit 3', ['file1', 'file2', 'file3'], ['file3'], [commit2])
     commit4 = self._add_commit('Commit 4', ['file1', 'file2', 'file3', 'file4'], ['file2', 'file4'], [commit3])
     prev_lcd = M.repository.LastCommit(
         path='',
         commit_id=commit3._id,
         entries=[
             dict(
                 name='file1',
                 commit_id=commit1._id),
             dict(
                 name='file2',
                 commit_id=commit2._id),
             dict(
                 name='file3',
                 commit_id=commit3._id),
         ],
     )
     session(prev_lcd).flush()
     lcd = M.repository.LastCommit.get(commit4.tree)
     self.assertEqual(self.repo._commits[lcd.commit_id].message, commit4.message)
     self.assertEqual(lcd.path, '')
     self.assertEqual(len(lcd.entries), 4)
     self.assertEqual(lcd.by_name['file1'], commit1._id)
     self.assertEqual(lcd.by_name['file2'], commit4._id)
     self.assertEqual(lcd.by_name['file3'], commit3._id)
     self.assertEqual(lcd.by_name['file4'], commit4._id)
开发者ID:abhinavthomas,项目名称:allura,代码行数:29,代码来源:test_repo.py

示例12: get_sortable_columns

    def get_sortable_columns(self):
        """
            Returns a dictionary of the sortable columns. Key is a model
            field name and value is sort column (for example - attribute).

            If `column_sortable_list` is set, will use it. Otherwise, will call
            `scaffold_sortable_columns` to get them from the model.
        """
        self._sortable_joins = dict()

        if self.column_sortable_list is None:
            return self.scaffold_sortable_columns()
        else:
            result = dict()

            for c in self.column_sortable_list:
                if isinstance(c, tuple):
                    column, path = self._get_field_with_path(c[1])
                    column_name = c[0]
                elif isinstance(c, InstrumentedAttribute):
                    column, path = self._get_field_with_path(c)
                    column_name = str(c)
                else:
                    column, path = self._get_field_with_path(c)
                    column_name = c

                result[column_name] = column

                if path:
                    self._sortable_joins[column_name] = path

            return result
开发者ID:bartaelterman,项目名称:snippets,代码行数:32,代码来源:view.py

示例13: save

    def save(self, request, datastream_rev=None, visualization_rev=None):
        if datastream_rev:
            lifecycle = VisualizationLifeCycleManager(user=request.user)
            visualization_rev = lifecycle.create(datastream_rev, language=request.user.language,  **self.cleaned_data)

            return dict(
                status='ok',
                revision_id=visualization_rev.id,
                messages=[ugettext('APP-VISUALIZATION-CREATEDSUCCESSFULLY-TEXT')]
            )
        elif visualization_rev:
            lifecycle = VisualizationLifeCycleManager(
                user=request.user,
                visualization_revision_id=visualization_rev['visualization_revision_id']
            )
            visualization_rev = lifecycle.edit(
                language=request.auth_manager.language,
                changed_fields=self.changed_data,
                **self.cleaned_data
            )
            return dict(
                status='ok',
                revision_id=visualization_rev.id,
                messages=[ugettext('APP-VISUALIZATION-CREATEDSUCCESSFULLY-TEXT')]
            )
开发者ID:anukat2015,项目名称:datal,代码行数:25,代码来源:forms.py

示例14: _compute_graph

 def _compute_graph(self):
     stack=[self.begin]
     index=dict()
     rindex=dict()
     count=Counter()
     graph=dict()
     def enter(state):
         n = count.get()
         index[state] = n
         rindex[n] = state
     enter(self.begin)
     while stack:
         I=stack.pop()
         table=dict()
         for X in self.grammar.symbols:
             transition=self.transition(I,X)
             if transition:
                 table[X]=transition
                 if transition not in index:
                     enter(transition)
                     stack.append(transition)
         graph[I]=table
     self._graph=graph
     self._index=index
     self._rindex=rindex
开发者ID:spetitjean,项目名称:XMG-2,代码行数:25,代码来源:LR0.py

示例15: test_height

 def test_height(self):
     prefix='thumb_'
     meta = dict(thumbnails=[dict(height=50, prefix=prefix, include=['*.jpg'])])
     self._test_generic_thumbnails(meta)
     for fn in IMAGES:
         im = Image.open(self._deployed_image(prefix, fn))
         assert im.size[1] == 50
开发者ID:AlfiyaZi,项目名称:hyde,代码行数:7,代码来源:test_images.py


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