_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q279600
mappable
test
def mappable(obj): """return whether an object is mappable or not.""" if isinstance(obj, (tuple,list)): return True for m in arrayModules: if isinstance(obj,m['type']): return True return False
python
{ "resource": "" }
q279601
Map.getPartition
test
def getPartition(self, seq, p, q): """Returns the pth partition of q partitions of seq.""" # Test for error conditions here if p<0 or p>=q: print "No partition exists." return remainder = len(seq)%q basesize = len(seq)//q hi = [] ...
python
{ "resource": "" }
q279602
pexpect_monkeypatch
test
def pexpect_monkeypatch(): """Patch pexpect to prevent unhandled exceptions at VM teardown. Calling this function will monkeypatch the pexpect.spawn class and modify its __del__ method to make it more robust in the face of failures that can occur if it is called when the Python VM is shutting down. ...
python
{ "resource": "" }
q279603
InteractiveRunner.run_file
test
def run_file(self,fname,interact=False,get_output=False): """Run the given file interactively. Inputs: -fname: name of the file to execute. See the run_source docstring for the meaning of the optional arguments.""" fobj = open(fname,'r') try: out...
python
{ "resource": "" }
q279604
InteractiveRunner.run_source
test
def run_source(self,source,interact=False,get_output=False): """Run the given source code interactively. Inputs: - source: a string of code to be executed, or an open file object we can iterate over. Optional inputs: - interact(False): if true, start to interact...
python
{ "resource": "" }
q279605
XmlReporter.report
test
def report(self, morfs, outfile=None): """Generate a Cobertura-compatible XML report for `morfs`. `morfs` is a list of modules or filenames. `outfile` is a file object to write the XML to. """ # Initial setup. outfile = outfile or sys.stdout # Create the DOM t...
python
{ "resource": "" }
q279606
XmlReporter.xml_file
test
def xml_file(self, cu, analysis): """Add to the XML report for a single file.""" # Create the 'lines' and 'package' XML elements, which # are populated later. Note that a package == a directory. package_name = rpartition(cu.name, ".")[0] className = cu.name package = s...
python
{ "resource": "" }
q279607
fetch_pi_file
test
def fetch_pi_file(filename): """This will download a segment of pi from super-computing.org if the file is not already present. """ import os, urllib ftpdir="ftp://pi.super-computing.org/.2/pi200m/" if os.path.exists(filename): # we already have it return else: # down...
python
{ "resource": "" }
q279608
reduce_freqs
test
def reduce_freqs(freqlist): """ Add up a list of freq counts to get the total counts. """ allfreqs = np.zeros_like(freqlist[0]) for f in freqlist: allfreqs += f return allfreqs
python
{ "resource": "" }
q279609
compute_n_digit_freqs
test
def compute_n_digit_freqs(filename, n): """ Read digits of pi from a file and compute the n digit frequencies. """ d = txt_file_to_digits(filename) freqs = n_digit_freqs(d, n) return freqs
python
{ "resource": "" }
q279610
txt_file_to_digits
test
def txt_file_to_digits(filename, the_type=str): """ Yield the digits of pi read from a .txt file. """ with open(filename, 'r') as f: for line in f.readlines(): for c in line: if c != '\n' and c!= ' ': yield the_type(c)
python
{ "resource": "" }
q279611
one_digit_freqs
test
def one_digit_freqs(digits, normalize=False): """ Consume digits of pi and compute 1 digit freq. counts. """ freqs = np.zeros(10, dtype='i4') for d in digits: freqs[int(d)] += 1 if normalize: freqs = freqs/freqs.sum() return freqs
python
{ "resource": "" }
q279612
two_digit_freqs
test
def two_digit_freqs(digits, normalize=False): """ Consume digits of pi and compute 2 digits freq. counts. """ freqs = np.zeros(100, dtype='i4') last = digits.next() this = digits.next() for d in digits: index = int(last + this) freqs[index] += 1 last = this th...
python
{ "resource": "" }
q279613
n_digit_freqs
test
def n_digit_freqs(digits, n, normalize=False): """ Consume digits of pi and compute n digits freq. counts. This should only be used for 1-6 digits. """ freqs = np.zeros(pow(10,n), dtype='i4') current = np.zeros(n, dtype=int) for i in range(n): current[i] = digits.next() for d in...
python
{ "resource": "" }
q279614
plot_two_digit_freqs
test
def plot_two_digit_freqs(f2): """ Plot two digits frequency counts using matplotlib. """ f2_copy = f2.copy() f2_copy.shape = (10,10) ax = plt.matshow(f2_copy) plt.colorbar() for i in range(10): for j in range(10): plt.text(i-0.2, j+0.2, str(j)+str(i)) plt.ylabel('...
python
{ "resource": "" }
q279615
plot_one_digit_freqs
test
def plot_one_digit_freqs(f1): """ Plot one digit frequency counts using matplotlib. """ ax = plt.plot(f1,'bo-') plt.title('Single digit counts in pi') plt.xlabel('Digit') plt.ylabel('Count') return ax
python
{ "resource": "" }
q279616
debugx
test
def debugx(expr,pre_msg=''): """Print the value of an expression from the caller's frame. Takes an expression, evaluates it in the caller's frame and prints both the given expression and the resulting value (as well as a debug mark indicating the name of the calling function. The input must be of a fo...
python
{ "resource": "" }
q279617
reverse
test
def reverse(view, *args, **kwargs): ''' User-friendly reverse. Pass arguments and keyword arguments to Django's `reverse` as `args` and `kwargs` arguments, respectively. The special optional keyword argument `query` is a dictionary of query (or GET) parameters that can be appended to the `reverse`d URL. Example...
python
{ "resource": "" }
q279618
is_private
test
def is_private(prefix, base): """prefix, base -> true iff name prefix + "." + base is "private". Prefix may be an empty string, and base does not contain a period. Prefix is ignored (although functions you write conforming to this protocol may make use of it). Return true iff base begins with an (a...
python
{ "resource": "" }
q279619
DocFileSuite
test
def DocFileSuite(*paths, **kw): """A unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument "module_relative". A number of options may be provided as keyword arguments: module_relative...
python
{ "resource": "" }
q279620
debug_src
test
def debug_src(src, pm=False, globs=None): """Debug a single doctest docstring, in argument `src`'""" testsrc = script_from_examples(src) debug_script(testsrc, pm, globs)
python
{ "resource": "" }
q279621
debug_script
test
def debug_script(src, pm=False, globs=None): "Debug a test script. `src` is the script, as a string." import pdb # Note that tempfile.NameTemporaryFile() cannot be used. As the # docs say, a file so created cannot be opened by name a second time # on modern Windows boxes, and execfile() needs to ...
python
{ "resource": "" }
q279622
debug
test
def debug(module, name, pm=False): """Debug a single doctest docstring. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the docstring with tests to be debugged. """ module = _normalize_module(module) te...
python
{ "resource": "" }
q279623
PickleShareDB.hdict
test
def hdict(self, hashroot): """ Get all data contained in hashed category 'hashroot' as dict """ hfiles = self.keys(hashroot + "/*") hfiles.sort() last = len(hfiles) and hfiles[-1] or '' if last.endswith('xx'): # print "using xx" hfiles = [last] + hfiles[:-...
python
{ "resource": "" }
q279624
PickleShareDB.hcompress
test
def hcompress(self, hashroot): """ Compress category 'hashroot', so hset is fast again hget will fail if fast_only is True for compressed items (that were hset before hcompress). """ hfiles = self.keys(hashroot + "/*") all = {} for f in hfiles: # pri...
python
{ "resource": "" }
q279625
PickleShareDB.keys
test
def keys(self, globpat = None): """ All keys in DB, or all keys matching a glob""" if globpat is None: files = self.root.walkfiles() else: files = [Path(p) for p in glob.glob(self.root/globpat)] return [self._normalized(p) for p in files if p.isfile()]
python
{ "resource": "" }
q279626
FilterSet.allow
test
def allow(self, record): """returns whether this record should be printed""" if not self: # nothing to filter return True return self._allow(record) and not self._deny(record)
python
{ "resource": "" }
q279627
FilterSet._any_match
test
def _any_match(matchers, record): """return the bool of whether `record` starts with any item in `matchers`""" def record_matches_key(key): return record == key or record.startswith(key + '.') return anyp(bool, map(record_matches_key, matchers))
python
{ "resource": "" }
q279628
LogCapture.formatError
test
def formatError(self, test, err): """Add captured log messages to error output. """ # logic flow copied from Capture.formatError test.capturedLogging = records = self.formatLogRecords() if not records: return err ec, ev, tb = err return (ec, self.addCa...
python
{ "resource": "" }
q279629
embed
test
def embed(**kwargs): """Call this to embed IPython at the current point in your program. The first invocation of this will create an :class:`InteractiveShellEmbed` instance and then call it. Consecutive calls just call the already created instance. Here is a simple example:: from IPython...
python
{ "resource": "" }
q279630
InteractiveShellEmbed.mainloop
test
def mainloop(self, local_ns=None, module=None, stack_depth=0, display_banner=None, global_ns=None): """Embeds IPython into a running python program. Input: - header: An optional header message can be specified. - local_ns, module: working local namespace (a dict) ...
python
{ "resource": "" }
q279631
_get_new_csv_writers
test
def _get_new_csv_writers(trans_title, meta_title, trans_csv_path, meta_csv_path): """ Prepare new csv writers, write title rows and return them. """ trans_writer = UnicodeWriter(trans_csv_path) trans_writer.writerow(trans_title) meta_writer = UnicodeWriter(meta_csv_path...
python
{ "resource": "" }
q279632
_prepare_locale_dirs
test
def _prepare_locale_dirs(languages, locale_root): """ Prepare locale dirs for writing po files. Create new directories if they doesn't exist. """ trans_languages = [] for i, t in enumerate(languages): lang = t.split(':')[0] trans_languages.append(lang) lang_path = os.path...
python
{ "resource": "" }
q279633
_write_entries
test
def _write_entries(po_files, languages, msgid, msgstrs, metadata, comment): """ Write msgstr for every language with all needed metadata and comment. Metadata are parser from string into dict, so read them only from gdocs. """ start = re.compile(r'^[\s]+') end = re.compile(r'[\s]+$') for i, ...
python
{ "resource": "" }
q279634
_write_header
test
def _write_header(po_path, lang, header): """ Write header into po file for specific lang. Metadata are read from settings file. """ po_file = open(po_path, 'w') po_file.write(header + '\n') po_file.write( 'msgid ""' + '\nmsgstr ""' + '\n"MIME-Version: ' + settings.ME...
python
{ "resource": "" }
q279635
Notifo.subscribe_user
test
def subscribe_user(self, user): """ method to subscribe a user to a service """ url = self.root_url + "subscribe_user" values = {} values["username"] = user return self._query(url, values)
python
{ "resource": "" }
q279636
init_parser
test
def init_parser(): """ function to init option parser """ usage = "usage: %prog -u user -s secret -n name [-l label] \ [-t title] [-c callback] [TEXT]" parser = OptionParser(usage, version="%prog " + notifo.__version__) parser.add_option("-u", "--user", action="store", dest="user", ...
python
{ "resource": "" }
q279637
run_python_module
test
def run_python_module(modulename, args): """Run a python module, as though with ``python -m name args...``. `modulename` is the name of the module, possibly a dot-separated name. `args` is the argument array to present as sys.argv, including the first element naming the module being executed. """ ...
python
{ "resource": "" }
q279638
run_python_file
test
def run_python_file(filename, args, package=None): """Run a python file as if it were the main program on the command line. `filename` is the path to the file to execute, it need not be a .py file. `args` is the argument array to present as sys.argv, including the first element naming the file being ex...
python
{ "resource": "" }
q279639
make_code_from_py
test
def make_code_from_py(filename): """Get source from `filename` and make a code object of it.""" # Open the source file. try: source_file = open_source(filename) except IOError: raise NoSource("No file to run: %r" % filename) try: source = source_file.read() finally: ...
python
{ "resource": "" }
q279640
make_code_from_pyc
test
def make_code_from_pyc(filename): """Get a code object from a .pyc file.""" try: fpyc = open(filename, "rb") except IOError: raise NoCode("No file to run: %r" % filename) try: # First four bytes are a version-specific magic number. It has to # match or we won't run the ...
python
{ "resource": "" }
q279641
html_tableify
test
def html_tableify(item_matrix, select=None, header=None , footer=None) : """ returnr a string for an html table""" if not item_matrix : return '' html_cols = [] tds = lambda text : u'<td>'+text+u' </td>' trs = lambda text : u'<tr>'+text+u'</tr>' tds_items = [map(tds, row) for row in ite...
python
{ "resource": "" }
q279642
SlidingInterval.current
test
def current(self, value): """set current cursor position""" current = min(max(self._min, value), self._max) self._current = current if current > self._stop : self._stop = current self._start = current-self._width elif current < self._start : ...
python
{ "resource": "" }
q279643
CompletionHtml.cancel_completion
test
def cancel_completion(self): """Cancel the completion should be called when the completer have to be dismissed This reset internal variable, clearing the temporary buffer of the console where the completion are shown. """ self._consecutive_tab = 0 self._slice_st...
python
{ "resource": "" }
q279644
CompletionHtml._select_index
test
def _select_index(self, row, col): """Change the selection index, and make sure it stays in the right range A little more complicated than just dooing modulo the number of row columns to be sure to cycle through all element. horizontaly, the element are maped like this : to r <...
python
{ "resource": "" }
q279645
CompletionHtml.select_up
test
def select_up(self): """move cursor up""" r, c = self._index self._select_index(r-1, c)
python
{ "resource": "" }
q279646
CompletionHtml.select_down
test
def select_down(self): """move cursor down""" r, c = self._index self._select_index(r+1, c)
python
{ "resource": "" }
q279647
CompletionHtml.select_left
test
def select_left(self): """move cursor left""" r, c = self._index self._select_index(r, c-1)
python
{ "resource": "" }
q279648
CompletionHtml.select_right
test
def select_right(self): """move cursor right""" r, c = self._index self._select_index(r, c+1)
python
{ "resource": "" }
q279649
CompletionHtml._update_list
test
def _update_list(self, hilight=True): """ update the list of completion and hilight the currently selected completion """ self._sliding_interval.current = self._index[0] head = None foot = None if self._sliding_interval.start > 0 : head = '...' if self._slid...
python
{ "resource": "" }
q279650
wordfreq
test
def wordfreq(text, is_filename=False): """Return a dictionary of words and word counts in a string.""" if is_filename: with open(text) as f: text = f.read() freqs = {} for word in text.split(): lword = word.lower() freqs[lword] = freqs.get(lword, 0) + 1 return fre...
python
{ "resource": "" }
q279651
print_wordfreq
test
def print_wordfreq(freqs, n=10): """Print the n most common words and counts in the freqs dict.""" words, counts = freqs.keys(), freqs.values() items = zip(counts, words) items.sort(reverse=True) for (count, word) in items[:n]: print(word, count)
python
{ "resource": "" }
q279652
WinHPCJob.tostring
test
def tostring(self): """Return the string representation of the job description XML.""" root = self.as_element() indent(root) txt = ET.tostring(root, encoding="utf-8") # Now remove the tokens used to order the attributes. txt = re.sub(r'_[A-Z]_','',txt) txt = '<?xm...
python
{ "resource": "" }
q279653
WinHPCJob.write
test
def write(self, filename): """Write the XML job description to a file.""" txt = self.tostring() with open(filename, 'w') as f: f.write(txt)
python
{ "resource": "" }
q279654
validate_pin
test
def validate_pin(pin): """ Validate the given pin against the schema. :param dict pin: The pin to validate: :raises pypebbleapi.schemas.DocumentError: If the pin is not valid. """ v = _Validator(schemas.pin) if v.validate(pin): return else: raise schemas.DocumentError(errors...
python
{ "resource": "" }
q279655
Timeline.send_shared_pin
test
def send_shared_pin(self, topics, pin, skip_validation=False): """ Send a shared pin for the given topics. :param list topics: The list of topics. :param dict pin: The pin. :param bool skip_validation: Whether to skip the validation. :raises pypebbleapi.schemas.DocumentE...
python
{ "resource": "" }
q279656
Timeline.delete_shared_pin
test
def delete_shared_pin(self, pin_id): """ Delete a shared pin. :param str pin_id: The id of the pin to delete. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ if not self.api_key: raise ValueError("You need to specify an api_key.") ...
python
{ "resource": "" }
q279657
Timeline.send_user_pin
test
def send_user_pin(self, user_token, pin, skip_validation=False): """ Send a user pin. :param str user_token: The token of the user. :param dict pin: The pin. :param bool skip_validation: Whether to skip the validation. :raises pypebbleapi.schemas.DocumentError: If the va...
python
{ "resource": "" }
q279658
Timeline.delete_user_pin
test
def delete_user_pin(self, user_token, pin_id): """ Delete a user pin. :param str user_token: The token of the user. :param str pin_id: The id of the pin to delete. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('DELET...
python
{ "resource": "" }
q279659
Timeline.subscribe
test
def subscribe(self, user_token, topic): """ Subscribe a user to the given topic. :param str user_token: The token of the user. :param str topic: The topic. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('POST', ...
python
{ "resource": "" }
q279660
Timeline.list_subscriptions
test
def list_subscriptions(self, user_token): """ Get the list of the topics which a user is subscribed to. :param str user_token: The token of the user. :return: The list of the topics. :rtype: list :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. ...
python
{ "resource": "" }
q279661
monitored
test
def monitored(total: int, name=None, message=None): """ Decorate a function to automatically begin and end a task on the progressmonitor. The function must have a parameter called 'monitor' """ def decorator(f): nonlocal name monitor_index = list(inspect.signature(f).parameters.keys(...
python
{ "resource": "" }
q279662
ProgressMonitor.begin
test
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)
python
{ "resource": "" }
q279663
ProgressMonitor.task
test
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()
python
{ "resource": "" }
q279664
ProgressMonitor.subtask
test
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) ...
python
{ "resource": "" }
q279665
ProgressMonitor.update
test
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...
python
{ "resource": "" }
q279666
ProgressMonitor.submonitor
test
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)...
python
{ "resource": "" }
q279667
ProgressMonitor.done
test
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...
python
{ "resource": "" }
q279668
page
test
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...
python
{ "resource": "" }
q279669
InstallRequirement.correct_build_location
test
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...
python
{ "resource": "" }
q279670
load_pyconfig_files
test
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 ...
python
{ "resource": "" }
q279671
PyFileConfigLoader.load_config
test
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...
python
{ "resource": "" }
q279672
PyFileConfigLoader._read_file_as_dict
test
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. ...
python
{ "resource": "" }
q279673
CommandLineConfigLoader._load_flag
test
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]....
python
{ "resource": "" }
q279674
KeyValueConfigLoader._decode_argv
test
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...
python
{ "resource": "" }
q279675
KeyValueConfigLoader.load_config
test
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...
python
{ "resource": "" }
q279676
ArgParseConfigLoader.load_config
test
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...
python
{ "resource": "" }
q279677
ArgParseConfigLoader._parse_args
test
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)
python
{ "resource": "" }
q279678
KVArgParseConfigLoader._convert_to_config
test
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._...
python
{ "resource": "" }
q279679
find_module
test
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...
python
{ "resource": "" }
q279680
BaseLauncher.on_stop
test
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)
python
{ "resource": "" }
q279681
BaseLauncher.notify_start
test
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 ...
python
{ "resource": "" }
q279682
BaseLauncher.notify_stop
test
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...
python
{ "resource": "" }
q279683
LocalProcessLauncher.interrupt_then_kill
test
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...
python
{ "resource": "" }
q279684
MPILauncher.find_args
test
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
python
{ "resource": "" }
q279685
MPILauncher.start
test
def start(self, n): """Start n instances of the program using mpiexec.""" self.n = n return super(MPILauncher, self).start()
python
{ "resource": "" }
q279686
SSHLauncher._send_file
test
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 ...
python
{ "resource": "" }
q279687
SSHLauncher._fetch_file
test
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...
python
{ "resource": "" }
q279688
SSHEngineSetLauncher.engine_count
test
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
python
{ "resource": "" }
q279689
SSHEngineSetLauncher.start
test
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: ...
python
{ "resource": "" }
q279690
WindowsHPCLauncher.start
test
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...
python
{ "resource": "" }
q279691
BatchSystemLauncher._context_default
test
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'')
python
{ "resource": "" }
q279692
BatchSystemLauncher.parse_job_id
test
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...
python
{ "resource": "" }
q279693
BatchSystemLauncher.write_batch_script
test
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...
python
{ "resource": "" }
q279694
BatchSystemLauncher.start
test
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...
python
{ "resource": "" }
q279695
RichIPythonWidget._context_menu_make
test
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...
python
{ "resource": "" }
q279696
RichIPythonWidget._append_jpg
test
def _append_jpg(self, jpg, before_prompt=False): """ Append raw JPG data to the widget.""" self._append_custom(self._insert_jpg, jpg, before_prompt)
python
{ "resource": "" }
q279697
RichIPythonWidget._append_png
test
def _append_png(self, png, before_prompt=False): """ Append raw PNG data to the widget. """ self._append_custom(self._insert_png, png, before_prompt)
python
{ "resource": "" }
q279698
RichIPythonWidget._append_svg
test
def _append_svg(self, svg, before_prompt=False): """ Append raw SVG data to the widget. """ self._append_custom(self._insert_svg, svg, before_prompt)
python
{ "resource": "" }
q279699
RichIPythonWidget._add_image
test
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, ...
python
{ "resource": "" }