Returns global variables for generating function from ``func_code``. Includes
        compiled regular expressions and imports, so it does not have to do it every
        time when validation function is called.
558197
def global_state(self):
        
        self._generate_func_code()

        return dict(
            REGEX_PATTERNS=self._compile_regexps,
            re=re,
            JsonSchemaException=JsonSchemaException,
        )
1023256
def _compilecode(function, name, impl, args, varargs, kwargs):
    

    newcodestr, generatedname, impl_name = _generatecode(
        function=function, name=name, impl=impl,
        args=args, varargs=varargs, kwargs=kwargs
    )

    try:
        __file__ = getfile(function)
    except TypeError:
        __file__ = '<string>'

    # compile newcodestr
    code = compile(newcodestr, __file__, 'single')

    # define the code with the new function
    _globals = {}
    exec_(code, _globals)

    # get new code
    _var = _globals[generatedname]
    newco = get_function_code(_var)

    # get new consts list
    newconsts = list(newco.co_consts)

    if PY3:
        newcode = list(newco.co_code)
    else:
        newcode = [ord(co) for co in newco.co_code]

    consts_values = {impl_name: impl}

    # change LOAD_GLOBAL to LOAD_CONST
    index = 0
    newcodelen = len(newcode)
    while index < newcodelen:
        if newcode[index] == LOAD_GLOBAL:
            oparg = newcode[index + 1] + (newcode[index + 2] << 8)
            name = newco.co_names[oparg]
            if name in consts_values:
                const_value = consts_values[name]
                if const_value in newconsts:
                    pos = newconsts.index(const_value)
                else:
                    pos = len(newconsts)
                    newconsts.append(consts_values[name])
                newcode[index] = LOAD_CONST
                newcode[index + 1] = pos & 0xFF
                newcode[index + 2] = pos >> 8
        index += 1

    codeobj = getcodeobj(newconsts, newcode, newco, get_function_code(function))
    # instanciate a new function
    if function is None or isbuiltin(function):
        result = FunctionType(codeobj, {})

    else:
        result = type(function)(
            codeobj,
            get_function_globals(function),
            function.__name__,
            get_function_defaults(function),
            get_function_closure(function)
        )

    return result
292471
def _generate_signature_for_function(self, func):
    """"""
    args_list = []
    argspec = inspect.getargspec(func)
    first_arg_with_default = (
        len(argspec.args or []) - len(argspec.defaults or []))
    for arg in argspec.args[:first_arg_with_default]:
      if arg == "self":
        # Python documentation typically skips `self` when printing method
        # signatures.
        continue
      args_list.append(arg)

    # TODO(mrry): This is a workaround for documenting signature of
    # functions that have the @contextlib.contextmanager decorator.
    # We should do something better.
    if argspec.varargs == "args" and argspec.keywords == "kwds":
      original_func = func.__closure__[0].cell_contents
      return self._generate_signature_for_function(original_func)

    if argspec.defaults:
      for arg, default in zip(
          argspec.args[first_arg_with_default:], argspec.defaults):
        if callable(default):
          args_list.append("%s=%s" % (arg, default.__name__))
        else:
          args_list.append("%s=%r" % (arg, default))
    if argspec.varargs:
      args_list.append("*" + argspec.varargs)
    if argspec.keywords:
      args_list.append("**" + argspec.keywords)
    return "(" + ", ".join(args_list) + ")"
706132
def get_function_body(self, func_indent):
        """"""
        cursor = self.code_editor.textCursor()
        line_number = cursor.blockNumber() + 1
        number_of_lines = self.code_editor.blockCount()
        body_list = []

        for idx in range(number_of_lines - line_number + 1):
            text = to_text_string(cursor.block().text())
            text_indent = get_indent(text)

            if text.strip() == '':
                pass
            elif len(text_indent) <= len(func_indent):
                break

            body_list.append(text)

            cursor.movePosition(QTextCursor.NextBlock)

        return '\n'.join(body_list)
123023
def get_functions_writing_to_variable(self, variable):
        '''
            
        '''
        return [f for f in self.functions if f.is_writing(variable)]
422776
def get_cfg(ast_func):
    
    cfg_func = cfg.Function()
    for ast_var in ast_func.input_variable_list:
        cfg_var = cfg_func.get_variable(ast_var.name)
        cfg_func.add_input_variable(cfg_var)
    for ast_var in ast_func.output_variable_list:
        cfg_var = cfg_func.get_variable(ast_var.name)
        cfg_func.add_output_variable(cfg_var)
    bb_start  = cfg.BasicBlock()
    cfg_func.add_basic_block(bb_start)
    for stmt in ast_func.body:
        bb_temp = bb_start
        bb_temp = process_cfg(stmt, bb_temp, cfg_func)
    cfg_func.clean_up()
    cfg_func.add_summary(ast_func.summary)
    return cfg_func
99617
def exec_func_src2(func, globals_=None, locals_=None, sentinal=None,
                   verbose=False, start=None, stop=None):
    
    import utool as ut
    sourcecode = ut.get_func_sourcecode(func, stripdef=True, stripret=True)
    if globals_ is None:
        globals_ = ut.get_parent_frame().f_globals
    if locals_ is None:
        locals_ = ut.get_parent_frame().f_locals
    if sentinal is not None:
        sourcecode = ut.replace_between_tags(sourcecode, '', sentinal)
    if start is not None or stop is not None:
        sourcecode = '\n'.join(sourcecode.splitlines()[slice(start, stop)])
    if verbose:
        print(ut.color_text(sourcecode, 'python'))
    # TODO: find the name of every variable that was assigned in the function
    # and get it from the context
    locals2_ = locals_.copy()
    globals2_ = globals_.copy()
    six.exec_(sourcecode, globals2_, locals2_)
    return locals2_
177582
def exec_func_src(func, globals_=None, locals_=None, key_list=None,
                  sentinal=None, update=None, keys=None, verbose=False,
                  start=None, stop=None):
    
    if keys is None:
        keys = key_list
    import utool as ut
    sourcecode = ut.get_func_sourcecode(func, stripdef=True, stripret=True)
    if update is None:
        update = ut.inIPython()
    if globals_ is None:
        globals_ = ut.get_parent_frame().f_globals
    if locals_ is None:
        locals_ = ut.get_parent_frame().f_locals
    if sentinal is not None:
        sourcecode = ut.replace_between_tags(sourcecode, '', sentinal)
    if start is not None or stop is not None:
        sourcecode = '\n'.join(sourcecode.splitlines()[slice(start, stop)])
    globals_new = globals_.copy()
    if locals_ is not None:
        globals_new.update(locals_)
        # globals_new.update({k: v for k, v in locals_.items()
        #                     if k not in globals_new})
    orig_globals = globals_new.copy()
    #six.exec_(sourcecode, globals_new, locals_)
    if verbose:
        print(ut.color_text(sourcecode, 'python'))
    six.exec_(sourcecode, globals_new)
    # Draw intermediate steps
    if keys is None:
        #return locals_
        # Remove keys created in function execution
        ut.delete_keys(globals_new, orig_globals.keys())
        if update:
            # update input globals?
            globals_.update(globals_new)
        # ~~ TODO autodetermine the keys from the function vars
        return globals_new
    else:
        if update:
            # update input globals?
            globals_.update(globals_new)
        #var_list = ut.dict_take(locals_, keys)
        var_list = ut.dict_take(globals_new, keys)
        return var_list
376112
function getPluralFunction(locale) {
  let fn = cldr.extractPluralRuleFunction(locale).toString();

  if (fn === EMPTY_RULE) {
    fn = DEFAULT_RULE;
  }

  fn = fn
    .replace(
      toRegExp('function anonymous(n\n/*``*/) {\n'),
      'function plural(n: number): number {\n  ')
    .replace(toRegExp('var'), 'let')
    .replace(toRegExp('if(typeof n==="string")n=parseInt(n,10);'), '')
    .replace(toRegExp('\n}'), ';\n}');

  // The replacement values must match the `Plural` enum from common.
  // We do not use the enum directly to avoid depending on that package.
  return fn
    .replace(toRegExp('"zero"'), ' 0')
    .replace(toRegExp('"one"'), ' 1')
    .replace(toRegExp('"two"'), ' 2')
    .replace(toRegExp('"few"'), ' 3')
    .replace(toRegExp('"many"'), ' 4')
    .replace(toRegExp('"other"'), ' 5');
}
479883
def get_decorators(func):
    
    decorators = []
    # Parse the source code of the function with ast to find the names of
    # all of its decorators.
    tree = ast.parse(inspect.getsource(func))
    for node in ast.iter_child_nodes(tree):
        for dnode in node.decorator_list:
            if isinstance(dnode, ast.Name):
                decorator = func.func_globals[dnode.id]
            elif isinstance(dnode, ast.Attribute):
                module = func.func_globals[dnode.value.id]
                decorator = getattr(module, dnode.attr)
            else:
                raise Exception("Unable to handle decorator node: %s" % dnode)
            decorators.append(decorator)
    return decorators
894520
def _visit_functiondef(self, cls, node, parent):
        """"""
        self._global_names.append({})
        node, doc = self._get_doc(node)
        newnode = cls(node.name, doc, node.lineno, node.col_offset, parent)
        if node.decorator_list:
            decorators = self.visit_decorators(node, newnode)
        else:
            decorators = None
        if PY3 and node.returns:
            returns = self.visit(node.returns, newnode)
        else:
            returns = None

        type_comment_args = type_comment_returns = None
        type_comment_annotation = self.check_function_type_comment(node)
        if type_comment_annotation:
            type_comment_returns, type_comment_args = type_comment_annotation
        newnode.postinit(
            args=self.visit(node.args, newnode),
            body=[self.visit(child, newnode) for child in node.body],
            decorators=decorators,
            returns=returns,
            type_comment_returns=type_comment_returns,
            type_comment_args=type_comment_args,
        )
        self._global_names.pop()
        return newnode
812764
function globals() {
    return {
        range: function(start, stop, step) {
            if(typeof stop === 'undefined') {
                stop = start;
                start = 0;
                step = 1;
            }
            else if(!step) {
                step = 1;
            }

            var arr = [];
            var i;
            if (step > 0) {
                for (i=start; i<stop; i+=step) {
                    arr.push(i);
                }
            } else {
                for (i=start; i>stop; i+=step) {
                    arr.push(i);
                }
            }
            return arr;
        },

        // lipsum: function(n, html, min, max) {
        // },

        cycler: function() {
            return cycler(Array.prototype.slice.call(arguments));
        },

        joiner: function(sep) {
            return joiner(sep);
        }
    };
}
930761
def make(self, src_templ, evaldict=None, addsource=False, **attrs):
        ""
        src = src_templ % vars(self) # expand name and signature
        evaldict = evaldict or {}
        mo = DEF.match(src)
        if mo is None:
            raise SyntaxError('not a valid function template\n%s' % src)
        name = mo.group(1) # extract the function name
        names = set([name] + [arg.strip(' *') for arg in
                             self.shortsignature.split(',')])
        for n in names:
            if n in ('_func_', '_call_'):
                raise NameError('%s is overridden in\n%s' % (n, src))
        if not src.endswith('\n'): # add a newline just for safety
            src += '\n' # this is needed in old versions of Python
        try:
            code = compile(src, '<string>', 'single')
            # print >> sys.stderr, 'Compiling %s' % src
            exec(code, evaldict)
        except:
            print('Error in generated code:', file=sys.stderr)
            print(src, file=sys.stderr)
            raise
        func = evaldict[name]
        if addsource:
            attrs['__source__'] = src
        self.update(func, **attrs)
        return func
778733
def _getGlobals(self, **kwargs):
        
        # Default globals
        globs = {
            "__builtins__": None,
            "all": all,
            "any": any,
            "bool": bool,
            "chr": chr,
            "cmp": cmp,
            "complex": complex,
            "divmod": divmod,
            "enumerate": enumerate,
            "float": float,
            "format": format,
            "frozenset": frozenset,
            "hex": hex,
            "int": int,
            "len": len,
            "list": list,
            "long": long,
            "math": math,
            "max": max,
            "min": min,
            "oct": oct,
            "ord": ord,
            "pow": pow,
            "range": range,
            "reversed": reversed,
            "round": round,
            "str": str,
            "sum": sum,
            "tuple": tuple,
            "xrange": xrange,
        }
        # Update with keyword arguments
        globs.update(kwargs)
        # Update with additional Python libraries
        for imp in self.getPythonImports():
            mod = imp["module"]
            func = imp["function"]
            member = self._getModuleMember(mod, func)
            if member is None:
                raise ImportError(
                    "Could not find member {} of module {}".format(
                        func, mod))
            globs[func] = member
        return globs
26963
def generate_validation_function(self, uri, name):
        
        self._validation_functions_done.add(uri)
        self.l('')
        with self._resolver.resolving(uri) as definition:
            with self.l('def {}(data):', name):
                self.generate_func_code_block(definition, 'data', 'data', clear_variables=True)
                self.l('return data')
521991
def get_global_vars(mod):
    ""
    # https://stackoverflow.com/questions/8820276/docstring-for-variable/31764368#31764368
    import ast,re
    with open(mod.__file__, 'r') as f: fstr = f.read()
    flines = fstr.splitlines()
    d = {}
    for node in ast.walk(ast.parse(fstr)):
        if isinstance(node,ast.Assign) and hasattr(node.targets[0], 'id'):
            key,lineno = node.targets[0].id,node.targets[0].lineno
            codestr = flines[lineno]
            match = re.match(f"^({key})\s*=\s*.*", codestr)
            if match and match.group(1) != '__all__': # only top level assignment
                d[key] = f'`{codestr}` {get_source_link(mod, lineno)}'
    return d
121130
def functions(self):
        
        out = {}
        for key in self._func_names:
            out[key[len(self._prefix):]] = getattr(self, key)
        return out