INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Post notification to all registered observers.
def post_notification(self, ntype, sender, *args, **kwargs): """Post notification to all registered observers. The registered callback will be called as:: callback(ntype, sender, *args, **kwargs) Parameters ---------- ntype : hashable The notification t...
Find all registered observers that should recieve notification
def _observers_for_notification(self, ntype, sender): """Find all registered observers that should recieve notification""" keys = ( (ntype,sender), (ntype, None), (None, sender), (None,None) ) obs = set(...
Add an observer callback to this notification center.
def add_observer(self, callback, ntype, sender): """Add an observer callback to this notification center. The given callback will be called upon posting of notifications of the given type/sender and will receive any additional arguments passed to post_notification. Parameters ...
Add a new background job and start it in a separate thread.
def new(self, func_or_exp, *args, **kwargs): """Add a new background job and start it in a separate thread. There are two types of jobs which can be created: 1. Jobs based on expressions which can be passed to an eval() call. The expression must be given as a string. For example: ...
Update the status of the job lists.
def _update_status(self): """Update the status of the job lists. This method moves finished jobs to one of two lists: - self.completed: jobs which completed successfully - self.dead: jobs which finished but died. It also copies those jobs to corresponding _report lists. Th...
Report summary for a given job group.
def _group_report(self,group,name): """Report summary for a given job group. Return True if the group had any elements.""" if group: print '%s jobs:' % name for job in group: print '%s : %s' % (job.num,job) print return True
Flush a given job group
def _group_flush(self,group,name): """Flush a given job group Return True if the group had any elements.""" njobs = len(group) if njobs: plural = {1:''}.setdefault(njobs,'s') print 'Flushing %s %s job%s.' % (njobs,name,plural) group[:] = [] ...
Print the status of newly finished jobs.
def _status_new(self): """Print the status of newly finished jobs. Return True if any new jobs are reported. This call resets its own state every time, so it only reports jobs which have finished since the last time it was called.""" self._update_status() new_comp = se...
Print a status of all jobs currently being managed.
def status(self,verbose=0): """Print a status of all jobs currently being managed.""" self._update_status() self._group_report(self.running,'Running') self._group_report(self.completed,'Completed') self._group_report(self.dead,'Dead') # Also flush the report queues ...
Remove a finished ( completed or dead ) job.
def remove(self,num): """Remove a finished (completed or dead) job.""" try: job = self.all[num] except KeyError: error('Job #%s not found' % num) else: stat_code = job.stat_code if stat_code == self._s_running: error('Job #...
Flush all finished jobs ( completed and dead ) from lists.
def flush(self): """Flush all finished jobs (completed and dead) from lists. Running jobs are never flushed. It first calls _status_new(), to update info. If any jobs have completed since the last _status_new() call, the flush operation aborts.""" # Remove the finished...
result ( N ) - > return the result of job N.
def result(self,num): """result(N) -> return the result of job N.""" try: return self.all[num].result except KeyError: error('Job #%s not found' % num)
Common initialization for all BackgroundJob objects
def _init(self): """Common initialization for all BackgroundJob objects""" for attr in ['call','strform']: assert hasattr(self,attr), "Missing attribute <%s>" % attr # The num tag can be set by an external job manager self.num = None self.stat...
Inserts a value in the ListVariable at an appropriate index.
def insert(self, idx, value): """ Inserts a value in the ``ListVariable`` at an appropriate index. :param idx: The index before which to insert the new value. :param value: The value to insert. """ self._value.insert(idx, value) self._rebuild()
Retrieve a copy of the Environment. Note that this is a shallow copy.
def copy(self): """ Retrieve a copy of the Environment. Note that this is a shallow copy. """ return self.__class__(self._data.copy(), self._sensitive.copy(), self._cwd)
Declare an environment variable as a special variable. This can be used even if the environment variable is not present.
def _declare_special(self, name, sep, klass): """ Declare an environment variable as a special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered special. :...
Declare an environment variable as a list - like special variable. This can be used even if the environment variable is not present.
def declare_list(self, name, sep=os.pathsep): """ Declare an environment variable as a list-like special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered l...
Declare an environment variable as a set - like special variable. This can be used even if the environment variable is not present.
def declare_set(self, name, sep=os.pathsep): """ Declare an environment variable as a set-like special variable. This can be used even if the environment variable is not present. :param name: The name of the environment variable that should be considered set...
A thin wrapper around subprocess. Popen. Takes the same options as subprocess. Popen with the exception of the cwd and env parameters which come from the Environment instance. Note that if the sole positional argument is a string it will be converted into a sequence using the shlex. split () function.
def call(self, args, **kwargs): """ A thin wrapper around ``subprocess.Popen``. Takes the same options as ``subprocess.Popen``, with the exception of the ``cwd``, and ``env`` parameters, which come from the ``Environment`` instance. Note that if the sole positional argu...
Change the working directory that processes should be executed in.
def cwd(self, value): """ Change the working directory that processes should be executed in. :param value: The new path to change to. If relative, will be interpreted relative to the current working directory. """ self._cwd = utils.c...
Swaps two cities in the route.
def move(self, state=None): """Swaps two cities in the route. :type state: TSPState """ state = self.state if state is None else state route = state a = random.randint(self.locked_range, len(route) - 1) b = random.randint(self.locked_range, len(route) - 1) ...
Calculates the length of the route.
def energy(self, state=None): """Calculates the length of the route.""" state = self.state if state is None else state route = state e = 0 if self.distance_matrix: for i in range(len(route)): e += self.distance_matrix["{},{}".format(route[i-1], route[i...
divide
def divide(cls, divisions, problem_data): """divide :type problem_data: dict """ tspp = TSPProblem(**problem_data) def routes_for_subgroup(cs): for city in cs: if city == tspp.start_city: continue cities = tspp.cit...
create an empty record
def _defaults(self, keys=None): """create an empty record""" d = {} keys = self._keys if keys is None else keys for key in keys: d[key] = None return d
Ensure that an incorrect table doesn t exist
def _check_table(self): """Ensure that an incorrect table doesn't exist If a bad (old) table does exist, return False """ cursor = self._db.execute("PRAGMA table_info(%s)"%self.table) lines = cursor.fetchall() if not lines: # table does not exist ...
Connect to the database and get new session number.
def _init_db(self): """Connect to the database and get new session number.""" # register adapters sqlite3.register_adapter(dict, _adapt_dict) sqlite3.register_converter('dict', _convert_dict) sqlite3.register_adapter(list, _adapt_bufs) sqlite3.register_converter('bufs', _...
Inverse of dict_to_list
def _list_to_dict(self, line, keys=None): """Inverse of dict_to_list""" keys = self._keys if keys is None else keys d = self._defaults(keys) for key,value in zip(keys, line): d[key] = value return d
Turn a mongodb - style search dict into an SQL query.
def _render_expression(self, check): """Turn a mongodb-style search dict into an SQL query.""" expressions = [] args = [] skeys = set(check.keys()) skeys.difference_update(set(self._keys)) skeys.difference_update(set(['buffers', 'result_buffers'])) if skeys: ...
Add a new Task Record by msg_id.
def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" d = self._defaults() d.update(rec) d['msg_id'] = msg_id line = self._dict_to_list(d) tups = '(%s)'%(','.join(['?']*len(line))) self._db.execute("INSERT INTO %s VALUES %s"%(self.table, tups)...
Get a specific Task Record by msg_id.
def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" cursor = self._db.execute("""SELECT * FROM %s WHERE msg_id==?"""%self.table, (msg_id,)) line = cursor.fetchone() if line is None: raise KeyError("No such msg: %r"%msg_id) return self._list_to_d...
Update the data in an existing record.
def update_record(self, msg_id, rec): """Update the data in an existing record.""" query = "UPDATE %s SET "%self.table sets = [] keys = sorted(rec.keys()) values = [] for key in keys: sets.append('%s = ?'%key) values.append(rec[key]) query ...
Remove a record from the DB.
def drop_matching_records(self, check): """Remove a record from the DB.""" expr,args = self._render_expression(check) query = "DELETE FROM %s WHERE %s"%(self.table, expr) self._db.execute(query,args)
Find records matching a query dict optionally extracting subset of keys.
def find_records(self, check, keys=None): """Find records matching a query dict, optionally extracting subset of keys. Returns list of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optional] ...
get all msg_ids ordered by time submitted.
def get_history(self): """get all msg_ids, ordered by time submitted.""" query = """SELECT msg_id FROM %s ORDER by submitted ASC"""%self.table cursor = self._db.execute(query) # will be a list of length 1 tuples return [ tup[0] for tup in cursor.fetchall()]
Standard warning printer. Gives formatting consistency.
def warn(msg,level=2,exit_val=1): """Standard warning printer. Gives formatting consistency. Output is sent to io.stderr (sys.stderr by default). Options: -level(2): allows finer control: 0 -> Do nothing, dummy function. 1 -> Print message. 2 -> Print 'WARNING:' + message. (Default ...
Read a config_file check the validity with a JSON Schema as specs and get default values from default_file if asked.
def parse(self, config_file=None, specs=None, default_file=None): """Read a config_file, check the validity with a JSON Schema as specs and get default values from default_file if asked. All parameters are optionnal. If there is no config_file defined, read the venv base dir an...
Output a simple table with several columns.
def table(rows): ''' Output a simple table with several columns. ''' output = '<table>' for row in rows: output += '<tr>' for column in row: output += '<td>{s}</td>'.format(s=column) output += '</tr>' output += '</table>' return output
Output a link tag.
def link(url, text='', classes='', target='', get="", **kwargs): ''' Output a link tag. ''' if not (url.startswith('http') or url.startswith('/')): # Handle additional reverse args. urlargs = {} for arg, val in kwargs.items(): if arg[:4] == "url_": u...
Output a script tag to a js file.
def jsfile(url): ''' Output a script tag to a js file. ''' if not url.startswith('http://') and not url[:1] == '/': #add media_url for relative paths url = settings.STATIC_URL + url return '<script type="text/javascript" src="{src}"></script>'.format( src=url)
Output a link tag to a css stylesheet.
def cssfile(url): ''' Output a link tag to a css stylesheet. ''' if not url.startswith('http://') and not url[:1] == '/': #add media_url for relative paths url = settings.STATIC_URL + url return '<link href="{src}" rel="stylesheet">'.format(src=url)
Image tag helper.
def img(url, alt='', classes='', style=''): ''' Image tag helper. ''' if not url.startswith('http://') and not url[:1] == '/': #add media_url for relative paths url = settings.STATIC_URL + url attr = { 'class': classes, 'alt': alt, 'style': style, 's...
Subtract the arg from the value.
def sub(value, arg): """Subtract the arg from the value.""" try: return valid_numeric(value) - valid_numeric(arg) except (ValueError, TypeError): try: return value - arg except Exception: return ''
Multiply the arg with the value.
def mul(value, arg): """Multiply the arg with the value.""" try: return valid_numeric(value) * valid_numeric(arg) except (ValueError, TypeError): try: return value * arg except Exception: return ''
Divide the arg by the value.
def div(value, arg): """Divide the arg by the value.""" try: return valid_numeric(value) / valid_numeric(arg) except (ValueError, TypeError): try: return value / arg except Exception: return ''
Return the modulo value.
def mod(value, arg): """Return the modulo value.""" try: return valid_numeric(value) % valid_numeric(arg) except (ValueError, TypeError): try: return value % arg except Exception: return ''
Return the verbose name of a model. The obj argument can be either a Model instance or a ModelForm instance. This allows to retrieve the verbose name of the model of a ModelForm easily without adding extra context vars.
def model_verbose(obj, capitalize=True): """ Return the verbose name of a model. The obj argument can be either a Model instance, or a ModelForm instance. This allows to retrieve the verbose name of the model of a ModelForm easily, without adding extra context vars. """ if isinstance(obj, M...
Use as a class decorator to add extra methods to your model manager. Example usage:
def extendManager(mixinClass): ''' Use as a class decorator to add extra methods to your model manager. Example usage: class Article(django.db.models.Model): published = models.DateTimeField() ... @extendManager class objects(object): def getPublished(self): return self.filter(published__lte...
Main method where all logic is defined
def run(): """Main method where all logic is defined""" config_option_help="'show' - displays configured options, 'set [section] [name] [value]' - sets config under a section,'set [name] [value]' - sets configuration globally" parser = OptionParser() parser.add_option("-a", "--add", action="...
Split user input into initial whitespace escape character function part and the rest.
def split_user_input(line, pattern=None): """Split user input into initial whitespace, escape character, function part and the rest. """ # We need to ensure that the rest of this routine deals only with unicode encoding = get_stream_enc(sys.stdin, 'utf-8') line = py3compat.cast_unicode(line, enc...
Return a class name ( string ) if the current URL matches the route name specified in className. If any URL keyword arguments are provided they must be matched as well.
def current(context, urlName, className = 'active', **kwargs): ''' Return a class name (string) if the current URL matches the route name specified in ``className``. If any URL keyword arguments are provided, they must be matched as well. :param urlName: The route name that the current URL should match. Example: '...
: param path: str: param urlName: str: returns: bool.
def pathMatches(path, urlName, **kwargs): ''' :param path: str :param urlName: str :returns: bool. ''' resolved = urlresolvers.resolve(path) # Different URL name => the current URL cannot match. resolvedName = '{r.namespace}:{r.url_name}'.format(r = resolved) if resolved.namespace else resolved.url_name if ur...
Register command - line options.
def options(self, parser, env): """ Register command-line options. """ parser.add_option("--processes", action="store", default=env.get('NOSE_PROCESSES', 0), dest="multiprocess_workers", metavar="NUM", ...
Configure plugin.
def configure(self, options, config): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass if not hasattr(options, 'multiprocess_workers'): self.enabled = False return # don't start inside o...
Run tests in suite inside of suite fixtures.
def run(self, result): """Run tests in suite inside of suite fixtures. """ # proxy the result for myself log.debug("suite %s (%s) run called, tests: %s", id(self), self, self._tests) if self.resultProxy: result, orig = self.resultProxy(result, self),...
Add a builtin and save the original.
def add_builtin(self, key, value): """Add a builtin and save the original.""" bdict = __builtin__.__dict__ orig = bdict.get(key, BuiltinUndefined) if value is HideBuiltin: if orig is not BuiltinUndefined: #same as 'key in bdict' self._orig_builtins[key] = orig...
Remove an added builtin and re - set the original.
def remove_builtin(self, key, orig): """Remove an added builtin and re-set the original.""" if orig is BuiltinUndefined: del __builtin__.__dict__[key] else: __builtin__.__dict__[key] = orig
Store ipython references in the __builtin__ namespace.
def activate(self): """Store ipython references in the __builtin__ namespace.""" add_builtin = self.add_builtin for name, func in self.auto_builtins.iteritems(): add_builtin(name, func)
Remove any builtins which might have been added by add_builtins or restore overwritten ones to their previous values.
def deactivate(self): """Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.""" remove_builtin = self.remove_builtin for key, val in self._orig_builtins.iteritems(): remove_builtin(key, val) self._orig...
Finds the true URL name of a package when the given name isn t quite correct. This is usually used to implement case - insensitivity.
def _find_url_name(self, index_url, url_name, req): """ Finds the true URL name of a package, when the given name isn't quite correct. This is usually used to implement case-insensitivity. """ if not index_url.url.endswith('/'): # Vaguely part of the PyPI API....
Return an iterable of triples ( pkg_resources_version_key link python_version ) that can be extracted from the given link.
def _link_package_versions(self, link, search_name): """ Return an iterable of triples (pkg_resources_version_key, link, python_version) that can be extracted from the given link. Meant to be overridden by subclasses, not called by clients. """ platform = get_pla...
Yields all links with the given relations
def explicit_rel_links(self, rels=('homepage', 'download')): """Yields all links with the given relations""" rels = set(rels) for anchor in self.parsed.findall(".//a"): if anchor.get("rel") and anchor.get("href"): found_rels = set(anchor.get("rel").split()) ...
Send a message to one more email address ( s ). With text content as primary and html content as alternative.
def send_multi_alt_email( subject, # single line with no line-breaks text_content, to_emails, html_content=None, from_email=DEFAULT_FROM_EMAIL, fail_silently=True ): """ Send a message to one more email address(s). With text content as primary and html content as alternative. ...
Send a message to one more email address ( s ). With html content as primary.
def send_html_email( subject, # single line with no line-breaks html_content, to_emails, from_email=DEFAULT_FROM_EMAIL, fail_silently=True ): """ Send a message to one more email address(s). With html content as primary. """ messenger = EmailMessage(subject, html_content, f...
Returns a form that only contains a subset of the original fields ( opcode: incude/ exclude fields ) Exampel: <fieldset > <legend > Business Info</ legend > <ul > { % trim_form orig_form fields biz_name biz_city biz_email biz_phone as new_form % } {{ new_form. as_ul }} </ ul > </ fieldset > OR: <fieldset > <legend > Bu...
def trim_form(parser, token): """ Returns a form that only contains a subset of the original fields (opcode: incude/exclude fields) Exampel: <fieldset> <legend>Business Info</legend> <ul> {% trim_form orig_form fields biz_name,biz_city,biz_...
Turn a command - line argument into a list.
def unshell_list(s): """Turn a command-line argument into a list.""" if not s: return None if sys.platform == 'win32': # When running coverage as coverage.exe, some of the behavior # of the shell is emulated: wildcards are expanded into a list of # filenames. So you have to ...
The main entry point to Coverage.
def main(argv=None): """The main entry point to Coverage. This is installed as the script entry point. """ if argv is None: argv = sys.argv[1:] try: start = time.clock() status = CoverageScript().command_line(argv) end = time.clock() if 0: print(...
Call optparse. parse_args but return a triple:
def parse_args(self, args=None, options=None): """Call optparse.parse_args, but return a triple: (ok, options, args) """ try: options, args = \ super(CoverageOptionParser, self).parse_args(args, options) except self.OptionParserError: ret...
Add a specialized option that is the action to execute.
def add_action(self, dash, dashdash, action_code): """Add a specialized option that is the action to execute.""" option = self.add_option(dash, dashdash, action='callback', callback=self._append_action ) option.action_code = action_code
Callback for an option that adds to the actions list.
def _append_action(self, option, opt_unused, value_unused, parser): """Callback for an option that adds to the `actions` list.""" parser.values.actions.append(option.action_code)
The bulk of the command line interface to Coverage.
def command_line(self, argv): """The bulk of the command line interface to Coverage. `argv` is the argument list to process. Returns 0 if all is well, 1 if something went wrong. """ # Collect the command-line options. if not argv: self.help_fn(topic='minimu...
Display an error message or the named topic.
def help(self, error=None, topic=None, parser=None): """Display an error message, or the named topic.""" assert error or topic or parser if error: print(error) print("Use 'coverage help' for help.") elif parser: print(parser.format_help().strip()) ...
Deal with help requests.
def do_help(self, options, args, parser): """Deal with help requests. Return True if it handled the request, False if not. """ # Handle help. if options.help: if self.classic: self.help_fn(topic='help') else: self.help_fn(...
Check for conflicts and problems in the options.
def args_ok(self, options, args): """Check for conflicts and problems in the options. Returns True if everything is ok, or False if not. """ for i in ['erase', 'execute']: for j in ['annotate', 'html', 'report', 'combine']: if (i in options.actions) and (j i...
Implementation of coverage run.
def do_execute(self, options, args): """Implementation of 'coverage run'.""" # Set the first path element properly. old_path0 = sys.path[0] # Run the script. self.coverage.start() code_ran = True try: try: if options.module: ...
Implementation of coverage debug.
def do_debug(self, args): """Implementation of 'coverage debug'.""" if not args: self.help_fn("What information would you like: data, sys?") return ERR for info in args: if info == 'sys': print("-- sys ----------------------------------------"...
Serialize an object into a list of sendable buffers. Parameters ---------- obj: object The object to be serialized threshold: float The threshold for not double - pickling the content. Returns ------- ( pmd [ bufs ] ): where pmd is the pickled metadata wrapper bufs is a list of data buffers
def serialize_object(obj, threshold=64e-6): """Serialize an object into a list of sendable buffers. Parameters ---------- obj : object The object to be serialized threshold : float The threshold for not double-pickling the content. Returns ------- ...
reconstruct an object serialized by serialize_object from data buffers.
def unserialize_object(bufs): """reconstruct an object serialized by serialize_object from data buffers.""" bufs = list(bufs) sobj = pickle.loads(bufs.pop(0)) if isinstance(sobj, (list, tuple)): for s in sobj: if s.data is None: s.data = bufs.pop(0) return unc...
pack up a function args and kwargs to be sent over the wire as a series of buffers. Any object whose data is larger than threshold will not have their data copied ( currently only numpy arrays support zero - copy )
def pack_apply_message(f, args, kwargs, threshold=64e-6): """pack up a function, args, and kwargs to be sent over the wire as a series of buffers. Any object whose data is larger than `threshold` will not have their data copied (currently only numpy arrays support zero-copy)""" msg = [pickle.dumps(can(f...
unpack f args kwargs from buffers packed by pack_apply_message () Returns: original f args kwargs
def unpack_apply_message(bufs, g=None, copy=True): """unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs""" bufs = list(bufs) # allow us to pop assert len(bufs) >= 3, "not enough buffers!" if not copy: for i in range(3): bufs[i] = buf...
Set the hook.
def set(self): """Set the hook.""" if sys.displayhook is not self.hook: self.old_hook = sys.displayhook sys.displayhook = self.hook
decorator to log unhandled exceptions raised in a method. For use wrapping on_recv callbacks so that exceptions do not cause the stream to be closed.
def log_errors(f, self, *args, **kwargs): """decorator to log unhandled exceptions raised in a method. For use wrapping on_recv callbacks, so that exceptions do not cause the stream to be closed. """ try: return f(self, *args, **kwargs) except Exception: self.log.error("Unca...
boolean check for whether a string is a zmq url
def is_url(url): """boolean check for whether a string is a zmq url""" if '://' not in url: return False proto, addr = url.split('://', 1) if proto.lower() not in ['tcp','pgm','epgm','ipc','inproc']: return False return True
validate a url for zeromq
def validate_url(url): """validate a url for zeromq""" if not isinstance(url, basestring): raise TypeError("url must be a string, not %r"%type(url)) url = url.lower() proto_addr = url.split('://') assert len(proto_addr) == 2, 'Invalid url: %r'%url proto, addr = proto_addr assert...
validate a potentially nested collection of urls.
def validate_url_container(container): """validate a potentially nested collection of urls.""" if isinstance(container, basestring): url = container return validate_url(url) elif isinstance(container, dict): container = container.itervalues() for element in container: ...
split a zmq url ( tcp:// ip: port ) into ( tcp ip port ).
def split_url(url): """split a zmq url (tcp://ip:port) into ('tcp','ip','port').""" proto_addr = url.split('://') assert len(proto_addr) == 2, 'Invalid url: %r'%url proto, addr = proto_addr lis = addr.split(':') assert len(lis) == 2, 'Invalid url: %r'%url addr,s_port = lis return proto,a...
turn multi - ip interfaces 0. 0. 0. 0 and * into connectable ones based on the location ( default interpretation of location is localhost ).
def disambiguate_ip_address(ip, location=None): """turn multi-ip interfaces '0.0.0.0' and '*' into connectable ones, based on the location (default interpretation of location is localhost).""" if ip in ('0.0.0.0', '*'): try: external_ips = socket.gethostbyname_ex(socket.gethostname())[2]...
turn multi - ip interfaces 0. 0. 0. 0 and * into connectable ones based on the location ( default interpretation is localhost ). This is for zeromq urls such as tcp:// *: 10101.
def disambiguate_url(url, location=None): """turn multi-ip interfaces '0.0.0.0' and '*' into connectable ones, based on the location (default interpretation is localhost). This is for zeromq urls, such as tcp://*:10101.""" try: proto,ip,port = split_url(url) except AssertionError: ...
helper method for implementing client. pull via client. apply
def _pull(keys): """helper method for implementing `client.pull` via `client.apply`""" user_ns = globals() if isinstance(keys, (list,tuple, set)): for key in keys: if not user_ns.has_key(key): raise NameError("name '%s' is not defined"%key) return map(user_ns.get,...
Selects and return n random ports that are available.
def select_random_ports(n): """Selects and return n random ports that are available.""" ports = [] for i in xrange(n): sock = socket.socket() sock.bind(('', 0)) while sock.getsockname()[1] in _random_ports: sock.close() sock = socket.socket() sock....
Relay interupt/ term signals to children for more solid process cleanup.
def signal_children(children): """Relay interupt/term signals to children, for more solid process cleanup.""" def terminate_children(sig, frame): log = Application.instance().log log.critical("Got signal %i, terminating children..."%sig) for child in children: child.terminate...
Turn a function into a remote function.
def remote(view, block=None, **flags): """Turn a function into a remote function. This method can be used for map: In [1]: @remote(view,block=True) ...: def func(a): ...: pass """ def remote_function(f): return RemoteFunction(view, f, block=block, **flags) return remo...
Turn a function into a parallel remote function.
def parallel(view, dist='b', block=None, ordered=True, **flags): """Turn a function into a parallel remote function. This method can be used for map: In [1]: @parallel(view, block=True) ...: def func(a): ...: pass """ def parallel_function(f): return ParallelFunction(view...
call a function on each element of a sequence remotely. This should behave very much like the builtin map but return an AsyncMapResult if self. block is False.
def map(self, *sequences): """call a function on each element of a sequence remotely. This should behave very much like the builtin map, but return an AsyncMapResult if self.block is False. """ # set _map as a flag for use inside self.__call__ self._map = True try...
Get the last n items in readline history.
def get_readline_tail(self, n=10): """Get the last n items in readline history.""" end = self.shell.readline.get_current_history_length() + 1 start = max(end-n, 1) ghi = self.shell.readline.get_history_item return [ghi(x) for x in range(start, end)]
Set the autoindent flag checking for readline support.
def set_autoindent(self,value=None): """Set the autoindent flag, checking for readline support. If called with no arguments, it acts as a toggle.""" if value != 0 and not self.has_readline: if os.name == 'posix': warn("The auto-indent feature requires the readline l...
Initialize logging in case it was requested at the command line.
def init_logstart(self): """Initialize logging in case it was requested at the command line. """ if self.logappend: self.magic('logstart %s append' % self.logappend) elif self.logfile: self.magic('logstart %s' % self.logfile) elif self.logstart: ...
Add a virtualenv to sys. path so the user can import modules from it. This isn t perfect: it doesn t use the Python interpreter with which the virtualenv was built and it ignores the -- no - site - packages option. A warning will appear suggesting the user installs IPython in the virtualenv but for many cases it probab...
def init_virtualenv(self): """Add a virtualenv to sys.path so the user can import modules from it. This isn't perfect: it doesn't use the Python interpreter with which the virtualenv was built, and it ignores the --no-site-packages option. A warning will appear suggesting the user instal...
Save the state of hooks in the sys module.
def save_sys_module_state(self): """Save the state of hooks in the sys module. This has to be called after self.user_module is created. """ self._orig_sys_module_state = {} self._orig_sys_module_state['stdin'] = sys.stdin self._orig_sys_module_state['stdout'] = sys.stdou...
Restore the state of the sys module.
def restore_sys_module_state(self): """Restore the state of the sys module.""" try: for k, v in self._orig_sys_module_state.iteritems(): setattr(sys, k, v) except AttributeError: pass # Reset what what done in self.init_sys_modules if self....
set_hook ( name hook ) - > sets an internal IPython hook.
def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): """set_hook(name,hook) -> sets an internal IPython hook. IPython exposes some of its internal API as user-modifiable hooks. By adding your function to one of these hooks, you can modify IPython's behavior to ca...