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

Python mx.Tools类代码示例

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

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



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

示例1: clear_cache

    def clear_cache(self):

        """ Clears the caches used (flushing any data not yet
            written).
        """
        if self.caching:
            #self.flush()
            Tools.method_mapply(self.caches,'clear',())
开发者ID:cumtjie,项目名称:commcarehq-venv,代码行数:8,代码来源:BeeStorage.py


示例2: rpcdecode

def rpcdecode(url,prefix='',decode=1,

              splitat=TextTools.splitat,charsplit=TextTools.charsplit,
              len=len,tuple=tuple,urldecode=urldecode):

    """ Decode a RPC encoded function/method call.

        Returns a tuple (name,args,kws) where args is a tuple of
        string arguments and kws is a dictionary containing the given
        keyword parameters or None. All parameters are returned as
        strings; it is up to the caller to decode them into
        e.g. integers, etc.

        If prefix is given and found it is removed from the name prior
        to returning it. decode can be set to false to prevent the url
        from being urldecoded prior to processing.

        The decode function also supports the syntax 'method' instead
        of 'method()' for calls without arguments.

    """
    if decode:
        url = urldecode(url)
    # Decode the method: method[(arg0,arg1,...,kw0=val0,kw1=val1,...)]
    name,rawargs = splitat(url,'(')
    if rawargs:
        # Cut out the pure argument part, ignoring any character after 
        # the final ')'
        rawargs,rest = splitat(rawargs,')',-1)
        # Argument list: split at ','
        args = charsplit(rawargs,',')
        if '=' in rawargs:
            kws = {}
            for i,arg in Tools.reverse(Tools.irange(args)):
                if '=' in arg:
                    k,v = splitat(arg,'=')
                    kws[k] = v
                    del args[i]
        else:
            kws = None
        args = tuple(args)
    else:
        args = ()
        kws = None
    if prefix:
        if name[:len(prefix)] == prefix:
            name = name[len(prefix):]
        return name,args,kws
    else:
        return name,args,kws
开发者ID:GymWenFLL,项目名称:tpp_libs,代码行数:50,代码来源:URL.py


示例3: feed_list

    def feed_list(self,table):

        """ Feeds a table (list of rows) which is converted
            to CSV. 

            No more than len(columns) items are written for each
            row. All rows are filled up with "" entries to have an
            equal number of items. None entries are converted to empty
            strings, all other objects are stringified.

        """
        columns = self.columns
        if columns:
            rowlen = len(columns)
        else:
            # Calculate the max. number of columns in the table
            rowlen = max(map(len,table))

        # Prepare an empty table
        t = [None] * len(table)
        _quote = self._quote

        # Fill in data
        for i,row in Tools.irange(table):
            row = _quote(row[:rowlen])
            if len(row) < rowlen:
                row[len(row):] = ['""'] * (rowlen - len(row))
            t[i] = self.separator.join(row)

        # Add final CRLF and add as CSV text
        t.append('')
        self.text = self.text + self.lineend.join(t)
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:32,代码来源:CSV.py


示例4: print_stack

def print_stack(file=_sys.stdout,levels=100,offset=0,locals=0):

    # Prepare frames
    try:
        raise ValueError
    except ValueError:
        # Go back offset+1 frames...
        f = _sys.exc_info()[2].tb_frame
        for i in range(offset + 1):
            if f.f_back is not None:
                f = f.f_back

    # Extract frames
    frames = []
    while f:
        frames.append(f)
        f = f.f_back
    frames.reverse()

    # Prepare stack
    stack = _traceback.extract_stack()

    # Make output
    file.write('Stack:\n')
    for (frame,(filename, lineno, name, line)) in \
            Tools.tuples(frames,stack)[-levels:]:
        file.write(' File "%s", line %d, in %s\n' % (filename,lineno,name))
        if line:
            file.write('  %s\n' % line.strip())
        if locals:
            print_frame_locals(frame,file,indent='   |',title='')
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:31,代码来源:Log.py


示例5: print_recursive

def print_recursive(obj,file=_sys.stdout,indent='',levels=1,
                    nonrecursive=(),filter=None):

    # Filter out nonrecursive types and objects
    try:
        if type(obj) in nonrecursive or \
           obj in nonrecursive:
            return
    except:
        # Error during compares result in the object not being
        # printed
        return
    
    # Print the object depending on its interface
    if hasattr(obj,'__dict__') and \
       obj.__dict__ is not None:
        print_dict(obj.__dict__,file,indent,levels,
                   nonrecursive=nonrecursive, filter=filter)

    elif hasattr(obj,'items'):
        print_dict(obj,file,indent,levels,1,
                   nonrecursive=nonrecursive, filter=filter)

    elif Tools.issequence(obj) and not is_string(obj):
        print_sequence(obj,file,indent,levels,
                       nonrecursive=nonrecursive)

    elif hasattr(obj,'__members__'):
        d = {}
        for attr in obj.__members__:
            d[attr] = getattr(obj,attr)
        print_dict(d, file, indent, levels,
                   nonrecursive=nonrecursive, filter=filter)
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:33,代码来源:Log.py


示例6: search_bench

def search_bench(word, text):

    iterations = Tools.trange(COUNT)
    print ('Searching for all occurences of %r using ...' % word)

    t0 = time.time()
    so = TextTools.TextSearch(word)
    for i in iterations:
        l = so.findall(text)
    t1 = time.time()
    count = len(l)

    print (' - mx.TextSearch.TextSearch().findall(): %5.3f ms (%i)' %
           ((t1 - t0) / COUNT * 1000.0, count))

    t0 = time.time()
    so = re.compile(word)
    for i in iterations:
        l = so.findall(text)
    t1 = time.time()
    count = len(l)
    
    print (' - re.compile().findall(): %5.3f ms (%i)' %
           ((t1 - t0) / COUNT * 1000.0, count))

    t0 = time.time()
    for i in iterations:
        count = text.count(word)
    t1 = time.time()
    
    print (' - text.count(): %5.3f ms (%i)' %
           ((t1 - t0) / COUNT * 1000.0, count))
开发者ID:leetaizhu,项目名称:Odoo_ENV_MAC_OS,代码行数:32,代码来源:testkj.py


示例7: free

    def free(self,position,

             OLD=OLD,HOT=HOT):

        """ Deletes an already written record by marking it OLD.

            The next garbage collection will make the change permanent
            and free the occupied space.

        """
        if self.state != HOT:
            self.mark(HOT)
        file = self.file
        file.seek(position + 5)
        file.write(OLD)

        if self.caching:
            Tools.method_mapply(self.caches,'delete',(position,))
开发者ID:cumtjie,项目名称:commcarehq-venv,代码行数:18,代码来源:BeeStorage.py


示例8: objects

    def objects(self,constructor):

        """ Builds a list of objects by calling the given constructor
            with keywords defined by mapping column names to values for
            each input line.

            .columns must have been set using .set_columns() or by
            processing a given CSV header.

        """
        lines = self.lines
        keys = self.columns
        if keys is None:
            raise Error,'no columns set'
        objs = [None] * len(lines)
        for i,line in Tools.irange(lines):
            kws = dict(Tools.tuples(keys, line))
            objs[i] = apply(constructor,(),kws)
        return objs
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:19,代码来源:CSV.py


示例9: feed_dict

    def feed_dict(self,table,rows=None):

        """ Feeds a table (dict of lists) which is converted
            to CSV. 

            Only the keys set as column names are used to form the CSV
            data.

            All lists in the dictionary must have equal length or at
            least rows number of entries, if rows is given. None
            entries are converted to empty strings, all other objects
            are stringified.

        """
        columns = self.columns
        if not columns:
            raise Error,'no output columns set'
        rowlen = len(columns)

        # Create an emtpy table
        if not rows:
            rows = 0
            for column in columns:
                nrows = len(table[column])
                if nrows > rows:
                    rows = nrows
        rowindices = Tools.trange(rows)
        t = [None] * rows
        for i in rowindices:
            t[i] = [None] * rowlen
            
        # Fill the table
        for j,k in Tools.irange(columns):
            for i in rowindices:
                t[i][j] = table[k][i]
                
        # Quote and join lines
        t = [self.separator.join(self._quote(x)) for x in t]

        # Add final CRLF and store CSV text
        t.append('')
        self.text = self.text + self.lineend.join(t)
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:42,代码来源:CSV.py


示例10: _unquote

    def _unquote(self,line):

        """ Unquote a CSV style quoted line of text.

            Internal method. Do not use directly.
        
        """
        for i,text in Tools.irange(line):
            if text[:1] == '"' and text[-1:] == '"':
                text = text[1:-1]
            line[i] = text.replace('""','"')
        return line
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:12,代码来源:CSV.py


示例11: feed_objects

    def feed_objects(self,objects,

                     getattr=getattr):

        """ Feeds a sequence of objects which is converted to CSV. 

            For each object the set column names are interpreted as
            object attributes and used as basis for the CSV data.

            None values are converted to empty strings, all other
            attributes are added stringified.

        """
        columns = self.columns
        if not columns:
            raise Error,'no output columns set'
        rowlen = len(columns)

        # Create an emtpy table
        rows = len(objects)
        rowindices = Tools.trange(rows)
        t = [None] * rows
        for i in rowindices:
            t[i] = [None] * rowlen
            
        # Fill the table
        icols = Tools.irange(columns)
        for i in rowindices:
            obj = objects[i]
            for j,name in icols:
                t[i][j] = str(getattr(obj, name))
                
        # Quote and join lines
        t = [self.separator.join(self._quote(x)) for x in t]

        # Add final CRLF and store CSV text
        t.append('')
        self.text = self.text + self.lineend.join(t)
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:38,代码来源:CSV.py


示例12: dictionary

    def dictionary(self):

        """ Return the current data as dictionary of lists of strings,
            with one entry for each column.

            .columns must have been set using .set_columns() or by
            processing a given CSV header.

        """
        table = {}
        lines = self.lines
        keys = self.columns
        if keys is None:
            raise Error,'no columns set'
        rows = len(lines)
        for k in keys:
            table[k] = [None] * rows
        for i, key in Tools.irange(keys):
            column = table[key]
            for j, row in Tools.irange(lines):
                if len(row) > i:
                    column[j] = row[i]
        return table
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:23,代码来源:CSV.py


示例13: _quote

    def _quote(self, line,

               str=str):

        """ CSV style quote the given line of text.
        """
        nline = ['""'] * len(line)
        for i,item in Tools.irange(line):
            if item is not None:
                text = str(item)
            else:
                text = ''
            nline[i] = '"%s"' % text.replace('"','""')
        return nline
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:14,代码来源:CSV.py


示例14: _quote

    def _quote(self, line,

               str=str):

        """ CSV style quote the given line of text.
        """
        nline = ['""'] * len(line)
        for i,item in Tools.irange(line):
            if item is None:
                text = ''
            elif isinstance(item, unicode):
                text = item.encode(self.encoding)
            else:
                text = str(item)
            nline[i] = '"%s"' % text.replace('"','""')
        return nline
开发者ID:rfleschenberg,项目名称:egenix-mx-base-python-2x3,代码行数:16,代码来源:CSV.py


示例15: filter_header

    def filter_header(self, header,

                      lower=TextTools.lower):

        """ Filter the given header line.

            The base class converts the column names to all lowercase
            and removes any whitespace included in the header.

            This method is only called in case the header was read
            from the data provided to the object.

        """
        l = [''] * len(header)
        for i,column in Tools.irange(header):
            l[i] = ''.join(lower(column).split())
        return l
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:17,代码来源:CSV.py


示例16: list

    def list(self):

        """ Return the current data as list of lists, each having
            self.width string entries.

            Missing entries are set to None.

        """
        width = self.width
        lines = self.lines
        table = [None] * len(lines)
        for i, row in Tools.irange(lines):
            row = row[:]
            if len(row) < width:
                row[len(row):] = [None]*(width-len(row))
            table[i] = row
        return table
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:17,代码来源:CSV.py


示例17: __str__

    def __str__(self):

        lines = self.list()
        desc = self.description()
        width = 0
        output = []
        write = output.append
        for col in desc:
            write('%-*s|' % (col[1],col[0]))
        write('\n')
        for col in desc:
            write('=' * col[1] + '+')
        write('\n')
        for line in lines:
            for i,item in Tools.irange(line):
                write('%-*s|' % (desc[i][1],item))
            write('\n')
        return ''.join(output)
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:18,代码来源:CSV.py


示例18: print_sequence

def print_sequence(obj,file=_sys.stdout,indent='',levels=2,
                   nonrecursive=()):

    l = []
    unfold = 0
    try:
        length = len(obj)
    except (AttributeError, ValueError, TypeError):
        return
    
    for i in Tools.trange(min(length,_VALUE_LEN_LIMIT)):
        try:
            value = obj[i]
        except:
            break
        try:
            r = repr(value)
        except:
            r = '*repr()-error*'

        # Truncate
        if len(r) > _VALUE_LEN_LIMIT:
            r = r[:_VALUE_LEN_LIMIT] + '...'

        # Write value
        l.append((value,r))

        # Only unfold sequences that have non-string items or string items
        # with more than on character
        if not is_string(value) or len(value) > 1:
            unfold = 1
            
    if len(obj) > _VALUE_LEN_LIMIT:
        l.append(('...','...truncated...'))

    # Unfold value object
    if unfold:
        for i,(value,rvalue) in irange(l):
            file.write('%s%-15s = %s\n' % (indent, '[%i]' % i, rvalue))
            if levels > 1:
                print_recursive(value,file,indent + '  ',levels-1,
                                nonrecursive=nonrecursive)
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:42,代码来源:Log.py


示例19: description

    def description(self, header=1):

        """ Return a list of tuples (column name, max length) found in the
            data. 

            If header is true (default), the column names themselves
            are included in the calculation.

        """
        lines = self.lines
        columns = self.columns
        width = len(columns)
        if header:
            lengths = []
            for column in columns:
                lengths.append(len(column))
        else:
            lengths = [0] * width
        for row in self.lines:
            for i,o in Tools.irange(row[:width]):
                if len(o) > lengths[i]:
                    lengths[i] = len(o)
        return map(None,columns,lengths)
开发者ID:ArslanRafique,项目名称:dist-packages,代码行数:23,代码来源:CSV.py


示例20: cut

    def cut(self,

            NOM=NOM,DENOM=DENOM):

        """ Force a cut of the cache's contents.

            This will make room for at least one new entry.
        """
        if _debug:
            print '  Cutting down cache size...'
        cachesize = self.cachesize
            
        # Cut the cache down to the entries in recent get history
        newdata = {}
        known_key = newdata.has_key
        data = self.data
        for id in self.get_history[-self.locality:]:
            if known_key(id):
                continue
            try:
                newdata[id] = data[id]
            except KeyError:
                pass

        cachesize = len(newdata)
        if _debug:
            print '   Size after cut to recent history:',cachesize

        # Check
        if cachesize * NOM >= self.max_cachesize * DENOM:

            # Calculate weights
            d = {}
            weights = _weights
            d_get = d.get
            for i,id in Tools.irange(self.get_history[-self.locality:]):
                if not known_key(id):
                    continue
                d[id] = d_get(id,0) + weights[i]

            # Delete all entries left from median
            ranking = Tools.sortedby(d.items(),1)
            if _debug:
                print '   Ranking:',ranking
            for id,weight in ranking[:len(d)/2]:
                if _debug:
                    print '   Deleting',id,'with weight =',weight
                del newdata[id]

            # Check
            cachesize = len(newdata)

            if cachesize * NOM >= self.max_cachesize * DENOM:
                # Ok, so the smart way didn't work...
                if _debug:
                    print '   Did not work, going the hard way...'
                newdata.clear()
                cachesize = 0

        self.data = newdata
        self.cachesize = cachesize
        self.cuts = self.cuts + 1
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:62,代码来源:Cache.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python DateTime.now函数代码示例发布时间:2022-05-27
下一篇:
Python mx.DateTime类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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