def Func(arg_0, arg_1):
    """Check arguments passed by user that are not checked by argparse itself."""
    if arg_0.asm_block not in ['auto', 'manual']:
        try:
            arg_0.asm_block = int(arg_0.asm_block)
        except ValueError:
            arg_1.error('--asm-block can only be "auto", "manual" or an integer')

    # Set default unit depending on performance model requested
    if not arg_0.unit:
        if 'Roofline' in arg_0.pmodel or 'RooflineIACA' in arg_0.pmodel:
            arg_0.unit = 'FLOP/s'
        else:
            arg_0.unit = 'cy/CL'


def Func():
    """Comand line interface of picklemerge."""
    arg_0 = argparse.ArgumentParser(
        description='Recursively merges two or more pickle files. Only supports pickles consisting '
        'of a single dictionary object.')
    arg_0.add_argument('destination', type=argparse.FileType('r+b'),
                        help='File to write to and include in resulting pickle. (WILL BE CHANGED)')
    arg_0.add_argument('source', type=argparse.FileType('rb'), nargs='+',
                        help='File to include in resulting pickle.')

    arg_1 = arg_0.parse_args()

    arg_2 = pickle.load(arg_1.destination)
    assert isinstance(arg_2, collections.Mapping), "only Mapping types can be handled."

    for arg_3 in arg_1.source:
        arg_4 = pickle.load(arg_3)
        assert isinstance(arg_4, collections.Mapping), "only Mapping types can be handled."

        update(arg_2, arg_4)

    arg_1.destination.seek(0)
    arg_1.destination.truncate()
    pickle.dump(arg_2, arg_1.destination)


def Func(*arg_0, **arg_1):
    """Create a sympy.Symbol with positive and integer assumptions."""
    arg_1.update({'positive': True,
                   'integer': True})
    return sympy.Symbol(*arg_0, **arg_1)


def Func(arg_0):
        """Check that information about kernel makes sens and is valid."""
        arg_1 = [v[0] for v in arg_0.variables.values()]
        assert len(set(arg_1)) <= 1, 'mixing of datatypes within a kernel is not supported.'


def Func(arg_0, arg_1, arg_2):
        """
        Set constant of name to value.

        :param name: may be a str or a sympy.Symbol
        :param value: must be an int
        """
        assert isinstance(arg_1, str) or isinstance(arg_1, sympy.Symbol), \
            "constant name needs to be of type str, unicode or a sympy.Symbol"
        assert type(arg_2) is int, "constant value needs to be of type int"
        if isinstance(arg_1, sympy.Symbol):
            arg_0.constants[arg_1] = arg_2
        else:
            arg_0.constants[arg_4(arg_1)] = arg_2


def Func(arg_0, arg_1, arg_2):
        """
        Return the offset from the iteration center in number of elements.

        The order of indices used in access is preserved.
        """
        # TODO to be replaced with compile_global_offsets
        arg_3 = 0
        arg_4 = arg_0.variables[arg_1][1]

        for arg_5, arg_6 in enumerate(arg_2):
            arg_7, arg_8, arg_9 = arg_6
            assert arg_7 == 'rel', 'Only relative access to arrays is supported at the moment'

            if arg_7 == 'rel':
                arg_3 += arg_0.subs_consts(
                    arg_9*reduce(operator.mul, arg_4[arg_5+1:], sympy.Integer(1)))
            else:
                # should not happen
                pass

        return arg_3


def Func(arg_0, arg_1=False):
        """Yield loop stack dictionaries in order from outer to inner."""
        for arg_2 in arg_0._loop_stack:
            if arg_1:
                yield {'index': arg_2[0],
                       'start': arg_0.subs_consts(arg_2[1]),
                       'stop': arg_0.subs_consts(arg_2[2]),
                       'increment': arg_0.subs_consts(arg_2[3])}
            else:
                yield {'index': arg_2[0], 'start': arg_2[1], 'stop': arg_2[2], 'increment': arg_2[3]}


def Func(arg_0, arg_1=True, arg_2=True):
        """
        Return the order of indices as they appear in array references.

        Use *source* and *destination* to filter output
        """
        if arg_1:
            arg_3 = chain(*arg_0.sources.values())
        else:
            arg_3 = []
        if arg_2:
            arg_3 = chain(arg_3, *arg_0.destinations.values())

        arg_4 = []
        for arg_5 in [aref for aref in arg_3 if aref is not None]:
            arg_6 = []
            for arg_7 in arg_5:
                arg_6.append(arg_7.free_symbols)
            arg_4.append(arg_6)

        return arg_4


def Func(arg_0, arg_1=True, arg_2=True):
        """
        Return a dictionary of lists of sympy accesses, for each variable.

        Use *source* and *destination* to filter output
        """
        arg_3 = defaultdict(list)
        # Compile sympy accesses
        for arg_4 in arg_0.variables:
            if arg_1:
                for arg_5 in arg_0.sources.get(arg_4, []):
                    if arg_5 is None:
                        continue
                    arg_3[arg_4].append(arg_0.access_to_sympy(arg_4, arg_5))
            if arg_2:
                for arg_6 in arg_0.destinations.get(arg_4, []):
                    if arg_6 is None:
                        continue
                    arg_3[arg_4].append(arg_0.access_to_sympy(arg_4, arg_6))

        return arg_3


def Func(arg_0, arg_1=None):
        """
        Return sympy expressions translating global_iterator to loop indices.

        If global_iterator is given, an integer is returned
        """
        # unwind global iteration count into loop counters:
        arg_2 = {}
        arg_3 = symbol_pos_int('global_iterator')
        arg_4 = implemented_function(sympy.Function(str('idiv')), lambda x, y: x//y)
        arg_5 = 1
        arg_6 = 1
        for arg_7, arg_8, arg_9, arg_10 in reversed(arg_0._loop_stack):
            arg_11 = symbol_pos_int(arg_7)

            # This unspools the iterations:
            arg_12 = arg_9-arg_8  # FIXME is incr handled correct here?
            arg_13 = arg_8+(arg_4(arg_3*arg_6, arg_5)*arg_10) % arg_12
            arg_5 = arg_5*arg_12
            arg_6 = arg_10

            arg_2[arg_11] = sympy.lambdify(
                arg_3,
                arg_0.subs_consts(arg_13), modules=[numpy, {'Mod': numpy.mod}])

            if arg_1 is not None:
                try:  # Try to resolve to integer if global_iterator was given
                    arg_2[arg_11] = sympy.Integer(arg_0.subs_consts(arg_13))
                    continue
                except (ValueError, TypeError):
                    arg_2[arg_11] = arg_2[arg_11](arg_1)

        return arg_2


def Func(arg_0):
        """
        Return global iterator sympy expression
        """
        Func = sympy.Integer(0)
        arg_2 = sympy.Integer(1)
        for arg_3, arg_4, arg_5, arg_6 in reversed(arg_0._loop_stack):
            arg_7 = symbol_pos_int(arg_3)
            arg_8 = arg_5 - arg_4  # FIXME is incr handled correct here?
            Func += (arg_7 - arg_4) * arg_2
            arg_2 *= arg_8
        return Func


def Func(arg_0, arg_1):
        """
        Transform a dictionary of indices to a global iterator integer.

        Inverse of global_iterator_to_indices().
        """
        arg_2 = arg_0.subs_consts(arg_0.global_iterator().subs(arg_1))
        return arg_2


def Func(arg_0, arg_1=arg_2.stdout):
        """Print kernel information in human readble format."""
        arg_4 = ('     idx |        min        max       step\n' +
                 '---------+---------------------------------\n')
        for arg_5 in arg_0._loop_stack:
            arg_4 += '{:>8} | {!r:>10} {!r:>10} {!r:>10}\n'.format(*arg_5)
        print(prefix_indent('loop stack:        ', arg_4), file=arg_1)

        arg_4 = ('    name |  offsets   ...\n' +
                 '---------+------------...\n')
        for arg_6, arg_7 in list(arg_0.sources.items()):
            arg_8 = '{:>8} | '.format(arg_6)
            arg_9 = '\n'.join(['{!r:}'.format(o) for o in arg_7])
            arg_4 += prefix_indent(arg_8, arg_9, later_prefix='         | ')
        print(prefix_indent('data sources:      ', arg_4), file=arg_1)

        arg_4 = ('    name |  offsets   ...\n' +
                 '---------+------------...\n')
        for arg_6, arg_7 in list(arg_0.destinations.items()):
            arg_8 = '{:>8} | '.format(arg_6)
            arg_9 = '\n'.join(['{!r:}'.format(o) for o in arg_7])
            arg_4 += prefix_indent(arg_8, arg_9, later_prefix='         | ')
        print(prefix_indent('data destinations: ', arg_4), file=arg_1)

        arg_4 = (' op | count \n' +
                 '----+-------\n')
        for arg_10, arg_11 in list(arg_0._flops.items()):
            arg_4 += '{:>3} | {:>4}\n'.format(arg_10, arg_11)
        arg_4 += '     =======\n'
        arg_4 += '      {:>4}'.format(sum(arg_0._flops.values()))
        print(prefix_indent('FLOPs:     ', arg_4), file=arg_1)


def Func(arg_0, arg_1=arg_2.stdout):
        """Print variables information in human readble format."""
        arg_4 = ('    name |   type size             \n' +
                 '---------+-------------------------\n')
        for arg_5, arg_6 in list(arg_0.variables.items()):
            arg_4 += '{:>8} | {:>6} {!s:<10}\n'.format(arg_5, arg_6[0], arg_6[1])
        print(prefix_indent('variables: ', arg_4), file=arg_1)


def Func(arg_0, arg_1=arg_2.stdout):
        """Print constants information in human readble format."""
        arg_4 = ('    name | value     \n' +
                 '---------+-----------\n')
        for arg_5, arg_6 in list(arg_0.constants.items()):
            arg_4 += '{!s:>8} | {:<10}\n'.format(arg_5, arg_6)
        print(prefix_indent('constants: ', arg_4), file=arg_1)


def Func(arg_0, arg_1=arg_2.stdout):
        """Print source code of kernel."""
        print(arg_0.kernel_code, file=arg_1)


def Func(arg_0, arg_1):
        """
        Convert mathematical expressions to a sympy representation.

        May only contain paranthesis, addition, subtraction and multiplication from AST.
        """
        if type(arg_1) is c_ast.ID:
            return symbol_pos_int(arg_1.name)
        elif type(arg_1) is c_ast.Constant:
            return sympy.Integer(arg_1.value)
        else:  # elif type(dim) is c_ast.BinaryOp:
            arg_2 = {
                '*': operator.mul,
                '+': operator.add,
                '-': operator.sub
            }

            return arg_2[arg_1.op](
                arg_0.Func(arg_1.left),
                arg_0.Func(arg_1.right))


def Func(arg_0, arg_1, arg_2=0):
        """
        Return a tuple of offsets of an ArrayRef object in all dimensions.

        The index order is right to left (c-code order).
        e.g. c[i+1][j-2] -> (-2, +1)

        If aref is actually a c_ast.ID, None will be returned.
        """
        if isinstance(arg_1, c_ast.ID):
            return None

        # Check for restrictions
        assert type(arg_1.name) in [c_ast.ArrayRef, c_ast.ID], \
            "array references must only be used with variables or other array references"
        assert type(arg_1.subscript) in [c_ast.ID, c_ast.Constant, c_ast.BinaryOp], \
            'array subscript must only contain variables or binary operations'

        # Convert subscript to sympy and append
        arg_3 = [arg_0.conv_ast_to_sym(arg_1.subscript)]

        # Check for more indices (multi-dimensional access)
        if type(arg_1.name) is c_ast.ArrayRef:
            arg_3 += arg_0.Func(arg_1.name, arg_2=arg_2+1)

        # Reverse to preserver order (the subscripts in the AST are traversed backwards)
        if arg_2 == 0:
            arg_3.reverse()

        return tuple(arg_3)


def Func(arg_0, arg_1):
        """
        Return base name of ArrayRef object.

        e.g. c[i+1][j-2] -> 'c'
        """
        if isinstance(arg_1.name, c_ast.ArrayRef):
            return arg_0.Func(arg_1.name)
        elif isinstance(arg_1.name, str):
            return arg_1.name
        else:
            return arg_1.name.name


def Func(arg_0, arg_1=True):
        """
        Generate constants declarations

        :return: list of declarations
        """
        arg_2 = []

        # Use type as provided by user in loop indices
        arg_3 = arg_0.get_index_type()

        arg_4 = 2  # subscript for cli input, 1 is reserved for repeat
        for arg_5 in arg_0.constants:
            # const long long N = strtoul(argv[2])
            # with increasing N and 1
            # TODO change subscript of argv depending on constant count
            arg_6 = c_ast.TypeDecl(arg_5.name, ['const'], c_ast.IdentifierType(arg_3))
            arg_7 = None
            if arg_1:
                arg_7 = c_ast.FuncCall(
                    c_ast.ID('atoi'),
                    c_ast.ExprList([c_ast.ArrayRef(c_ast.ID('argv'),
                                                   c_ast.Constant('int', str(arg_4)))]))
            arg_4 += 1
            arg_2.append(c_ast.Decl(
                arg_5.name, ['const'], [], [],
                arg_6, arg_7, None))

        return arg_2


def Func(arg_0):
        """Return array declarations."""
        return [arg_1 for arg_1 in arg_0.kernel_ast.block_items
                if type(arg_1) is c_ast.Decl and type(arg_1.type) is c_ast.ArrayDecl]


def Func(arg_0):
        """Return kernel loop nest including any preceding pragmas and following swaps."""
        arg_1 = [s for s in arg_0.kernel_ast.block_items
                     if type(s) in [c_ast.For, c_ast.Pragma, c_ast.FuncCall]]
        assert len(arg_1) >= 1, "Found to few for statements in kernel"
        return arg_1


def Func(arg_0, arg_1):
        """
        Generate initialization statements for arrays.

        :param array_dimensions: dictionary of array dimensions

        :return: list of nodes
        """
        arg_2 = deepcopy(deepcopy(arg_0.get_kernel_loop_nest()))
        # traverse to the inner most for loop:
        arg_3 = arg_0._find_inner_most_loop(arg_2)
        arg_4 = arg_3.stmt
        arg_3.stmt = c_ast.Compound([])

        arg_6 = str(random.uniform(1.0, 0.1))

        # find all array references in original orig_inner_stmt
        for arg_7 in find_node_type(arg_4, c_ast.ArrayRef):
            # transform to 1d references
            transform_multidim_to_1d_ref(arg_7, arg_1)
            # build static assignments and inject into inner_most.stmt
            arg_3.stmt.block_items.append(c_ast.Assignment(
                '=', arg_7, c_ast.Constant('float', arg_6)))

        return arg_2


def Func(arg_0):
        """
        Generate false if branch with dummy calls

        Requires kerncraft.h to be included, which defines dummy(...) and var_false.

        :return: dummy statement
        """
        # Make sure nothing gets removed by inserting dummy calls
        arg_1 = []
        for arg_2 in arg_0.kernel_ast.block_items:
            # Only consider toplevel declarations from kernel ast
            if type(arg_2) is not c_ast.Decl: continue
            if type(arg_2.type) is c_ast.ArrayDecl:
                arg_1.append(c_ast.FuncCall(
                    c_ast.ID('dummy'),
                    c_ast.ExprList([c_ast.ID(arg_2.name)])))
            else:
                arg_1.append(c_ast.FuncCall(
                    c_ast.ID('dummy'),
                    c_ast.ExprList([c_ast.UnaryOp('&', c_ast.ID(arg_2.name))])))
        arg_3 = c_ast.If(
            cond=c_ast.ID('var_false'),
            iftrue=c_ast.Compound(arg_1),
            iffalse=None)
        return arg_3


def Func(arg_0, arg_1='kernel'):
        """Build and return kernel function declaration"""
        arg_2, arg_3 = arg_0._build_array_declarations(with_init=False)
        arg_4 = arg_0._build_scalar_declarations(with_init=False)
        arg_5 = arg_0._build_const_declartions(with_init=False)
        return c_ast.FuncDecl(args=c_ast.ParamList(params=arg_2 + arg_4 +
                                                          arg_5),
                              type=c_ast.TypeDecl(declname=arg_1,
                                                  quals=[],
                                                  type=c_ast.IdentifierType(names=['void'])))


def Func(arg_0, arg_1=True):
        """Build and return scalar variable declarations"""
        # copy scalar declarations from from kernel ast
        arg_2 = [deepcopy(arg_3) for arg_3 in arg_0.kernel_ast.block_items
                               if type(arg_3) is c_ast.Decl and type(arg_3.type) is c_ast.TypeDecl]
        # add init values to declarations
        if arg_1:
            random.seed(2342)  # we want reproducible random numbers
            for arg_3 in arg_2:
                if arg_3.type.type.names[0] in ['double', 'float']:
                    arg_3.init = c_ast.Constant('float', str(random.uniform(1.0, 0.1)))
                elif arg_3.type.type.names[0] in ['int', 'long', 'long long',
                                              'unsigned int', 'unsigned long', 'unsigned long long']:
                    arg_3.init = c_ast.Constant('int', 2)

        return arg_2


def Func(arg_0, arg_1=False, arg_2=False, arg_3='kernel'):
        """
        Generate and return compilable source code with kernel function from AST.

        :param openmp: if true, OpenMP code will be generated
        :param as_filename: if true, will save to file and return filename
        :param name: name of kernel function
        """
        assert arg_0.kernel_ast is not None, "AST does not exist, this could be due to running " \
                                            "based on a kernel description rather than code."
        arg_4 = 'kernel'
        if arg_1:
            arg_4 += '-omp'
        arg_4 += '.c'

        arg_5, arg_6 = arg_0._get_intermediate_file(
            arg_4, machine_and_compiler_dependent=False)

        # Use already cached version
        if arg_6:
            arg_7 = arg_5.read()
        else:
            arg_8, arg_9 = arg_0._build_array_declarations()

            # Prepare actual kernel loop nest
            if arg_1:
                # with OpenMP code
                arg_10 = deepcopy(arg_0.get_kernel_loop_nest())
                # find all array references in kernel
                for arg_11 in find_node_type(arg_10, c_ast.ArrayRef):
                    # transform to 1d references
                    transform_multidim_to_1d_ref(arg_11, arg_9)
                arg_12 = [p for p in find_node_type(arg_10, c_ast.Pragma)
                               if 'omp' in p.string]
                # TODO if omp parallel was found, remove it (also replace "parallel for" -> "for")
                # if no omp for pragmas are present, insert suitable ones
                if not arg_12:
                    arg_10.insert(0, c_ast.Pragma("omp for"))
                # otherwise do not change anything
            else:
                # with original code
                arg_10 = deepcopy(arg_0.get_kernel_loop_nest())
                # find all array references in kernel
                for arg_11 in find_node_type(arg_10, c_ast.ArrayRef):
                    # transform to 1d references
                    transform_multidim_to_1d_ref(arg_11, arg_9)

            arg_13 = c_ast.FuncDef(decl=c_ast.Decl(
                arg_3=arg_3, type=arg_0._build_kernel_function_declaration(arg_3=arg_3), quals=[],
                storage=[], funcspec=[], init=None, bitsize=None),
                body=c_ast.Compound(block_items=arg_10),
                param_decls=None)

            # Generate code
            arg_7 = CGenerator().visit(arg_13)

            # Insert missing #includes from template to top of code
            arg_7 = '#include "kerncraft.h"\n\n' + arg_7

            # Store to file
            arg_5.write(arg_7)
        arg_5.close()

        if arg_2:
            return arg_5.name
        else:
            return arg_7


def Func(arg_0, arg_1='kernel'):
        """Generate and return kernel call ast."""
        return c_ast.FuncCall(arg_1=c_ast.ID(arg_1=arg_1), args=c_ast.ExprList(exprs=[
            c_ast.ID(arg_1=arg_2.name) for arg_2 in (
                    arg_0._build_array_declarations()[0] +
                    arg_0._build_scalar_declarations() +
                    arg_0._build_const_declartions())]))


def Func(arg_0, arg_1=False, arg_2='kernel'):
        """
        Generate and return compilable source code from AST.
        """
        # TODO produce nicer code, including help text and other "comfort features".
        assert arg_0.kernel_ast is not None, "AST does not exist, this could be due to running " \
                                            "based on a kernel description rather than code."

        arg_3, arg_4 = arg_0._get_intermediate_file('main.c',
                                                            machine_and_compiler_dependent=False)

        # Use already cached version
        if arg_4:
            arg_5 = arg_3.read()
        else:
            arg_6 = CParser()
            arg_7 = arg_0.CODE_TEMPLATE
            arg_8 = arg_6.parse(clean_code(arg_7,
                                                   macros=True, comments=True, pragmas=False))
            arg_9 = deepcopy(arg_8)

            # Define and replace DECLARE_CONSTS
            replace_id(arg_9, "DECLARE_CONSTS", arg_0._build_const_declartions(with_init=True))

            # Define and replace DECLARE_ARRAYS
            arg_10, arg_11 = arg_0._build_array_declarations()
            replace_id(arg_9, "DECLARE_ARRAYS", arg_10)

            # Define and replace DECLARE_INIT_SCALARS
            replace_id(arg_9, "DECLARE_INIT_SCALARS", arg_0._build_scalar_declarations())

            # Define and replace DUMMY_CALLS
            replace_id(arg_9, "DUMMY_CALLS", arg_0._build_dummy_calls())

            # Define and replace KERNEL_DECL
            arg_9.ext.insert(0, arg_0._build_kernel_function_declaration(
                name=arg_2))

            # Define and replace KERNEL_CALL
            replace_id(arg_9, "KERNEL_CALL", arg_0._build_kernel_call())

            # Define and replace INIT_ARRAYS based on previously generated kernel
            replace_id(arg_9, "INIT_ARRAYS", arg_0._build_array_initializations(arg_11))

            # Generate code
            arg_5 = CGenerator().visit(arg_9)

            # Insert missing #includes from template to top of code
            arg_5 = '\n'.join([l for l in arg_7.split('\n') if l.startswith("#include")]) + \
                   '\n\n' + arg_5

            # Store to file
            arg_3.write(arg_5)
        arg_3.close()

        if arg_1:
            return arg_3.name
        else:
            return arg_5


def Func(arg_0, arg_1, arg_2='auto',
                      arg_3='auto_with_manual_fallback', arg_4=False):
        """
        Run an IACA analysis and return its outcome.

        *asm_block* controls how the to-be-marked block is chosen. "auto" (default) results in
        the largest block, "manual" results in interactive and a number in the according block.

        *pointer_increment* is the number of bytes the pointer is incremented after the loop or
           - 'auto': automatic detection, RuntimeError is raised in case of failure
           - 'auto_with_manual_fallback': automatic detection, fallback to manual input
           - 'manual': prompt user
        """
        arg_5 = arg_0.compile_kernel(assembly=True, arg_4=arg_4)
        arg_6 = os.path.splitext(arg_5)[0]+'-iaca.s'
        with open(arg_5, 'r') as in_file, open(arg_6, 'w') as out_file:
            arg_0.asm_block = iaca.iaca_instrumentation(
                in_file, out_file,
                block_selection=arg_2,
                arg_3=arg_3)
        arg_7 = arg_0.assemble_to_object(arg_6, arg_4=arg_4)
        return iaca.iaca_analyse_instrumented_binary(arg_7, arg_1), arg_0.asm_block


def Func(arg_0, arg_1=None, arg_2=False, arg_3=False):
        """Compile source to executable with likwid capabilities and return the executable name."""
        arg_4, arg_5 = arg_0._machine.get_compiler()

        arg_6 = arg_0.compile_kernel(arg_3=arg_3, arg_2=arg_2)
        arg_7, arg_8 = arg_0._get_intermediate_file(
            os.path.splitext(os.path.basename(arg_6))[0], binary=True, fp=False)

        if not arg_8:
            arg_9 = arg_0.get_main_code(as_filename=True)

            if not (('LIKWID_INCLUDE' in os.environ or 'LIKWID_INC' in os.environ) and
                    'LIKWID_LIB' in os.environ):
                print('Could not find LIKWID_INCLUDE (e.g., "-I/app/likwid/4.1.2/include") and '
                      'LIKWID_LIB (e.g., "-L/apps/likwid/4.1.2/lib") environment variables',
                      file=sys.stderr)
                sys.exit(1)

            arg_5 += [
                '-std=c99',
                '-I'+reduce_path(os.path.abspath(os.path.dirname(
                    os.path.realpath(__file__)))+'/headers/'),
                os.environ.get('LIKWID_INCLUDE', ''),
                os.environ.get('LIKWID_INC', ''),
                '-llikwid']

            # This is a special case for unittesting
            if os.environ.get('LIKWID_LIB') == '':
                arg_5 = arg_5[:-1]

            if arg_1 is None:
                arg_1 = []
            arg_1 += os.environ['LIKWID_LIB'].split(' ') + ['-pthread']
            arg_5 += os.environ['LIKWID_LIB'].split(' ') + ['-pthread']

            arg_10 = [reduce_path(os.path.abspath(os.path.dirname(
                os.path.realpath(__file__)))+'/headers/dummy.c'),
                       arg_6, arg_9]

            arg_11 = [arg_4] + arg_10 + arg_5 + ['-o', arg_7]
            # remove empty arguments
            arg_11 = list(filter(bool, arg_11))
            if arg_2:
                print('Executing (Func): ', ' '.join(arg_11))
            try:
                subprocess.check_output(arg_11)
            except subprocess.CalledProcessError as e:
                print("Build failed:", e, file=sys.stderr)
                sys.exit(1)
        else:
            if arg_2:
                print('Executing (Func): ', 'using cached', arg_7)

        return arg_7


def Func(arg_0, arg_1):
        """Convert any string to a sympy object or None."""
        if isinstance(arg_1, int):
            return sympy.Integer(arg_1)
        elif isinstance(arg_1, list):
            return tuple([arg_0.Func(arg_2) for arg_2 in arg_1])
        elif arg_1 is None:
            return None
        else:
            # Step 1 build expression with the whole alphabet redefined:
            arg_3 = {c: symbol_pos_int(c) for c in arg_1 if c in string.ascii_letters}
            # TODO find nicer solution for N and other pre-mapped letters
            arg_4 = parse_expr(arg_1, arg_3=arg_3)
            # Replace all free symbols with positive integer versions:
            arg_3.update(
                {arg_1.name: symbol_pos_int(arg_1.name) for arg_1 in arg_4.free_symbols})
            return parse_expr(arg_1, arg_3=arg_3)


def Func(arg_0):
        """Return identifier which is either the machine file name or sha256 checksum of data."""
        if arg_0._path:
            return os.path.basename(arg_0._path)
        else:
            return hashlib.sha256(hashlib.sha256(repr(arg_0._data).encode())).hexdigest()


def Func(arg_0, arg_1=1):
        """
        Return a cachesim.CacheSimulator object based on the machine description.

        :param cores: core count (default: 1)
        """
        arg_2 = {}
        for arg_3 in arg_0['memory hierarchy']:
            # Skip main memory
            if 'cache per group' not in arg_3:
                continue
            arg_2[arg_3['level']] = deepcopy(arg_3['cache per group'])
            # Scale size of shared caches according to cores
            if arg_3['cores per group'] > 1:
                arg_2[arg_3['level']]['sets'] //= arg_1

        arg_4, arg_5, arg_6 = cachesim.CacheSimulator.from_dict(arg_2)

        return arg_4


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5=None):
        """
        Return best fitting bandwidth according to number of threads, read and write streams.

        :param cache_level: integer of cache (0 is L1, 1 is L2 ...)
        :param read_streams: number of read streams expected
        :param write_streams: number of write streams expected
        :param threads_per_core: number of threads that are run on each core
        :param cores: if not given, will choose maximum bandwidth for single NUMA domain
        """
        # try to find best fitting kernel (closest to read/write ratio):
        # write allocate has to be handled in kernel information (all writes are also reads)
        # TODO support for non-write-allocate architectures
        try:
            arg_6 = arg_2/arg_3
        except ZeroDivisionError:
            arg_6 = float('inf')
        arg_7 = 'load'
        arg_8 = arg_0['benchmarks']['kernels'][arg_7]
        arg_9 = float('inf')
        for arg_10, arg_11 in sorted(arg_0['benchmarks']['kernels'].items()):
            try:
                arg_12 = ((arg_11['read streams']['streams'] +
                                 arg_11['write streams']['streams'] -
                                 arg_11['read+write streams']['streams']) /
                                arg_11['write streams']['streams'])
            except ZeroDivisionError:
                arg_12 = float('inf')

            if abs(arg_12 - arg_6) < abs(arg_9 - arg_6):
                arg_7 = arg_10
                arg_8 = arg_11
                arg_9 = arg_12

        # choose smt, and then use max/saturation bw
        arg_13 = arg_0['memory hierarchy'][arg_1]['level']
        arg_14 = \
            arg_0['benchmarks']['measurements'][arg_13][arg_4]
        assert arg_4 == arg_14['threads per core'], \
            'malformed measurement dictionary in machine file.'
        if arg_5 is not None:
            # Used by Roofline model
            arg_15 = arg_14['cores'].index(arg_5)
            arg_16 = arg_14['results'][arg_7][arg_15]
        else:
            # Used by ECM model
            # Choose maximum number of cores to get bandwidth for
            arg_17 = min(arg_0['memory hierarchy'][arg_1]['cores per group'],
                            arg_0['cores per NUMA domain'])
            arg_16 = max(arg_14['results'][arg_7][:arg_17])

        # Correct bandwidth due to miss-measurement of write allocation
        # TODO support non-temporal stores and non-write-allocate architectures
        if arg_1 == 0:
            # L1 does not have write-allocate, so everything is measured correctly
            arg_18 = 1.0
        else:
            arg_18 = (float(arg_8['read streams']['bytes']) +
                      2.0*float(arg_8['write streams']['bytes']) -
                      float(arg_8['read+write streams']['bytes'])) / \
                     (float(arg_8['read streams']['bytes']) +
                      float(arg_8['write streams']['bytes']))
        arg_16 = arg_16 * arg_18

        return arg_16, arg_7


def Func(arg_0, arg_1=None, arg_2=None):
        """
        Return tuple of compiler and compiler flags.

        Selects compiler and flags from machine description file, commandline arguments or call
        arguements.
        """
        if arg_0._args:
            arg_1 = arg_1 or arg_0._args.compiler
            arg_2 = arg_2 or arg_0._args.compiler_flags
        if arg_1 is None:
            # Select first available compiler in machine description file's compiler dict
            for arg_3 in arg_0['compiler'].keys():
                # Making sure compiler is available:
                if find_executable(arg_3) is not None:
                    arg_1 = arg_3
                    break
            else:
                raise RuntimeError("No compiler ({}) was found. Add different one in machine file, "
                                   "via --compiler argument or make sure it will be found in "
                                   "$PATH.".format(list(arg_0['compiler'].keys())))
        if arg_2 is None:
            # Select from machine description file
            arg_2 = arg_0['compiler'].get(arg_1, '')

        return arg_1, arg_2.split(' ')


def Func(arg_0):
        """
        Parse events in machine description to tuple representation used in Benchmark module.

        Examples:
        >>> Func('PERF_EVENT:REG[0-3]')
        ('PERF_EVENT', 'REG[0-3]')
        >>> Func('PERF_EVENT:REG[0-3]:STAY:FOO=23:BAR=0x23')
        ('PERF_EVENT', 'REG[0-3]', {'STAY': None, 'FOO': 23, 'BAR': 35})

        """
        arg_1 = arg_0.split(':')
        assert len(arg_1) >= 2, "Atleast one colon (:) is required in the event name"
        arg_2 = arg_1[:2]
        arg_3 = {}
        for arg_4 in arg_1[2:]:
            if '=' in arg_4:
                arg_5, arg_6 = arg_4.split('=')
                if arg_6.startswith('0x'):
                    arg_3[arg_5] = int(arg_6, 16)
                else:
                    arg_3[arg_5] = int(arg_6)
            else:
                arg_3[arg_4] = None
        arg_2.append(arg_3)
        return tuple(arg_2)


def Func(arg_0, arg_1=0):
        """Enforce that no ranges overlap in internal storage."""
        arg_2 = arg_1
        while arg_2+1 < len(arg_0.data):
            if arg_0.data[arg_2][1] >= arg_0.data[arg_2+1][0]:
                # beginning of i+1-th range is contained in i-th range
                if arg_0.data[arg_2][1] < arg_0.data[arg_2+1][1]:
                    # i+1-th range is longer, thus enlarge i-th range
                    arg_0.data[arg_2][1] = arg_0.data[arg_2+1][1]

                # removed contained range
                del arg_0.data[arg_2+1]
            arg_2 += 1


def Func(arg_0, arg_1, arg_2=True):
        """Align iteration with cacheline boundary."""
        # FIXME handle multiple datatypes
        arg_3 = arg_0.kernel.datatypes_size[arg_0.kernel.datatype]
        arg_4 = arg_0.machine['cacheline size']
        arg_5 = int(arg_4 // arg_3)

        # Gathering some loop information:
        arg_6 = list(arg_0.kernel.get_loop_stack(subs_consts=True))[-1]
        arg_7 = arg_6['increment']

        # do this by aligning either writes (preferred) or reads
        # Assumption: writes (and reads) increase linearly
        arg_8 = arg_0.kernel.compile_global_offsets(arg_1=arg_1)[0]
        if len(arg_8[1]):
            # we have a write to work with:
            arg_9 = min(arg_8[1])
        else:
            # we use reads
            arg_9 = min(arg_8[0])

        arg_10 = arg_9 - \
               (int(arg_9) >> arg_0.csim.first_level.cl_bits << arg_0.csim.first_level.cl_bits)
        if arg_10 == 0:
            return arg_1
        elif arg_2:
            return arg_1 - (arg_10 // arg_3) // arg_7
        else:
            return arg_1 + (arg_5 - arg_10 // arg_3) // arg_7


def Func(arg_0):
        """Return a list with number of loaded cache lines per memory hierarchy level."""
        return [arg_0.stats[arg_1]['LOAD_count'] / arg_0.first_dim_factor
                for arg_1 in range(len(arg_0.machine['memory hierarchy']))]


def Func(arg_0):
        """Return a list with number of hit cache lines per memory hierarchy level."""
        return [arg_0.stats[arg_1]['HIT_count']/arg_0.first_dim_factor
                for arg_1 in range(len(arg_0.machine['memory hierarchy']))]


def Func(arg_0):
        """Return a list with number of missed cache lines per memory hierarchy level."""
        return [arg_0.stats[arg_1]['MISS_count']/arg_0.first_dim_factor
                for arg_1 in range(len(arg_0.machine['memory hierarchy']))]


def Func(arg_0):
        """Return a list with number of stored cache lines per memory hierarchy level."""
        return [arg_0.stats[arg_1]['STORE_count']/arg_0.first_dim_factor
                for arg_1 in range(len(arg_0.machine['memory hierarchy']))]


def Func(arg_0):
        """Return a list with number of evicted cache lines per memory hierarchy level."""
        return [arg_0.stats[arg_1]['EVICT_count']/arg_0.first_dim_factor
                for arg_1 in range(len(arg_0.machine['memory hierarchy']))]


def Func(arg_0):
        """Return verbose information about the predictor."""
        arg_1 = arg_0.first_dim_factor
        arg_2 = {'memory hierarchy': [], 'cache stats': arg_0.stats,
                 'cachelines in stats': arg_1}
        for arg_3, arg_4 in list(enumerate(arg_0.machine['memory hierarchy'])):
            arg_2['memory hierarchy'].append({
                'index': len(arg_2['memory hierarchy']),
                'level': '{}'.format(arg_4['level']),
                'total loads': arg_0.stats[arg_3]['LOAD_byte']/arg_1,
                'total misses': arg_0.stats[arg_3]['MISS_byte']/arg_1,
                'total hits': arg_0.stats[arg_3]['HIT_byte']/arg_1,
                'total stores': arg_0.stats[arg_3]['STORE_byte']/arg_1,
                'total evicts': arg_0.stats[arg_3]['EVICT_byte']/arg_1,
                'total lines load': arg_0.stats[arg_3]['LOAD_count']/arg_1,
                'total lines misses': arg_0.stats[arg_3]['MISS_count']/arg_1,
                'total lines hits': arg_0.stats[arg_3]['HIT_count']/arg_1,
                'total lines stores': arg_0.stats[arg_3]['STORE_count']/arg_1,
                'total lines evicts': arg_0.stats[arg_3]['EVICT_count']/arg_1,
                'cycles': None})
        return arg_2


def Func(arg_0, arg_1=arg_2.stdout):
        """Report gathered analysis data in human readable form."""
        if arg_0.verbose > 1:
            with pprint_nosort():
                pprint.pprint(arg_0.results)

        if arg_0.verbose > 0:
            print('Runtime (per repetition): {:.2g} s'.format(
                arg_0.results['Runtime (per repetition) [s]']),
                file=arg_1)
        if arg_0.verbose > 0:
            print('Iterations per repetition: {!s}'.format(
                arg_0.results['Iterations per repetition']),
                file=arg_1)
        print('Runtime (per cacheline update): {:.2f} cy/CL'.format(
            arg_0.results['Runtime (per cacheline update) [cy/CL]']),
            file=arg_1)
        print('MEM volume (per repetition): {:.0f} Byte'.format(
            arg_0.results['MEM volume (per repetition) [B]']),
            file=arg_1)
        print('Performance: {:.2f} MFLOP/s'.format(arg_0.results['Performance [MFLOP/s]']),
              file=arg_1)
        print('Performance: {:.2f} MLUP/s'.format(arg_0.results['Performance [MLUP/s]']),
              file=arg_1)
        print('Performance: {:.2f} It/s'.format(arg_0.results['Performance [MIt/s]']),
              file=arg_1)
        if arg_0.verbose > 0:
            print('MEM bandwidth: {:.2f} MByte/s'.format(arg_0.results['MEM BW [MByte/s]']),
                  file=arg_1)
        print('', file=arg_1)

        if not arg_0.no_phenoecm:
            print("Data Transfers:")
            print("{:^8} |".format("cache"), end='')
            for arg_4 in arg_0.results['data transfers'].values():
                for arg_5 in sorted(arg_4):
                    print(" {:^14}".format(arg_5), end='')
                print()
                break
            for arg_6, arg_4 in sorted(arg_0.results['data transfers'].items()):
                print("{!s:^8} |".format(arg_6), end='')
                for arg_7, arg_8 in sorted(arg_4.items()):
                    print(" {!s:^14}".format(arg_8), end='')
                print()
            print()

            print('Phenomenological ECM model: {{ {T_OL:.1f} || {T_nOL:.1f} | {T_L1L2:.1f} | '
                  '{T_L2L3:.1f} | {T_L3MEM:.1f} }} cy/CL'.format(
                **{arg_7: float(arg_8) for arg_7, arg_8 in arg_0.results['ECM'].items()}),
                file=arg_1)
            print('T_OL assumes that two loads per cycle may be retiered, which is true for '
                  '128bit SSE/half-AVX loads on SNB and IVY, and 256bit full-AVX loads on HSW, '
                  'BDW, SKL and SKX, but it also depends on AGU availability.',
                  file=arg_1)


def Func(arg_0):
        """Return True iff this function should be considered public."""
        if arg_0.all is not None:
            return arg_0.name in arg_0.all
        else:
            return not arg_0.name.startswith("_")


def Func(arg_0):
        """Return True iff this method should be considered public."""
        # Check if we are a setter/deleter method, and mark as private if so.
        for arg_1 in arg_0.decorators:
            # Given 'foo', match 'foo.bar' but not 'foobar' or 'sfoo'
            if re.compile(r"^{}\.".format(arg_0.name)).match(arg_1.name):
                return False
        arg_2 = (
            not arg_0.name.startswith("_")
            or arg_0.name in VARIADIC_MAGIC_METHODS
            or arg_0.is_magic
        )
        return arg_0.parent.Func and arg_2


def Func(arg_0, arg_1, arg_2):
        """Parse the given file-like object and return its Module object."""
        arg_0.log = arg_3
        arg_0.source = arg_1.readlines()
        arg_5 = "".join(arg_0.source)
        # This may raise a SyntaxError:
        compile(arg_5, arg_2, "exec")
        arg_0.stream = TokenStream(StringIO(arg_5))
        arg_0.filename = arg_2
        arg_0.all = None
        arg_0.future_imports = set()
        arg_0._accumulated_decorators = []
        return arg_0.Func_module()


def Func(arg_0, arg_1):
        """Consume one token and verify it is of the expected kind."""
        arg_2 = arg_0.stream.move()
        assert arg_2.kind == arg_1


def Func(arg_0, arg_1, arg_2=None):
        """Skip tokens in the stream until a certain token kind is reached.

        If `value` is specified, tokens whose values are different will also
        be skipped.
        """
        while arg_0.current is not None:
            if arg_0.current.kind == arg_1 and (
                arg_2 is None or arg_0.current.value == arg_2
            ):
                arg_0.consume(arg_1)
                return
            arg_0.stream.move()


def Func(arg_0):
        """Parse a single docstring and return its value."""
        arg_0.log.debug(
            "parsing docstring, token is %r (%s)", arg_0.current.kind, arg_0.current.value
        )
        while arg_0.current.kind in (tk.COMMENT, tk.NEWLINE, tk.NL):
            arg_0.stream.move()
            arg_0.log.debug(
                "parsing docstring, token is %r (%s)",
                arg_0.current.kind,
                arg_0.current.value,
            )
        if arg_0.current.kind == tk.STRING:
            arg_1 = arg_0.current.value
            arg_0.stream.move()
            return arg_1
        return None


def Func(arg_0):
        """Parse a 'from x import y' statement.

        The purpose is to find __future__ statements.
        """
        arg_0.log.debug("parsing from/import statement.")
        arg_1 = arg_0._parse_from_import_source()
        arg_0._parse_from_import_names(arg_1)


def Func(arg_0, arg_1):
        """Parse the 'y' part in a 'from x import y' statement."""
        if arg_0.current.value == "(":
            arg_0.consume(tk.OP)
            arg_2 = (tk.OP,)
        else:
            arg_2 = (tk.NEWLINE, tk.ENDMARKER)
        while arg_0.current.kind not in arg_2 and not (
            arg_0.current.kind == tk.OP and arg_0.current.value == ";"
        ):
            if arg_0.current.kind != tk.NAME:
                arg_0.stream.move()
                continue
            arg_0.log.debug(
                "parsing import, token is %r (%s)",
                arg_0.current.kind,
                arg_0.current.value,
            )
            if arg_1:
                arg_0.log.debug("found future import: %s", arg_0.current.value)
                arg_0.future_imports.add(arg_0.current.value)
            arg_0.consume(tk.NAME)
            arg_0.log.debug(
                "parsing import, token is %r (%s)",
                arg_0.current.kind,
                arg_0.current.value,
            )
            if arg_0.current.kind == tk.NAME and arg_0.current.value == "as":
                arg_0.consume(tk.NAME)  # as
                if arg_0.current.kind == tk.NAME:
                    arg_0.consume(tk.NAME)  # new name, irrelevant
            if arg_0.current.value == ",":
                arg_0.consume(tk.OP)
            arg_0.log.debug(
                "parsing import, token is %r (%s)",
                arg_0.current.kind,
                arg_0.current.value,
            )


def Func(arg_0):
        """Use docutils to check docstrings are valid RST."""
        # Is there any reason not to call load_source here?
        if arg_0.err is not None:
            assert arg_0.source is None
            arg_1 = "%s%03i %s" % (
                rst_prefix,
                rst_fail_load,
                "Failed to load file: %s" % arg_0.err,
            )
            yield 0, 0, arg_1, type(arg_0)
            arg_2 = []
        try:
            arg_2 = parse(StringIO(arg_0.source), arg_0.filename)
        except SyntaxError as err:
            arg_1 = "%s%03i %s" % (
                rst_prefix,
                rst_fail_parse,
                "Failed to parse file: %s" % err,
            )
            yield 0, 0, arg_1, type(arg_0)
            arg_2 = []
        except AllError:
            arg_1 = "%s%03i %s" % (
                rst_prefix,
                rst_fail_all,
                "Failed to parse __all__ entry.",
            )
            yield 0, 0, arg_1, type(arg_0)
            arg_2 = []
        for arg_3 in arg_2:
            if not arg_3.docstring:
                # People can use flake8-docstrings to report missing
                # docstrings
                continue
            try:
                # Note we use the PEP257 trim algorithm to remove the
                # leading whitespace from each line - this avoids false
                # positive severe error "Unexpected section title."
                arg_4 = trim(dequote_docstring(arg_3.docstring))
                # Off load RST validation to reStructuredText-lint
                # which calls docutils internally.
                # TODO: Should we pass the Python filename as filepath?
                arg_5 = list(rst_lint.lint(arg_4))
            except Exception as err:
                # e.g. UnicodeDecodeError
                arg_1 = "%s%03i %s" % (
                    rst_prefix,
                    rst_fail_lint,
                    "Failed to lint docstring: %s - %s" % (arg_3.name, err),
                )
                yield arg_3.start, 0, arg_1, type(arg_0)
                continue
            for arg_6 in arg_5:
                # TODO - make this a configuration option?
                if arg_6.level <= 1:
                    continue
                # Levels:
                #
                # 0 - debug   --> we don't receive these
                # 1 - info    --> RST1## codes
                # 2 - warning --> RST2## codes
                # 3 - error   --> RST3## codes
                # 4 - severe  --> RST4## codes
                #
                # Map the string to a unique code:
                arg_1 = arg_6.message.split("\n", 1)[0]
                arg_7 = code_mapping(arg_6.level, arg_1)
                assert arg_7 < 100, arg_7
                arg_7 += 100 * arg_6.level
                arg_1 = "%s%03i %s" % (rst_prefix, arg_7, arg_1)

                # This will return the line number by combining the
                # start of the docstring with the offet within it.
                # We don't know the column number, leaving as zero.
                yield arg_3.start + arg_6.line, 0, arg_1, type(arg_0)


def Func(arg_0):
        """Load the source for the specified file."""
        if arg_0.filename in arg_0.STDIN_NAMES:
            arg_0.filename = "stdin"
            if sys.version_info[0] < 3:
                arg_0.source = sys.stdin.read()
            else:
                arg_0.source = TextIOWrapper(sys.stdin.buffer, errors="ignore").read()
        else:
            # Could be a Python 2.7 StringIO with no context manager, sigh.
            # with tokenize_open(self.filename) as fd:
            #     self.source = fd.read()
            arg_3 = tokenize_open(arg_0.filename)
            arg_0.source = arg_3.read()
            arg_3.close()


def Func(arg_0):
    """
    Trusted commands cannot be run remotely

    :param f:
    :return:
    """
    def arg_3(arg_1, arg_2):
        if arg_1.trusted:
            arg_0(arg_1, arg_2)
        else:
            print("Sorry cannot do %s here." % arg_0.__name__[3:])

    global Funcs
    Funcs.add(arg_0.__name__)
    arg_3.__doc__ = arg_0.__doc__
    return arg_3


def Func(arg_0, arg_1):
        """
        Escape newlines in any responses
        """
        if arg_1.lower() == 'off':
            arg_0.escape_nl = False
        else:
            arg_0.escape_nl = True


def Func(arg_0, arg_1):
        """
        Attempt to restart the bot.
        """
        arg_0.bot._frame = 0
        arg_0.bot._namespace.clear()
        arg_0.bot._namespace.update(arg_0.bot._initial_namespace)


def Func(arg_0, arg_1):
        """
        Resume playback if bot is paused
        """
        if arg_0.pause_speed is None:
            arg_0.bot._speed = arg_0.pause_speed
            arg_0.pause_speed = None
        arg_0.print_response("Play")


def Func(arg_0, arg_1):
        """
        List bot variables and values
        """
        if arg_0.bot._vars:
            arg_2 = max([len(arg_4) for arg_4 in arg_0.bot._vars])
            for arg_3, (arg_4, arg_5) in enumerate(arg_0.bot._vars.items()):
                arg_6 = arg_3 < len(arg_0.bot._vars) - 1
                arg_0.print_response("%s = %s" % (arg_4.ljust(arg_2), arg_5.value), arg_6=arg_6)
        else:
            arg_0.print_response("No vars")


def Func(arg_0, arg_1):
        """
        Make the current window fullscreen
        """
        arg_0.bot.canvas.sink.trigger_fullscreen_action(True)
        print(arg_0.response_prompt, file=arg_0.stdout)


def Func(arg_0, arg_1):
        """
        Set a variable.
        """
        try:
            arg_2, arg_3 = [part.strip() for part in arg_1.split('=')]
            if arg_2 not in arg_0.bot._vars:
                arg_0.print_response('No such variable %s enter vars to see available vars' % arg_2)
                return
            arg_4 = arg_0.bot._vars[arg_2]
            arg_4.value = arg_4.sanitize(arg_3.strip(';'))

            arg_5, arg_6 = arg_0.bot.canvas.sink.var_changed(arg_2, arg_4.value)
            if arg_5:
                print('{}={}'.format(arg_2, arg_4.value), file=arg_0.stdout)
            else:
                print('{}\n'.format(arg_6), file=arg_0.stdout)
        except Exception as e:
            print('Invalid Syntax.', e)
            return


def Func(arg_0, arg_1):
        """
        Allow commands to have a last parameter of 'cookie=somevalue'

        TODO somevalue will be prepended onto any output lines so
        that editors can distinguish output from certain kinds
        of events they have sent.

        :param line:
        :return:
        """
        arg_2 = shlex.split(arg_1 or "")
        if arg_2 and 'cookie=' in arg_2[-1]:
            arg_3 = arg_1.index('cookie=')
            arg_4 = arg_1[arg_3 + 7:]
            arg_1 = arg_1[:arg_3].strip()
            arg_0.cookie = arg_4
        if arg_1.startswith('#'):
            return ''
        elif '=' in arg_1:
            # allow  somevar=somevalue

            # first check if we really mean a command
            arg_5 = arg_1.partition(" ")[0]
            if hasattr(arg_0, "do_%s" % arg_5):
                return arg_1

            if not arg_1.startswith("set "):
                return "set " + arg_1
            else:
                return arg_1
        if len(arg_2) and arg_2[0] in arg_0.shortcuts:
            return "%s %s" % (arg_0.shortcuts[arg_2[0]], " ".join(arg_2[1:]))
        else:
            return arg_1


def Func(arg_0, arg_1, arg_2='#fefefe'):
    """
    Draw a daisy at x, y
    """
    # save location, size etc
    _ctx.push()

    # save fill and stroke
    arg_3 =_ctx.fill()
    arg_4 = _ctx.stroke()

    arg_5 = (1.0 / _ctx.HEIGHT) * float(arg_1 * 0.5) * 4.0

    # draw stalk
    _ctx.strokewidth(arg_5 * 2.0)
    _ctx.stroke('#3B240B')

    _ctx.line(arg_0 + (sin(arg_0 * 0.1) * 10.0), arg_1 + 80, arg_0 + sin(_ctx.FRAME * 0.1), arg_1)

    # draw flower
    _ctx.translate(-20, 0)
    _ctx.scale(arg_5)

    # draw petals
    _ctx.fill(arg_2)
    _ctx.nostroke()
    for arg_6 in xrange(0, 360, 45):
        _ctx.rotate(degrees=45)
        _ctx.rect(arg_0, arg_1, 40, 8, 1)

    # draw centre
    _ctx.fill('#F7FE2E')
    _ctx.ellipse(arg_0 + 15, arg_1, 10, 10)

    # restore fill and stroke
    _ctx.fill(arg_3)
    _ctx.stroke(arg_4)

    # restore location, size etc
    _ctx.pop()


def Func(arg_0, arg_1, arg_2=None):
        """load context-free grammar"""
        arg_0.grammar = arg_0._load(arg_1, arg_2=arg_2)
        arg_0.refs = {}
        for arg_4 in arg_0.grammar.getElementsByTagName("ref"):
            arg_0.refs[arg_4.attributes["id"].value] = arg_4


def Func(arg_0, arg_1=" "):

    """Replaces HTML special characters by readable characters.

    As taken from Leif K-Brooks algorithm on:
    http://groups-beta.google.com/group/comp.lang.python

    """

    def _repl_func(arg_2):
        try:
            if arg_2.group(1): # Numeric character reference
                return unichr( int(arg_2.group(2)) )
            else:
                try: return cp1252[ unichr(int(arg_2.group(3))) ].strip()
                except: return unichr( name2codepoint[arg_2.group(3)] )
        except:
            return arg_1

    # Force to Unicode.
    if not isinstance(arg_0, unicode):
        arg_0 = UnicodeDammit(arg_0).unicode

    # Don't want some weird unicode character here
    # that truncate_spaces() doesn't know of:
    arg_0 = arg_0.replace(" ", " ")

    # The ^> makes sure nothing inside a tag (i.e. href with query arguments) gets processed.
    arg_3 = re.compile(r'&(?:(#)(\d+)|([^;^> ]+));')
    return arg_3.sub(_repl_func, arg_0)


def Func(arg_0, arg_1=10):

    """ Returns True when the url generates a "404 Not Found" error.
    """

    try: arg_2 = open(arg_0, arg_1)
    except HTTP404NotFound:
        return True
    except:
        return False

    return False


def Func(arg_0, arg_1=[], arg_2=10):

    """ Determine the MIME-type of the document behind the url.

    MIME is more reliable than simply checking the document extension.
    Returns True when the MIME-type starts with anything in the list of types.

    """

    # Types can also be a single string for convenience.
    if isinstance(arg_1, str):
        arg_1 = [arg_1]

    try: arg_3 = open(arg_0, arg_2)
    except:
        return False

    arg_4 = arg_3.info()["Content-Type"]
    for arg_5 in arg_1:
        if arg_4.startswith(arg_5): return True

    return False


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None, arg_5=None, arg_6=1.0, arg_7=None, arg_8=True, **arg_9):
        '''Draws a Func form path, in x,y and resize it to width, height dimensions.
        '''
        return arg_0.Image(arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, **arg_9)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5=0.0, arg_6=True, **arg_7):
        '''
        Draw a Funcangle from x, y of width, height.

        :param startx: top left x-coordinate
        :param starty: top left y-coordinate

        :param width: height  Size of Funcangle.
        :roundness: Corner roundness defaults to 0.0 (a right-angle).
        :draw: If True draws immediately.
        :fill: Optionally pass a fill color.

        :return: path representing the Funcangle.

        '''
        arg_8 = arg_0.BezierPath(**arg_7)
        arg_8.Func(arg_1, arg_2, arg_3, arg_4, arg_5, arg_0.Funcmode)
        if arg_6:
            arg_8.draw()
        return arg_8


def Func(arg_0, arg_1=None):
        '''
        Set the current rectmode.

        :param mode: CORNER, CENTER, CORNERS
        :return: rectmode if mode is None or valid.
        '''
        if arg_1 in (arg_0.CORNER, arg_0.CENTER, arg_0.CORNERS):
            arg_0.rectmode = arg_1
            return arg_0.rectmode
        elif arg_1 is None:
            return arg_0.rectmode
        else:
            raise ShoebotError(_("rectmode: invalid input"))


def Func(arg_0, arg_1=None):
        '''
        Set the current ellipse drawing mode.

        :param mode: CORNER, CENTER, CORNERS
        :return: ellipsemode if mode is None or valid.
        '''
        if arg_1 in (arg_0.CORNER, arg_0.CENTER, arg_0.CORNERS):
            arg_0.ellipsemode = arg_1
            return arg_0.ellipsemode
        elif arg_1 is None:
            return arg_0.ellipsemode
        else:
            raise ShoebotError(_("ellipsemode: invalid input"))


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=arg_5, arg_6=True, **arg_7):
        '''Draw an Func.

        Arrows can be two types: NORMAL or FORTYFIVE.

        :param x: top left x-coordinate
        :param y: top left y-coordinate
        :param width: width of Func
        :param type:  NORMAL or FORTYFIVE
        :draw:  If True draws Func immediately

        :return: Path object representing the Func.
        '''
        # Taken from Nodebox
        arg_8 = arg_0.BezierPath(**arg_7)
        if arg_4 == arg_0.NORMAL:
            arg_9 = arg_3 * .4
            arg_10 = arg_3 * .2
            arg_8.moveto(arg_1, arg_2)
            arg_8.lineto(arg_1 - arg_9, arg_2 + arg_9)
            arg_8.lineto(arg_1 - arg_9, arg_2 + arg_10)
            arg_8.lineto(arg_1 - arg_3, arg_2 + arg_10)
            arg_8.lineto(arg_1 - arg_3, arg_2 - arg_10)
            arg_8.lineto(arg_1 - arg_9, arg_2 - arg_10)
            arg_8.lineto(arg_1 - arg_9, arg_2 - arg_9)
            arg_8.lineto(arg_1, arg_2)
        elif arg_4 == arg_0.FORTYFIVE:
            arg_9 = .3
            arg_10 = 1 + arg_9
            arg_8.moveto(arg_1, arg_2)
            arg_8.lineto(arg_1, arg_2 + arg_3 * (1 - arg_9))
            arg_8.lineto(arg_1 - arg_3 * arg_9, arg_2 + arg_3)
            arg_8.lineto(arg_1 - arg_3 * arg_9, arg_2 + arg_3 * arg_10 * .4)
            arg_8.lineto(arg_1 - arg_3 * arg_10 * .6, arg_2 + arg_3)
            arg_8.lineto(arg_1 - arg_3, arg_2 + arg_3 * arg_10 * .6)
            arg_8.lineto(arg_1 - arg_3 * arg_10 * .4, arg_2 + arg_3 * arg_9)
            arg_8.lineto(arg_1 - arg_3, arg_2 + arg_3 * arg_9)
            arg_8.lineto(arg_1 - arg_3 * (1 - arg_9), arg_2)
            arg_8.lineto(arg_1, arg_2)
        else:
            raise NameError(_("Func: available types for Func() are NORMAL and FORTYFIVE\n"))
        if arg_6:
            arg_8.draw()
        return arg_8


def Func(arg_0, arg_1, arg_2):
        '''Move relatively to the last point.'''
        if arg_0._path is None:
            raise ShoebotError(_("No current path. Use beginpath() first."))
        arg_0._path.Func(arg_1, arg_2)


def Func(arg_0, arg_1, arg_2):
        '''Draw a line using relative coordinates.'''
        if arg_0._path is None:
            raise ShoebotError(_("No current path. Use beginpath() first."))
        arg_0._path.Func(arg_1, arg_2)


def Func(arg_0, arg_1=None):
        '''
        Set the current Func mode.

        :param mode: CENTER or CORNER'''
        if arg_1:
            arg_0._canvas.mode = arg_1
        return arg_0._canvas.mode


def Func(arg_0, arg_1=1, arg_2=None):
        '''
        Set a Func at which to draw objects.

        1.0 draws objects at their natural size

        :param x: Scale on the horizontal plane
        :param y: Scale on the vertical plane
        '''
        if not arg_2:
            arg_2 = arg_1
        if arg_1 == 0:
            # Cairo borks on zero values
            arg_1 = 1
        if arg_2 == 0:
            arg_2 = 1
        arg_0._canvas.Func(arg_1, arg_2)


def Func(arg_0):
        ''' Stop applying strokes to new paths.

        :return: stroke color before Func was called.
        '''
        arg_1 = arg_0._canvas.strokecolor
        arg_0._canvas.strokecolor = None
        return arg_1


def Func(arg_0, arg_1=None):
        '''Set the stroke width.

        :param w: Stroke width.
        :return: If no width was specified then current width is returned.
        '''
        if arg_1 is not None:
            arg_0._canvas.strokewidth = arg_1
        else:
            return arg_0._canvas.strokewidth


def Func(arg_0, arg_1=None, arg_2=None):
        '''Set the Func to be used with new text instances.

        :param Funcpath: path to truetype or opentype Func.
        :param Funcsize: size of Func

        :return: current current Funcpath (if Funcpath param not set)
        Accepts TrueType and OpenType files. Depends on FreeType being
        installed.'''
        if arg_1 is not None:
            arg_0._canvas.Funcfile = arg_1
        else:
            return arg_0._canvas.Funcfile
        if arg_2 is not None:
            arg_0._canvas.Funcsize = arg_2


def Func(arg_0, arg_1, arg_2=None):
        '''Returns the height of a string of text according to the current
        font settings.

        :param txt: string to measure
        :param width: width of a line of text in a block
        '''
        arg_3 = arg_2
        return arg_0.textmetrics(arg_1, arg_2=arg_3)[1]


def Func(arg_0):

    """ Graph background color.
    """

    if arg_0.background == None:
        arg_0._ctx.background(None)
    else:
        arg_0._ctx.background(arg_0.background)

    if arg_0.depth:
        try:
            arg_1 = colors.color(arg_0.background).darker(0.2)
            arg_2 = arg_0._ctx.rect(0, 0, arg_0._ctx.WIDTH, arg_0._ctx.HEIGHT, draw=False)
            colors.gradientfill(arg_2, arg_1, arg_1.lighter(0.35))
            colors.shadow(dx=0, dy=0, blur=2, alpha=0.935, arg_1=arg_0.background)
        except:
            pass


def Func(arg_0, arg_1, arg_2=1.0):

    """ Visualization of a node's id.
    """

    if arg_0.text:
        #s._ctx.lineheight(1)
        arg_0._ctx.font(arg_0.font)
        arg_0._ctx.fontsize(arg_0.fontsize)
        arg_0._ctx.nostroke()
        arg_0._ctx.fill(
            arg_0.text.r,
            arg_0.text.g,
            arg_0.text.b,
            arg_0.text.a * arg_2
        )

        # Cache an outlined label text and translate it.
        # This enhances the speed and avoids wiggling text.
        try: arg_3 = arg_1._textpath
        except:
            arg_4 = arg_1.label
            try: arg_4 = unicode(arg_4)
            except:
                try: arg_4 = arg_4.decode("utf-8")
                except:
                    pass
            # Abbreviation.
            #root = node.graph.root
            #if txt != root and txt[-len(root):] == root:
            #    txt = txt[:len(txt)-len(root)]+root[0]+"."
            arg_5, arg_6 = 0, 0
            if arg_0.align == 2: #CENTER
                arg_5 = -arg_0._ctx.textwidth(arg_4, arg_0.textwidth) / 2
                arg_6 =  arg_0._ctx.textheight(arg_4) / 2
            arg_1._textpath = arg_0._ctx.textpath(arg_4, arg_5, arg_6, width=arg_0.textwidth)
            arg_3 = arg_1._textpath

        if arg_0.depth:
            try: __colors.shadow(arg_5=2, arg_6=4, blur=5, arg_2=0.3*arg_2)
            except: pass

        arg_0._ctx.push()
        arg_0._ctx.translate(arg_1.x, arg_1.y)
        arg_0._ctx.scale(arg_2)
        arg_0._ctx.drawpath(arg_3.copy())
        arg_0._ctx.pop()


def Func(arg_0, arg_1, Func, arg_3=1.0):

    """ Visualization of a single edge between two nodes.
    """

    arg_1.moveto(Func.node1.x, Func.node1.y)
    if Func.node2.style == BACK:
        arg_1.curveto(
            Func.node1.x,
            Func.node2.y,
            Func.node2.x,
            Func.node2.y,
            Func.node2.x,
            Func.node2.y,
        )
    else:
        arg_1.lineto(
            Func.node2.x,
            Func.node2.y
        )


def Func(arg_0, arg_1, arg_2=1.0):

    """ Visualization of the label accompanying an edge.
    """

    if arg_0.text and arg_1.label != "":
        arg_0._ctx.nostroke()
        arg_0._ctx.fill(
            arg_0.text.r,
            arg_0.text.g,
            arg_0.text.b,
            arg_0.text.a * arg_2*0.75
        )
        arg_0._ctx.lineheight(1)
        arg_0._ctx.font(arg_0.font)
        arg_0._ctx.fontsize(arg_0.fontsize*0.75)

        # Cache an outlined label text and translate it.
        # This enhances the speed and avoids wiggling text.
        try: arg_3 = arg_1._textpath
        except:
            try: arg_4 = unicode(arg_1.label)
            except:
                try: arg_4 = arg_1.label.decode("utf-8")
                except:
                    pass
            arg_1._textpath = arg_0._ctx.textpath(arg_4, arg_0._ctx.textwidth(" "), 0, width=arg_0.textwidth)
            arg_3 = arg_1._textpath

        # Position the label centrally along the edge line.
        arg_6  = degrees( atan2(arg_1.node2.y-arg_1.node1.y, arg_1.node2.x-arg_1.node1.x) )
        arg_7  = sqrt((arg_1.node2.x-arg_1.node1.x)**2 +(arg_1.node2.y-arg_1.node1.y)**2)
        arg_7  = abs(arg_7-arg_0._ctx.textwidth(arg_1.label)) * 0.5

        arg_0._ctx.push()
        arg_0._ctx.transform(CORNER)
        arg_0._ctx.translate(arg_1.node1.x, arg_1.node1.y)
        arg_0._ctx.rotate(-arg_6)
        arg_0._ctx.translate(arg_7, arg_0.fontsize*1.0)
        arg_0._ctx.scale(arg_2)

        # Flip labels on the left hand side so they are legible.
        if 90 < arg_6%360 < 270:
            arg_0._ctx.translate(arg_0._ctx.textwidth(arg_1.label), -arg_0.fontsize*2.0)
            arg_0._ctx.transform(CENTER)
            arg_0._ctx.rotate(180)
            arg_0._ctx.transform(CORNER)

        arg_0._ctx.drawpath(arg_3.copy())
        arg_0._ctx.pop()


def Func(arg_0, arg_1, **arg_2):
        """ Creates a new style which inherits from the default style,
        or any other style which name is supplied to the optional template parameter.
        """
        if arg_1 == "default":
            arg_0[arg_1] = style(arg_1, arg_0._ctx, **arg_2)
            return arg_0[arg_1]
        arg_3 = arg_2.get("template", "default")
        arg_4 = arg_0[arg_1] = arg_0[arg_3].copy(arg_1)
        for arg_5 in arg_2:
            if arg_4.__dict__.has_key(arg_5):
                arg_4.__dict__[arg_5] = arg_2[arg_5]
        return arg_4


def Func(arg_0, arg_1):
        """ Returns a Func of all styles and a Func of the styleguide.
        """
        arg_2 = styles(arg_1)
        arg_2.guide = arg_0.guide.Func(arg_1)
        dict.__init__(arg_2, [(arg_4.name, arg_4.Func()) for arg_4 in arg_0.values()])
        return arg_2


def Func(arg_0):
        """ Check the rules for each node in the graph and Func the style.
        """
        arg_1 = arg_0.order + arg_0.keys()
        arg_2 = []; [arg_2.append(arg_3) for arg_3 in arg_1 if arg_3 not in arg_2]
        for arg_4 in arg_0.graph.nodes:
            for arg_5 in arg_2:
                if arg_0.has_key(arg_5) and arg_0[arg_5](arg_0.graph, arg_4):
                    arg_4.style = arg_5


def Func(arg_0, arg_1):
        """ Returns a Func of the styleguide for the given graph.
        """
        arg_2 = styleguide(arg_1)
        arg_2.order = arg_0.order
        dict.__init__(arg_2, [(arg_4, arg_5) for arg_4, arg_5 in arg_0.iteritems()])
        return arg_2


def Func(arg_0):
        """
        Loads all possible TUIO profiles and returns a dictionary with the
        profile addresses as keys and an instance of a profile as the value
        """
        arg_1 = {}
        for arg_2, arg_3 in inspect.getmembers(profiles):
            if inspect.isclass(arg_3) and arg_2.endswith('Profile') and arg_2 != 'TuioProfile':
                # Adding profile to the self.profiles dictionary
                arg_4 = arg_3()
                arg_1[arg_4.address] = arg_4
                # setting convenient variable to access objects of profile
                try:
                    setattr(arg_0, arg_4.list_label, arg_4.objs)
                except AttributeError:
                    continue
                # Mapping callback method to every profile
                arg_0.manager.add(arg_0.callback, arg_4.address)
        return arg_1


def Func(arg_0):
        """
        Tells the connection manager to receive the next 1024 byte of messages
        to analyze.
        """
        try:
            arg_0.manager.handle(arg_0.socket.recv(1024))
        except socket.error:
            pass


def Func(arg_0, arg_1, arg_2=False, arg_3=None):
    """
    Func that works even if folder already exists
    """
    # http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth
    if not os.path.exists(arg_1):
        os.makedirs(arg_1)
        shutil.copystat(arg_0, arg_1)
    arg_4 = os.listdir(arg_0)
    if arg_3:
        arg_5 = arg_3(arg_0, arg_4)
        arg_4 = [x for x in arg_4 if x not in arg_5]
    for arg_6 in arg_4:
        arg_7 = os.path.join(arg_0, arg_6)
        arg_8 = os.path.join(arg_1, arg_6)
        if arg_2 and os.path.islink(arg_7):
            if os.path.lexists(arg_8):
                os.remove(arg_8)
            os.symlink(os.readlink(arg_7), arg_8)
            try:
                arg_9 = os.lstat(arg_7)
                arg_10 = stat.S_IMODE(arg_9.st_mode)
                os.lchmod(arg_8, arg_10)
            except:
                pass  # lchmod not available
        elif os.path.isdir(arg_7):
            Func(arg_7, arg_8, arg_2, arg_3)
        else:
            shutil.copy2(arg_7, arg_8)


def Func(arg_0, arg_1=0, arg_2=10, arg_3=False, arg_4=False):

    """ Returns a Google news query formatted as a GoogleSearch list object.
    """

    arg_5 = GOOGLE_NEWS
    return GoogleSearch(arg_0, arg_1, arg_5, "", arg_2, arg_3, arg_4)


def Func(arg_0, arg_1=0, arg_2=10, arg_3=False, arg_4=False):

    """ Returns a Google blogs query formatted as a GoogleSearch list object.
    """

    arg_5 = GOOGLE_BLOGS
    return GoogleSearch(arg_0, arg_1, arg_5, "", arg_2, arg_3, arg_4)


def Func(arg_0, arg_1):

        """ Creates a unique filename in the cache for the id.
        """

        arg_2 = md5(arg_1).hexdigest()
        return os.path.join(arg_0.path, arg_2+arg_0.type)


def Func(arg_0, arg_1):

        """ Returns the age of the cache entry, in days.
        """

        arg_2 = arg_0.hash(arg_1)
        if os.path.exists(arg_2):
            arg_3 = datetime.datetime.fromtimestamp(os.stat(arg_2)[8])
            Func = datetime.datetime.today() - arg_3
            return Func.days
        else:
            return 0


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7=False):
    """ Returns a list of points where the circle and the line intersect.
            Returns an empty list when the circle and the line do not intersect.
    """
    # Based on: http://www.vb-helper.com/howto_net_line_circle_intersections.html
    arg_8 = arg_5 - arg_3
    arg_9 = arg_6 - arg_4
    arg_10 = arg_8 * arg_8 + arg_9 * arg_9
    arg_11 = 2 * (arg_8 * (arg_3 - arg_0) + arg_9 * (arg_4 - arg_1))
    arg_12 = pow(arg_3 - arg_0, 2) + pow(arg_4 - arg_1, 2) - arg_2 * arg_2
    arg_13 = arg_11 * arg_11 - 4 * arg_10 * arg_12
    if arg_10 <= 0.0000001 or arg_13 < 0:
        return []
    elif arg_13 == 0:
        # One point of intersection.
        arg_14 = -arg_11 / (2 * arg_10)
        return [(arg_3 + arg_14 * arg_8, arg_4 + arg_14 * arg_9)]
    else:
        # Two points of intersection.
        # A point of intersection lies on the line segment if 0 <= t <= 1,
        # and on an extension of the segment otherwise.
        arg_15 = []
        arg_16 = sqrt(arg_13)
        arg_17 = (-arg_11 + arg_16) / (2 * arg_10)
        arg_18 = (-arg_11 - arg_16) / (2 * arg_10)
        if arg_7 or 0 <= arg_17 <= 1:
            arg_15.append((arg_3 + arg_17 * arg_8, arg_4 + arg_17 * arg_9))
        if arg_7 or 0 <= arg_18 <= 1:
            arg_15.append((arg_3 + arg_18 * arg_8, arg_4 + arg_18 * arg_9))
        return arg_15


def Func(arg_0, arg_1):
        """ Returns a BezierPath object with the transformation applied.
        """
        arg_2 = arg_1.__class__() # Create a new BezierPath.
        for arg_3 in arg_1:
            if arg_3.cmd == "close":
                arg_2.closepath()
            elif arg_3.cmd == "moveto":
                arg_2.moveto(*arg_0.apply(arg_3.x, arg_3.y))
            elif arg_3.cmd == "lineto":
                arg_2.lineto(*arg_0.apply(arg_3.x, arg_3.y))
            elif arg_3.cmd == "curveto":
                arg_4, arg_5 = arg_0.apply(arg_3.ctrl1.x, arg_3.ctrl1.y)
                arg_6, arg_7 = arg_0.apply(arg_3.ctrl2.x, arg_3.ctrl2.y)
                arg_8, arg_9 = arg_0.apply(arg_3.x, arg_3.y)
                arg_2.curveto(arg_4, arg_5, arg_6, arg_7, arg_8, arg_9)
        return arg_2


def Func(arg_0, arg_1):
        """ Returns bounds that encompass the Func of the two.
            If there is no overlap between the two, None is returned.
        """
        if not arg_0.intersects(arg_1):
            return None
        arg_2, arg_3 = max(arg_0.x, arg_1.x), max(arg_0.y, arg_1.y)
        return Bounds(arg_2, arg_3,
            min(arg_0.x+arg_0.width, arg_1.x+arg_1.width) - arg_2,
            min(arg_0.y+arg_0.height, arg_1.y+arg_1.height) - arg_3)


def Func(arg_0):
    '''Prints an Func message, the help message and quits'''
    global parser
    print (_("Error: ") + arg_0)
    print ()
    parser.print_help()
    sys.exit()


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None, arg_5=1000000, arg_6=False, **arg_7):
        '''
        Draws an outlined path of the input text
        '''
        arg_1 = arg_0.Text(arg_1, arg_2, arg_3, arg_4, arg_5, **arg_7)
        arg_8 = arg_1.path
        if draw:
            arg_8.draw()
        return arg_8


def Func(arg_0, arg_1=1, arg_2=10, arg_3=None, arg_4=10, arg_5=False, arg_6=False):

    """ Returns a Yahoo web query formatted as a YahooSearch list object.
    """

    arg_7 = YAHOO_SEARCH
    return YahooSearch(arg_0, arg_1, arg_2, arg_7, arg_3, arg_4, arg_5, arg_6)


def Func(arg_0, arg_1=1, arg_2=10, arg_3=10, arg_4=False, arg_5=False):

    """ Returns a Yahoo images query formatted as a YahooSearch list object.
    """

    arg_6 = YAHOO_IMAGES
    return YahooSearch(arg_0, arg_1, arg_2, arg_6, None, arg_3, arg_4, arg_5)


def Func(arg_0, arg_1=1, arg_2=10, arg_3=10, arg_4=False, arg_5=False):

    """ Returns a Yahoo news query formatted as a YahooSearch list object.
    """

    arg_6 = YAHOO_NEWS
    return YahooSearch(arg_0, arg_1, arg_2, arg_6, None, arg_3, arg_4, arg_5)


def Func(arg_0, arg_1):

        """Flattens the given layers on the canvas.

        Merges the given layers with the indices in the list
        on the bottom layer in the list.
        The other layers are discarded.

        """

        arg_1.sort()
        if arg_1[0] == 0: del arg_1[0]
        arg_0.flatten(arg_1)


def Func(arg_0, arg_1):

        """Exports the flattened canvas.

        Flattens the canvas.
        PNG retains the alpha channel information.
        Other possibilities are JPEG and GIF.

        """

        arg_0.flatten()
        arg_0.layers[1].img.save(arg_1)
        return arg_1


def Func(arg_0):

        """Moves the layer Func in the stacking order.

        """

        arg_1 = arg_0.index()
        if arg_1 != None:
            del arg_0.canvas.layers[arg_1]
            arg_1 = min(len(arg_0.canvas.layers), arg_1+1)
            arg_0.canvas.layers.insert(arg_1, arg_0)


def Func(arg_0):

        """Moves the layer Func in the stacking order.

        """

        arg_1 = arg_0.index()
        if arg_1 != None:
            del arg_0.canvas.layers[arg_1]
            arg_1 = max(0, arg_1-1)
            arg_0.canvas.layers.insert(arg_1, arg_0)


def Func(arg_0):

        """Creates a copy of the current layer.

        This copy becomes the top layer on the canvas.

        """

        arg_1 = arg_0.canvas.layer(arg_0.img.copy(), arg_0.x, arg_0.y, arg_0.name)
        arg_2 = arg_0.canvas.layers[arg_1]
        arg_2.alpha = arg_0.alpha
        arg_2.blend = arg_0.blend


def Func(arg_0, arg_1=1.0):

        """Increases or decreases the Func in the layer.

        The given value is a percentage to increase
        or decrease the image Func,
        for example 1.2 means Func at 120%.

        """

        arg_2 = ImageEnhance.Contrast(arg_0.img)
        arg_0.img = arg_2.enhance(arg_1)


def Func(arg_0):

        """Inverts the layer.

        """

        arg_1 = arg_0.img.split()[3]
        arg_0.img = arg_0.img.convert("RGB")
        arg_0.img = ImageOps.Func(arg_0.img)
        arg_0.img = arg_0.img.convert("RGBA")
        arg_0.img.putalpha(arg_1)


def Func(arg_0, arg_1, arg_2):

        """Positions the layer at the given coordinates.

        The x and y parameters define where to position
        the top left corner of the layer,
        measured from the top left of the canvas.

        """

        arg_0.x = arg_1
        arg_0.y = arg_2


def Func(arg_0, arg_1=1.0, arg_2=1.0):

        """Resizes the layer to the given width and height.

        When width w or height h is a floating-point number,
        Funcs percentual,
        otherwise Funcs to the given size in pixels.

        """

        from types import FloatType
        arg_3, arg_4 = arg_0.img.size
        if type(arg_1) == FloatType: arg_1 = int(arg_1*arg_3)
        if type(arg_2) == FloatType: arg_2 = int(arg_2*arg_4)

        arg_0.img = arg_0.img.resize((arg_1,arg_2), INTERPOLATION)
        arg_0.w = arg_1
        arg_0.h = arg_2


def Func(arg_0, arg_1):

        """Rotates the layer.

        Rotates the layer by given angle.
        Positive numbers Func counter-clockwise,
        negative numbers Func clockwise.

        Rotate commands are executed instantly,
        so many subsequent Funcs will distort the image.

        """

        #When a layer Funcs, its corners will fall outside
        #of its defined width and height.
        #Thus, its bounding box needs to be expanded.

        #Calculate the diagonal width, and angle from the layer center.
        #This way we can use the layers's corners
        #to calculate the bounding box.

        from math import sqrt, pow, sin, cos, degrees, radians, asin
        arg_2, arg_3 = arg_0.img.size
        arg_4 = sqrt(pow(arg_2,2) + pow(arg_3,2))
        arg_5 = degrees(asin((arg_2*0.5) / (arg_4*0.5)))

        arg_1 = arg_1 % 360
        if arg_1 > 90 and arg_1 <= 270: arg_5 += 180

        arg_6 = sin(radians(arg_5 + arg_1)) * arg_4
        arg_6 = max(arg_6, sin(radians(arg_5 - arg_1)) * arg_4)
        arg_6 = int(abs(arg_6))

        arg_7 = cos(radians(arg_5 + arg_1)) * arg_4
        arg_7 = max(arg_7, cos(radians(arg_5 - arg_1)) * arg_4)
        arg_7 = int(abs(arg_7))

        arg_8 = int((arg_6-arg_2) / 2)
        arg_9 = int((arg_7-arg_3) / 2)
        arg_4 = int(arg_4)

        #The rotation box's background color
        #is the mean pixel value of the rotating image.
        #This is the best option to avoid borders around
        #the Funcd image.

        arg_10 = ImageStat.Stat(arg_0.img).mean
        arg_10 = (int(arg_10[0]), int(arg_10[1]), int(arg_10[2]), 0)

        arg_11 = Image.new("RGBA", (arg_4,arg_4), arg_10)
        arg_11.paste(arg_0.img, ((arg_4-arg_2)/2, (arg_4-arg_3)/2))
        arg_11 = arg_11.Func(arg_1, INTERPOLATION)
        arg_11 = arg_11.crop(((arg_4-arg_6)/2+2, (arg_4-arg_7)/2, arg_4-(arg_4-arg_6)/2, arg_4-(arg_4-arg_7)/2))
        arg_0.img = arg_11

        #Since Func changes the bounding box size,
        #update the layers' width, height, and position,
        #so it Funcs from the center.

        arg_0.x += (arg_0.w-arg_6)/2
        arg_0.y += (arg_0.h-arg_7)/2
        arg_0.w = arg_6
        arg_0.h = arg_7


def Func(arg_0, arg_1=arg_2):

        """Flips the layer, either HORIZONTAL or VERTICAL.

        """

        if arg_1 == arg_2:
            arg_0.img = arg_0.img.transpose(Image.FLIP_LEFT_RIGHT)
        if arg_1 == VERTICAL:
            arg_0.img = arg_0.img.transpose(Image.FLIP_TOP_BOTTOM)


def Func(arg_0, arg_1=1.0):

        """Increases or decreases the sharpness in the layer.

        The given value is a percentage to increase
        or decrease the image sharpness,
        for example 0.8 means sharpness at 80%.

        """

        arg_2 = ImageEnhance.Sharpness(arg_0.img)
        arg_0.img = arg_2.enhance(arg_1)


def Func(arg_0):

        """Returns a histogram for each RGBA channel.

        Returns a 4-tuple of lists, r, g, b, and a.
        Each list has 255 items, a count for each pixel value.

        """

        arg_1 = arg_0.img.histogram()
        arg_2 = arg_1[0:255]
        arg_3 = arg_1[256:511]
        arg_4 = arg_1[512:767]
        arg_5 = arg_1[768:1024]

        return arg_2, arg_3, arg_4, arg_5


def Func(arg_0, arg_1, arg_2=None):
        """
        Initialise bot namespace with info in shoebot.data

        :param filename: Will be set to __file__ in the namespace
        """
        from shoebot import data
        for arg_3 in dir(data):
            arg_1[arg_3] = getattr(data, arg_3)

        for arg_3 in dir(arg_0):
            if arg_3[0] != '_':
                arg_1[arg_3] = getattr(arg_0, arg_3)

        arg_1['_ctx'] = arg_0  # Used in older nodebox scripts.
        arg_1['__file__'] = arg_2


def Func(arg_0, arg_1, arg_2):
        ''' Return False if bot should quit '''
        if arg_1 == 0:
            # First frame always runs
            return True
        if arg_2:
            if arg_1 < arg_2:
                return True
        elif arg_2 is None:
            if arg_0._dynamic:
                return True
            else:
                return False
            return True
        if not arg_0._dynamic:
            return False

        return False


def Func(arg_0, arg_1):
        ''' Sets a new accessible variable.

        :param v: Variable.
        '''
        arg_2 = arg_0._oldvars.get(arg_1.name)
        if arg_2 is not None:
            if isinstance(arg_2, Variable):
                if arg_2.compliesTo(arg_1):
                    arg_1.value = arg_2.value
            else:
                # Set from commandline
                arg_1.value = arg_1.sanitize(arg_2)
        else:
            for arg_4 in VarListener.listeners:
                arg_4.var_added(arg_1)
        arg_0._vars[arg_1.name] = arg_1
        arg_0._namespace[arg_1.name] = arg_1.value
        arg_0._oldvars[arg_1.name] = arg_1
        return arg_1


def Func(arg_0, arg_1, arg_2=[], arg_3="id"):

        """Creates a new table.

        Creates a table with the given name,
        containing the list of given fields.
        Since SQLite uses manifest typing, no data type need be supplied.
        The primary key is "id" by default,
        an integer that can be set or otherwise autoincrements.

        """

        for arg_4 in arg_2:
            if arg_4 == arg_3: arg_2.remove(arg_3)
        arg_5  = "create table "+arg_1+" "
        arg_5 += "("+arg_3+" integer primary key"
        for arg_4 in arg_2: arg_5 += ", "+arg_4+" varchar(255)"
        arg_5 += ")"
        arg_0._cur.execute(arg_5)
        arg_0._con.commit()
        arg_0.index(arg_1, arg_3, unique=True)
        arg_0.connect(arg_0._name)


def Func(arg_0, arg_1, arg_2, arg_3=False, arg_4=True):

        """Creates a table index.

        Creates an index on the given table,
        on the given field with unique values enforced or not,
        in ascending or descending order.

        """

        if arg_3: arg_5 = "unique "
        else: arg_5 = ""
        if arg_4: arg_6 = "asc"
        else: arg_6 = "desc"
        arg_7  = "create "+arg_5+"index index_"+arg_1+"_"+arg_2+" "
        arg_7 += "on "+arg_1+"("+arg_2+" "+arg_6+")"
        arg_0._cur.execute(arg_7)
        arg_0._con.commit()


def Func(arg_0):

        """Commits any pending transactions and Funcs the database.
        """

        arg_0._con.commit()
        arg_0._cur.Func()
        arg_0._con.Func()


def Func(arg_0, arg_1, *arg_2, **arg_3):

        """ Edits the row with given id.
        """

        if arg_2 and arg_3:
            return
        if arg_2 and type(arg_2[0]) == dict:
            arg_4 = [k for k in arg_2[0]]
            arg_5 = [arg_2[0][k] for k in arg_2[0]]
        if arg_3:
            arg_4 = [k for k in arg_3]
            arg_5 = [arg_3[k] for k in arg_3]

        arg_6  = "update "+arg_0._name+" set "+"=?, ".join(arg_4)+"=? where "+arg_0._key+"="+unicode(arg_1)
        arg_0._db._cur.execute(arg_6, arg_5)
        arg_0._db._i += 1
        if arg_0._db._i >= arg_0._db._commit:
            arg_0._db._i = 0
            arg_0._db._con.commit()


def Func(arg_0, arg_1, arg_2="=", arg_3=None):

        """ Deletes the row with given id.
        """

        if arg_3 == None: arg_3 = arg_0._key
        try: arg_1 = unicode(arg_1)
        except: pass
        arg_4 = "delete from "+arg_0._name+" where "+arg_3+" "+arg_2+" ?"
        arg_0._db._cur.execute(arg_4, (arg_1,))


def Func(arg_0=False, arg_1=None):
    """
    Get the next available event or None

    :param block:
    :param timeout:
    :return: None or (event, data)
    """
    try:
        return channel.listen(arg_0=arg_0, arg_1=arg_1).next()['data']
    except StopIteration:
        return None


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None):
    """
    Publish an event ot any subscribers.

    :param event_t:  event type
    :param data:     event data
    :param extra_channels:
    :param wait:
    :return:
    """
    arg_4 = Event(arg_0, arg_1)
    pubsub.publish("shoebot", arg_4)
    for arg_5 in arg_2 or []:
        pubsub.publish(arg_5, arg_4)
    if arg_3 is not None:
        arg_6 = pubsub.subscribe(arg_3)
        arg_6.listen(arg_3)


def Func(arg_0, arg_1):
        '''
        Sets call_transform_mode to point to the
        center_transform or corner_transform
        '''
        if arg_1 == CENTER:
            arg_0._call_transform_mode = arg_0._center_transform
        elif arg_1 == CORNER:
            arg_0._call_transform_mode = arg_0._corner_transform
        else:
            raise ValueError('mode must be CENTER or CORNER')


def Func(arg_0, arg_1=()):
        """
        Doesn't store exactly the same items as Nodebox for ease of implementation,
        it has enough to get the Nodebox Dentrite example working.
        """
        for arg_2, arg_3 in STATES.items():
            if arg_2 in arg_1:
                continue
            setattr(arg_0, arg_3, getattr(arg_0._bot._canvas, arg_2))


def Func(arg_0, arg_1, arg_2=None, arg_3=None, arg_4=None):
        """
        Load changed code into the execution environment.

        Until the code is executed correctly, it will be
        in the 'tenuous' state.
        """
        with LiveExecution.lock:
            arg_0.good_cb = arg_2
            arg_0.bad_cb = arg_3
            try:
                # text compile
                compile(arg_1 + '\n\n', arg_4 or arg_0.filename, "exec")
                arg_0.edited_source = arg_1
            except Exception as e:
                if arg_3:
                    arg_0.edited_source = None
                    arg_6 = traceback.format_exc()
                    arg_0.call_bad_cb(arg_6)
                return
            if arg_4 is not None:
                arg_0.filename = arg_4


def Func(arg_0):
        """
        Attempt to known good or tenuous source.
        """
        with LiveExecution.lock:
            if arg_0.edited_source:
                arg_1, arg_2 = arg_0.Func_tenuous()
                if arg_1:
                    return

            arg_0.do_exec(arg_0.known_good, arg_0.ns)


def Func(arg_0):
        """
        Context in which the user can run the source in a custom manner.

        If no exceptions occur then the source will move from 'tenuous'
        to 'known good'.

        >>> with Func() as (known_good, source, ns):
        >>> ...  exec source in ns
        >>> ...  ns['draw']()

        """
        with LiveExecution.lock:
            if arg_0.edited_source is None:
                yield True, arg_0.known_good, arg_0.ns
                return

            arg_1 = copy.copy(arg_0.ns)
            try:
                yield False, arg_0.edited_source, arg_0.ns
                arg_0.known_good = arg_0.edited_source
                arg_0.edited_source = None
                arg_0.call_good_cb()
                return
            except Exception as ex:
                arg_4 = traceback.format_exc()
                arg_0.call_bad_cb(arg_4)
                arg_0.edited_source = None
                arg_0.ns.clear()
                arg_0.ns.update(arg_1)


def Func(arg_0, arg_1=10):

        """ Boids keep a small distance from other boids.

        Ensures that boids don't collide into each other,
        in a smoothly accelerated motion.

        """

        arg_2 = vy = vz = 0
        for arg_3 in arg_0.boids:
            if arg_3 != arg_0:
                if abs(arg_0.x-arg_3.x) < arg_1: arg_2 += (arg_0.x-arg_3.x)
                if abs(arg_0.y-arg_3.y) < arg_1: vy += (arg_0.y-arg_3.y)
                if abs(arg_0.z-arg_3.z) < arg_1: vz += (arg_0.z-arg_3.z)

        return arg_2, vy, vz


def Func(arg_0):

        """ Returns the angle towards which the boid is steering.
        """

        from math import atan, pi, degrees
        arg_1 = degrees(atan(arg_0.vy/arg_0.vx)) + 360
        if arg_0.vx < 0: arg_1 += 180

        return arg_1


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=50.0):

        """ Tendency towards a particular place.
        """

        return (arg_1-arg_0.x)/arg_4, (arg_2-arg_0.y)/arg_4, (arg_3-arg_0.z)/arg_4


def Func(arg_0, arg_1):

        """ Returns a Func of the layout for the given graph.
        """

        arg_2 = arg_0.__class__(arg_1, arg_0.n)
        arg_2.i = 0
        return arg_2


def Func(arg_0):

        """ Remove nodes and edges and reset the layout.
        """

        dict.Func(arg_0)
        arg_0.nodes = []
        arg_0.edges = []
        arg_0.root  = None

        arg_0.layout.i = 0
        arg_0.alpha = 0


def Func(arg_0, arg_1, arg_2):

        """ Remove edges between nodes with given id's.
        """

        for arg_3 in list(arg_0.edges):
            if arg_1 in (arg_3.node1.id, arg_3.node2.id) and \
               arg_2 in (arg_3.node1.id, arg_3.node2.id):
                arg_3.node1.links.remove(arg_3.node2)
                arg_3.node2.links.remove(arg_3.node1)
                arg_0.edges.remove(arg_3)


def Func(arg_0, arg_1, arg_2):
        """ Returns the Func between the nodes with given id1 and id2.
        """
        if arg_1 in arg_0 and \
           arg_2 in arg_0 and \
           arg_0[arg_2] in arg_0[arg_1].links:
            return arg_0[arg_1].links.Func(arg_2)
        return None


def Func(arg_0, arg_1=10):

        """ Iterates the graph layout and Funcs node positions.
        """

        # The graph fades in when initially constructed.
        arg_0.alpha += 0.05
        arg_0.alpha = min(arg_0.alpha, 1.0)

        # Iterates over the graph's layout.
        # Each step the graph's bounds are recalculated
        # and a number of iterations are processed,
        # more and more as the layout progresses.
        if arg_0.layout.i == 0:
            arg_0.layout.prepare()
            arg_0.layout.i += 1
        elif arg_0.layout.i == 1:
            arg_0.layout.iterate()
        elif arg_0.layout.i < arg_0.layout.n:
            arg_3 = min(arg_1, arg_0.layout.i / 10 + 1)
            for arg_4 in range(arg_3):
                arg_0.layout.iterate()

        # Calculate the absolute center of the graph.
        arg_5, arg_6 = arg_0.layout.bounds
        arg_0.x = _ctx.WIDTH - arg_6.x*arg_0.d - arg_5.x*arg_0.d
        arg_0.y = _ctx.HEIGHT - arg_6.y*arg_0.d - arg_5.y*arg_0.d
        arg_0.x /= 2
        arg_0.y /= 2

        return not arg_0.layout.done


def Func(arg_0, arg_1=0):
        """ Removes all nodes with less or equal links than depth.
        """
        for arg_2 in list(arg_0.nodes):
            if len(arg_2.links) <= arg_1:
                arg_0.remove_node(arg_2.id)


def Func(arg_0, arg_1=True):
        """ Calculates betweenness centrality and returns an node id -> weight dictionary.
        Node betweenness weights are updated in the process.
        """
        arg_2 = proximity.brandes_Func(arg_0, arg_1)
        for arg_3, arg_4 in arg_2.iteritems(): arg_0[arg_3]._betweenness = arg_4
        return arg_2


def Func(arg_0, arg_1=True, arg_2=True, arg_3={},
                               arg_4=None, arg_5=100, arg_6=0.0001):
        """ Calculates eigenvector centrality and returns an node id -> weight dictionary.
        Node eigenvalue weights are updated in the process.
        """
        arg_7 = proximity.Func(
            arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6
        )
        for arg_8, arg_9 in arg_7.iteritems(): arg_0[arg_8]._eigenvalue = arg_9
        return arg_7


def Func(arg_0, arg_1=0.0):
        """ Returns nodes sorted by betweenness centrality.
        Nodes with a lot of passing traffic will be at the front of the list.
        """
        arg_2 = [(arg_4.betweenness, arg_4) for arg_4 in arg_0.nodes if arg_4.betweenness > arg_1]
        arg_2.sort(); arg_2.reverse()
        return [arg_4 for arg_3, arg_4 in arg_2]


def Func(arg_0, arg_1):
        """ Returns nodes with the given category attribute.
        """
        return [arg_2 for arg_2 in arg_0.nodes if arg_2.category == arg_1]


def Func(arg_0, arg_1=2):
        """ Returns a list of leaves, nodes connected to leaves, etc.
        """
        arg_2 = []
        for arg_3 in arg_0.leaves: arg_2 += arg_3.flatten(arg_1-1)
        return cluster.unique(arg_2)


def Func(arg_0):
        """ The number of edges in relation to the total number of possible edges.
        """
        return 2.0*len(arg_0.edges) / (len(arg_0.nodes) * (len(arg_0.nodes)-1))


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=0, arg_5=90):

    """ Compute a cubic Bezier approximation of an elliptical arc.

    (x1, y1) and (x2, y2) are the corners of the enclosing rectangle.
    The coordinate system has coordinates that increase to the right and down.
    Angles, measured in degress, start with 0 to the right (the positive X axis)
    and increase counter-clockwise.
    The arc extends from start_angle to start_angle+extent.
    I.e. start_angle=0 and extent=180 yields an openside-down semi-circle.

    The resulting coordinates are of the form (x1,y1, x2,y2, x3,y3, x4,y4)
    such that the curve goes from (x1, y1) to (x4, y4) with (x2, y2) and
    (x3, y3) as their respective Bezier control points.
    """

    arg_0,arg_1, arg_2,arg_3 = min(arg_0,arg_2), max(arg_1,arg_3), max(arg_0,arg_2), min(arg_1,arg_3)

    if abs(arg_5) <= 90:
        arg_6 = float(arg_5)
        arg_7 = 1
    else:
        arg_7 = int(ceil(abs(arg_5)/90.))
        if arg_7 == 0:
            warnings.warn('Invalid value for extent: %r' % arg_5)
            return []
        arg_6 = float(arg_5) / arg_7

    arg_8 = (arg_0+arg_2)/2.
    arg_9 = (arg_1+arg_3)/2.
    arg_10 = (arg_2-arg_0)/2.
    arg_11 = (arg_3-arg_1)/2.
    arg_12 = radians(arg_6) / 2
    arg_13 = abs(4. / 3. * (1. - cos(arg_12)) / sin(arg_12))

    if arg_6 < 0:
        arg_14 = -1
    else:
        arg_14 = 1

    arg_15 = []

    for arg_16 in range(arg_7):
        arg_17 = radians(arg_4 + arg_16*arg_6)
        arg_18 = radians(arg_4 + (arg_16+1)*arg_6)
        arg_19 = cos(arg_17)
        arg_20 = cos(arg_18)
        arg_21 = sin(arg_17)
        arg_22 = sin(arg_18)
        if arg_6 > 0:
            arg_23 = -arg_13
        else:
            arg_23 = arg_13
        arg_15.append((arg_8 + arg_10 * arg_19,
                          arg_9 - arg_11 * arg_21,
                          arg_8 + arg_10 * (arg_19 + arg_23 * arg_21),
                          arg_9 - arg_11 * (arg_21 - arg_23 * arg_19),
                          arg_8 + arg_10 * (arg_20 - arg_23 * arg_22),
                          arg_9 - arg_11 * (arg_22 + arg_23 * arg_20),
                          arg_8 + arg_10 * arg_20,
                          arg_9 - arg_11 * arg_22))

    return arg_15


def Func(arg_0, arg_1, arg_2, arg_3):
    """ The Func in degrees between two vectors.
    """
    arg_4 = 1.0
    arg_5 = (arg_0*arg_3 - arg_1*arg_2)
    if arg_5 < 0:
        arg_4 = -1.0
    arg_6 = arg_0*arg_2 + arg_1*arg_3
    arg_7 = hypot(arg_0,arg_1) * hypot(arg_2,arg_3)
    arg_8 = min(max(arg_6/arg_7, -1.0), 1.0)
    return arg_4 * degrees(acos(arg_8))


def Func(arg_0):
        '''
        If size is not set, otherwise set size to DEFAULT_SIZE
        and return it.

        This means, only the first call to size() is valid.
        '''
        if not arg_0.size:
            arg_0.size = arg_0.DEFAULT_SIZE
        return arg_0.size


def Func(arg_0, arg_1):
        '''
        Passes the drawqueue to the sink for rendering
        '''
        arg_0.sink.render(arg_0.size_or_default(), arg_1, arg_0._drawqueue)
        arg_0.reset_drawqueue()


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):

        """ Reflects the point x, y through origin x0, y0.
        """

        arg_5 = arg_1 - (arg_3-arg_1)
        arg_6 = arg_2 - (arg_4-arg_2)
        return arg_5, arg_6


def Func(arg_0, arg_1, arg_2, arg_3=2):

        """ Returns true when x, y is on the path stroke outline.
        """

        if arg_0.path != None and len(arg_0.path) > 1 \
        and arg_0.path.contains(arg_1, arg_2):
            # If all points around the mouse are also part of the path,
            # this means we are somewhere INSIDE the path.
            # Only points near the edge (i.e. on the outline stroke)
            # should propagate.
            if not arg_0.path.contains(arg_1+arg_3, arg_2) \
            or not arg_0.path.contains(arg_1, arg_2+arg_3) \
            or not arg_0.path.contains(arg_1-arg_3, arg_2) \
            or not arg_0.path.contains(arg_1, arg_2-arg_3) \
            or not arg_0.path.contains(arg_1+arg_3, arg_2+arg_3) \
            or not arg_0.path.contains(arg_1-arg_3, arg_2-arg_3) \
            or not arg_0.path.contains(arg_1+arg_3, arg_2-arg_3) \
            or not arg_0.path.contains(arg_1-arg_3, arg_2+arg_3):
                return True

        return False


def Func(arg_0):

        """ Exports the path as SVG.

        Uses the filename given when creating this object.
        The file is automatically updated to reflect
        changes to the path.

        """

        arg_1 = ""
        if len(arg_0._points) > 0:
            arg_1 += "M "+str(arg_0._points[0].x)+" "+str(arg_0._points[0].y)+" "
            for arg_2 in arg_0._points:
                if arg_2.cmd == MOVETO:
                    arg_1 += "M "+str(arg_2.x)+" "+str(arg_2.y)+" "
                elif arg_2.cmd == LINETO:
                    arg_1 += "L "+str(arg_2.x)+" "+str(arg_2.y)+" "
                elif arg_2.cmd == CURVETO:
                    arg_1 += "C "
                    arg_1 += str(arg_2.ctrl1.x)+" "+str(arg_2.ctrl1.y)+" "
                    arg_1 += str(arg_2.ctrl2.x)+" "+str(arg_2.ctrl2.y)+" "
                    arg_1 += str(arg_2.x)+" "+str(arg_2.y)+" "

        arg_3 = "rgb("
        arg_3 += str(int(arg_0.path_color.r*255)) + ","
        arg_3 += str(int(arg_0.path_color.g*255)) + ","
        arg_3 += str(int(arg_0.path_color.b*255)) + ")"

        arg_4  = '<?xml version="1.0"?>\n'
        arg_4 += '<svg width="'+str(_ctx.WIDTH)+'pt" height="'+str(_ctx.HEIGHT)+'pt">\n'
        arg_4 += '<g>\n'
        arg_4 += '<path d="'+arg_1+'" fill="none" stroke="'+arg_3+'" stroke-width="'+str(arg_0.strokewidth)+'" />\n'
        arg_4 += '</g>\n'
        arg_4 += '</svg>\n'

        arg_5 = open(arg_0.file+".svg", "w")
        arg_5.write(arg_4)
        arg_5.close()