Register me as an IPython extension
    
    Captures all C output during execution and forwards to sys.
    
    Does nothing on terminal IPython.
    
    Use: %load_ext wurlitzer
187412
def load_ipython_extension(ip):
    
    if not getattr(ip, 'kernel'):
        warnings.warn(
            "wurlitzer extension doesn't do anything in terminal IPython"
        )
        return
    ip.events.register('pre_execute', sys_pipes_forever)
    ip.events.register('post_execute', stop_sys_pipes)
231759
def setup(self):
        

        # SIGTSTP will be received from i3bar indicating that all output should
        # stop and we should consider py3status suspended.  It is however
        # important that any processes using i3 ipc should continue to receive
        # those events otherwise it can lead to a stall in i3.
        signal(SIGTSTP, self.i3bar_stop)
        # SIGCONT indicates output should be resumed.
        signal(SIGCONT, self.i3bar_start)

        # log py3status and python versions
        self.log("=" * 8)
        msg = "Starting py3status version {version} python {python_version}"
        self.log(msg.format(**self.config))

        try:
            # if running from git then log the branch and last commit
            # we do this by looking in the .git directory
            git_path = os.path.join(os.path.dirname(__file__), "..", ".git")
            # branch
            with open(os.path.join(git_path, "HEAD"), "r") as f:
                out = f.readline()
            branch = "/".join(out.strip().split("/")[2:])
            self.log("git branch: {}".format(branch))
            # last commit
            log_path = os.path.join(git_path, "logs", "refs", "heads", branch)
            with open(log_path, "r") as f:
                out = f.readlines()[-1]
            sha = out.split(" ")[1][:7]
            msg = ":".join(out.strip().split("\t")[-1].split(":")[1:])
            self.log("git commit: {}{}".format(sha, msg))
        except:  # noqa e722
            pass

        self.log("window manager: {}".format(self.config["wm_name"]))

        if self.config["debug"]:
            self.log("py3status started with config {}".format(self.config))

        if self.config["gevent"]:
            self.is_gevent = self.gevent_monkey_patch_report()
        else:
            self.is_gevent = False

        # read i3status.conf
        config_path = self.config["i3status_config_path"]
        self.log("config file: {}".format(self.config["i3status_config_path"]))
        self.config["py3_config"] = process_config(config_path, self)

        # setup i3status thread
        self.i3status_thread = I3status(self)

        # If standalone or no i3status modules then use the mock i3status
        # else start i3status thread.
        i3s_modules = self.config["py3_config"]["i3s_modules"]
        if self.config["standalone"] or not i3s_modules:
            self.i3status_thread.mock()
            i3s_mode = "mocked"
        else:
            for module in i3s_modules:
                self.log("adding module {}".format(module))
            i3s_mode = "started"
            self.i3status_thread.start()
            while not self.i3status_thread.ready:
                if not self.i3status_thread.is_alive():
                    # i3status is having a bad day, so tell the user what went
                    # wrong and do the best we can with just py3status modules.
                    err = self.i3status_thread.error
                    self.notify_user(err)
                    self.i3status_thread.mock()
                    i3s_mode = "mocked"
                    break
                time.sleep(0.1)
        if self.config["debug"]:
            self.log(
                "i3status thread {} with config {}".format(
                    i3s_mode, self.config["py3_config"]
                )
            )

        # add i3status thread monitoring task
        if i3s_mode == "started":
            task = CheckI3StatusThread(self.i3status_thread, self)
            self.timeout_queue_add(task)

        # setup input events thread
        self.events_thread = Events(self)
        self.events_thread.daemon = True
        self.events_thread.start()
        if self.config["debug"]:
            self.log("events thread started")

        # initialise the command server
        self.commands_thread = CommandServer(self)
        self.commands_thread.daemon = True
        self.commands_thread.start()
        if self.config["debug"]:
            self.log("commands thread started")

        # initialize the udev monitor (lazy)
        self.udev_monitor = UdevMonitor(self)

        # suppress modules' ouput wrt issue #20
        if not self.config["debug"]:
            sys.stdout = open("/dev/null", "w")
            sys.stderr = open("/dev/null", "w")

        # get the list of py3status configured modules
        self.py3_modules = self.config["py3_config"]["py3_modules"]

        # get a dict of all user provided modules
        self.log("modules include paths: {}".format(self.config["include_paths"]))
        user_modules = self.get_user_configured_modules()
        if self.config["debug"]:
            self.log("user_modules={}".format(user_modules))

        if self.py3_modules:
            # load and spawn i3status.conf configured modules threads
            self.load_modules(self.py3_modules, user_modules)
270934
def execute_in_namespace(func, use_network_ns=True):
    
    flags = (signal.SIGCHLD |
        libc.CLONE_NEWNS | libc.CLONE_NEWUTS | libc.CLONE_NEWIPC | libc.CLONE_NEWUSER |
        libc.CLONE_NEWPID)
    if use_network_ns:
        flags |= libc.CLONE_NEWNET

    # We use the syscall clone() here, which is similar to fork().
    # Calling it without letting Python know about it is dangerous (especially because
    # we want to execute Python code in the child, too), but so far it seems to work.
    # Basically we attempt to do (almost) the same that os.fork() does (cf. function os_fork_impl
    # in https://github.com/python/cpython/blob/master/Modules/posixmodule.c).
    # We currently do not take the import lock os.lock() does because it is only available
    # via an internal API, and because the child should never import anything anyway
    # (inside the container, modules might not be visible).
    # It is very important, however, that we have the GIL during clone(),
    # otherwise the child will often deadlock when trying to execute Python code.
    # Luckily, the ctypes module allows us to hold the GIL while executing the
    # function by using ctypes.PyDLL as library access instead of ctypes.CLL.

    def child_func():
        # This is necessary for correcting the Python interpreter state after a
        # fork-like operation. For example, it resets the GIL and fixes state of
        # several modules like threading and signal.
        ctypes.pythonapi.PyOS_AfterFork()

        return func()

    with allocate_stack() as stack:
        pid = libc.clone(ctypes.CFUNCTYPE(ctypes.c_int)(child_func), stack, flags, None)
    return pid
1097536
def _load_wurlitzer(self):
        """"""
        # Wurlitzer has no effect on Windows
        if not os.name == 'nt':
            from IPython.core.getipython import get_ipython
            # Enclose this in a try/except because if it fails the
            # console will be totally unusable.
            # Fixes spyder-ide/spyder#8668
            try:
                get_ipython().run_line_magic('reload_ext', 'wurlitzer')
            except Exception:
                pass
159653
def do_execute(self):
        
        formatstr = str(self.resolve_option("format"))
        expanded = self.storagehandler.expand(formatstr)
        self._output.append(Token(expanded))
        return None
792655
def compile_cxxfile(module_name, cxxfile, output_binary=None, **kwargs):
    '''

    '''

    builddir = mkdtemp()
    buildtmp = mkdtemp()

    extension_args = make_extension(python=True, **kwargs)

    extension = PythranExtension(module_name,
                                 [cxxfile],
                                 **extension_args)

    try:
        setup(name=module_name,
              ext_modules=[extension],
              cmdclass={"build_ext": PythranBuildExt},
              # fake CLI call
              script_name='setup.py',
              script_args=['--verbose'
                           if logger.isEnabledFor(logging.INFO)
                           else '--quiet',
                           'build_ext',
                           '--build-lib', builddir,
                           '--build-temp', buildtmp]
              )
    except SystemExit as e:
        raise CompileError(str(e))

    def copy(src_file, dest_file):
        # not using shutil.copy because it fails to copy stat across devices
        with open(src_file, 'rb') as src:
            with open(dest_file, 'wb') as dest:
                dest.write(src.read())

    ext = sysconfig.get_config_var('SO')
    # Copy all generated files including the module name prefix (.pdb, ...)
    for f in glob.glob(os.path.join(builddir, module_name + "*")):
        if f.endswith(ext):
            if not output_binary:
                output_binary = os.path.join(os.getcwd(), module_name + ext)
            copy(f, output_binary)
        else:
            if not output_binary:
                output_directory = os.getcwd()
            else:
                output_directory = os.path.dirname(output_binary)
            copy(f, os.path.join(output_directory, os.path.basename(f)))
    shutil.rmtree(builddir)
    shutil.rmtree(buildtmp)

    logger.info("Generated module: " + module_name)
    logger.info("Output: " + output_binary)

    return output_binary
1318971
def load_ipython_extension(ip):
    
    #ip = get_ipython()
    ip.register_magics(CustomMagics)
    # enable C# (CSHARP) highlight
    patch = ("IPython.config.cell_magic_highlight['clrmagic'] = "
             "{'reg':[/^%%CS/]};")
    js = display.Javascript(data=patch,
                            lib=["https://github.com/codemirror/CodeMirror/blob/master/mode/clike/clike.js"])
724941
def do_execute(self):
        
        result = None
        f = None
        try:
            if bool(self.resolve_option("append")):
                f = open(str(self.resolve_option("output")), "a")
            else:
                f = open(str(self.resolve_option("output")), "w")
            f.write(str(self.input.payload))
            f.write("\n")
        except Exception as e:
            result = self.full_name + "\n" + traceback.format_exc()
        finally:
            if f is not None:
                f.close()
        return result
1057477
def output_capturing():
    """"""
    out = sys.stdout

    sys.stdout = StringIO()

    try:
        yield

    finally:
        sys.stdout = out
1133667
def load_library_permanently(filename):
    
    with ffi.OutputString() as outerr:
        if ffi.lib.LLVMPY_LoadLibraryPermanently(
                _encode_string(filename), outerr):
            raise RuntimeError(str(outerr))
1244018
def _compiled(self):
        """"""
        # Dev Notes:
        # Because of fast locals in functions in both CPython and PyPy, getting a
        # function to execute makes the code a few times faster than
        # just executing it in the global exec scope.
        prog = [self._prog_start]

        simple_func = {  # OPS
            'w': lambda x: x,
            'r': lambda x: x,
            '~': lambda x: '(~' + x + ')',
            '&': lambda l, r: '(' + l + '&' + r + ')',
            '|': lambda l, r: '(' + l + '|' + r + ')',
            '^': lambda l, r: '(' + l + '^' + r + ')',
            'n': lambda l, r: '(~(' + l + '&' + r + '))',
            '+': lambda l, r: '(' + l + '+' + r + ')',
            '-': lambda l, r: '(' + l + '-' + r + ')',
            '*': lambda l, r: '(' + l + '*' + r + ')',
            '<': lambda l, r: 'int(' + l + '<' + r + ')',
            '>': lambda l, r: 'int(' + l + '>' + r + ')',
            '=': lambda l, r: 'int(' + l + '==' + r + ')',
            'x': lambda sel, f, t: '({}) if ({}==0) else ({})'.format(f, sel, t),
        }

        def shift(value, direction, shift_amt):
            if shift_amt == 0:
                return value
            else:
                return '(%s %s %d)' % (value, direction, shift_amt)

        def make_split():
            if split_start_bit == 0:
                bit = '(%d & %s)' % ((1 << split_length) - 1, source)
            elif len(net.args[0]) - split_start_bit == split_length:
                bit = '(%s >> %d)' % (source, split_start_bit)
            else:
                bit = '(%d & (%s >> %d))' % ((1 << split_length) - 1, source, split_start_bit)
            return shift(bit, '<<', split_res_start_bit)

        for net in self.block:
            if net.op in simple_func:
                argvals = (self._arg_varname(arg) for arg in net.args)
                expr = simple_func[net.op](*argvals)
            elif net.op == 'c':
                expr = ''
                for i in range(len(net.args)):
                    if expr is not '':
                        expr += ' | '
                    shiftby = sum(len(j) for j in net.args[i+1:])
                    expr += shift(self._arg_varname(net.args[i]), '<<', shiftby)
            elif net.op == 's':
                source = self._arg_varname(net.args[0])
                expr = ''
                split_length = 0
                split_start_bit = -2
                split_res_start_bit = -1

                for i, b in enumerate(net.op_param):
                    if b != split_start_bit + split_length:
                        if split_start_bit >= 0:
                            # create a wire
                            expr += make_split() + '|'
                        split_length = 1
                        split_start_bit = b
                        split_res_start_bit = i
                    else:
                        split_length += 1
                expr += make_split()
            elif net.op == 'm':
                read_addr = self._arg_varname(net.args[0])
                mem = net.op_param[1]
                if isinstance(net.op_param[1], RomBlock):
                    expr = 'd["%s"]._get_read_data(%s)' % (self._mem_varname(mem), read_addr)
                else:  # memories act async for reads
                    expr = 'd["%s"].get(%s, %s)' % (self._mem_varname(mem),
                                                    read_addr, self.default_value)
            elif net.op == '@':
                mem = self._mem_varname(net.op_param[1])
                write_addr, write_val, write_enable = (self._arg_varname(a) for a in net.args)
                prog.append('    if {}:'.format(write_enable))
                prog.append('        mem_ws.append(("{}", {}, {}))'
                            .format(mem, write_addr, write_val))
                continue  # memwrites are special
            else:
                raise PyrtlError('FastSimulation cannot handle primitive "%s"' % net.op)

            # prog.append('    #  ' + str(net))
            result = self._dest_varname(net.dests[0])
            if len(net.dests[0]) == self._no_mask_bitwidth[net.op](net):
                prog.append("    %s = %s" % (result, expr))
            else:
                mask = str(net.dests[0].bitmask)
                prog.append('    %s = %s & %s' % (result, mask, expr))

        # add traced wires to dict
        if self.tracer is not None:
            for wire_name in self.tracer.trace:
                wire = self.block.wirevector_by_name[wire_name]
                if not isinstance(wire, (Input, Const, Register, Output)):
                    v_wire_name = self._varname(wire)
                    prog.append('    outs["%s"] = %s' % (wire_name, v_wire_name))

        prog.append("    return regs, outs, mem_ws")
        return '\n'.join(prog)
1317874
def unload_ipython_extension(ip):
    
    if not getattr(ip, 'kernel'):
        return
    ip.events.unregister('pre_execute', sys_pipes_forever)
    ip.events.unregister('post_execute', stop_sys_pipes)
776875
def execute(self, conn, app, release_version, pset_hash, output_label, global_tag, transaction = False):
        
        binds = {}
        binds["app_name"]=app
        binds["release_version"]=release_version
        binds["pset_hash"]=pset_hash
        binds["output_module_label"]=output_label
        binds["global_tag"]=global_tag

        result = self.dbi.processData(self.sql, binds, conn, transaction)

        plist = self.formatDict(result)

	if len(plist) < 1: return -1
        return plist[0]["output_mod_config_id"]
823253
def do_execute(self):
        
        result = None
        evl = self.input.payload
        pltclassifier.plot_prc(
            evl,
            class_index=self.resolve_option("class_index"),
            title=self.resolve_option("title"),
            key_loc=self.resolve_option("key_loc"),
            outfile=self.resolve_option("outfile"),
            wait=bool(self.resolve_option("wait")))
        return result
459303
def ipath_from_ext(self, ext):
        
        return os.path.join(self.workdir, self.prefix.idata + "_" + ext)
576306
def extern_call(self, context_handle, func, args_ptr, args_len):
    """"""
    c = self._ffi.from_handle(context_handle)
    runnable = c.from_value(func[0])
    args = tuple(c.from_value(arg[0]) for arg in self._ffi.unpack(args_ptr, args_len))
    return self.call(c, runnable, args)
177058
def iprompt(self, out=sys.stdout):
        """"""

        cmds = """
        Commands:
          i -- index: print current iteration index
          p -- pause: interrupt sampling and return to the main console.
                      Sampling can be resumed later with icontinue().
          h -- halt:  stop sampling and truncate trace. Sampling cannot be
                      resumed for this chain.
          b -- bg:    return to the main console. The sampling will still
                      run in a background thread. There is a possibility of
                      malfunction if you interfere with the Sampler's
                      state or the database during sampling. Use this at your
                      own risk.
        """

        print_("""==============
 PyMC console
==============

        PyMC is now sampling. Use the following commands to query or pause the sampler.
        """, file=out)
        print_(cmds, file=out)

        prompt = True
        try:
            while self.status in ['running', 'paused']:
                    # sys.stdout.write('pymc> ')
                if prompt:
                    out.write('pymc > ')
                    out.flush()

                if self._exc_info is not None:
                    a, b, c = self._exc_info
                    reraise(a, b, c)

                cmd = utils.getInput().strip()
                if cmd == 'i':
                    print_(
                        'Current iteration: %i of %i' %
                        (self._current_iter, self._iter), file=out)
                    prompt = True
                elif cmd == 'p':
                    self.status = 'paused'
                    break
                elif cmd == 'h':
                    self.status = 'halt'
                    self._halt()
                    break
                elif cmd == 'b':
                    return
                elif cmd == '\n':
                    prompt = True
                    pass
                elif cmd == '':
                    prompt = False
                else:
                    print_('Unknown command: ', cmd, file=out)
                    print_(cmds, file=out)
                    prompt = True

        except KeyboardInterrupt:
            if not self.status == 'ready':
                self.status = 'halt'
                self._halt()

        if self.status == 'ready':
            print_("Sampling terminated successfully.", file=out)
        else:
            print_('Waiting for current iteration to finish...', file=out)
            while self._sampling_thread.isAlive():
                sleep(.1)
            print_('Exiting interactive prompt...', file=out)
            if self.status == 'paused':
                print_(
                    'Call icontinue method to continue, or call halt method to truncate traces and stop.',
                    file=out)