_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q279400
InteractiveShell.init_user_ns
test
def init_user_ns(self): """Initialize all user-visible namespaces to their minimum defaults. Certain history lists are also initialized here, as they effectively act as user namespaces. Notes ----- All data structures here are only filled in, they are NOT reset by this ...
python
{ "resource": "" }
q279401
InteractiveShell.all_ns_refs
test
def all_ns_refs(self): """Get a list of references to all the namespace dictionaries in which IPython might store a user-created object. Note that this does not include the displayhook, which also caches objects from the output.""" return [self.user_ns, self.user_global_...
python
{ "resource": "" }
q279402
InteractiveShell.reset
test
def reset(self, new_session=True): """Clear all internal namespaces, and attempt to release references to user objects. If new_session is True, a new history session will be opened. """ # Clear histories self.history_manager.reset(new_session) # Reset counter use...
python
{ "resource": "" }
q279403
InteractiveShell.del_var
test
def del_var(self, varname, by_name=False): """Delete a variable from the various namespaces, so that, as far as possible, we're not keeping any hidden references to it. Parameters ---------- varname : str The name of the variable to delete. by_name : bool ...
python
{ "resource": "" }
q279404
InteractiveShell.reset_selective
test
def reset_selective(self, regex=None): """Clear selective variables from internal namespaces based on a specified regular expression. Parameters ---------- regex : string or compiled pattern, optional A regular expression pattern that will be used in searching ...
python
{ "resource": "" }
q279405
InteractiveShell.push
test
def push(self, variables, interactive=True): """Inject a group of variables into the IPython user namespace. Parameters ---------- variables : dict, str or list/tuple of str The variables to inject into the user's namespace. If a dict, a simple update is done. ...
python
{ "resource": "" }
q279406
InteractiveShell._ofind
test
def _ofind(self, oname, namespaces=None): """Find an object in the available namespaces. self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic Has special code to detect magic functions. """ oname = oname.strip() #print '1- oname: <%r>' % oname # dbg i...
python
{ "resource": "" }
q279407
InteractiveShell._ofind_property
test
def _ofind_property(self, oname, info): """Second part of object finding, to look for property details.""" if info.found: # Get the docstring of the class property if it exists. path = oname.split('.') root = '.'.join(path[:-1]) if info.parent is not None:...
python
{ "resource": "" }
q279408
InteractiveShell._object_find
test
def _object_find(self, oname, namespaces=None): """Find an object and return a struct with info about it.""" inf = Struct(self._ofind(oname, namespaces)) return Struct(self._ofind_property(oname, inf))
python
{ "resource": "" }
q279409
InteractiveShell._inspect
test
def _inspect(self, meth, oname, namespaces=None, **kw): """Generic interface to the inspector system. This function is meant to be called by pdef, pdoc & friends.""" info = self._object_find(oname, namespaces) if info.found: pmethod = getattr(self.inspector, meth) ...
python
{ "resource": "" }
q279410
InteractiveShell.init_history
test
def init_history(self): """Sets up the command history, and starts regular autosaves.""" self.history_manager = HistoryManager(shell=self, config=self.config) self.configurables.append(self.history_manager)
python
{ "resource": "" }
q279411
InteractiveShell.excepthook
test
def excepthook(self, etype, value, tb): """One more defense for GUI apps that call sys.excepthook. GUI frameworks like wxPython trap exceptions and call sys.excepthook themselves. I guess this is a feature that enables them to keep running after exceptions that would otherwise kill their...
python
{ "resource": "" }
q279412
InteractiveShell.showtraceback
test
def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, exception_only=False): """Display the exception that just occurred. If nothing is known about the exception, this is the method which should be used throughout the code for presenting user tracebacks, ...
python
{ "resource": "" }
q279413
InteractiveShell._showtraceback
test
def _showtraceback(self, etype, evalue, stb): """Actually show a traceback. Subclasses may override this method to put the traceback on a different place, like a side channel. """ print >> io.stdout, self.InteractiveTB.stb2text(stb)
python
{ "resource": "" }
q279414
InteractiveShell.showsyntaxerror
test
def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. If a filename is given, it is stuffed in the exception instead of what was there before (because Python's parser always uses "<s...
python
{ "resource": "" }
q279415
InteractiveShell.pre_readline
test
def pre_readline(self): """readline hook to be used at the start of each line. Currently it handles auto-indent only.""" if self.rl_do_indent: self.readline.insert_text(self._indent_current_str()) if self.rl_next_input is not None: self.readline.insert_text(self...
python
{ "resource": "" }
q279416
InteractiveShell.complete
test
def complete(self, text, line=None, cursor_pos=None): """Return the completed text and a list of completions. Parameters ---------- text : string A string of text to be completed on. It can be given as empty and instead a line/position pair are given. In ...
python
{ "resource": "" }
q279417
InteractiveShell.set_custom_completer
test
def set_custom_completer(self, completer, pos=0): """Adds a new custom completer function. The position argument (defaults to 0) is the index in the completers list where you want the completer to be inserted.""" newcomp = types.MethodType(completer,self.Completer) self.Complet...
python
{ "resource": "" }
q279418
InteractiveShell.set_completer_frame
test
def set_completer_frame(self, frame=None): """Set the frame of the completer.""" if frame: self.Completer.namespace = frame.f_locals self.Completer.global_namespace = frame.f_globals else: self.Completer.namespace = self.user_ns self.Completer.glob...
python
{ "resource": "" }
q279419
InteractiveShell.run_line_magic
test
def run_line_magic(self, magic_name, line): """Execute the given line magic. Parameters ---------- magic_name : str Name of the desired magic function, without '%' prefix. line : str The rest of the input line as a single string. """ fn = sel...
python
{ "resource": "" }
q279420
InteractiveShell.find_magic
test
def find_magic(self, magic_name, magic_kind='line'): """Find and return a magic of the given type by name. Returns None if the magic isn't found.""" return self.magics_manager.magics[magic_kind].get(magic_name)
python
{ "resource": "" }
q279421
InteractiveShell.define_macro
test
def define_macro(self, name, themacro): """Define a new macro Parameters ---------- name : str The name of the macro. themacro : str or Macro The action to do upon invoking the macro. If a string, a new Macro object is created by passing the ...
python
{ "resource": "" }
q279422
InteractiveShell.system_raw
test
def system_raw(self, cmd): """Call the given cmd in a subprocess using os.system Parameters ---------- cmd : str Command to execute. """ cmd = self.var_expand(cmd, depth=1) # protect os.system from UNC paths on Windows, which it can't handle: if...
python
{ "resource": "" }
q279423
InteractiveShell.auto_rewrite_input
test
def auto_rewrite_input(self, cmd): """Print to the screen the rewritten form of the user's command. This shows visual feedback by rewriting input lines that cause automatic calling to kick in, like:: /f x into:: ------> f(x) after the user's input prompt....
python
{ "resource": "" }
q279424
InteractiveShell.user_variables
test
def user_variables(self, names): """Get a list of variable names from the user's namespace. Parameters ---------- names : list of strings A list of names of variables to be read from the user namespace. Returns ------- A dict, keyed by the input names ...
python
{ "resource": "" }
q279425
InteractiveShell.user_expressions
test
def user_expressions(self, expressions): """Evaluate a dict of expressions in the user's namespace. Parameters ---------- expressions : dict A dict with string keys and string values. The expression values should be valid Python expressions, each of which will be ev...
python
{ "resource": "" }
q279426
InteractiveShell.ev
test
def ev(self, expr): """Evaluate python expression expr in user namespace. Returns the result of evaluation """ with self.builtin_trap: return eval(expr, self.user_global_ns, self.user_ns)
python
{ "resource": "" }
q279427
InteractiveShell.safe_execfile_ipy
test
def safe_execfile_ipy(self, fname): """Like safe_execfile, but for .ipy files with IPython syntax. Parameters ---------- fname : str The name of the file to execute. The filename must have a .ipy extension. """ fname = os.path.abspath(os.path.exp...
python
{ "resource": "" }
q279428
InteractiveShell._run_cached_cell_magic
test
def _run_cached_cell_magic(self, magic_name, line): """Special method to call a cell magic with the data stored in self. """ cell = self._current_cell_magic_body self._current_cell_magic_body = None return self.run_cell_magic(magic_name, line, cell)
python
{ "resource": "" }
q279429
InteractiveShell.run_cell
test
def run_cell(self, raw_cell, store_history=False, silent=False): """Run a complete IPython cell. Parameters ---------- raw_cell : str The code (including IPython code such as %magic functions) to run. store_history : bool If True, the raw and translated cell ...
python
{ "resource": "" }
q279430
InteractiveShell.run_ast_nodes
test
def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'): """Run a sequence of AST nodes. The execution mode depends on the interactivity parameter. Parameters ---------- nodelist : list A sequence of AST nodes to run. cell_name : str W...
python
{ "resource": "" }
q279431
InteractiveShell.enable_pylab
test
def enable_pylab(self, gui=None, import_all=True): """Activate pylab support at runtime. This turns on support for matplotlib, preloads into the interactive namespace all of numpy and pylab, and configures IPython to correctly interact with the GUI event loop. The GUI backend to be use...
python
{ "resource": "" }
q279432
InteractiveShell.var_expand
test
def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): """Expand python variables in a string. The depth argument indicates how many frames above the caller should be walked to look for the local namespace where to expand variables. The global namespace for expansion is alway...
python
{ "resource": "" }
q279433
InteractiveShell.mktempfile
test
def mktempfile(self, data=None, prefix='ipython_edit_'): """Make a new tempfile and return its filename. This makes a call to tempfile.mktemp, but it registers the created filename internally so ipython cleans it up at exit time. Optional inputs: - data(None): if data is giv...
python
{ "resource": "" }
q279434
InteractiveShell.extract_input_lines
test
def extract_input_lines(self, range_str, raw=False): """Return as a string a set of input history slices. Parameters ---------- range_str : string The set of slices is given as a string, like "~5/6-~4/2 4:8 9", since this function is for use by magic functions wh...
python
{ "resource": "" }
q279435
InteractiveShell.find_user_code
test
def find_user_code(self, target, raw=True, py_only=False): """Get a code string from history, file, url, or a string or macro. This is mainly used by magic functions. Parameters ---------- target : str A string specifying code to retrieve. This will be tried respect...
python
{ "resource": "" }
q279436
InteractiveShell.atexit_operations
test
def atexit_operations(self): """This will be executed at the time of exit. Cleanup operations and saving of persistent data that is done unconditionally by IPython should be performed here. For things that may depend on startup flags or platform specifics (such as having readli...
python
{ "resource": "" }
q279437
broadcast
test
def broadcast(client, sender, msg_name, dest_name=None, block=None): """broadcast a message from one engine to all others.""" dest_name = msg_name if dest_name is None else dest_name client[sender].execute('com.publish(%s)'%msg_name, block=None) targets = client.ids targets.remove(sender) return...
python
{ "resource": "" }
q279438
send
test
def send(client, sender, targets, msg_name, dest_name=None, block=None): """send a message from one to one-or-more engines.""" dest_name = msg_name if dest_name is None else dest_name def _send(targets, m_name): msg = globals()[m_name] return com.send(targets, msg) client[sender...
python
{ "resource": "" }
q279439
skipif
test
def skipif(skip_condition, msg=None): """ Make function raise SkipTest exception if a given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the test suite is ...
python
{ "resource": "" }
q279440
knownfailureif
test
def knownfailureif(fail_condition, msg=None): """ Make function raise KnownFailureTest exception if given condition is true. If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that may require costly imports, to delay the cost until the ...
python
{ "resource": "" }
q279441
deprecated
test
def deprecated(conditional=True): """ Filter deprecation warnings while running the test suite. This decorator can be used to filter DeprecationWarning's, to avoid printing them during the test suite run, while checking that the test actually raises a DeprecationWarning. Parameters -------...
python
{ "resource": "" }
q279442
list_profiles_in
test
def list_profiles_in(path): """list profiles in a given root directory""" files = os.listdir(path) profiles = [] for f in files: full_path = os.path.join(path, f) if os.path.isdir(full_path) and f.startswith('profile_'): profiles.append(f.split('_',1)[-1]) return profiles
python
{ "resource": "" }
q279443
list_bundled_profiles
test
def list_bundled_profiles(): """list profiles that are bundled with IPython.""" path = os.path.join(get_ipython_package_dir(), u'config', u'profile') files = os.listdir(path) profiles = [] for profile in files: full_path = os.path.join(path, profile) if os.path.isdir(full_path) and p...
python
{ "resource": "" }
q279444
WorkingSet.find
test
def find(self, req): """Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it do...
python
{ "resource": "" }
q279445
run
test
def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None, encoding='utf-8'): """ This function runs the given command; waits for it to finish; then returns all output as a string. STDERR is included in output. If the full path to the co...
python
{ "resource": "" }
q279446
which
test
def which (filename): """This takes a given filename; tries to find it in the environment path; then checks if it is executable. This returns the full path to the filename if found and executable. Otherwise this returns None.""" # Special case where filename already contains a path. if os.path.dir...
python
{ "resource": "" }
q279447
spawnb.next
test
def next (self): # File-like object. """This is to support iterators over a file-like object. """ result = self.readline() if result == self._empty_buffer: raise StopIteration return result
python
{ "resource": "" }
q279448
spawnb.send
test
def send(self, s): """This sends a string to the child process. This returns the number of bytes written. If a log file was set then the data is also written to the log. """ time.sleep(self.delaybeforesend) s2 = self._cast_buffer_type(s) if self.logfile is not ...
python
{ "resource": "" }
q279449
spawnb.sendintr
test
def sendintr(self): """This sends a SIGINT to the child. It does not require the SIGINT to be the first character on a line. """ if hasattr(termios, 'VINTR'): char = termios.tcgetattr(self.child_fd)[6][termios.VINTR] else: # platform does not define VINTR so ass...
python
{ "resource": "" }
q279450
spawnb._prepare_regex_pattern
test
def _prepare_regex_pattern(self, p): "Recompile unicode regexes as bytes regexes. Overridden in subclass." if isinstance(p.pattern, unicode): p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE) return p
python
{ "resource": "" }
q279451
spawnb.expect
test
def expect(self, pattern, timeout = -1, searchwindowsize=-1): """This seeks through the stream until a pattern is matched. The pattern is overloaded and may take several types. The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled...
python
{ "resource": "" }
q279452
spawnb.expect_loop
test
def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1): """This is the common loop used inside expect. The 'searcher' should be an instance of searcher_re or searcher_string, which describes how and what to search for in the input. See expect() for other arguments, return...
python
{ "resource": "" }
q279453
spawn._prepare_regex_pattern
test
def _prepare_regex_pattern(self, p): "Recompile bytes regexes as unicode regexes." if isinstance(p.pattern, bytes): p = re.compile(p.pattern.decode(self.encoding), p.flags) return p
python
{ "resource": "" }
q279454
searcher_string.search
test
def search(self, buffer, freshlen, searchwindowsize=None): """This searches 'buffer' for the first occurence of one of the search strings. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. It helps to avoid searching the same, poss...
python
{ "resource": "" }
q279455
searcher_re.search
test
def search(self, buffer, freshlen, searchwindowsize=None): """This searches 'buffer' for the first occurence of one of the regular expressions. 'freshlen' must indicate the number of bytes at the end of 'buffer' which have not been searched before. See class spawn for the 'searchwindow...
python
{ "resource": "" }
q279456
log_listener
test
def log_listener(log:logging.Logger=None, level=logging.INFO): """Progress Monitor listener that logs all updates to the given logger""" if log is None: log = logging.getLogger("ProgressMonitor") def listen(monitor): name = "{}: ".format(monitor.name) if monitor.name is not None else "" ...
python
{ "resource": "" }
q279457
unpack_directory
test
def unpack_directory(filename, extract_dir, progress_filter=default_filter): """"Unpack" a directory, using the same interface as for archives Raises ``UnrecognizedFormat`` if `filename` is not a directory """ if not os.path.isdir(filename): raise UnrecognizedFormat("%s is not a directory" % (f...
python
{ "resource": "" }
q279458
Context.emit
test
def emit(self, msg, level=1, debug=False): """ Emit a message to the user. :param msg: The message to emit. If ``debug`` is ``True``, the message will be emitted to ``stderr`` only if the ``debug`` attribute is ``True``. If ``debug`` ...
python
{ "resource": "" }
q279459
CommandSession.last_error
test
def last_error(self): """Get the output of the last command exevuted.""" if not len(self.log): raise RuntimeError('Nothing executed') try: errs = [l for l in self.log if l[1] != 0] return errs[-1][2] except IndexError: # odd case where th...
python
{ "resource": "" }
q279460
CommandSession.check_output
test
def check_output(self, cmd): """Wrapper for subprocess.check_output.""" ret, output = self._exec(cmd) if not ret == 0: raise CommandError(self) return output
python
{ "resource": "" }
q279461
Analysis.find_source
test
def find_source(self, filename): """Find the source for `filename`. Returns two values: the actual filename, and the source. The source returned depends on which of these cases holds: * The filename seems to be a non-source file: returns None * The filename is a sourc...
python
{ "resource": "" }
q279462
Analysis.arcs_executed
test
def arcs_executed(self): """Returns a sorted list of the arcs actually executed in the code.""" executed = self.coverage.data.executed_arcs(self.filename) m2fl = self.parser.first_line executed = [(m2fl(l1), m2fl(l2)) for (l1,l2) in executed] return sorted(executed)
python
{ "resource": "" }
q279463
Analysis.arcs_missing
test
def arcs_missing(self): """Returns a sorted list of the arcs in the code not executed.""" possible = self.arc_possibilities() executed = self.arcs_executed() missing = [ p for p in possible if p not in executed and p[0] not in self.no_branc...
python
{ "resource": "" }
q279464
Analysis.arcs_unpredicted
test
def arcs_unpredicted(self): """Returns a sorted list of the executed arcs missing from the code.""" possible = self.arc_possibilities() executed = self.arcs_executed() # Exclude arcs here which connect a line to itself. They can occur # in executed data in some cases. This is w...
python
{ "resource": "" }
q279465
Analysis.branch_lines
test
def branch_lines(self): """Returns a list of line numbers that have more than one exit.""" exit_counts = self.parser.exit_counts() return [l1 for l1,count in iitems(exit_counts) if count > 1]
python
{ "resource": "" }
q279466
Analysis.total_branches
test
def total_branches(self): """How many total branches are there?""" exit_counts = self.parser.exit_counts() return sum([count for count in exit_counts.values() if count > 1])
python
{ "resource": "" }
q279467
Analysis.missing_branch_arcs
test
def missing_branch_arcs(self): """Return arcs that weren't executed from branch lines. Returns {l1:[l2a,l2b,...], ...} """ missing = self.arcs_missing() branch_lines = set(self.branch_lines()) mba = {} for l1, l2 in missing: if l1 in branch_lines: ...
python
{ "resource": "" }
q279468
Analysis.branch_stats
test
def branch_stats(self): """Get stats about branches. Returns a dict mapping line numbers to a tuple: (total_exits, taken_exits). """ exit_counts = self.parser.exit_counts() missing_arcs = self.missing_branch_arcs() stats = {} for lnum in self.branch_line...
python
{ "resource": "" }
q279469
Numbers.set_precision
test
def set_precision(cls, precision): """Set the number of decimal places used to report percentages.""" assert 0 <= precision < 10 cls._precision = precision cls._near0 = 1.0 / 10**precision cls._near100 = 100.0 - cls._near0
python
{ "resource": "" }
q279470
Numbers._get_pc_covered
test
def _get_pc_covered(self): """Returns a single percentage value for coverage.""" if self.n_statements > 0: pc_cov = (100.0 * (self.n_executed + self.n_executed_branches) / (self.n_statements + self.n_branches)) else: pc_cov = 100.0 return p...
python
{ "resource": "" }
q279471
Numbers._get_pc_covered_str
test
def _get_pc_covered_str(self): """Returns the percent covered, as a string, without a percent sign. Note that "0" is only returned when the value is truly zero, and "100" is only returned when the value is truly 100. Rounding can never result in either "0" or "100". """ ...
python
{ "resource": "" }
q279472
highlight_text
test
def highlight_text(needles, haystack, cls_name='highlighted', words=False, case=False): """ Applies cls_name to all needles found in haystack. """ if not needles: return haystack if not haystack: return '' if words: pattern = r"(%s)" % "|".join(['\\b{}\\b'.format(re.escape(n)) ...
python
{ "resource": "" }
q279473
highlight
test
def highlight(string, keywords, cls_name='highlighted'): """ Given an list of words, this function highlights the matched text in the given string. """ if not keywords: return string if not string: return '' include, exclude = get_text_tokenizer(keywords) highlighted = highlight_tex...
python
{ "resource": "" }
q279474
highlight_words
test
def highlight_words(string, keywords, cls_name='highlighted'): """ Given an list of words, this function highlights the matched words in the given string. """ if not keywords: return string if not string: return '' include, exclude = get_text_tokenizer(keywords) highlighted = highli...
python
{ "resource": "" }
q279475
AbstractSandbox.run
test
def run(self, func): """Run 'func' under os sandboxing""" try: self._copy(self) if _file: __builtin__.file = self._file __builtin__.open = self._open self._active = True return func() finally: self._active = ...
python
{ "resource": "" }
q279476
unquote_ends
test
def unquote_ends(istr): """Remove a single pair of quotes from the endpoints of a string.""" if not istr: return istr if (istr[0]=="'" and istr[-1]=="'") or \ (istr[0]=='"' and istr[-1]=='"'): return istr[1:-1] else: return istr
python
{ "resource": "" }
q279477
indent
test
def indent(instr,nspaces=4, ntabs=0, flatten=False): """Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number...
python
{ "resource": "" }
q279478
marquee
test
def marquee(txt='',width=78,mark='*'): """Return the input string centered in a 'marquee'. :Examples: In [16]: marquee('A test',40) Out[16]: '**************** A test ****************' In [17]: marquee('A test',40,'-') Out[17]: '---------------- A test ----------------' ...
python
{ "resource": "" }
q279479
format_screen
test
def format_screen(strng): """Format a string for screen printing. This removes some latex-type format codes.""" # Paragraph continue par_re = re.compile(r'\\$',re.MULTILINE) strng = par_re.sub('',strng) return strng
python
{ "resource": "" }
q279480
dedent
test
def dedent(text): """Equivalent of textwrap.dedent that ignores unindented first line. This means it will still dedent strings like: '''foo is a bar ''' For use in wrap_paragraphs. """ if text.startswith('\n'): # text starts with blank line, don't ignore the first line ...
python
{ "resource": "" }
q279481
wrap_paragraphs
test
def wrap_paragraphs(text, ncols=80): """Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns. """ para...
python
{ "resource": "" }
q279482
_find_optimal
test
def _find_optimal(rlist , separator_size=2 , displaywidth=80): """Calculate optimal info to columnize a list of string""" for nrow in range(1, len(rlist)+1) : chk = map(max,_chunks(rlist, nrow)) sumlength = sum(chk) ncols = len(chk) if sumlength+separator_size*(ncols-1) <= displa...
python
{ "resource": "" }
q279483
_get_or_default
test
def _get_or_default(mylist, i, default=None): """return list item number, or default if don't exist""" if i >= len(mylist): return default else : return mylist[i]
python
{ "resource": "" }
q279484
compute_item_matrix
test
def compute_item_matrix(items, empty=None, *args, **kwargs) : """Returns a nested list, and info to columnize items Parameters : ------------ items : list of strings to columize empty : (default None) default value to fill list if needed separator_size : int (default=2) ...
python
{ "resource": "" }
q279485
SList.fields
test
def fields(self, *fields): """ Collect whitespace-separated fields from string list Allows quick awk-like usage of string lists. Example data (in var a, created by 'a = !ls -l'):: -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog drwxrwxrwx+ 6 ville None 0 O...
python
{ "resource": "" }
q279486
IPythonConsoleApp.build_kernel_argv
test
def build_kernel_argv(self, argv=None): """build argv to be passed to kernel subprocess""" if argv is None: argv = sys.argv[1:] self.kernel_argv = swallow_argv(argv, self.frontend_aliases, self.frontend_flags) # kernel should inherit default config file from frontend ...
python
{ "resource": "" }
q279487
IPythonConsoleApp.init_ssh
test
def init_ssh(self): """set up ssh tunnels, if needed.""" if not self.sshserver and not self.sshkey: return if self.sshkey and not self.sshserver: # specifying just the key implies that we are connecting directly self.sshserver = self.ip se...
python
{ "resource": "" }
q279488
pretty
test
def pretty(obj, verbose=False, max_width=79, newline='\n'): """ Pretty print the object's representation. """ stream = StringIO() printer = RepresentationPrinter(stream, verbose, max_width, newline) printer.pretty(obj) printer.flush() return stream.getvalue()
python
{ "resource": "" }
q279489
pprint
test
def pprint(obj, verbose=False, max_width=79, newline='\n'): """ Like `pretty` but print to stdout. """ printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline) printer.pretty(obj) printer.flush() sys.stdout.write(newline) sys.stdout.flush()
python
{ "resource": "" }
q279490
_get_mro
test
def _get_mro(obj_class): """ Get a reasonable method resolution order of a class and its superclasses for both old-style and new-style classes. """ if not hasattr(obj_class, '__mro__'): # Old-style class. Mix in object to make a fake new-style class. try: obj_class = type(obj...
python
{ "resource": "" }
q279491
_default_pprint
test
def _default_pprint(obj, p, cycle): """ The default print function. Used if an object does not provide one and it's none of the builtin objects. """ klass = getattr(obj, '__class__', None) or type(obj) if getattr(klass, '__repr__', None) not in _baseclass_reprs: # A user-provided repr. ...
python
{ "resource": "" }
q279492
_seq_pprinter_factory
test
def _seq_pprinter_factory(start, end, basetype): """ Factory that returns a pprint function useful for sequences. Used by the default pprint for tuples, dicts, lists, sets and frozensets. """ def inner(obj, p, cycle): typ = type(obj) if basetype is not None and typ is not basetype a...
python
{ "resource": "" }
q279493
_dict_pprinter_factory
test
def _dict_pprinter_factory(start, end, basetype=None): """ Factory that returns a pprint function used by the default pprint of dicts and dict proxies. """ def inner(obj, p, cycle): typ = type(obj) if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:...
python
{ "resource": "" }
q279494
_super_pprint
test
def _super_pprint(obj, p, cycle): """The pprint for the super type.""" p.begin_group(8, '<super: ') p.pretty(obj.__self_class__) p.text(',') p.breakable() p.pretty(obj.__self__) p.end_group(8, '>')
python
{ "resource": "" }
q279495
_re_pattern_pprint
test
def _re_pattern_pprint(obj, p, cycle): """The pprint function for regular expression patterns.""" p.text('re.compile(') pattern = repr(obj.pattern) if pattern[:1] in 'uU': pattern = pattern[1:] prefix = 'ur' else: prefix = 'r' pattern = prefix + pattern.replace('\\\\', '\...
python
{ "resource": "" }
q279496
_type_pprint
test
def _type_pprint(obj, p, cycle): """The pprint for classes and types.""" if obj.__module__ in ('__builtin__', 'exceptions'): name = obj.__name__ else: name = obj.__module__ + '.' + obj.__name__ p.text(name)
python
{ "resource": "" }
q279497
_function_pprint
test
def _function_pprint(obj, p, cycle): """Base pprint for all functions and builtin functions.""" if obj.__module__ in ('__builtin__', 'exceptions') or not obj.__module__: name = obj.__name__ else: name = obj.__module__ + '.' + obj.__name__ p.text('<function %s>' % name)
python
{ "resource": "" }
q279498
_exception_pprint
test
def _exception_pprint(obj, p, cycle): """Base pprint for all exceptions.""" if obj.__class__.__module__ in ('exceptions', 'builtins'): name = obj.__class__.__name__ else: name = '%s.%s' % ( obj.__class__.__module__, obj.__class__.__name__ ) step = len(name...
python
{ "resource": "" }
q279499
for_type
test
def for_type(typ, func): """ Add a pretty printer for a given type. """ oldfunc = _type_pprinters.get(typ, None) if func is not None: # To support easy restoration of old pprinters, we need to ignore Nones. _type_pprinters[typ] = func return oldfunc
python
{ "resource": "" }