Search is not available for this dataset
text
stringlengths
75
104k
def begin(self, total: int, name=None, message=None): """Call before starting work on a monitor, specifying name and amount of work""" self.total = total message = message or name or "Working..." self.name = name or "ProgressMonitor" self.update(0, message)
def task(self, total: int, name=None, message=None): """Wrap code into a begin and end call on this monitor""" self.begin(total, name, message) try: yield self finally: self.done()
def subtask(self, units: int): """Create a submonitor with the given units""" sm = self.submonitor(units) try: yield sm finally: if sm.total is None: # begin was never called, so the subtask cannot be closed self.update(units) ...
def progress(self)-> float: """What percentage (range 0-1) of work is done (including submonitors)""" if self.total is None: return 0 my_progress = self.worked my_progress += sum(s.progress * weight for (s, weight) in self.sub_monitors.items()) ...
def update(self, units: int=1, message: str=None): """Increment the monitor with N units worked and an optional message""" if self.total is None: raise Exception("Cannot call progressmonitor.update before calling begin") self.worked = min(self.total, self.worked+units) if mes...
def submonitor(self, units: int, *args, **kargs) -> 'ProgressMonitor': """ Create a sub monitor that stands for N units of work in this monitor The sub task should call .begin (or use @monitored / with .task) before calling updates """ submonitor = ProgressMonitor(*args, **kargs)...
def done(self, message: str=None): """ Signal that this task is done. This is completely optional and will just call .update with the remaining work. """ if message is None: message = "{self.name} done".format(**locals()) if self.name else "Done" self.update(u...
def page(strng, start=0, screen_lines=0, pager_cmd=None, html=None, auto_html=False): """Print a string, piping through a pager. This version ignores the screen_lines and pager_cmd arguments and uses IPython's payload system instead. Parameters ---------- strng : str Text to pag...
def from_line(cls, name, comes_from=None, isolated=False): """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. """ from pip.index import Link url = None if is_url(name): marker_sep = '...
def correct_build_location(self): """If the build location was a temporary directory, this will move it to a new more permanent location""" if self.source_dir is not None: return assert self.req is not None assert self._temp_build_dir old_location = self._temp...
def uninstall(self, auto_confirm=False): """ Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation w...
def load_pyconfig_files(config_files, path): """Load multiple Python config files, merging each of them in turn. Parameters ========== config_files : list of str List of config files names to load and merge into the config. path : unicode The full path to the location of the config ...
def load_config(self): """Load the config from a file and return it as a Struct.""" self.clear() try: self._find_file() except IOError as e: raise ConfigFileNotFound(str(e)) self._read_file_as_dict() self._convert_to_config() return self.co...
def _read_file_as_dict(self): """Load the config file into self.config, with recursive loading.""" # This closure is made available in the namespace that is used # to exec the config file. It allows users to call # load_subconfig('myconfig.py') to load config files recursively. ...
def _exec_config_str(self, lhs, rhs): """execute self.config.<lhs> = <rhs> * expands ~ with expanduser * tries to assign with raw eval, otherwise assigns with just the string, allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not* equivalent are `--C.a...
def _load_flag(self, cfg): """update self.config from a flag, which can be a dict or Config""" if isinstance(cfg, (dict, Config)): # don't clobber whole config sections, update # each section from config: for sec,c in cfg.iteritems(): self.config[sec]....
def _decode_argv(self, argv, enc=None): """decode argv if bytes, using stin.encoding, falling back on default enc""" uargv = [] if enc is None: enc = DEFAULT_ENCODING for arg in argv: if not isinstance(arg, unicode): # only decode if not already de...
def load_config(self, argv=None, aliases=None, flags=None): """Parse the configuration and generate the Config object. After loading, any arguments that are not key-value or flags will be stored in self.extra_args - a list of unparsed command-line arguments. This is used for ar...
def load_config(self, argv=None, aliases=None, flags=None): """Parse command line arguments and return as a Config object. Parameters ---------- args : optional, list If given, a list with the structure of sys.argv[1:] to parse arguments from. If not given, the inst...
def _parse_args(self, args): """self.parser->self.parsed_data""" # decode sys.argv to support unicode command-line options enc = DEFAULT_ENCODING uargs = [py3compat.cast_unicode(a, enc) for a in args] self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
def _convert_to_config(self): """self.parsed_data->self.config""" for k, v in vars(self.parsed_data).iteritems(): exec "self.config.%s = v"%k in locals(), globals()
def _convert_to_config(self): """self.parsed_data->self.config, parse unrecognized extra args via KVLoader.""" # remove subconfigs list from namespace before transforming the Namespace if '_flags' in self.parsed_data: subcs = self.parsed_data._flags del self.parsed_data._...
def find_module(name, path=None): """imp.find_module variant that only return path of module. The `imp.find_module` returns a filehandle that we are not interested in. Also we ignore any bytecode files that `imp.find_module` finds. Parameters ---------- name : str name of module to...
def get_init(dirname): """Get __init__ file path for module directory Parameters ---------- dirname : str Find the __init__ file in directory `dirname` Returns ------- init_path : str Path to __init__ file """ fbase = os.path.join(dirname, "__init__") for e...
def find_mod(module_name): """Find module `module_name` on sys.path Return the path to module `module_name`. If `module_name` refers to a module directory then return path to __init__ file. Return full path of module or None if module is missing or does not have .py or .pyw extension. We are n...
def on_stop(self, f): """Register a callback to be called with this Launcher's stop_data when the process actually finishes. """ if self.state=='after': return f(self.stop_data) else: self.stop_callbacks.append(f)
def notify_start(self, data): """Call this to trigger startup actions. This logs the process startup and sets the state to 'running'. It is a pass-through so it can be used as a callback. """ self.log.debug('Process %r started: %r', self.args[0], data) self.start_data ...
def notify_stop(self, data): """Call this to trigger process stop actions. This logs the process stopping and sets the state to 'after'. Call this to trigger callbacks registered via :meth:`on_stop`.""" self.log.debug('Process %r stopped: %r', self.args[0], data) self.stop_data...
def interrupt_then_kill(self, delay=2.0): """Send INT, wait a delay and then send KILL.""" try: self.signal(SIGINT) except Exception: self.log.debug("interrupt failed") pass self.killer = ioloop.DelayedCallback(lambda : self.signal(SIGKILL), delay*100...
def start(self, n): """Start n engines by profile or profile_dir.""" dlist = [] for i in range(n): if i > 0: time.sleep(self.delay) el = self.launcher_class(work_dir=self.work_dir, config=self.config, log=self.log, profi...
def find_args(self): """Build self.args using all the fields.""" return self.mpi_cmd + ['-n', str(self.n)] + self.mpi_args + \ self.program + self.program_args
def start(self, n): """Start n instances of the program using mpiexec.""" self.n = n return super(MPILauncher, self).start()
def start(self, n): """Start n engines by profile or profile_dir.""" self.n = n return super(MPIEngineSetLauncher, self).start(n)
def _send_file(self, local, remote): """send a single file""" remote = "%s:%s" % (self.location, remote) for i in range(10): if not os.path.exists(local): self.log.debug("waiting for %s" % local) time.sleep(1) else: break ...
def send_files(self): """send our files (called before start)""" if not self.to_send: return for local_file, remote_file in self.to_send: self._send_file(local_file, remote_file)
def _fetch_file(self, remote, local): """fetch a single file""" full_remote = "%s:%s" % (self.location, remote) self.log.info("fetching %s from %s", local, full_remote) for i in range(10): # wait up to 10s for remote file to exist check = check_output(self.ssh_cmd...
def fetch_files(self): """fetch remote files (called after start)""" if not self.to_fetch: return for remote_file, local_file in self.to_fetch: self._fetch_file(remote_file, local_file)
def _remote_profile_dir_default(self): """turns /home/you/.ipython/profile_foo into .ipython/profile_foo """ home = get_home_dir() if not home.endswith('/'): home = home+'/' if self.profile_dir.startswith(home): return self.profile_dir[len(home):]...
def engine_count(self): """determine engine count from `engines` dict""" count = 0 for n in self.engines.itervalues(): if isinstance(n, (tuple,list)): n,args = n count += n return count
def start(self, n): """Start engines by profile or profile_dir. `n` is ignored, and the `engines` config property is used instead. """ dlist = [] for host, n in self.engines.iteritems(): if isinstance(n, (tuple, list)): n, args = n else: ...
def start(self, n): """Start n copies of the process using the Win HPC job scheduler.""" self.write_job_file(n) args = [ 'submit', '/jobfile:%s' % self.job_file, '/scheduler:%s' % self.scheduler ] self.log.debug("Starting Win HPC Job: %s" % (se...
def _context_default(self): """load the default context with the default values for the basic keys because the _trait_changed methods only load the context if they are set to something other than the default value. """ return dict(n=1, queue=u'', profile_dir=u'', cluster_id=u'')
def parse_job_id(self, output): """Take the output of the submit command and return the job id.""" m = self.job_id_regexp.search(output) if m is not None: job_id = m.group() else: raise LauncherError("Job id couldn't be determined: %s" % output) self.job_i...
def write_batch_script(self, n): """Instantiate and write the batch script to the work_dir.""" self.n = n # first priority is batch_template if set if self.batch_template_file and not self.batch_template: # second priority is batch_template_file with open(self.bat...
def start(self, n): """Start n copies of the process using a batch system.""" self.log.debug("Starting %s: %r", self.__class__.__name__, self.args) # Here we save profile_dir in the context so they # can be used in the batch script template as {profile_dir} self.write_batch_scrip...
def start(self, n): """Start n copies of the process using LSF batch system. This cant inherit from the base class because bsub expects to be piped a shell script in order to honor the #BSUB directives : bsub < script """ # Here we save profile_dir in the context so they ...
def check_filemode(filepath, mode): """Return True if 'file' matches ('permission') which should be entered in octal. """ filemode = stat.S_IMODE(os.stat(filepath).st_mode) return (oct(filemode) == mode)
def _context_menu_make(self, pos): """ Reimplemented to return a custom context menu for images. """ format = self._control.cursorForPosition(pos).charFormat() name = format.stringProperty(QtGui.QTextFormat.ImageName) if name: menu = QtGui.QMenu() menu.ad...
def _pre_image_append(self, msg, prompt_number): """ Append the Out[] prompt and make the output nicer Shared code for some the following if statement """ self.log.debug("pyout: %s", msg.get('content', '')) self._append_plain_text(self.output_sep, True) self._append_htm...
def _handle_pyout(self, msg): """ Overridden to handle rich data types, like SVG. """ if not self._hidden and self._is_from_this_session(msg): content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if data...
def _handle_display_data(self, msg): """ Overridden to handle rich data types, like SVG. """ if not self._hidden and self._is_from_this_session(msg): source = msg['content']['source'] data = msg['content']['data'] metadata = msg['content']['metadata'] ...
def _append_jpg(self, jpg, before_prompt=False): """ Append raw JPG data to the widget.""" self._append_custom(self._insert_jpg, jpg, before_prompt)
def _append_png(self, png, before_prompt=False): """ Append raw PNG data to the widget. """ self._append_custom(self._insert_png, png, before_prompt)
def _append_svg(self, svg, before_prompt=False): """ Append raw SVG data to the widget. """ self._append_custom(self._insert_svg, svg, before_prompt)
def _add_image(self, image): """ Adds the specified QImage to the document and returns a QTextImageFormat that references it. """ document = self._control.document() name = str(image.cacheKey()) document.addResource(QtGui.QTextDocument.ImageResource, ...
def _copy_image(self, name): """ Copies the ImageResource with 'name' to the clipboard. """ image = self._get_image(name) QtGui.QApplication.clipboard().setImage(image)
def _get_image(self, name): """ Returns the QImage stored as the ImageResource with 'name'. """ document = self._control.document() image = document.resource(QtGui.QTextDocument.ImageResource, QtCore.QUrl(name)) return image
def _get_image_tag(self, match, path = None, format = "png"): """ Return (X)HTML mark-up for the image-tag given by match. Parameters ---------- match : re.SRE_Match A match to an HTML image tag as exported by Qt, with match.group("Name") containing the matched i...
def _insert_img(self, cursor, img, fmt): """ insert a raw image, jpg or png """ try: image = QtGui.QImage() image.loadFromData(img, fmt.upper()) except ValueError: self._insert_plain_text(cursor, 'Received invalid %s data.'%fmt) else: forma...
def _insert_svg(self, cursor, svg): """ Insert raw SVG data into the widet. """ try: image = svg_to_image(svg) except ValueError: self._insert_plain_text(cursor, 'Received invalid SVG data.') else: format = self._add_image(image) se...
def _save_image(self, name, format='PNG'): """ Shows a save dialog for the ImageResource with 'name'. """ dialog = QtGui.QFileDialog(self._control, 'Save Image') dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) dialog.setDefaultSuffix(format.lower()) dialog.setNameFilte...
def safe_unicode(e): """unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on. """ try: return unicode(e) except UnicodeError: pass try: return py3compat.str_to_unicode(str(e)) except UnicodeError: pass try: ...
def _exit_now_changed(self, name, old, new): """stop eventloop when exit_now fires""" if new: loop = ioloop.IOLoop.instance() loop.add_timeout(time.time()+0.1, loop.stop)
def init_environment(self): """Configure the user's environment. """ env = os.environ # These two ensure 'ls' produces nice coloring on BSD-derived systems env['TERM'] = 'xterm-color' env['CLICOLOR'] = '1' # Since normal pagers don't work at all (over pexpect we ...
def auto_rewrite_input(self, cmd): """Called to show the auto-rewritten input for autocall and friends. FIXME: this payload is currently not correctly processed by the frontend. """ new = self.prompt_manager.render('rewrite') + cmd payload = dict( source='IPy...
def ask_exit(self): """Engage the exit actions.""" self.exit_now = True payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', exit=True, keepkernel=self.keepkernel_on_exit, ) self.payload_manager.write_payload(payload)
def set_next_input(self, text): """Send the specified text to the frontend to be presented at the next input cell.""" payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input', text=text ) self.payload_manager.write_payload(payload)
def check_running(process_name="apache2"): ''' CHECK if process (default=apache2) is not running ''' if not gurumate.base.get_pid_list(process_name): fail("Apache process '%s' doesn't seem to be working" % process_name) return False #unreachable return True
def get_listening_ports(process_name="apache2"): ''' returns a list of listening ports for running process (default=apache2) ''' ports = set() for _, address_info in gurumate.base.get_listening_ports(process_name): ports.add(address_info[1]) return list(ports)
def read(self, filename): """Read a filename as UTF-8 configuration data.""" kwargs = {} if sys.version_info >= (3, 2): kwargs['encoding'] = "utf-8" return configparser.RawConfigParser.read(self, filename, **kwargs)
def getlist(self, section, option): """Read a list of strings. The value of `section` and `option` is treated as a comma- and newline- separated list of strings. Each value is stripped of whitespace. Returns the list of strings. """ value_list = self.get(section, opti...
def getlinelist(self, section, option): """Read a list of full-line strings. The value of `section` and `option` is treated as a newline-separated list of strings. Each value is stripped of whitespace. Returns the list of strings. """ value_list = self.get(section, op...
def from_environment(self, env_var): """Read configuration from the `env_var` environment variable.""" # Timidity: for nose users, read an environment variable. This is a # cheap hack, since the rest of the command line arguments aren't # recognized, but it solves some users' problems. ...
def from_args(self, **kwargs): """Read config values from `kwargs`.""" for k, v in iitems(kwargs): if v is not None: if k in self.MUST_BE_LIST and isinstance(v, string_class): v = [v] setattr(self, k, v)
def from_file(self, filename): """Read configuration from a .rc file. `filename` is a file name to read. """ self.attempted_config_files.append(filename) cp = HandyConfigParser() files_read = cp.read(filename) if files_read is not None: # return value changed ...
def set_attr_from_config_option(self, cp, attr, where, type_=''): """Set an attribute on self if it exists in the ConfigParser.""" section, option = where.split(":") if cp.has_option(section, option): method = getattr(cp, 'get'+type_) setattr(self, attr, method(section, o...
def expand_user(path): """Expand '~'-style usernames in strings. This is similar to :func:`os.path.expanduser`, but it computes and returns extra information that will be useful if the input was being used in computing completions, and you wish to return the completions with the original '~' instea...
def delims(self, delims): """Set the delimiters for line splitting.""" expr = '[' + ''.join('\\'+ c for c in delims) + ']' self._delim_re = re.compile(expr) self._delims = delims self._delim_expr = expr
def split_line(self, line, cursor_pos=None): """Split a line of text with a cursor at the given position. """ l = line if cursor_pos is None else line[:cursor_pos] return self._delim_re.split(l)[-1]
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match. """ #print 'Completer->global_matches, txt=%r' % text # dbg ...
def attr_matches(self, text): """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible com...
def _greedy_changed(self, name, old, new): """update the splitter and readline delims when greedy is changed""" if new: self.splitter.delims = GREEDY_DELIMS else: self.splitter.delims = DELIMS if self.readline: self.readline.set_completer_delims(self....
def file_matches(self, text): """Match filenames, expanding ~USER type strings. Most of the seemingly convoluted logic in this completer is an attempt to handle filenames with spaces in them. And yet it's not quite perfect, because Python's readline doesn't expose all of the GN...
def magic_matches(self, text): """Match magics""" #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg # Get all shell magics now rather than statically, so magics loaded at # runtime show up too. lsm = self.shell.magics_manager.lsmagic() line_magics ...
def alias_matches(self, text): """Match internal system aliases""" #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg # if we are not in the first 'item', alias matching # doesn't make sense - unless we are starting with 'sudo' command. main_text = self.te...
def python_matches(self,text): """Match attributes or global python names""" #io.rprint('Completer->python_matches, txt=%r' % text) # dbg if "." in text: try: matches = self.attr_matches(text) if text.endswith('.') and self.omit__names: ...
def _default_arguments(self, obj): """Return the list of default arguments of obj if it is callable, or empty list otherwise.""" if not (inspect.isfunction(obj) or inspect.ismethod(obj)): # for classes, check for __init__,__new__ if inspect.isclass(obj): ...
def python_func_kw_matches(self,text): """Match named parameters (kwargs) of the last open function""" if "." in text: # a parameter cannot be dotted return [] try: regexp = self.__funcParamsRegex except AttributeError: regexp = self.__funcParamsRegex = re.compil...
def complete(self, text=None, line_buffer=None, cursor_pos=None): """Find completions for the given text and line context. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. Note that both the text and the line_buffer...
def rlcomplete(self, text, state): """Return the state-th possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. Parameters ---------- text : string Text to pe...
def _match_one(self, rec, tests): """Check if a specific record matches tests.""" for key,test in tests.iteritems(): if not test(rec.get(key, None)): return False return True
def _match(self, check): """Find all the matches for a check dict.""" matches = [] tests = {} for k,v in check.iteritems(): if isinstance(v, dict): tests[k] = CompositeFilter(v) else: tests[k] = lambda o: o==v for rec in se...
def _extract_subdict(self, rec, keys): """extract subdict of keys""" d = {} d['msg_id'] = rec['msg_id'] for key in keys: d[key] = rec[key] return copy(d)
def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" if self._records.has_key(msg_id): raise KeyError("Already have msg_id %r"%(msg_id)) self._records[msg_id] = rec
def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" if not msg_id in self._records: raise KeyError("No such msg_id %r"%(msg_id)) return copy(self._records[msg_id])
def drop_matching_records(self, check): """Remove a record from the DB.""" matches = self._match(check) for m in matches: del self._records[m['msg_id']]
def find_records(self, check, keys=None): """Find records matching a query dict, optionally extracting subset of keys. Returns dict keyed by msg_id of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optio...
def get_history(self): """get all msg_ids, ordered by time submitted.""" msg_ids = self._records.keys() return sorted(msg_ids, key=lambda m: self._records[m]['submitted'])
def quiet(self): """Should we silence the display hook because of ';'?""" # do not print output if input ends in ';' try: cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] if cell.rstrip().endswith(';'): return True except Inde...
def write_output_prompt(self): """Write the output prompt. The default implementation simply writes the prompt to ``io.stdout``. """ # Use write, not print which adds an extra space. io.stdout.write(self.shell.separate_out) outprompt = self.shell.prompt_manager.r...