Python types.DictType() Examples

The following are 30 code examples of types.DictType(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module types , or try the search function .
Example #1
Source File: Switchboard.py    From oss-ftp with MIT License 7 votes vote down vote up
def __init__(self, initfile):
        self.__initfile = initfile
        self.__colordb = None
        self.__optiondb = {}
        self.__views = []
        self.__red = 0
        self.__green = 0
        self.__blue = 0
        self.__canceled = 0
        # read the initialization file
        fp = None
        if initfile:
            try:
                try:
                    fp = open(initfile)
                    self.__optiondb = marshal.load(fp)
                    if not isinstance(self.__optiondb, DictType):
                        print >> sys.stderr, \
                              'Problem reading options from file:', initfile
                        self.__optiondb = {}
                except (IOError, EOFError, ValueError):
                    pass
            finally:
                if fp:
                    fp.close() 
Example #2
Source File: bartercast.py    From p2ptv-pi with MIT License 6 votes vote down vote up
def validBarterCastMsg(self, bartercast_data):
        if not type(bartercast_data) == DictType:
            raise RuntimeError, 'bartercast: received data is not a dictionary'
            return False
        if not bartercast_data.has_key('data'):
            raise RuntimeError, "bartercast: 'data' key doesn't exist"
            return False
        if not type(bartercast_data['data']) == DictType:
            raise RuntimeError, "bartercast: 'data' value is not dictionary"
            return False
        for permid in bartercast_data['data'].keys():
            if not bartercast_data['data'][permid].has_key('u') or not bartercast_data['data'][permid].has_key('d'):
                raise RuntimeError, "bartercast: datafield doesn't contain 'u' or 'd' keys"
                return False

        return True 
Example #3
Source File: Switchboard.py    From datafari with Apache License 2.0 6 votes vote down vote up
def __init__(self, initfile):
        self.__initfile = initfile
        self.__colordb = None
        self.__optiondb = {}
        self.__views = []
        self.__red = 0
        self.__green = 0
        self.__blue = 0
        self.__canceled = 0
        # read the initialization file
        fp = None
        if initfile:
            try:
                try:
                    fp = open(initfile)
                    self.__optiondb = marshal.load(fp)
                    if not isinstance(self.__optiondb, DictType):
                        print >> sys.stderr, \
                              'Problem reading options from file:', initfile
                        self.__optiondb = {}
                except (IOError, EOFError, ValueError):
                    pass
            finally:
                if fp:
                    fp.close() 
Example #4
Source File: utilities.py    From timeseries with MIT License 6 votes vote down vote up
def table_output(data):
    '''Get a table representation of a dictionary.'''
    if type(data) == DictType:
        data = data.items()
    headings = [ item[0] for item in data ]
    rows = [ item[1] for item in data ]
    columns = zip(*rows)
    if len(columns):
        widths = [ max([ len(str(y)) for y in row ]) for row in rows ]
    else:
        widths = [ 0 for c in headings ]
    for c, heading in enumerate(headings):
        widths[c] = max(widths[c], len(heading))
    column_count = range(len(rows))
    table = [ ' '.join([ headings[c].ljust(widths[c]) for c in column_count ]) ]
    table.append(' '.join([ '=' * widths[c] for c in column_count ]))
    for column in columns:
        table.append(' '.join([ str(column[c]).ljust(widths[c]) for c in column_count ]))
    return '\n'.join(table) 
Example #5
Source File: exception.py    From girlfriend with MIT License 6 votes vote down vote up
def __init__(self, msg):
        """
            :param msg 可以是一个字符串,也可以是一个key为locale的字典
        """
        if isinstance(msg, types.DictType):
            country_code, _ = locale.getlocale(locale.LC_ALL)
            msg = msg[country_code]

        if isinstance(msg, unicode):
            super(GirlFriendException, self).__init__(msg.encode("utf-8"))
            self.msg = msg
        elif isinstance(msg, str):
            super(GirlFriendException, self).__init__(msg)
            self.msg = msg.decode("utf-8")
        else:
            raise TypeError 
Example #6
Source File: table.py    From girlfriend with MIT License 6 votes vote down vote up
def _get_table_type(self, data):
        # 自动推断应该使用的table类型
        if self._table_type is not None:
            return self._table_type

        # 空列表
        if data is None or len(data) == 0:
            return ListTable

        # 默认取第一行进行推断
        row = data[0]
        if isinstance(row, SequenceCollectionType):
            return ListTable
        elif isinstance(row, types.DictType):
            return DictTable
        else:
            return ObjectTable 
Example #7
Source File: sstruct.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def unpack(format, data, object=None):
	if object is None:
		object = {}
	formatstring, names, fixes = getformat(format)
	if type(object) is types.DictType:
		dict = object
	else:
		dict = object.__dict__
	elements = struct.unpack(formatstring, data)
	for i in range(len(names)):
		name = names[i]
		value = elements[i]
		if fixes.has_key(name):
			# fixed point conversion
			value = value / fixes[name]
		dict[name] = value
	return object 
Example #8
Source File: queue_manager.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def append(self, dict_obj):
        """
            Appended in list object a dictionary that represents
            the body of the message that will be sent to queue.

            :param dict_obj: Dict object

        """

        try:

            if not isinstance(dict_obj, types.DictType):
                raise ValueError(
                    u'QueueManagerError - The type must be a instance of Dict')

            self._msgs.append(dict_obj)
            self.log.debug('dict_obj:%s', dict_obj)

        except Exception, e:
            self.log.error(
                u'QueueManagerError - Error on appending objects to queue.')
            self.log.error(e)
            raise Exception(
                'QueueManagerError - Error on appending objects to queue.') 
Example #9
Source File: ut_pex.py    From p2ptv-pi with MIT License 6 votes vote down vote up
def check_ut_pex(d):
    if type(d) != DictType:
        raise ValueError('ut_pex: not a dict')
    same_apeers = []
    apeers = check_ut_pex_peerlist(d, 'added')
    dpeers = check_ut_pex_peerlist(d, 'dropped')
    if 'added.f' in d:
        addedf = d['added.f']
        if type(addedf) != StringType:
            raise ValueError('ut_pex: added.f: not string')
        if len(addedf) != len(apeers) and not len(addedf) == 0:
            raise ValueError('ut_pex: added.f: more flags than peers')
        addedf = map(ord, addedf)
        for i in range(min(len(apeers), len(addedf)) - 1, -1, -1):
            if addedf[i] & 4:
                same_apeers.append(apeers.pop(i))
                addedf.pop(i)

    if DEBUG:
        print >> sys.stderr, 'ut_pex: Got', apeers
    return (same_apeers, apeers, dpeers) 
Example #10
Source File: coverage.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def restore(self):
        global c
        c = {}
        self.cexecuted = {}
        if not os.path.exists(self.cache):
            return
        try:
            cache = open(self.cache, 'rb')
            import marshal
            cexecuted = marshal.load(cache)
            cache.close()
            if isinstance(cexecuted, types.DictType):
                self.cexecuted = cexecuted
        except:
            pass

    # canonical_filename(filename).  Return a canonical filename for the
    # file (that is, an absolute path with no redundant components and
    # normalized case).  See [GDR 2001-12-04b, 3.3]. 
Example #11
Source File: recipe-302742.py    From code with MIT License 6 votes vote down vote up
def _CheckSequence(self, newseq, oldseq, checklen=True):
        """ Scan sequence comparing new and old values of individual items
            return True when the first difference is found.
            Compare sequence lengths if checklen is True. It is False on first 
            call because self.__dict__ has _snapshot as an extra entry 
        """
        if checklen and len(newseq) <> len(oldseq):
            return True
        if type(newseq) is types.DictType:
            for key in newseq:
                if key == '_snapshot':
                    continue
                if key not in oldseq:
                    return True
                if self._CheckItem(newseq[key], oldseq[key]):
                    return True
        else:
            for k in range(len(newseq)):
                if self._CheckItem(newseq[k], oldseq[k]):
                    return True
        return 0 
Example #12
Source File: monitoring.py    From automatron with Apache License 2.0 6 votes vote down vote up
def schedule(scheduler, runbook, target, config, dbc, logger):
    ''' Setup schedule for new runbooks and targets '''
    # Default schedule (every minute)
    task_schedule = {
        'second' : 0,
        'minute' : '*',
        'hour' : '*',
        'day' : '*',
        'month' : '*',
        'day_of_week' : '*'
    }
    # If schedule is present override default
    if 'schedule' in target['runbooks'][runbook].keys():
        if type(target['runbooks'][runbook]['schedule']) == types.DictType:
            for key in target['runbooks'][runbook]['schedule'].keys():
                task_schedule[key] = target['runbooks'][runbook]['schedule'][key]
        elif type(target['runbooks'][runbook]['schedule']) == types.StringType:
            breakdown = target['runbooks'][runbook]['schedule'].split(" ")
            task_schedule = {
                'second' : 0,
                'minute' : breakdown[0],
                'hour' : breakdown[1],
                'day' : breakdown[2],
                'month' :  breakdown[3],
                'day_of_week' : breakdown[4]
            }
    cron = CronTrigger(
        second=task_schedule['second'],
        minute=task_schedule['minute'],
        hour=task_schedule['hour'],
        day=task_schedule['day'],
        month=task_schedule['month'],
        day_of_week=task_schedule['day_of_week'],
    )
    return scheduler.add_job(
        monitor,
        trigger=cron,
        args=[runbook, target, config, dbc, logger]
    ) 
Example #13
Source File: aot.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def prettify(obj):
    if hasattr(obj, 'getSource'):
        return obj.getSource()
    else:
        #basic type
        t = type(obj)

        if t in _SIMPLE_BUILTINS:
            return repr(obj)

        elif t is types.DictType:
            out = ['{']
            for k,v in obj.items():
                out.append('\n\0%s: %s,' % (prettify(k), prettify(v)))
            out.append(len(obj) and '\n\0}' or '}')
            return string.join(out, '')

        elif t is types.ListType:
            out = ["["]
            for x in obj:
                out.append('\n\0%s,' % prettify(x))
            out.append(len(obj) and '\n\0]' or ']')
            return string.join(out, '')

        elif t is types.TupleType:
            out = ["("]
            for x in obj:
                out.append('\n\0%s,' % prettify(x))
            out.append(len(obj) and '\n\0)' or ')')
            return string.join(out, '')
        else:
            raise TypeError("Unsupported type %s when trying to prettify %s." % (t, obj)) 
Example #14
Source File: optparse.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def __cmp__(self, other):
        if isinstance(other, Values):
            return cmp(self.__dict__, other.__dict__)
        elif isinstance(other, types.DictType):
            return cmp(self.__dict__, other)
        else:
            return -1 
Example #15
Source File: optparse.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not callable(self.callback):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example #16
Source File: expsuite.py    From htmpapers with GNU Affero General Public License v3.0 5 votes vote down vote up
def expand_param_list(self, paramlist):
        """ expands the parameters list according to one of these schemes:
            grid: every list item is combined with every other list item
            list: every n-th list item of parameter lists are combined 
        """
        # for one single experiment, still wrap it in list
        if type(paramlist) == types.DictType:
            paramlist = [paramlist]
        
        # get all options that are iteratable and build all combinations (grid) or tuples (list)
        iparamlist = []
        for params in paramlist:
            if ('experiment' in params and params['experiment'] == 'single'):
                iparamlist.append(params)
            else:
                iterparams = [p for p in params if hasattr(params[p], '__iter__')]
                if len(iterparams) > 0:
                    # write intermediate config file
                    self.mkdir(os.path.join(params['path'], params['name']))
                    self.write_config_file(params, os.path.join(params['path'], params['name']))

                    # create sub experiments (check if grid or list is requested)
                    if 'experiment' in params and params['experiment'] == 'list':
                        iterfunc = itertools.izip
                    elif ('experiment' not in params) or ('experiment' in params and params['experiment'] == 'grid'):
                        iterfunc = itertools.product
                    else:
                        raise SystemExit("unexpected value '%s' for parameter 'experiment'. Use 'grid', 'list' or 'single'."%params['experiment'])

                    for il in iterfunc(*[params[p] for p in iterparams]):
                        par = params.copy()
                        converted = str(zip(iterparams, map(convert_param_to_dirname, il)))
                        par['name'] = par['name'] + '/' + re.sub("[' \[\],()]", '', converted)
                        for i, ip in enumerate(iterparams):
                            par[ip] = il[i]
                        iparamlist.append(par)
                else:
                    iparamlist.append(params)

        return iparamlist 
Example #17
Source File: optparse.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example #18
Source File: aot.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def prettify(obj):
    if hasattr(obj, 'getSource'):
        return obj.getSource()
    else:
        #basic type
        t = type(obj)

        if t in _SIMPLE_BUILTINS:
            return repr(obj)

        elif t is types.DictType:
            out = ['{']
            for k,v in obj.items():
                out.append('\n\0%s: %s,' % (prettify(k), prettify(v)))
            out.append(len(obj) and '\n\0}' or '}')
            return string.join(out, '')

        elif t is types.ListType:
            out = ["["]
            for x in obj:
                out.append('\n\0%s,' % prettify(x))
            out.append(len(obj) and '\n\0]' or ']')
            return string.join(out, '')

        elif t is types.TupleType:
            out = ["("]
            for x in obj:
                out.append('\n\0%s,' % prettify(x))
            out.append(len(obj) and '\n\0)' or ')')
            return string.join(out, '')
        else:
            raise TypeError("Unsupported type %s when trying to prettify %s." % (t, obj)) 
Example #19
Source File: aot.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def getSource(self):
        #XXX make state be foo=bar instead of a dict.
        if self.stateIsDict:
            stateDict = self.state
        elif isinstance(self.state, Ref) and isinstance(self.state.obj, types.DictType):
            stateDict = self.state.obj
        else:
            stateDict = None
        if stateDict is not None:
            try:
                return "Instance(%r, %s)" % (self.klass, dictToKW(stateDict))
            except NonFormattableDict:
                return "Instance(%r, %s)" % (self.klass, prettify(stateDict))
        return "Instance(%r, %s)" % (self.klass, prettify(self.state)) 
Example #20
Source File: aot.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getSource(self):
        #XXX make state be foo=bar instead of a dict.
        if self.stateIsDict:
            stateDict = self.state
        elif isinstance(self.state, Ref) and isinstance(self.state.obj, types.DictType):
            stateDict = self.state.obj
        else:
            stateDict = None
        if stateDict is not None:
            try:
                return "Instance(%r, %s)" % (self.klass, dictToKW(stateDict))
            except NonFormattableDict:
                return "Instance(%r, %s)" % (self.klass, prettify(stateDict))
        return "Instance(%r, %s)" % (self.klass, prettify(self.state)) 
Example #21
Source File: QuestPath.py    From Pirates-Online-Rewritten with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getTargetType(self):
        if self.__goalType == types.DictType:
            return self.__goalData.get(self.TYPE_IDX)
        return (0, 0, 0, 0) 
Example #22
Source File: web_utils.py    From htcondor-ce with Apache License 2.0 5 votes vote down vote up
def ad_to_json(ad):
    result = {}
    for key in ad:
        val_expr = ad.lookup(key)
        if classad.ExprTree("%s =?= UNDEFINED" % key).eval(ad):
            result[key] = {"_condor_type": "expr", "expr": val_expr.__repr__()}
        else:
            val = val_expr.eval()
            if isinstance(val, types.ListType) or isinstance(val, types.DictType):
                result[key] = {"_condor_type": "expr", "expr": val_expr.__repr__()}
            else:
                result[key] = val
    return result 
Example #23
Source File: concurrent.py    From girlfriend with MIT License 5 votes vote down vote up
def _execute(self, context, sub_args):
        executable = self._get_executable(context)
        results = []
        for args in sub_args:
            if self._error_break:  # 检查任务是否已被中断
                return
            try:
                result = None
                if args is None:
                    result = executable(context)
                elif isinstance(args, SequenceCollectionType):
                    result = executable(context, *args)
                elif isinstance(args, types.DictType):
                    result = executable(context, **args)
            except Exception as e:
                context.logger.exception(
                    u"并行任务'{}'的子任务运行出错,处理方式为:'{}'".format(
                        self.name, self._error_action))
                if self._error_action == "stop":
                    # rethrow异常,中断工作流
                    self._error_break = True  # 标记任务已中断
                    raise e
                elif self._error_action == "continue":
                    # 调用用户自定义error_handler
                    if self._error_handler is not None:
                        exc_type, exc_value, tb = sys.exc_info()
                        self._error_handler(context, exc_type, exc_value, tb)
                    # 被忽略任务的结果作为None添加到结果列表
                    results.append(self._error_default_value)
            else:
                results.append(result)

        if self._sub_join is not None:
            return self._sub_join(context, results)
        return results 
Example #24
Source File: table.py    From girlfriend with MIT License 5 votes vote down vote up
def append(self, row):
        if not isinstance(row, types.DictType):
            raise InvalidTypeException(u"DictTable只能接受字典类型的行对象")
        if len(row) != self.column_num:
            raise InvalidSizeException(
                u"新行的列数为{0},表格的列数为{1},两者不一致".format(len(row), self.column_num)
            )
        self._data.append(row) 
Example #25
Source File: orm.py    From girlfriend with MIT License 5 votes vote down vote up
def __call__(self, query_result):
        if not query_result:
            return {}
        row_0 = query_result[0]
        if isinstance(row_0,
                      (types.ListType, types.TupleType, types.DictType)):
            return {row[self._key_index]: row for row in query_result}
        return {getattr(row, self._key_index): row for row in query_result} 
Example #26
Source File: recipe-302742.py    From code with MIT License 5 votes vote down vote up
def _CopyItem(self, item):
        """ Return shallow copy of item. If item is a sequence, recursively
            shallow copy each member that is also a sequence
        """ 
        newitem = copy.copy(item)
        if type(newitem) is types.DictType:
            for key in newitem:
                if type(newitem[key]) in SeqType:
                    newitem[key] = self._CopyItem(newitem[key])
        elif type(newitem) is types.ListType:
            for k in range(len(newitem)):
                if type(newitem[k]) in SeqType:
                    newitem[k] = self._CopyItem(newitem[k])
        return newitem 
Example #27
Source File: recipe-334621.py    From code with MIT License 5 votes vote down vote up
def __setitem__(self, i, row):
        if type(row) == types.DictType:
            row = [row[x] for x in self.columns]
        row = tuple(row)
        if len(row) != len(self.columns):
            raise TypeError, 'Row must contain %d elements.' % len(self.columns)
        self.rows[i] = row 
Example #28
Source File: recipe-334621.py    From code with MIT License 5 votes vote down vote up
def append(self, row):
        if type(row) == types.DictType:
            row = [row[x] for x in self.columns]
        row = tuple(row)
        if len(row) != len(self.columns):
            raise TypeError, 'Row must contain %d elements.' % len(self.columns)
        self.rows.append(row) 
Example #29
Source File: QuestPath.py    From Pirates-Online-Rewritten with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getLocation(self):
        if self.__goalType == types.DictType:
            return self.__goalData.get(self.LOCATION_IDX)
        return None 
Example #30
Source File: optparse.py    From meddle with MIT License 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self)