def shell(): """Run interactive PySistem shell""" import pysistem.models import code modules = ('checkers', 'compilers', 'contests', 'problems', 'users', 'submissions', 'test_pairs', 'groups', 'lessons', 'settings') context = dict(app=_request_ctx_stack.top.app) for module in modules: mod = getattr(__import__('pysistem.%s.model' % module), module).model for obj in dir(mod): if not obj.startswith('_'): context[obj] = getattr(mod, obj) # Try IPython try: try: # 0.10.x from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed() ipshell(global_ns=dict(), local_ns=context, colors='Linux') except ImportError: # 0.12+ from IPython import embed embed(user_ns=context, colors='Linux') return except ImportError: pass code.interact(local=context)
def main(): # web link url = "http://www.cnn.com" if "-l" in sys.argv: url = sys.argv[2] # get html from web page html = urlopen(url) # create beautiful object bsObj = BeautifulSoup(html.read()) # create a list of all the link html tags on the webpage links = bsObj.findAll("link") # for each link in links for link in links: print link tempLink = str(link) print "Domain: " + tempLink[tempLink.find("href") + 4 : tempLink.find("rel")] # drop into interactive python shell code.interact(local=locals()) # print stuff print (bsObj.prettify()[0:100])
def shell(): """Run a Python shell inside Flask application context.""" with flask_app.test_request_context(): context = dict(app=_request_ctx_stack.top.app) # Use basic python shell code.interact(local=context)
def run(self, no_ipython, no_bpython): """ Runs the shell. If no_bpython is False or use_bpython is True, then a BPython shell is run (if installed). Else, if no_ipython is False or use_python is True then a IPython shell is run (if installed). """ context = self.get_context() if not no_bpython: # Try BPython try: from bpython import embed embed(banner=self.banner, locals_=self.get_context()) return except ImportError: # Try IPython if not no_ipython: try: import IPython try: sh = IPython.Shell.IPShellEmbed(banner=self.banner) except AttributeError: sh = IPython.frontend.terminal.embed.InteractiveShellEmbed(banner1=self.banner) sh(global_ns=dict(), local_ns=context) return except ImportError: pass # Use basic python shell code.interact(self.banner, local=context)
def run_plain(): # Using normal Python shell import code imported_objects = import_objects(options, self.style) try: # Try activating rlcompleter, because it's handy. import readline except ImportError: pass else: # We don't have to wrap the following import in a 'try', because # we already know 'readline' was imported successfully. import rlcompleter readline.set_completer(rlcompleter.Completer(imported_objects).complete) readline.parse_and_bind("tab:complete") # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system # conventions and get $PYTHONSTARTUP first then import user. if use_pythonrc: pythonrc = os.environ.get("PYTHONSTARTUP") if pythonrc and os.path.isfile(pythonrc): global_ns = {} with open(pythonrc) as rcfile: try: six.exec_(compile(rcfile.read(), pythonrc, 'exec'), global_ns) imported_objects.update(global_ns) except NameError: pass # This will import .pythonrc.py as a side-effect try: import user # NOQA except ImportError: pass code.interact(local=imported_objects)
def interact(msgIndexFile, fldIndexFile): global server, options msgIndex = deserialize(msgIndexFile) fldIndex = deserialize(fldIndexFile) if server is None: server = ImapServer(options.server, options.port, options.email, options.pwd) server.select(server.AllMailFolder, readonly=True) banner = '\nBaGoMa server instance is "s"'; instructions = """ Hit Ctrl-D to exit interpreter and continue program. Some things to do: s.getFolders() s.uid('SEARCH', '5:90') s.saveMsg(5190, '__Test01', options.backupDir, s.AllMailFolder) """ try: from IPython.Shell import IPShellEmbed s = server ipshell = IPShellEmbed('', banner=banner) ipshell(instructions) except ImportError: import code code.interact(banner + "\n" + instructions, local=dict(s=server, options=options, msgIndex=msgIndex, fldIndex=fldIndex))
def start_shell(self, runner): try: import IPython except: IPython = None if not hasattr(self, "bridge"): self.start_jsbridge_network() jsobj = JSObject(self.bridge, window_string) if IPython is None or self.options.usecode: import code code.interact( local={ "jsobj": jsobj, "getBrowserWindow": lambda: getBrowserWindow(self.bridge), "back_channel": self.back_channel, } ) else: from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed([]) ipshell( local_ns={ "jsobj": jsobj, "getBrowserWindow": lambda: getBrowserWindow(self.bridge), "back_channel": self.back_channel, } ) runner.stop()
def _run(): global _run _run = lambda: None msg = """ =================================================== Welcome to Face++ Interactive Shell! Here, you can explore and play with Face++ APIs :) --------------------------------------------------- Getting Started: 0. Register a user and API key on http://www.faceplusplus.com 1. Write your API key/secret in apikey.cfg 2. Start this interactive shell and try various APIs For example, to find all faces in a local image file, just type: api.detection.detect(img = File(r'<path to the image file>')) Enjoy! """ try: from IPython import embed embed(banner2 = msg) except ImportError: import code code.interact(msg, local = globals())
def keyboard(banner='Type EOF/^D to continue'): """Clone of the matlab keyboard() function. Drop down into interactive shell for debugging Use it like the matlab keyboard command -- dumps you into interactive shell where you can poke around and look at variables in the current stack frame The idea and code are stolen from something Fredrick Lundh posted on the web a while back. """ import code, sys # use exception trick to pick up the current frame try: raise None except: frame = sys.exc_info()[2].tb_frame.f_back # evaluate commands in current namespace namespace = frame.f_globals.copy() namespace.update(frame.f_locals) code.interact(banner=banner, local=namespace)
def inputMenu(inputDict, header = None, footer = None, errorMsg = 'That is not an option please select a different value.', promptMsg = 'What is your selection: ', extraOptions = True): s = '' if header: s += '{}\n'.format(header) for k in inputDict.keys(): s += '{0}) {1}\n'.format(k,inputDict[k]) if extraOptions: s += 'i) open python console\n' s += 'q) quit\n' if footer: s += '{}\n'.format(footer) print(s, end = '') selection = input(promptMsg) if selection in inputDict: return selection elif extraOptions and selection == 'q': sys.exit() elif extraOptions and selection == 'i': bannerMsg = 'Python {0} on {1}\nType "help", "copyright", "credits" or "license" for more information.\nmetaknowledge is imported as "metaknowledge" and Networkx is imported as "nx".\n'.format(sys.version, platform.system()) if RC: bannerMsg += "The metaknowledge RecordCollection is called 'RC'" if G: bannerMsg += " and the Networkx graph is called 'G'." else: bannerMsg += '.' code.interact(local = globals(), banner = bannerMsg) else: print('\033[93m\a' + errorMsg + '\033[0m') #Not windows compatible return inputMenu(inputDict, header = header, footer = footer, errorMsg = errorMsg, promptMsg = promptMsg)
def on_error(self,e): self.info['run_status'] = 'error' # construct meaningful traceback import traceback, sys, code type, value, tb = sys.exc_info() tbs = [] tbm = [] while tb is not None: stb = traceback.extract_tb(tb) filename = stb[0][0] tdir,fn = os.path.split(filename) maindir = os.path.dirname(sys.modules['__main__'].__file__) if tdir == maindir: tbs.append(tb) tbm.append("{} : {} : {} : {}".format(fn,stb[0][1],stb[0][2],stb[0][3])) tb = tb.tb_next # print custom traceback print("\n\n- Experiment error traceback (use --gdb to debug) -\n") print("\n".join(tbm)+"\n") print("{}: {}\n".format(e.__class__.__name__,e)) # enter interactive mode (i.e. post mortem) if FLAGS.gdb: print("\nPost Mortem:") for i in reversed(range(len(tbs))): print("Level {}: {}".format(i,tbm[i])) # pdb.post_mortem(tbs[i]) frame = tbs[i].tb_frame ns = dict(frame.f_globals) ns.update(frame.f_locals) code.interact(banner="", local=ns) print("\n")
def shell_command(): """Run an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to it's configuration. This is useful for executing small snippets of management code without having to manually configure the application. """ import code from flask.globals import _app_ctx_stack app = _app_ctx_stack.top.app banner = 'Python %s on %s\nApp: %s [%s]\nInstance: %s' % ( sys.version, sys.platform, app.import_name, app.env, app.instance_path, ) ctx = {} # Support the regular Python interpreter startup script if someone # is using it. startup = os.environ.get('PYTHONSTARTUP') if startup and os.path.isfile(startup): with open(startup, 'r') as f: eval(compile(f.read(), startup, 'exec'), ctx) ctx.update(app.make_shell_context()) code.interact(banner=banner, local=ctx)
def keyboard(banner=None): ''' Function that mimics the matlab keyboard command ''' # use exception trick to pick up the current frame try: raise None except: frame = sys.exc_info()[2].tb_frame.f_back if sys.version_info < (3,): eval('print "# Use quit() to exit :) Happy debugging!"') else: eval('print("# Use quit() to exit :) Happy debugging!")') # evaluate commands in current namespace namespace = frame.f_globals.copy() namespace.update(frame.f_locals) if not ('quit' in namespace): # Make sure that 'quit' is defined def leave(): raise SystemExit namespace['quit']=leave def exitNLevel(n=1): NLevel = 'raise SystemExit; ' * n exec(NLevel) namespace['exitNLevel']=exitNLevel try: code.interact(banner=banner, local=namespace) except SystemExit: return
def interactive_browser(srcdir=None): """ launch an interactive view for browsing the original archives. """ info("launching interactive data browser...") # the variable is actually used, in the interactive prompt. # pylint: disable=unused-variable data, game_versions = mount_input(srcdir) if not data: warn("cannot launch browser as no valid input assets were found.") return def save(path, target): """ save a path to a custom target """ with path.open("rb") as infile: with open(target, "rb") as outfile: outfile.write(infile.read()) def save_slp(path, target, palette=None): """ save a slp as png. """ from .texture import Texture from .slp import SLP from .driver import get_palette if not palette: palette = get_palette(data, game_versions) with path.open("rb") as slpfile: tex = Texture(SLP(slpfile.read()), palette) out_path, filename = os.path.split(target) tex.save(Directory(out_path).root, filename) import code from pprint import pprint import rlcompleter completer = rlcompleter.Completer(locals()) readline.parse_and_bind("tab: complete") readline.parse_and_bind("set show-all-if-ambiguous on") readline.set_completer(completer.complete) code.interact( banner=("\nuse `pprint` for beautiful output!\n" "you can access stuff by the `data` variable!\n" "`data` is an openage.util.fslike.path.Path!\n" "* list contents: `pprint(list(data['graphics'].list()))`\n" "* dump data: `save(data['file/path'], '/tmp/outputfile')`.\n" "* save a slp as png: `save_slp(data['dir/123.slp'], '/tmp/pic.png')`.\n"), local=locals() )
def full_hydrate(self, bundle): import code;code.interact(local=locals()) accept = bundle.data.get("accept") group_name = bundle.data.get("group") if accept: bundle.obj.accept(group_name) return bundle
def upload(self): service = auth(self.user) bucket = service.get_bucket(self.bucket_id) key = boto.s3.key.Key(bucket) key.key = self.key_id pf = ProgressFile(self.pathname, 'r') try: # actually upload key.set_contents_from_file(pf) if self.debug_mode: import code code.interact(local=locals()) self.new_url = key.generate_url(0) ret = True except: self.ret_text = "internet archive error: ", sys.exc_info()[0] ret = False return ret
def run_shell(self, no_ipython, no_bpython, quiet): # based on the flask-script Shell.run() method context = self.get_context() if not no_bpython: try: from bpython import embed embed(banner=self.banner, locals_=context) return except ImportError: pass if not no_ipython: try: from IPython.terminal.ipapp import TerminalIPythonApp ipython_app = TerminalIPythonApp.instance(user_ns=context, display_banner=not quiet) ipython_app.initialize(argv=[]) ipython_app.shell.show_banner(self.banner) ipython_app.start() return except ImportError: pass # Use basic python shell import code code.interact(self.banner, local=context)
def startInterpreter(argv=None, prog=None): import code, optparse connectOptions = {} replVariables = {'r':net.Connection._r, 'rethinkdb':net.Connection._r} banner = 'The RethinkDB driver has been imported as `r`.' # -- get host/port setup # - parse command line parser = utils_common.CommonOptionsParser(prog=prog, description='An interactive Python shell (repl) with the RethinkDB driver imported') options, args = parser.parse_args(argv if argv is not None else sys.argv[1:], connect=False) if args: parser.error('No positional arguments supported. Unrecognized option(s): %s' % args) # -- open connection try: replVariables['conn'] = options.retryQuery.conn() replVariables['conn'].repl() banner += ''' A connection to %s:%d has been established as `conn` and can be used by calling `run()` on a query without any arguments.''' % (options.hostname, options.driver_port) except errors.ReqlDriverError as e: banner += '\nWarning: %s' % str(e) if options.debug: banner += '\n' + traceback.format_exc() # -- start interpreter code.interact(banner=banner + '\n==========', local=replVariables)
def up_richard(self, ep): host = pw.richard[ep.show.client.richard_id] endpoint = 'http://{hostname}/api/v2'.format( hostname=host['host']) v_id = get_video_id(ep.public_url) video_data = get_video(api_url=endpoint, auth_token=host['api_key'], video_id=v_id) if video_data['state'] == STATE_LIVE: print("Already STATE_LIVE, 403 coming.") else: video_data['state'] = 1 try: update_video(endpoint, auth_token=host['api_key'], video_id=v_id, video_data=video_data) except Http4xxException as exc: print(exc) print("told you this was coming.") except MissingRequiredData as exc: print(exc) # this shouldn't happen, prolly debugging something. import code code.interact(local=locals()) return True
def main(): args = parse_args() load_config(args.conf_file) dbs = DBSession() code.interact(banner="BakedPytato", local=globals())
def interact(PS1, PS2, BANNER, *arg, **kwarg): def Completer(text, stat): if text.startswith('.') or text.startswith('/'): ret = path_matches(text) elif '.' not in text: ret = global_matches(text) else: ret = attr_matches(text) try: return ret[stat] except IndexError: return None @utils.regExitCallback def exit_interact(): """ Clean all when exit """ print "Goodbye..." ## Compatible for Mac OS since Mac OS ship libedit for readline if "libedit" in readline.__doc__: import rlcompleter readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") ## Change PS sys.ps1, sys.ps2 = PS1, PS2 delims = readline.get_completer_delims().replace('/','') readline.set_completer_delims(delims) readline.set_completer(Completer) ## Run Interpreter code.interact(banner=BANNER, local=globals())
def interact(msg=None): """Start an interactive interpreter session in the current environment. On Unix: <Control>-D exits the interactive session and returns to normal execution. In Windows: <Control>-Z <Enter> exists the interactive session and returns to normal execution. """ # use exception trick to pick up the current frame try: raise None except: frame = sys.exc_info()[2].tb_frame.f_back # evaluate commands in current namespace namespace = frame.f_globals.copy() namespace.update(frame.f_locals) # exit on interrupt def handler(signum, frame): print() exit(0) signal.signal(signal.SIGINT, handler) if not msg: _, filename, line, _, _, _ = inspect.stack()[1] msg = 'Interacting at File "{0}", line {1} \n'.format(filename, line) msg += ' Unix: <Control>-D continues the program; \n' msg += ' Windows: <Control>-Z <Enter> continues the program; \n' msg += ' exit() or <Control>-C exits the program' code.interact(msg, None, namespace)
def main(): parser = argparse.ArgumentParser() parser.add_argument('--package', action='append') parser.add_argument('--dir', action='append') parser.add_argument('-m', action='store', metavar='MODULE') args, rest = parser.parse_known_args() if args.package: PACKAGES.extend(args.package) if args.dir: DIRS.extend(os.path.abspath(d) for d in args.dir) if not PACKAGES and not DIRS: DIRS.append(os.getcwd()) if args.m: sys.argv[1:] = rest runpy.run_module(args.m, run_name='__main__', alter_sys=True) elif rest: sys.argv = rest converted = maybe_2to3(rest[0]) with open(converted) as f: new_globals = dict(__name__='__main__', __file__=rest[0]) exec(f.read(), new_globals) else: import code code.interact()
def stats(self): nb_users = self.session.query(Logins.user).distinct().count() nb_src = self.session.query(Logins.src).distinct().count() nb_asn = self.session.query(ASN.asn).distinct().count() print '[+] users: %d'%(nb_users) print '[+] src IPS: %d'%(nb_src) print '[+] src ASN: %d'%(nb_asn) # show distance-based risks self.distanceRisk() return # show countries countries=dict() users_cc=dict() users_asn=dict() #asn_country_cache=dict([(asn,cc) # for asn,prefix,cc in self.getASNCache()]) try: for date,time,user,src,asn,cc in self.session.query(Logins,IP2ASN)\ .join(Logins.src == IP2ASN.ip).filter(Logins.user == user).\ order_by(Logins.user,ASN.cc): if cc not in countries: countries[cc]=0 if user not in users_asn: users_asn[user]=[] users_cc[user]=[] countries[cc]+=1 users_asn[user].append(asn) users_cc[user].append(cc) except sqlite3.OperationalError,e: import code code.interact(local=locals())
def main(args): #print('株価指標データをダウンロードしcsvファイルに保存') #fetchStockIndexes() #print('株価指標データを読み込む') all_data = load_exchange_dataframes(args.target_brand) #print('終値を取得') using_data = get_using_data(all_data) #print('データを学習に使える形式に正規化') log_return_data = get_log_return_data(using_data) #print('答と学習データを作る') num_categories, training_test_data = build_training_data( log_return_data, args.target_brand, use_subset=args.use_subset) #print('学習データをトレーニング用とテスト用に分割する') dataset = split_training_test_data(num_categories, training_test_data) #print('器械学習のネットワークを作成') env = smarter_network(dataset) if args.inspect: import code print('Press Ctrl-d to proceed') code.interact(local=locals()) #print('学習') return train(env, steps=args.steps, checkin_interval=args.checkin)
def drop_to_shell(local): import rlcompleter import readline import code readline.parse_and_bind("tab: complete") code.interact(local=local)
def console(): t = Terminal() # clear screen print(t.clear, end="") # retrieve vended display object try: calculon.disp = Pyro4.Proxy(ENV['uri']) except: print(t.bold("Failed to connect to display")) calculon.disp = None repl.disp = calculon.disp # connect to voltron calculon.V = VoltronProxy() calculon.V.disp = calculon.disp calculon.V.update_disp() # run repl code.InteractiveConsole.runsource = repl.CalculonInterpreter().runsource code.interact(local=locals()) # clean up calculon.V._disconnect() if calculon.disp: calculon.disp._pyroRelease()
def shell(ipython: bool=True): """Run the application shell. :param ipython: Use IPython as shell """ app.loop.run_until_complete(app.start()) banner = '\nInteractive Muffin Shell\n' namespace = app.cfg.MANAGE_SHELL if callable(namespace): namespace = namespace() banner += "Loaded objects: %s" % list(namespace.keys()) if ipython: try: from IPython.terminal.embed import InteractiveShellEmbed sh = InteractiveShellEmbed(banner1=banner) except ImportError: pass else: sh(local_ns=namespace) return from code import interact interact(banner, local=namespace) app.loop.run_until_complete(app.finish())
def main(): parser = optparse.OptionParser() parser.add_option('-v', '--verbose', action='count') options, args = parser.parse_args() if not args: app_id = default_app_id(ROOT) else: app_id = args[0] host = None if len(args) > 1: host = args[1] if options.verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.ERROR) predefined_vars = setup_env(app_id, host) prompt = ( 'App Engine interactive console for "%s".\n' 'Available symbols:\n' ' %s\n') % (app_id, ', '.join(sorted(predefined_vars))) code.interact(prompt, None, predefined_vars)
def main(): usage = "Usage: %prog [ options ] file | md5 [ file | md5 [ ... ] ]" parser = optparse.OptionParser(usage) parser.add_option("-d", "--debug", dest="debug", default=False, action="store_true", help="Turn on debugging messages") parser.add_option("-p", "--print_stats", dest="print_stats", default=False, action="store_true") options, args = parser.parse_args() if options.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) logging.debug("Collecting statistics about given package files.") configuration.SetUpSqlobjectConnection() pkgstat_objs = checkpkg_lib.GetPackageStatsByFilenamesOrMd5s( args, options.debug) bar = progressbar.ProgressBar() bar.maxval = len(pkgstat_objs) bar.start() counter = itertools.count() pkgstats = [] for pkgstat in pkgstat_objs: pkgstats.append(pkgstat.GetAllStats()) bar.update(counter.next()) bar.finish() if options.print_stats: print "import datetime" print "pkgstat_objs = ", pprint.pprint(pkgstats) else: code.interact(local=locals())
raise StopIteration() def stop(self): self.enter(-1, 0, self._stop_raise) self.thread = None def __repr__(self): return "{}(active={}, len(queue)={})".format( self.__class__.__name__, self.is_active, len(self.queue) ) if __name__ == '__main__': s = ThreadScheduler() import threading import code import readline import rlcompleter import os python_history = os.path.expanduser('~/.python_history') vars = globals() vars.update(locals()) readline.set_completer(rlcompleter.Completer(vars).complete) readline.parse_and_bind("tab: complete") readline.read_history_file(python_history) code.interact(local=vars) readline.write_history_file(python_history)
def get_python(self, head): if head is not None: pprint(head) exit = "use 'ctrl+d' to get back parat loop".replace('"', "") code.interact(local=locals())
def interactive_browser(srcdir=None): """ launch an interactive view for browsing the original archives. """ info("launching interactive data browser...") # the variables are actually used, in the interactive prompt. # pylint: disable=possibly-unused-variable data, game_versions = mount_input(srcdir) if not data: warn("cannot launch browser as no valid input assets were found.") return def save(path, target): """ save a path to a custom target """ with path.open("rb") as infile: with open(target, "rb") as outfile: outfile.write(infile.read()) def save_slp(path, target, palette=None): """ save a slp as png. """ from .texture import Texture from .slp import SLP from .driver import get_palette if not palette: palette = get_palette(data) with path.open("rb") as slpfile: tex = Texture(SLP(slpfile.read()), palette) out_path, filename = os.path.split(target) tex.save(Directory(out_path).root, filename) import code from pprint import pprint import rlcompleter completer = rlcompleter.Completer(locals()) readline.parse_and_bind("tab: complete") readline.parse_and_bind("set show-all-if-ambiguous on") readline.set_completer(completer.complete) code.interact(banner=( "\nuse `pprint` for beautiful output!\n" "you can access stuff by the `data` variable!\n" "`data` is an openage.util.fslike.path.Path!\n\n" "* version detection: pprint(game_versions)\n" "* list contents: pprint(list(data['graphics'].list()))\n" "* dump data: save(data['file/path'], '/tmp/outputfile')\n" "* save a slp as png: save_slp(data['dir/123.slp'], '/tmp/pic.png')\n" ), local=locals())
def test(interface="en1"): """ Test function """ global drop, total, bytes_got, bytes_real, bytes_diff drop = 0 total = 0 bytes_got = 0 bytes_real = 0 bytes_diff = 0 def cb(obj, data, sec, usec, length): global drop, total, bytes_got, bytes_real, bytes_diff #print ">>>",data t, d = pcapc.stats(obj.pcap) bytes_got += len(data) bytes_real += length nbd = bytes_real - bytes_got if nbd != bytes_diff: bytes_diff = nbd print "lost bytes:", nbd if t > total: total = t + 500 print t, "total" if d > drop: drop = d print d, "dropped" p = pkt.ethernet(data) ip = p.find('ipv4') if ip: print ip.srcip, "\t", ip.dstip, p print "\n".join(["%i. %s" % x for x in enumerate(PCap.get_device_names())]) if interface.startswith("#"): interface = int(interface[1:]) interface = PCap.get_device_names()[interface] print "Interface:", interface p = PCap(interface, callback=cb, filter="icmp") #[icmptype] != icmp-echoreply") #filter = "ip host 74.125.224.148") p.set_direction(True, True) def ping(eth='00:18:02:6e:ce:55', ip='192.168.0.1'): e = pkt.ethernet() e.src = p.addresses['ethernet']['addr'] or '02:00:00:11:22:33' e.dst = EthAddr(eth) e.type = e.IP_TYPE ipp = pkt.ipv4() ipp.protocol = ipp.ICMP_PROTOCOL ipp.srcip = p.addresses['AF_INET']['addr'] ipp.dstip = IPAddr(ip) icmp = pkt.icmp() icmp.type = pkt.ICMP.TYPE_ECHO_REQUEST icmp.payload = "PingPing" * 6 ipp.payload = icmp e.payload = ipp p.inject(e) def broadcast(): ping('ff:ff:ff:ff:ff:ff', '255.255.255.255') import code code.interact(local=locals())
from functions import * link = device_comms.connect() from matplotlib import pyplot as plt import code code.interact(local=locals())
def main(argv): parser = ArgumentParser(usage=__doc__.lstrip()) parser.add_argument("--verbose", "-v", action="count", default=1, help="more verbosity") parser.add_argument("--debug-info", action="store_true", help=("add --verbose-cfg to build_src to show compiler " "configuration output while creating " "_numpyconfig.h and config.h")) parser.add_argument("--no-build", "-n", action="store_true", default=False, help="do not build the project (use system installed version)") parser.add_argument("--build-only", "-b", action="store_true", default=False, help="just build, do not run any tests") parser.add_argument("--doctests", action="store_true", default=False, help="Run doctests in module") parser.add_argument("--refguide-check", action="store_true", default=False, help="Run refguide (doctest) check (do not run regular tests.)") parser.add_argument("--coverage", action="store_true", default=False, help=("report coverage of project code. HTML output goes " "under build/coverage")) parser.add_argument("--lint", default=None, help="'<Target Branch>' or 'uncommitted', passed to " "tools/linter.py [--branch BRANCH] " "[--uncommitted]") parser.add_argument("--durations", action="store", default=-1, type=int, help=("Time N slowest tests, time all if 0, time none if < 0")) parser.add_argument("--gcov", action="store_true", default=False, help=("enable C code coverage via gcov (requires GCC). " "gcov output goes to build/**/*.gc*")) parser.add_argument("--lcov-html", action="store_true", default=False, help=("produce HTML for C code coverage information " "from a previous run with --gcov. " "HTML output goes to build/lcov/")) parser.add_argument("--mode", "-m", default="fast", help="'fast', 'full', or something that could be " "passed to nosetests -A [default: fast]") parser.add_argument("--submodule", "-s", default=None, help="Submodule whose tests to run (cluster, constants, ...)") parser.add_argument("--pythonpath", "-p", default=None, help="Paths to prepend to PYTHONPATH") parser.add_argument("--tests", "-t", action='append', help="Specify tests to run") parser.add_argument("--python", action="store_true", help="Start a Python shell with PYTHONPATH set") parser.add_argument("--ipython", "-i", action="store_true", help="Start IPython shell with PYTHONPATH set") parser.add_argument("--shell", action="store_true", help="Start Unix shell with PYTHONPATH set") parser.add_argument("--mypy", action="store_true", help="Run mypy on files with NumPy on the MYPYPATH") parser.add_argument("--debug", "-g", action="store_true", help="Debug build") parser.add_argument("--parallel", "-j", type=int, default=0, help="Number of parallel jobs during build") parser.add_argument("--warn-error", action="store_true", help="Set -Werror to convert all compiler warnings to errors") parser.add_argument("--cpu-baseline", default=None, help="Specify a list of enabled baseline CPU optimizations"), parser.add_argument("--cpu-dispatch", default=None, help="Specify a list of dispatched CPU optimizations"), parser.add_argument("--disable-optimization", action="store_true", help="Disable CPU optimized code(dispatch,simd,fast...)"), parser.add_argument("--simd-test", default=None, help="Specify a list of CPU optimizations to be " "tested against NumPy SIMD interface"), parser.add_argument("--show-build-log", action="store_true", help="Show build output rather than using a log file") parser.add_argument("--bench", action="store_true", help="Run benchmark suite instead of test suite") parser.add_argument("--bench-compare", action="store", metavar="COMMIT", help=("Compare benchmark results of current HEAD to " "BEFORE. Use an additional " "--bench-compare=COMMIT to override HEAD with " "COMMIT. Note that you need to commit your " "changes first!")) parser.add_argument("args", metavar="ARGS", default=[], nargs=REMAINDER, help="Arguments to pass to pytest, asv, mypy, Python or shell") args = parser.parse_args(argv) if args.durations < 0: args.durations = -1 if args.bench_compare: args.bench = True args.no_build = True # ASV does the building if args.lcov_html: # generate C code coverage output lcov_generate() sys.exit(0) if args.pythonpath: for p in reversed(args.pythonpath.split(os.pathsep)): sys.path.insert(0, p) if args.gcov: gcov_reset_counters() if args.debug and args.bench: print("*** Benchmarks should not be run against debug " "version; remove -g flag ***") if args.lint: check_lint(args.lint) if not args.no_build: # we need the noarch path in case the package is pure python. site_dir, site_dir_noarch = build_project(args) sys.path.insert(0, site_dir) sys.path.insert(0, site_dir_noarch) os.environ['PYTHONPATH'] = site_dir + os.pathsep + site_dir_noarch else: _temp = __import__(PROJECT_MODULE) site_dir = os.path.sep.join(_temp.__file__.split(os.path.sep)[:-2]) extra_argv = args.args[:] if not args.bench: # extra_argv may also lists selected benchmarks if extra_argv and extra_argv[0] == '--': extra_argv = extra_argv[1:] if args.python: # Debugging issues with warnings is much easier if you can see them print("Enabling display of all warnings") import warnings import types warnings.filterwarnings("always") if extra_argv: # Don't use subprocess, since we don't want to include the # current path in PYTHONPATH. sys.argv = extra_argv with open(extra_argv[0], 'r') as f: script = f.read() sys.modules['__main__'] = types.ModuleType('__main__') ns = dict(__name__='__main__', __file__=extra_argv[0]) exec(script, ns) sys.exit(0) else: import code code.interact() sys.exit(0) if args.ipython: # Debugging issues with warnings is much easier if you can see them print("Enabling display of all warnings and pre-importing numpy as np") import warnings; warnings.filterwarnings("always") import IPython import numpy as np IPython.embed(colors='neutral', user_ns={"np": np}) sys.exit(0) if args.shell: shell = os.environ.get('SHELL', 'cmd' if os.name == 'nt' else 'sh') print("Spawning a shell ({})...".format(shell)) subprocess.call([shell] + extra_argv) sys.exit(0) if args.mypy: try: import mypy.api except ImportError: raise RuntimeError( "Mypy not found. Please install it by running " "pip install -r test_requirements.txt from the repo root" ) os.environ['MYPYPATH'] = site_dir # By default mypy won't color the output since it isn't being # invoked from a tty. os.environ['MYPY_FORCE_COLOR'] = '1' config = os.path.join( site_dir, "numpy", "typing", "tests", "data", "mypy.ini", ) report, errors, status = mypy.api.run( ['--config-file', config] + args.args ) print(report, end='') print(errors, end='', file=sys.stderr) sys.exit(status) if args.coverage: dst_dir = os.path.join(ROOT_DIR, 'build', 'coverage') fn = os.path.join(dst_dir, 'coverage_html.js') if os.path.isdir(dst_dir) and os.path.isfile(fn): shutil.rmtree(dst_dir) extra_argv += ['--cov-report=html:' + dst_dir] if args.refguide_check: cmd = [os.path.join(ROOT_DIR, 'tools', 'refguide_check.py'), '--doctests'] if args.submodule: cmd += [args.submodule] os.execv(sys.executable, [sys.executable] + cmd) sys.exit(0) if args.bench: # Run ASV for i, v in enumerate(extra_argv): if v.startswith("--"): items = extra_argv[:i] if v == "--": i += 1 # skip '--' indicating further are passed on. bench_args = extra_argv[i:] break else: items = extra_argv bench_args = [] if args.tests: items += args.tests if args.submodule: items += [args.submodule] for a in items: bench_args.extend(['--bench', a]) if not args.bench_compare: cmd = ['asv', 'run', '-n', '-e', '--python=same'] + bench_args ret = subprocess.call(cmd, cwd=os.path.join(ROOT_DIR, 'benchmarks')) sys.exit(ret) else: commits = [x.strip() for x in args.bench_compare.split(',')] if len(commits) == 1: commit_a = commits[0] commit_b = 'HEAD' elif len(commits) == 2: commit_a, commit_b = commits else: p.error("Too many commits to compare benchmarks for") # Check for uncommitted files if commit_b == 'HEAD': r1 = subprocess.call(['git', 'diff-index', '--quiet', '--cached', 'HEAD']) r2 = subprocess.call(['git', 'diff-files', '--quiet']) if r1 != 0 or r2 != 0: print("*"*80) print("WARNING: you have uncommitted changes --- " "these will NOT be benchmarked!") print("*"*80) # Fix commit ids (HEAD is local to current repo) out = subprocess.check_output(['git', 'rev-parse', commit_b]) commit_b = out.strip().decode('ascii') out = subprocess.check_output(['git', 'rev-parse', commit_a]) commit_a = out.strip().decode('ascii') # generate config file with the required build options asv_cfpath = [ '--config', asv_compare_config( os.path.join(ROOT_DIR, 'benchmarks'), args, # to clear the cache if the user changed build options (commit_a, commit_b) ) ] cmd = ['asv', 'continuous', '-e', '-f', '1.05', commit_a, commit_b] + asv_cfpath + bench_args ret = subprocess.call(cmd, cwd=os.path.join(ROOT_DIR, 'benchmarks')) sys.exit(ret) if args.build_only: sys.exit(0) else: __import__(PROJECT_MODULE) test = sys.modules[PROJECT_MODULE].test if args.submodule: tests = [PROJECT_MODULE + "." + args.submodule] elif args.tests: tests = args.tests else: tests = None # Run the tests under build/test if not args.no_build: test_dir = site_dir else: test_dir = os.path.join(ROOT_DIR, 'build', 'test') if not os.path.isdir(test_dir): os.makedirs(test_dir) shutil.copyfile(os.path.join(ROOT_DIR, '.coveragerc'), os.path.join(test_dir, '.coveragerc')) cwd = os.getcwd() try: os.chdir(test_dir) result = test(args.mode, verbose=args.verbose, extra_argv=extra_argv, doctests=args.doctests, coverage=args.coverage, durations=args.durations, tests=tests) finally: os.chdir(cwd) if isinstance(result, bool): sys.exit(0 if result else 1) elif result.wasSuccessful(): sys.exit(0) else: sys.exit(1)
def interact(argv=sys.argv): # pragma: no cover banner = "\033[1mSnimpy\033[0m ({0}) -- {1}.\n".format( snimpy.__version__, snimpy.__doc__) banner += " load -> load an additional MIB\n" banner += " M -> manager object" local = {"conf": conf, "M": manager.Manager, "load": manager.load, "timedelta": timedelta, "snmp": manager.snmp } if len(argv) <= 1: manager.Manager._complete = True for ms in conf.mibs: manager.load(ms) globals().update(local) if len(argv) > 1: argv = argv[1:] exec(compile(open(argv[0]).read(), argv[0], 'exec')) in local return try: import rlcompleter import readline except ImportError: readline = None try: try: # ipython >= 0.11 from IPython.frontend.terminal.embed import InteractiveShellEmbed from IPython.config.loader import Config cfg = Config() try: # >= 0.12 cfg.PromptManager.in_template = "Snimpy [\\#]> " cfg.PromptManager.out_template = "Snimpy [\\#]: " except ImportError: # 0.11 cfg.InteractiveShellEmbed.prompt_in1 = "Snimpy [\\#]> " cfg.InteractiveShellEmbed.prompt_out = "Snimpy [\\#]: " if conf.ipythonprofile: cfg.InteractiveShellEmbed.profile = conf.ipythonprofile shell = InteractiveShellEmbed( config=cfg, banner1=banner, user_ns=local) # Not interested by traceback in this module shell.InteractiveTB.tb_offset += 1 except ImportError: # ipython < 0.11 from IPython.Shell import IPShellEmbed argv = ["-prompt_in1", "Snimpy [\\#]> ", "-prompt_out", "Snimpy [\\#]: "] if conf.ipythonprofile: argv += ["-profile", conf.ipythonprofile] shell = IPShellEmbed(argv=argv, banner=banner, user_ns=local) # Not interested by traceback in this module shell.IP.InteractiveTB.tb_offset += 1 except ImportError: shell = None if shell and conf.ipython: shell() else: if readline: if conf.histfile: try: readline.read_history_file( os.path.expanduser(conf.histfile)) except IOError: pass atexit.register(lambda: readline.write_history_file( os.path.expanduser(conf.histfile))) readline.set_completer(rlcompleter.Completer(local).complete) readline.parse_and_bind("tab: menu-complete") sys.ps1 = conf.prompt code.interact(banner=banner, local=local)
def interactive_main(_locals): import code code.interact(local=_locals)
def apply(self, ui): with ui.paused(): code.interact(local=locals())
def drop(scapy_ses): code.interact(banner="Test '%s' failed. " "exit() to stop, Ctrl-D to leave " "this interpreter and continue " "with the current test campaign" % t.name, local=scapy_ses)
def main(argv): parser = ArgumentParser(usage=__doc__.lstrip()) parser.add_argument("--verbose", "-v", action="count", default=1, help="more verbosity") parser.add_argument( "--no-build", "-n", action="store_true", default=False, help="do not build the project (use system installed version)") parser.add_argument("--build-only", "-b", action="store_true", default=False, help="just build, do not run any tests") parser.add_argument("--doctests", action="store_true", default=False, help="Run doctests in module") parser.add_argument( "--coverage", action="store_true", default=False, help=("report coverage of project code. HTML output goes " "under build/coverage")) parser.add_argument( "--gcov", action="store_true", default=False, help=("enable C code coverage via gcov (requires GCC). " "gcov output goes to build/**/*.gc*")) parser.add_argument("--lcov-html", action="store_true", default=False, help=("produce HTML for C code coverage information " "from a previous run with --gcov. " "HTML output goes to build/lcov/")) parser.add_argument("--mode", "-m", default="fast", help="'fast', 'full', or something that could be " "passed to nosetests -A [default: fast]") parser.add_argument( "--submodule", "-s", default=None, help="Submodule whose tests to run (cluster, constants, ...)") parser.add_argument("--pythonpath", "-p", default=None, help="Paths to prepend to PYTHONPATH") parser.add_argument("--tests", "-t", action='append', help="Specify tests to run") parser.add_argument("--python", action="store_true", help="Start a Python shell with PYTHONPATH set") parser.add_argument("--ipython", "-i", action="store_true", help="Start IPython shell with PYTHONPATH set") parser.add_argument("--shell", action="store_true", help="Start Unix shell with PYTHONPATH set") parser.add_argument("--debug", "-g", action="store_true", help="Debug build") parser.add_argument("--show-build-log", action="store_true", help="Show build output rather than using a log file") parser.add_argument("--bench", action="store_true", help="Run benchmark suite instead of test suite") parser.add_argument("args", metavar="ARGS", default=[], nargs=REMAINDER, help="Arguments to pass to Nose, Python or shell") args = parser.parse_args(argv) if args.lcov_html: # generate C code coverage output lcov_generate() sys.exit(0) if args.pythonpath: for p in reversed(args.pythonpath.split(os.pathsep)): sys.path.insert(0, p) if args.gcov: gcov_reset_counters() if not args.no_build: site_dir = build_project(args) sys.path.insert(0, site_dir) os.environ['PYTHONPATH'] = site_dir extra_argv = args.args[:] if extra_argv and extra_argv[0] == '--': extra_argv = extra_argv[1:] if args.python: if extra_argv: # Don't use subprocess, since we don't want to include the # current path in PYTHONPATH. sys.argv = extra_argv with open(extra_argv[0], 'r') as f: script = f.read() sys.modules['__main__'] = imp.new_module('__main__') ns = dict(__name__='__main__', __file__=extra_argv[0]) exec_(script, ns) sys.exit(0) else: import code code.interact() sys.exit(0) if args.ipython: import IPython IPython.embed(user_ns={}) sys.exit(0) if args.shell: shell = os.environ.get('SHELL', 'sh') print("Spawning a Unix shell...") os.execv(shell, [shell] + extra_argv) sys.exit(1) if args.coverage: dst_dir = os.path.join(ROOT_DIR, 'build', 'coverage') fn = os.path.join(dst_dir, 'coverage_html.js') if os.path.isdir(dst_dir) and os.path.isfile(fn): shutil.rmtree(dst_dir) extra_argv += ['--cover-html', '--cover-html-dir=' + dst_dir] test_dir = os.path.join(ROOT_DIR, 'build', 'test') if args.build_only: sys.exit(0) elif args.submodule: modname = PROJECT_MODULE + '.' + args.submodule try: __import__(modname) if args.bench: test = sys.modules[modname].bench else: test = sys.modules[modname].test except (ImportError, KeyError, AttributeError) as e: print("Cannot run tests for %s (%s)" % (modname, e)) sys.exit(2) elif args.tests: def fix_test_path(x): # fix up test path p = x.split(':') p[0] = os.path.relpath(os.path.abspath(p[0]), test_dir) return ':'.join(p) tests = [fix_test_path(x) for x in args.tests] def test(*a, **kw): extra_argv = kw.pop('extra_argv', ()) extra_argv = extra_argv + tests[1:] kw['extra_argv'] = extra_argv from numpy.testing import Tester if args.bench: return Tester(tests[0]).bench(*a, **kw) else: return Tester(tests[0]).test(*a, **kw) else: __import__(PROJECT_MODULE) if args.bench: test = sys.modules[PROJECT_MODULE].bench else: test = sys.modules[PROJECT_MODULE].test # Run the tests under build/test try: shutil.rmtree(test_dir) except OSError: pass try: os.makedirs(test_dir) except OSError: pass shutil.copyfile(os.path.join(ROOT_DIR, '.coveragerc'), os.path.join(test_dir, '.coveragerc')) cwd = os.getcwd() try: os.chdir(test_dir) if args.bench: result = test(args.mode, verbose=args.verbose, extra_argv=extra_argv) else: result = test(args.mode, verbose=args.verbose, extra_argv=extra_argv, doctests=args.doctests, coverage=args.coverage) finally: os.chdir(cwd) if isinstance(result, bool): sys.exit(0 if result else 1) elif result.wasSuccessful(): sys.exit(0) else: sys.exit(1)
RX = J['Subscription'] rxid = RX['subscriptionId']['$'] expires = int(RX['expires']['$'], 10) self.subscriptions[rxid] = (time.time(), expires, event) self.sequences[rxid] = 1 elif R.status == 403: J = json.loads(R.read()) if 'ErrorInfo' in J and J['ErrorInfo']['errorCode'][ '$'] == '110842': # Our Channel Set has gone missing? Generate a new one. sleep(5) self.newchannelset() sleep(5) if not self.closing and not hasattr(sys, 'stopservice'): return self.newsubscriptions() else: debug(R.status, J) else: debug(R.status, R.read()) def unsubscribe(self, rxid): return self.delete(self.url(events, version, 'subscription', rxid)) def url(self, *args): # debug('/'.join(itertools.chain([''], args))) return '/'.join(itertools.chain([''], args)) if __name__ == '__main__': interact(local=globals())
nlp = spacy.load('en') def process(review): # look up dictionary doc = [d for d in nlp(review.lower())] doc = [w.text if w not in saved_word_dict else '<UNK>' for w in doc] if len(doc) >= args.doc_maxlen: doc = doc[:args.doc_maxlen] else: doc.extend(['<NULL>'] * (args.doc_maxlen - len(doc))) doc = torch.LongTensor([saved_word_dict[w] for w in doc]) logit = model.forward(Variable(doc.unsqueeze(0)), 0) _, index = logit.max(1) print(logit, 'pos' if index == 1 else 'neg') banner = """ Sentimental Analysis on IMDb Movie Reviews >> ex = "This movie is full of entertaining." >> process(ex) """ def usage(): print(banner) code.interact(banner=banner, local=locals())
banner += "\nRunning in DEBUG mode.\n" elif dopal.__dopal_mode__ == 2: banner += '\nWARNING: Running in "epydoc" mode.\n' my_locals['connection'] = connection if interface is not None: my_locals['interface'] = interface my_locals['__import__'] = __import__ print print '------------------------' print import code code.interact(banner, local=my_locals) if __name__ == '__main__': def _main(env): return main() import dopal.scripting dopal.scripting.ext_run( 'dopal.interact', _main, make_connection=False, setup_logging=False, timeout=8,
opt = parser.parse_args() cap = cv2.VideoCapture(0) def show(img): plt.imshow(img); plt.show() while True: # get frame ret, frame = cap.read() # display frame cv2.imshow('frame', frame) frame = tf.cast(frame, tf.float32) / 255. frame = tf.stack((frame[:, :, 2], frame[:, :, 1], frame[:, :, 0]), axis=2) if opt.int: code.interact(local={**locals(), **globals()}) frame = tf.expand_dims(frame, 0) frame = tf.image.resize(frame, (224, 224)) if opt.int: code.interact(local={**locals(), **globals()}) raw_prediction = resnet.predict(frame) if opt.int: code.interact(local={**locals(), **globals()}) prediction = tf.keras.applications.imagenet_utils.decode_predictions(raw_prediction) if opt.int: code.interact(local={**locals(), **globals()}) print(prediction) # exit if user enters 'q' key on keyboard if cv2.waitKey(1) & 0xFF == ord('q'):
def shell(): import argparse import code import os import sys import libnbdmod import nbd description = '''Network Block Device (NBD) shell''' epilog = '''Please read the nbdsh(1) manual page for full usage.''' parser = argparse.ArgumentParser(prog='nbdsh', description=description, epilog=epilog) short_options = [] long_options = [] parser.add_argument('--base-allocation', action='store_true', help='request the "base:allocation" meta context') long_options.append("--base-allocation") parser.add_argument('-c', '--command', action='append', help="run a Python statement " "(may be used multiple times)") short_options.append("-c") long_options.append("--command") parser.add_argument('-n', action='store_true', help="do not create the implicit handle 'h'") short_options.append("-n") parser.add_argument('--opt-mode', action='store_true', help='request opt mode during connection') long_options.append("--opt-mode") parser.add_argument('-u', '--uri', help="connect to NBD URI") short_options.append("-u") long_options.append("--uri") # For back-compat, provide --connect as an undocumented synonym to --uri parser.add_argument('--connect', dest='uri', help=argparse.SUPPRESS) parser.add_argument('-v', '--verbose', action='store_true') short_options.append("-v") long_options.append("--verbose") parser.add_argument('-V', '--version', action='store_true') short_options.append("-V") long_options.append("--version") # These hidden options are used by bash tab completion. parser.add_argument("--short-options", action='store_true', help=argparse.SUPPRESS) parser.add_argument("--long-options", action='store_true', help=argparse.SUPPRESS) args = parser.parse_args() # It's an error if -n is passed with certain other options. if args.n and (args.base_allocation or args.opt_mode or args.uri is not None): print("error: -n option cannot be used with " + "--base-allocation, --opt-mode or --uri", file=sys.stderr) exit(1) # Handle the informational options which exit. if args.version: libnbdmod.display_version("nbdsh") exit(0) if args.short_options: short_options.sort() print("\n".join(short_options)) exit(0) if args.long_options: long_options.sort() print("\n".join(long_options)) exit(0) # Create the banner and prompt. banner = make_banner(args) sys.ps1 = "nbd> " # If verbose, set LIBNBD_DEBUG=1 if args.verbose: os.environ["LIBNBD_DEBUG"] = "1" # Create the handle. if not args.n: h = nbd.NBD() h.set_handle_name("nbdsh") # Set other attributes in the handle. if args.base_allocation: h.add_meta_context(nbd.CONTEXT_BASE_ALLOCATION) if args.opt_mode: h.set_opt_mode(True) # Parse the URI. if args.uri is not None: try: h.connect_uri(args.uri) except nbd.Error as ex: print("nbdsh: unable to connect to uri '%s': %s" % (args.uri, ex.string), file=sys.stderr) sys.exit(1) # If there are no -c or --command parameters, go interactive, # otherwise we run the commands and exit. if not args.command: code.interact(banner=banner, local=locals(), exitmsg='') else: # https://stackoverflow.com/a/11754346 d = dict(locals(), **globals()) try: for c in args.command: if c != '-': exec(c, d, d) else: exec(sys.stdin.read(), d, d) except nbd.Error as ex: if nbd.NBD().get_debug(): traceback.print_exc() else: print("nbdsh: command line script failed: %s" % ex.string, file=sys.stderr) sys.exit(1)
def shell(env, help): cprt = 'Type "help" for more information.' banner = "Python %s on %s\n%s" % (sys.version, sys.platform, cprt) banner += '\n\n' + help + '\n' interact(banner, local=env)
def sample(self, iframe, patches, FOAsize, seed=None, verbose=False, debug=False): if seed is not None: np.random.seed(seed) self.patch = patches self.FOAsize = FOAsize numPatch = len(self.patch) if iframe == 0: #first frame self.s_ampl = [] self.s_dir = [] self.fix_dur = [] self.fix_pos = [] z = 0 #start from the CB self.z_prev = 0 m = self.patch[0].center s = np.asarray(self.patch[0].axes) S = np.eye(2) * s arrivingFOA = np.random.multivariate_normal(m, S) self.allFOA.append(arrivingFOA) self.newFOA = arrivingFOA prevFOA = arrivingFOA self.curr_fix_dur = 0 else: if self.z_prev >= numPatch: self.z_prev = np.random.choice(numPatch, 1, p=np.ones(numPatch) / numPatch)[0] curr_value = self.patch[self.z_prev].value #other_values = [patch.value for i,patch in enumerate(self.patch) if i!=self.z_prev] others_rho = [ patch.compute_rho(np.array(self.patch[self.z_prev].center), False, self.kappa) for i, patch in enumerate(self.patch) if i != self.z_prev ] #other_values = [patch.expect for i,patch in enumerate(self.patch)] #Q = np.mean(other_values) Q = np.mean(others_rho) curr_rho = self.patch[self.z_prev].compute_rho( np.array(self.patch[self.z_prev].center), False, self.kappa) #mean value of all the other patches A = self.phi / (curr_value + self.eps) gp = curr_rho * np.exp(-A * self.curr_fix_dur) dist = gp - Q #distance of the current gut-f value from the average patch value jump_prob = 1 - logistic(20, dist) rand_num = np.random.rand( ) #for the random choice (evaluate a new jump or not) if debug: print('\nCurrent Values for patches:') print([patch.value for patch in self.patch]) print('\nInstantaneous Reward Rate: ' + str(gp)) print('Current value for the present patch: ' + str(curr_value)) print('Current mean value for other patches: ' + str(Q)) print('Distance between threshold and GUT: ' + str(dist)) print('Jump Probability: ' + str(jump_prob)) print('Random Number: ' + str(rand_num) + '\n') import code code.interact(local=locals()) if rand_num < jump_prob: #possible saccade rho = np.array([ patch.compute_rho(np.array(self.patch[self.z_prev].center), True, self.kappa) for patch in self.patch ]) pi_prob = rho / np.sum(rho) z = np.random.choice(numPatch, 1, p=pi_prob)[0] #choose a new patch if debug: print('\npi_prob: ') print(pi_prob) print('Choice:') print(z) import code code.interact(local=locals()) rand_num2 = np.random.rand( ) #for the random choice (small saccade of keep fixating) if z != self.z_prev or rand_num2 > 0.6: #increase the value on the rhs to decrease the number of small saccades # if here, then a new patch has been choosen, OR a small saccade will take place self.z_prev = z m = self.patch[z].center s = np.asarray(self.patch[z].axes) * 3 S = np.eye(2) * s self.newFOA = np.random.multivariate_normal( m, S) #choose position inside the (new) patch prevFOA = self.allFOA[-1] else: # if here, will keep fixating the same patch z = self.z_prev prevFOA = self.allFOA[-1] self.newFOA = prevFOA else: # keep fixating... z = self.z_prev prevFOA = self.allFOA[-1] self.newFOA = prevFOA #timeOfFlight = euclidean(self.newFOA, prevFOA) timeOfFlight = np.linalg.norm(self.newFOA - prevFOA) #Possible FLY -------------------------------------------------------------------------------------------------------------------------------------------- if timeOfFlight > self.FOAsize: if verbose: print('\nnew and prev: ', self.newFOA, prevFOA) #different patch from current print('\n\tFLY!!!! New patch: ' + self.patch[z].label) self.FLY = True self.SAME_PATCH = False self.allFOA.append(self.newFOA) self.s_ampl.append(timeOfFlight) curr_sdir = np.arctan2(self.newFOA[1] - prevFOA[1], self.newFOA[0] - prevFOA[0]) + np.pi self.s_dir.append(curr_sdir) self.fix_dur.append(self.curr_fix_dur) self.fix_pos.append(prevFOA) self.curr_fix_dur = 0 else: self.FLY = False self.SAME_PATCH = True self.curr_fix_dur += 1 / self.video_fr #FEED --------------------------------------------------------------------------------------------------------------------------------------------------- if self.SAME_PATCH == True and iframe > 0: #if we are approximately within the same patch retrieve previous exploitation/feed state and continue the local walk... if verbose: print('\n\tSame Patch, continuing exporation...') startxy = self.xylast #t_patch = self.t_patchlast alphap = self.alphaplast mup = self.newFOA #dtp = self.dtplast sigmap = self.sigma_last elif self.SAME_PATCH == False or iframe == 0: #...init new exploitation/feed state for starting a new random walk if verbose: print('\n\tExploring new Patch...') #t_patch = np.round(np.max([self.patch[z].axes[0], self.patch[z].axes[1]]))*2 #setting the length of the feeding proportional to major axis #self.t_patchlast = t_patch #dtp = 1/t_patch #time step #self.dtplast = dtp if iframe == 0: startxy = self.newFOA else: startxy = self.sampled_gaze[-1][-1, :] mup = self.newFOA if not self.FLY: alphap = np.max([self.patch[z].axes[0], self.patch[z].axes[1] ]) * 10 sigmap = 1 else: alphap = timeOfFlight / 5. sigmap = 15 self.alphaplast = alphap self.sigma_last = sigmap walk = sample_OU_trajectory(numOfpoints=10, alpha=alphap, mu=mup, startxy=startxy, dt=1 / alphap, sigma=sigmap) arrivingFOA = np.round(walk[-1, :]) self.xylast = arrivingFOA #self.muplast = mup self.sampled_gaze.append(walk)
def main(input_file, output_file, debug): if input_file == '-': if debug: raise BaseException("cannot run --debug with stdin input") input_file = sys.stdin else: input_file = open(input_file) # store / filter input tmpf = NamedTemporaryFile() # created digest output = NamedTemporaryFile() # mailbox needs filename :( that's breaking duck typing! # with below From hack I could probably split msgs myself altogether for line in input_file: # mutt pipe-to doesn't do mbox format :( this will break soon :) if line.startswith('Delivered-To: '): tmpf.write('From [email protected] Thu Aug 15 16:24:28 2019\n') tmpf.write(line) tmpf.flush() tmpf.seek(0) mbox = mailbox.mbox(tmpf.name) # transform headers to dict, lowercase and merge multiline headers, decode # quoted-printable bodies mbox_usable = [] for msg in mbox: mbox_usable.append(MyMail()) mbox_usable[-1].headers = normalize_headers(msg._headers) # Get the only part or the text/plain one if there are multiple payload = msg.get_payload() if isinstance(payload, type([])): for submsg in payload: subpart_headers = normalize_headers(submsg._headers) if subpart_headers['content-type'].startswith('text/plain'): # add headers from multipart subpart mbox_usable[-1].headers.update(subpart_headers) mbox_usable[-1].body = maybe_decode( mbox_usable[-1].headers['content-transfer-encoding'], submsg.get_payload()) break else: print "warning: message doesn't have text/plain part" else: mbox_usable[-1].body = maybe_decode( mbox_usable[-1].headers['content-transfer-encoding'], payload) mbox_usable.sort(key=lambda x: parsedate(x.headers['date'])) if debug: code.interact(local=locals()) first = True for msg in mbox_usable: if first is True: print >> output, '>____________________________________________________________________<' print >> output, 'Date: ', msg.headers.get('date') print >> output, 'Subject: ', msg.headers.get('subject') print >> output print >> output, msg.body first = False else: print >> output, '>____________________________________________________________________<' print >> output, 'Date: ', msg.headers.get('date') print >> output, filter_stuff(msg.body) output.flush() tmpf.close() os.system("vim -c 'set ft=mail' -c 'set wrap' '%s'" % output.name)
def shell_command(): ctx = current_app.make_shell_context() interact(local=ctx)
def shell(*args): interact('ibl shell.\n\nschema modules:\n\n - {m}\n' .format(m='\n - '.join( '.'.join(m.__name__.split('.')[1:]) for m in __all__)), local=globals())
def config(name, online_name): swap = SWAP.load(name) config = swap.config config.online_name = online_name code.interact(local={**globals(), **locals()}) swap.save()
from pyrw.rwe import ReadWriteEverything rwe = ReadWriteEverything() header = ''' | --------------------------------------------- | | rwe object has been created for your usage... | | %-45s | | --------------------------------------------- |''' % rwe.getRWEVersion() print(header) try: import IPython start_interactive = lambda: IPython.embed(display_banner=False) except ImportError: print("| Install IPython to have a more complete |") print("| interactive experience. |") print("| --------------------------------------------- |") import code start_interactive = lambda: code.interact(banner='', local=dict(rwe=rwe)) start_interactive()
def embed(): code.interact(local=dict(globals(), **locals()))
# Old way to embed IPython kept for backward compatibility try: args = [''] # IPython command line args (will be seen as sys.argv) ipshell = IPython.Shell.IPShellEmbed(args, banner=banner) ipshell(local_ns=session) except AttributeError, e: pass # In the IPython cookbook, see # 'Updating-code-for-use-with-IPython-0.11-and-later' IPython.embed(user_ns=session, banner2=banner) else: code.interact(banner=the_banner % (conf.version), local=session, readfunc=conf.readfunc) if conf.session: save_session(conf.session, session) for k in globkeys: try: del (__builtin__.__dict__[k]) except: pass if __name__ == "__main__": interact()
def __init__(self, address, port, active, session_id, name, event_handler=None, custom_connection_handler=None): secsgem.GemHostHandler.__init__(self, address, port, active, session_id, name, event_handler, custom_connection_handler) self.MDLN = "gemhost" self.SOFTREV = "1.0.0" commLogFileHandler = CommunicationLogFileHandler("log", "h") commLogFileHandler.setFormatter(logging.Formatter("%(asctime)s: %(message)s")) logging.getLogger("hsms_communication").addHandler(commLogFileHandler) logging.getLogger("hsms_communication").propagate = False logging.basicConfig(format='%(asctime)s %(name)s.%(funcName)s: %(message)s', level=logging.DEBUG) h = SampleHost("127.0.0.1", 5000, False, 0, "samplehost") h.enable() code.interact("host object is available as variable 'h'", local=locals()) h.disable()
def main(): import argparse parser = argparse.ArgumentParser(description='WiPy copy tool', epilog="""\ For configuration, a file called ``wipy-ftp.ini`` should be present. Run "%(prog)s write-ini" to create one. Adapt as needed when connected via router. """) parser.add_argument('action', type=lambda s: s.lower(), help='Action to execute, try "help"') parser.add_argument('path', nargs='?', help='pathname used for some actions') parser.add_argument('destination', nargs='?', help='target used for some actions') parser.add_argument('-v', '--verbose', action='store_true', help='show more diagnostic messages') parser.add_argument('--defaults', action='store_true', help='do not read ini file, use default settings') parser.add_argument( '--ini', help='alternate name for settings file (default: %(default)s)', default='wipy-ftp.ini') parser.add_argument( '--simulate', metavar='DIR', help='do not access WiPy, put files in given directory instead') # parser.add_argument('--noexp', action='store_true', help='skip steps involving the expansion board and SD storage') args = parser.parse_args() #~ print(args) logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO) if args.action == 'write-ini': with open(args.ini, 'w') as f: f.write(INI_TEMPLATE) logging.info('"{}" written'.format(args.ini)) sys.exit(0) if args.simulate: logging.info('using simulator') target = WiPySimulator(args.simulate) else: logging.info('using ftp') target = WiPyFTP(None if args.defaults else args.ini) if args.action == 'cp': with WiPyActions(target) as wipy: with open(args.path, 'rb') as src: wipy.put(args.destination, src) elif args.action == 'cat': with WiPyActions(target) as wipy: wipy.get(args.path, sys.stdout.buffer) elif args.action == 'ls': with WiPyActions(target) as wipy: wipy.ls(args.path) elif args.action == 'sync-lib': with WiPyActions(target) as wipy: wipy.install_lib() elif args.action == 'sync-top': with WiPyActions(target) as wipy: wipy.install_top() elif args.action == 'install': with WiPyActions(target) as wipy: wipy.backup() wipy.install_top() wipy.install_lib() if input('Connect to an access point? [Y/n]: ').upper() in ('', 'Y'): wipy.config_wlan() elif args.action == 'config-wlan': with WiPyActions(target) as wipy: print('Configure the WiPy to connect to an access point') wipy.config_wlan() elif args.action == 'config-ulog': with WiPyActions(target) as wipy: print( 'Configure the WiPy to send ulog (syslog compatible) messages to following IP address' ) wipy.config_ulog() elif args.action == 'fwupgrade': with WiPyActions(target) as wipy: print('upload /flash/sys/mcuimg.bin') wipy.put('/flash/sys/mcuimg.bin', open('mcuimg.bin', 'rb')) print('press reset button on WiPy to complete upgrade') elif args.action == 'backup': with WiPyActions(target) as wipy: wipy.backup() elif args.action == 'interact': # local REPL loop with established FTP connection for development with WiPyActions(target) as wipy: import code try: import rlcompleter import readline except ImportError as e: logging.warning('readline support failed: {}'.format(e)) else: readline.set_completer( rlcompleter.Completer(locals()).complete) readline.parse_and_bind("tab: complete") code.interact(local=locals()) else: sys.stdout.write("""\ ACTIONS are: - "write-ini" create ``wipy-ftp.ini`` with default settings - "install" copy boot.py, main.py and /lib from the PC to the WiPy - "sync-lib" copies only /lib - "sync-top" copies only boot.py, main.py - "config-wlan" ask for SSID/Password and write wlanconfig.py on WiPy - "ls" with optional remote path argument: list files - "cp" with local source and remote destination: uploads binary file - "cat" with remote filename: show file contents - "backup" download everything in /flash - "fwupgrade" write mcuimg.bin file to WiPy for firmware upgrade - "help" this text """)
def plain_shell(user_ns): sys.exit(code.interact(banner=get_banner(), local=user_ns))
def interact(): """ startup a python interpeter and return when it has finished """ import code return code.interact()
source_addr_ton=smpplib.consts.SMPP_TON_INTL, # source_addr_npi=smpplib.consts.SMPP_NPI_ISDN, # Make sure it is a byte string, not unicode: source_addr=sender, dest_addr_ton=smpplib.consts.SMPP_TON_INTL, # dest_addr_npi=smpplib.consts.SMPP_NPI_ISDN, # Make sure thease two params are byte strings, not unicode: destination_addr=receiver, short_message=part, data_coding=encoding_flag, esm_class=msg_type_flag, registered_delivery=True, ) if __name__ == '__main__': client = smpplib.client.Client('localhost', 2775) client.set_message_sent_handler(message_sent_handler) client.set_message_received_handler(message_received_handler) client.connect() client.bind_transceiver(system_id='login', password='******') t = Thread(target=client.listen) t.start() context = {'send_message': send_message} embed(user_ns=context) code.interact(local=concurrent)