Exemple #1
0
def parse(fileobj, custom_parsers=None, key_hooks=[]):
    section_stack = []
    res = OrderedDict()
    for line in fileobj:
        line = line.strip()
        if not line:
            continue
        elif line.startswith('['):
            (depth, section_name) = parse_section(line)
            diff = len(section_stack) - depth + 1
            if diff < 0:
                msg = 'Too high depth for subsection, missed previous'
                raise ParseError(msg)
            for _ in range(diff):
                section_stack.pop()
            reduce(dict.__getitem__, section_stack, res)[section_name] = OrderedDict()
            section_stack.append(section_name)
        elif line.startswith('#') or line.startswith(';'):
            pass
        elif '=' in line:
            (key, value) = parse_assignment(line, custom_parsers=custom_parsers)
            section = reduce(dict.__getitem__, section_stack, res)
            for hook in (key_hooks + [default_key_hook]):
                if hook(section, key, value) is not None:
                    break
        else:
            raise ParseError('Unrecognized line: `{0}`'.format(line))
    return res
Exemple #2
0
def parse(fileobj, custom_parsers=None):
    section_stack = []
    res = {}
    for line in fileobj:
        line = line.strip()
        if not line:
            continue
        elif line.startswith("["):
            (depth, section_name) = parse_section(line)
            diff = len(section_stack) - depth + 1
            if diff < 0:
                msg = "Too high depth for subsection, missed previous"
                raise ParseError(msg)
            for _ in range(diff):
                section_stack.pop()

            reduce(dict.__getitem__, section_stack, res)[section_name] = {}
            section_stack.append(section_name)
        elif line.startswith("#") or line.startswith(";"):
            pass
        elif "=" in line:
            (key, value) = parse_assignment(line, custom_parsers=custom_parsers)
            reduce(dict.__getitem__, section_stack, res)[key] = value
        else:
            raise ParseError("Unrecognized line: `{0}`".format(line))
    return res
Exemple #3
0
def reduce(function, initval=None):
	"""
	Curried version of the built-in reduce.

	>>> reduce(lambda x,y: x+y)( [1, 2, 3, 4, 5] )
	15
	"""
	if initval is None:
		return lambda s: __builtin__.reduce(function, s)
	else:
		return lambda s: __builtin__.reduce(function, s, initval)
Exemple #4
0
 def get_all_project_incoming_messages(cls, contacts_list):
     if len(contacts_list) > 0:
         query = reduce(operator.or_, (Q(urn__contains=contact)
                                       for contact in contacts_list))
         return cls.objects.filter(query, direction='in').all()
     else:
         return "No project contacts yet"
Exemple #5
0
 def get_weekly_project_contacts(cls, project_groups_list):
     if len(project_groups_list) > 0:
         query = reduce(operator.or_, (Q(groups__contains=item) for item in project_groups_list))
         date_diff = datetime.datetime.now() - datetime.timedelta(days=7)
         return cls.objects.filter(query, created_on__range=(date_diff, datetime.datetime.now())).all()
     else:
         return "No projects added yet"
Exemple #6
0
    def rewrite(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        from __builtin__ import reduce

        if '' == digits:
            return []

        kvmaps = {
            '2': 'abc',
            '3': 'def',
            '4': 'ghi',
            '5': 'jkl',
            '6': 'mno',
            '7': 'pqrs',
            '8': 'tuv',
            '9': 'wxyz'
        }

        # reduce 的[''] 為initial, 就是 acc.
        # digit 為digits的sequence elements.
        # first 為 ['']
        # second 為 digits[0]
        return reduce(
            lambda first, second:
            [f + s for f in first for s in kvmaps[second]], digits, [''])
Exemple #7
0
 def get_project_contacts(cls, project_groups_list):
     if len(project_groups_list) > 0:
         query = reduce(operator.or_, (Q(groups__contains=item)
                                       for item in project_groups_list))
         return cls.objects.filter(query).all()
     else:
         return "No projects added yet"
Exemple #8
0
 def get_monthly_failed_messages(cls, contacts_list):
     if len(contacts_list) > 0:
         query = reduce(operator.or_, (Q(urn__contains=contact) for contact in contacts_list))
         date_diff = datetime.datetime.now() - datetime.timedelta(days=7)
         return cls.objects.filter(query, sent_on__range=(date_diff, datetime.datetime.now())).exclude(
             status='failed').all()
     else:
         return "No project contacts yet"
Exemple #9
0
 def get_all_project_outgoing_messages(cls, contacts_list):
     if len(contacts_list) > 0:
         query = reduce(operator.or_, (Q(urn__contains=contact)
                                       for contact in contacts_list))
         return cls.objects.filter(
             query, direction='out').exclude(status='queued').all()
     else:
         return "No project contacts yet"
Exemple #10
0
 def get_all_project_messages(cls, contacts_list):
     query = reduce(operator.or_,
                    (Q(urn__contains=contact) for contact in contacts_list))
     date_diff = datetime.datetime.now() - datetime.timedelta(days=42)
     return cls.objects.filter(
         query,
         sent_on__range=(date_diff,
                         datetime.datetime.now())).all().order_by('urn')
Exemple #11
0
 def get_weekly_hanging_messages(cls, contacts_list):
     if len(contacts_list) > 0:
         query = reduce(operator.or_, (Q(urn__contains=contact) for contact in contacts_list))
         date_diff = datetime.datetime.now() - datetime.timedelta(days=7)
         return cls.objects.filter(query, direction='out', sent_on__range=(date_diff, datetime.datetime.now()))\
             .exclude(status__in=['delivered', 'failed']).all()
     else:
         return "No project contacts yet"
Exemple #12
0
def join(lists):
    """
    Return a list which is the concatenation of all elements of input list.

    >>> join([[1,2], [3,4,5], [6,7]])
    [1, 2, 3, 4, 5, 6, 7]
    """
    from operator import concat
    return __builtin__.reduce(concat, lists)
Exemple #13
0
def reduce(inp, f, init=None):
    if init is not None:
        initializer = init()
    else:
        initializer = 0
    def reducewrapper(result, value):
        return f(result=result, value=value)

    return (__builtin__.reduce(reducewrapper, inp, initializer),)
Exemple #14
0
def join(lists):
    """
    Return a list which is the concatenation of all elements of input list.

    >>> join([[1,2], [3,4,5], [6,7]])
    [1, 2, 3, 4, 5, 6, 7]
    """
    from operator import concat
    return __builtin__.reduce(concat, lists)
def do_combine(raw_key, raw_values):
    def merge_dict(left, right):
        for k, v in right.iteritems():
            if not isinstance(v, dict):
                left[k] = left.get(k, 0) + v
                continue
            if k not in left:
                left[k] = v
                continue
            merge_dict(left[k], v)
        return left
    def merge(left, right):
        return (left[0] + right[0], merge_dict(left[1], right[1]))
    return raw_key, __builtin__.reduce(merge, raw_values)
Exemple #16
0
def reduce(function, initval=None):
    """
    Curried version of the built-in reduce.

    >>> reduce(lambda x,y: x+y)( [1, 2, 3, 4, 5] )
    15
    >>> reduce(lambda x,y: x+y, initval=10)( [1, 2, 3, 4, 5] )
    25
    """
    if initval is None:
        return cytoolz.curry(__builtin__.reduce)(function)
    else:
        # TODO: Port to cytoolz
        return lambda s: __builtin__.reduce(function, s, initval)
Exemple #17
0
 def ipt_to_quarter(self, ipt_w):
     ipt_q = []
     q_cache = []
     for index, val in enumerate(ipt_w):
         val_date = datetime_from_millis(val[0])
         val_ppsqft = val[1]
         q_record = {'yr': val_date.year, 'quarter': (val_date.month/4) + 1, 'ppsqft': val_ppsqft}
         if index == 0 or (q_cache[-1]['yr'] == q_record['yr'] and q_cache[-1]['quarter'] == q_record['quarter']):
             q_cache.append(q_record)
         else:
             q_med = statistics.median(map(lambda x: x['ppsqft'], q_cache))
             q_avg = reduce(lambda x, y: {'ppsqft': x['ppsqft'] + y['ppsqft']}, q_cache)['ppsqft']/float(len(q_cache))
             ipt_q.append({'yr': q_cache[-1]['yr'], 'quarter': q_cache[-1]['quarter'], 'ppsqft_avg': q_avg, 'ppsqft_med': q_med})
             del q_cache[:]
             q_cache.append(q_record)
     return ipt_q
Exemple #18
0
def simple_reduce(f, data):
    """
    Apply f of two arguments cumulatively to the items
    of data, from left to right, so as to reduce the iterable
    to a single value.

    :param f: function to apply to reduce data
    :param data: List of items to be reduced
    :return: result of reduce the data to a single value
    """

    try:
        if IS_PYTHON3:
            import functools
            return functools.reduce(f, data)
        else:
            import __builtin__  # noqa
            return __builtin__.reduce(f, data)
    except Exception as e:
        raise e
Exemple #19
0
def reduce(fn, x, init):
    """
    Repeatedly applies the given binary function to the elements of the
    sequence.  Using the infix notation <fn>, reduction computes the
    value: init <fn> x[0] <fn> ... <fn> x[len(x)-1].
    
    The given function is required to be both associative and
    commutative.

        >>> reduce(op_add, [1, 2, 3, 4, 5], 0)
        15

        >>> reduce(op_add, [1, 2, 3, 4, 5], 10)
        25

        >>> reduce(op_add, [], 10)
        10

    Unlike the Python built-in reduce, the Copperhead reduce function
    makes the initial value mandatory.
    """
    return __builtin__.reduce(fn, x, init)
Exemple #20
0
    def rewrite2(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        from __builtin__ import reduce

        if '' == digits:
            return []

        kvmaps = {
            '2': 'abc',
            '3': 'def',
            '4': 'ghi',
            '5': 'jkl',
            '6': 'mno',
            '7': 'pqrs',
            '8': 'tuv',
            '9': 'wxyz'
        }

        def f(first, second):
            # first as [chars]
            # second as [digits]
            print("first: {}".format(first))
            print("second: {}".format(second))
            result = []

            for f in first:
                for s in kvmaps[second]:
                    result.append(f + s)

            print("result: {}".format(result))

            return result

        r = reduce(f, digits, [''])  # second, first
        print(r)
        return r
Exemple #21
0
def reduce(fn, x, init):
    """
    Repeatedly applies the given binary function to the elements of the
    sequence.  Using the infix notation <fn>, reduction computes the
    value: init <fn> x[0] <fn> ... <fn> x[len(x)-1].
    
    The given function is required to be both associative and
    commutative.

        >>> reduce(op_add, [1, 2, 3, 4, 5], 0)
        15

        >>> reduce(op_add, [1, 2, 3, 4, 5], 10)
        25

        >>> reduce(op_add, [], 10)
        10

    Unlike the Python built-in reduce, the Copperhead reduce function
    makes the initial value mandatory.
    """
    return __builtin__.reduce(fn, x, init)
Exemple #22
0
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        from __builtin__ import reduce

        if '' == digits:
            return []

        kvmaps = {
            '2': 'abc',
            '3': 'def',
            '4': 'ghi',
            '5': 'jkl',
            '6': 'mno',
            '7': 'pqrs',
            '8': 'tuv',
            '9': 'wxyz'
        }

        return reduce(
            lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]],
            digits, [''])
Exemple #23
0
 def hl_join(segments):
     return reduce(operator.iadd, segments, [])
Exemple #24
0
if sys.platform == 'win32':
    __import__('msvcrt').setmode(sys.stdout.fileno(), os.O_BINARY) if hasattr(sys.stdout, 'fileno') else None
    __import__('msvcrt').setmode(sys.stderr.fileno(), os.O_BINARY) if hasattr(sys.stderr, 'fileno') else None

# use the current virtualenv if it exists
builtins._ = os.path.join(user.home.replace('\\', os.sep).replace('/', os.sep), '.python-virtualenv', 'Scripts' if __import__('platform').system() == 'Windows' else 'bin', 'activate_this.py')
if os.path.exists(builtins._): execfile(builtins._, {'__file__':builtins._})

# add ~/.python/* to python module search path
map(sys.path.append, __import__('glob').iglob(os.path.join(user.home.replace('\\', os.sep).replace('/', os.sep), '.python', '*')))

## some functional primitives in the default namespace
# box any specified arguments
fbox = fboxed = lambda *a: a
# return a closure that executes ``f`` with the arguments unboxed.
funbox = lambda f, *a, **k: lambda *ap, **kp: f(*(a + builtins.reduce(operator.add, builtins.map(builtins.tuple, ap), ())), **builtins.dict(k.items() + kp.items()))
# return a closure that will check that its argument is an instance of ``type``.
finstance = lambda *type: frpartial(builtins.isinstance, type)
# return a closure that will check if its argument has an item ``key``.
fhasitem = fitemQ = lambda key: fcompose(fcatch(frpartial(operator.getitem, key)), builtins.iter, builtins.next, fpartial(operator.eq, builtins.None))
# return a closure that will get a particular element from an object
fgetitem = fitem = lambda item, *default: lambda object: default[0] if default and item not in object else object[item] 
# return a closure that will check if its argument has an ``attribute``.
fhasattr = fattributeQ = lambda attribute: frpartial(builtins.hasattr, attribute)
# return a closure that will get a particular attribute from an object
fgetattr = fattribute = lambda attribute, *default: lambda object: getattr(object, attribute, *default)
# return a closure that always returns ``object``.
fconstant = fconst = falways = lambda object: lambda *a, **k: object
# a closure that returns it's argument always
fpassthru = fpass = fidentity = fid = lambda object: object
# a closure that returns a default value if its object is false-y
Exemple #25
0
def format_name(s):
    return s[0].upper() + s[1:].lower()


print map(format_name, ['adam', 'LISA', 'barT'])

print "------reduce"


def prod(x, y):
    res = x * y
    return res


print reduce(prod, [2, 3, 4, 5, 6])

print "1~100平方根是整数的"
lAll = range(1, 101)


def isSqrtInteger(x):
    res = False
    tmp = math.sqrt(x)
    iTmp = int(tmp)
    if tmp == iTmp:
        res = True
    return res


print filter(isSqrtInteger, lAll)
def data_do_combine(raw_key, raw_values):
    def merge_dict(left, right):
        for k, v in right.iteritems():
            if not isinstance(v, dict):
                left[k] = left.get(k, 0) + v
                continue
            if k not in left:
                left[k] = v
                continue
            merge_dict(left[k], v)
        return left

    def merge_stack(left, right):
        leftStack, leftNative = left
        rightStack, rightNative = right

        if not leftNative and not rightNative:
            # neither has native stack

            # appUpdateChannel
            prio = (CHAN_PRIO.find(leftStack[1][0]) -
                    CHAN_PRIO.find(rightStack[1][0]))
            if prio != 0:
                return left if prio > 0 else right

            # appVersion
            prio = cmp(mapreduce_common.partitionVersion(leftStack[1][1]),
                       mapreduce_common.partitionVersion(rightStack[1][1]))
            if prio != 0:
                return left if prio > 0 else right

            # appBuildID
            return left if leftStack[1][2] >= rightStack[1][2] else right

        if not leftNative or not rightNative:
            # one has native stack
            return left if leftNative else right

        leftPseudo = leftStack[0]
        rightPseudo = rightStack[0]

        def starts_with_pseudo(native, pseudo):
            return native[0: len(pseudo)] == pseudo

        def merge_native_stack_info(left, right):
            leftNative, leftInfo = left
            rightNative, rightInfo = right

            leftStartsWithPseudo = starts_with_pseudo(leftNative, leftPseudo)
            rightStartsWithPseudo = starts_with_pseudo(rightNative, rightPseudo)

            if leftStartsWithPseudo != rightStartsWithPseudo:
                # because the native stack is taken some time after the pseudostack,
                # the native stack may not correspond to the pseudostack anymore.
                # so we prefer the native stack that starts with the pseudostack.
                return left if leftStartsWithPseudo else right

            prio = (ARCH_PRIO.find(leftInfo['arch']) -
                    ARCH_PRIO.find(rightInfo['arch']))
            if prio != 0:
                return left if prio > 0 else right

            prio = (PLAT_PRIO.find(leftInfo['platform']) -
                    PLAT_PRIO.find(rightInfo['platform']))
            if prio != 0:
                return left if prio > 0 else right

            prio = cmp(mapreduce_common.partitionVersion(leftInfo['appVersion']),
                       mapreduce_common.partitionVersion(rightInfo['appVersion']))
            if prio != 0:
                return left if prio > 0 else right

            if leftInfo['appBuildID'] >= rightInfo['appBuildID']:
                return left
            return right

        # both have native stacks
        for dim_key, dim_vals in leftNative.iteritems():
            if dim_key not in rightNative:
                continue
            for dim_val, native_stack_info in rightNative[dim_key].iteritems():
                if dim_val not in dim_vals:
                    dim_vals[dim_val] = native_stack_info
                    continue
                dim_vals[dim_val] = merge_native_stack_info(
                    dim_vals[dim_val], native_stack_info)

        return left

    def merge(left, right):
        if len(left) < 3 or len(right) < 3:
            return (left[0] + right[0], merge_dict(left[1], right[1]))

        return (left[0] + right[0],
                merge_dict(left[1], right[1]),
                merge_stack(left[2], right[2]))

    return raw_key, __builtin__.reduce(merge, raw_values)
Exemple #27
0
import sys,os,itertools,operator,functools,user,__builtin__

# use the current virtualenv if it exists
__builtin__._=os.path.join(user.home.replace('\\',os.sep).replace('/',os.sep),'.python-virtualenv','Scripts' if __import__('platform').system() == 'Windows' else 'bin', 'activate_this.py')
if os.path.exists(__builtin__._): execfile(__builtin__._,{'__file__':__builtin__._})

# add ~/.python/* to python module search path
map(sys.path.append,__import__('glob').iglob(os.path.join(user.home.replace('\\',os.sep).replace('/',os.sep),'.python','*')))

## include some functional primitives in the default namespace

# box any specified arguments
box = lambda *a: a
# return a closure that executes ``f`` with the arguments unboxed.
unbox = lambda f, *a, **k: lambda *ap, **kp: f(*(a + __builtin__.reduce(operator.add, __builtin__.map(__builtin__.tuple,ap), ())), **__builtin__.dict(k.items() + kp.items()))
# return a closure that always returns ``n``.
identity = lambda n: lambda *a, **k: n
# return the first, second, or third item of a box.
first, second, third = operator.itemgetter(0), operator.itemgetter(1), operator.itemgetter(2)
# return a closure that executes a list of functions one after another from left-to-right
fcompose = compose = lambda *f: __builtin__.reduce(lambda f1,f2: lambda *a: f1(f2(*a)), __builtin__.reversed(f))
# return a closure that executes function ``f`` whilst discarding any extra arguments
fdiscard = lambda f: lambda *a, **k: f()
# return a closure that executes function ``crit`` and then executes ``f`` or ``t`` based on whether or not it's successful.
fcondition = lambda f, t: lambda crit: lambda *a, **k: t(*a, **k) if crit(*a, **k) else f(*a, **k)
# return a closure that takes a list of functions to execute with the provided arguments
fmaplist = fap = lambda *fa: lambda *a, **k: (f(*a, **k) for f in fa)
#lazy = lambda f, state={}: lambda *a, **k: state[(f,a,__builtin__.tuple(__builtin__.sorted(k.items())))] if (f,a,__builtin__.tuple(__builtin__.sorted(k.items()))) in state else state.setdefault((f,a,__builtin__.tuple(__builtin__.sorted(k.items()))), f(*a, **k))
#lazy = lambda f, *a, **k: lambda *ap, **kp: f(*(a+ap), **dict(k.items() + kp.items()))
# return a memoized closure that's lazy and only executes when evaluated
def lazy(f, *a, **k):
Exemple #28
0
 def get_all_unregistered_contacts(cls, groups_list):
     if len(groups_list) > 0:
         query = reduce(operator.or_,
                        (Q(groups__contains=item) for item in groups_list))
         return cls.objects.exclude(query).all()
Exemple #29
0
def _jug_reduce(reducer, inputs):
    import __builtin__
    reducer = _get_function(reducer)
    return __builtin__.reduce(reducer, chain(inputs))
Exemple #30
0
def _jug_map_reduce(reducer, mapper, inputs):
    import __builtin__
    reducer = _get_function(reducer)
    mapper = _get_function(mapper)
    return __builtin__.reduce(reducer, __builtin__.map(mapper, inputs))
Exemple #31
0
def reduce(f, xs):
    return __builtin__.reduce(f, xs)
Exemple #32
0
import __builtin__
import logging,sys,weakref
import itertools,operator,functools
import six,types,heapq,collections

import multiprocessing,Queue
import idaapi

__all__ = ['fbox','fboxed','box','boxed','funbox','unbox','finstance','fconstant','fpassthru','fpass','fidentity','fid','first','second','third','last','fcompose','compose','fdiscard','fcondition','fmaplist','fap','flazy','fmemo','fpartial','partial','fapply','fcurry','frpartial','freversed','frev','fexc','fexception','fcatch','itake','iget','imap','ifilter']

### functional programming primitives (FIXME: probably better to document these with examples)

# box any specified arguments
fbox = fboxed = box = boxed = lambda *a: a
# return a closure that executes ``f`` with the arguments unboxed.
funbox = unbox = lambda f, *a, **k: lambda *ap, **kp: f(*(a + __builtin__.reduce(operator.add, __builtin__.map(__builtin__.tuple,ap), ())), **__builtin__.dict(k.items() + kp.items()))
# return a closure that will check that ``object`` is an instance of ``type``.
finstance = lambda type: lambda object: isinstance(object, type)
# return a closure that always returns ``object``.
fconstant = fconst = lambda object: lambda *a, **k: object
# a closure that returns it's argument
fpassthru = fpass = fidentity = fid = lambda object: object
# return the first, second, or third item of a box.
first, second, third, last = operator.itemgetter(0), operator.itemgetter(1), operator.itemgetter(2), operator.itemgetter(-1)
# return a closure that executes a list of functions one after another from left-to-right
fcompose = compose = lambda *f: __builtin__.reduce(lambda f1,f2: lambda *a: f1(f2(*a)), __builtin__.reversed(f))
# return a closure that executes function ``f`` whilst discarding any extra arguments
fdiscard = lambda f: lambda *a, **k: f()
# return a closure that executes function ``crit`` and then executes ``f`` or ``t`` based on whether or not it's successful.
fcondition = fcond = lambda crit: lambda t, f: \
    lambda *a, **k: t(*a, **k) if crit(*a, **k) else f(*a, **k)
Exemple #33
0
def _jug_map_reduce(reducer, mapper, inputs):
    import __builtin__
    reducer = _get_function(reducer)
    mapper = _get_function(mapper)
    return __builtin__.reduce(reducer, __builtin__.map(mapper, inputs))
Exemple #34
0
def build(node,parent=None):
    global xmlns,inClass
    tag=node.tag.replace(xmlns,"")
    children = node.getchildren()
    _name_ = None
    if 'name' in node.attrib: _name_= node.attrib['name']
    if(tag=="name"):
        return node.text # Name(id=node.text)
    elif(tag=="num"):
        return Num(n=int(node.text))
    elif(tag=="Num"):
        return Num(n=int(node.attrib["value"]))
    elif tag=="value":
        return build(children[0])
    elif(tag=="If"):
        test = build(children[0])
        body = [build(children[1])]
        if len(children)>2:
            orelse=flatList(build(children[2]))
        else:
            orelse=[]
        return If(test=test,body=body,orelse=orelse)
    elif(tag=="True"):
        return name('True') #WTF
    elif(tag=="False"):
        return name('False') #WTF
    elif(tag=="Nil"):
        return name('None') #WTF
    elif(tag=="String" or tag=="string"):
        xs=map(build, children)
        def bin_add(a,b):
            return BinOp(a, Add(),b)
        xss= __builtin__.reduce(bin_add, xs[1:], xs[0]) # BinOp the whole list, nice Karsten++
        return xss
    elif(tag=="Str" or tag=="str" or tag=="var" or tag=="variable"):
        if(hasattr(node,'value')): return Str(s=node.attrib['value'])
        else:return Str(s=node.text)
    # elif(tag=="Call" and parent=="Assign"):
    #     tag="Variable" #VCall in ruby
    elif(tag=="Argument" or tag=="argument"):
        if(len(children)>0):
            return build(children[0])
        return name(_name_)
    elif (tag=="Call" or tag=="call") and _name_=='[]':
        value=name(to_s(children[0]))
        _slice=map(build,children[1].getchildren())
        _slice=to_s(_slice[0])
        return Subscript(value=value,slice=_slice,ctx=Load())
    elif tag=="Assign" or tag=="assign":
        if not _name_ :
            name0 = children[0]
            _name_ = build(name0).s
            children.remove(name0)
            # return map(build,children) # ruby lamda etc
        # if parent=="For":
        #     return name(_name_)
        if _name_[-1]=='=': _name_=_name_[0:-1] # ruby a.b=c name:'b='
        value = build(children[0])
        if _name_ =='[]':
            value=name(children[0].attrib['name'])
            _slice=build(children[1].getchildren()[0]) # RUBY WTF
            value2=map(build,children[1].getchildren()[1:])
            return Assign(targets=[Subscript(value=value,slice=_slice,ctx=Load())],value=value2)
        if len(children)==2:
            value2 =map( build,children[1].getchildren())
            if len(value2)==1: value2=value2[0]
            return Assign(targets=[Attribute(attr=_name_,value=value)],value=value2)
        return Assign(targets=[name(_name_)],value=value)
    elif(tag=="Const"):
        return name(_name_)
    elif(tag=="Variable" or tag=="variable"):
        return name(_name_)# todo: CALL if in block!
        # return Name(id=node.attrib['value'], ctx=Load()) #WTF
    elif tag=="Body":
        return map(build, children)
    elif(tag=='Arguments'): # not AST node
        args=map(build, children)
        return arguments(args=args,defaults=[],vararg=None,kwarg=None)
    elif(tag=='Array'): # not AST node
        args=map(build, children)
        return List(elts=args,ctx=Load())
    elif tag=="Alias":
        return Assign(targets=[build(children[0])],value=build(children[1]))
    elif tag=="Args":
        return map(build, children)
    elif tag=="Or":
        return Or(body=map(build, children))
    elif tag=="And":
        return And(body=map(build, children))

    elif tag=="Block":
        return map(build, children)
    elif(tag=='Hash'): # not AST node
        args=map(build, children)
        a=args[0].elts
        hash=dict(zip(a[0::2], a[1::2])) # nice
        return Dict(keys=hash.keys(),values=hash.values())


    if not tag in kast.types:
        print("UNKNOWN tag %s"%(tag))
        if(len(children)==0):return
    construct= kast.types[tag]
    if callable(construct):
        elem=construct()
    else:elem=construct

    # 'data'
    if(tag=="Call"):
        pass #debug
    if(tag=="Class"):
        inClass=True
    elif(tag=='Arguments'):
        pass
    elif tag=="Self":
        return elem
    #     print("debug Class!")
    # if(tag=="Method"): # FunctionDef
    #     print("debug Method!")


    attribs=node.attrib
    for a in attribs:
        v=attribs[a]
        if(a=='lineno' or a=='col_offset'):v=int(v)
        if(a=='n'):v=int(v)
        if(v=='True'):v=True
        if(v=='False'):v=False
        if(v=='Load'):v=Load()
        if(v=='Store'):v=Store()
        if(isinstance(v,str) and not isinstance(elem,Name)) and tag!="Method" :
            v=parseString(a,v,tag)
        if a.endswith("s") and not isinstance(v,list):v=[v]
        elem.__setattr__(a,v)

    # expect=elem._fields # [x for x in dir(elem) if not x.startswith("_")]
    body=[]
    # if(isinstance(node,Name)):
    #     print("KL")
    # if children==[] and node.text and node.text.strip()!="": #// too late!
    #     val=parseString(tag, node.text)
    #     elem.__setattr__(tag, val)
    #     if(len(expect)==1):
    #         elem=construct(val)
    for c in children:
        babies=c.getchildren() # look ahead
        childName=c.tag.replace(xmlns,"").lower()
        if(childName=="block"):
            childName="body"
        if(childName=="const"):
            if tag=="Class":
                childName="bases"
                child=[name(c.attrib['name'])]
            else:
                childName="object"
                child=name(c.attrib['name'])
        elif(childName=="name"):
            if "name" in c.attrib:
                child=c.attrib['name']
                # child=parseString(childName,c.attrib['name'])
            else:
                child=c.text
        elif(childName=="variable"):
            if tag=="Call":
                childName="object"
            child=name(c.attrib['name'])
        elif(childName=="num"):
            if 'value' in c.attrib:
                child=Num(n=int(c.attrib['value']))
            else:
                child=Num(n=int(c.text))
        # elif childName=="default":
        #     child=build(c)
        elif(childName=="true"):
            childName="value"
            child=name('True')
        elif(childName=="false"):
            childName="value"
            child=name('False')
        elif(childName=="nil"):
            childName="value"
            child=name('None')
        # elif(childName=="array"):
        #     body.append(child)
        elif(childName=="str"): # NAME!!?? REALLY??
            childName="value"
            if(hasattr(c,'value')):
                child=Str(c.attrib['value']) # Name(id=c.attrib['value'], ctx=Load()) #WTF
            else:
                child=Str(id=c.text)
        elif not childName in kast.types: #i.e.: body=...
            if babies==[] and c.text and c.text.strip()!="":
                child=parseString(childName, c.text)
            elif len(babies)==1 and not childName in ['args','body','values']:#
                child=build(babies[0],tag)  # <<<<<<<<<<<<<<<<
            else:
                child=[build(n,tag) for n in babies] # <<<<<<<
            if childName in ["array"]: body.append(child)
        else:
            child=build(c,tag) # <<<<<<
            if(isinstance(child,list)):
                body=child
            else:
                if not tag=="For": # ...
                    body.append(child)
        if isinstance(elem,FunctionDef) and childName!="body":
            if(childName=='args'):
                for a in child:
                    # elem.args.append(a)
                    elem.args.args.append(a)
            else: body.append(child)
        else:
            elem.__setattr__(childName, child)
    if len(body)>0:
        elem.body=body
    attribs=dir(elem)
    if not 'lineno' in attribs:
        elem.lineno=0 #hack
    if not 'col_offset' in attribs:
        elem.col_offset=0 #hack
    if(tag=="Call"):
        if get_func_name(elem.func)=='import':
            return do_import(elem.args)
    if(tag=="Class"):
        inClass=False
        if isinstance(elem,ClassDef):
            classes[elem.name]=elem
    elif tag=="Super":
        elem.func=name('super')
    elif tag=="For":
        elem.target=elem.target.targets[0]
    return elem
Exemple #35
0
def reduce(f, xs):
    return __builtin__.reduce(f, xs)
Exemple #36
0
def _jug_map_reduce(reducer, mapper, inputs):
    import __builtin__

    return __builtin__.reduce(reducer, __builtin__.map(mapper, inputs))
Exemple #37
0
def _jug_reduce(reducer, inputs):
    import __builtin__
    reducer = _get_function(reducer)
    return __builtin__.reduce(reducer, chain(inputs))
Exemple #38
0
def _jug_reduce(reducer, inputs):
    import __builtin__

    return __builtin__.reduce(reducer, chain(inputs))
Exemple #39
0
 def hl_join(segments):
     return reduce(operator.iadd, segments, [])
Exemple #40
0
 def inner(candidate):
     return reduce(lambda acc, f: f(acc), funcs, candidate)