_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q279500
for_type_by_name
test
def for_type_by_name(type_module, type_name, func): """ Add a pretty printer for a type specified by the module and name of a type rather than the type object itself. """ key = (type_module, type_name) oldfunc = _deferred_type_pprinters.get(key, None) if func is not None:
python
{ "resource": "" }
q279501
PrettyPrinter.text
test
def text(self, obj): """Add literal text to the output.""" width = len(obj) if self.buffer: text = self.buffer[-1] if not isinstance(text, Text):
python
{ "resource": "" }
q279502
PrettyPrinter.breakable
test
def breakable(self, sep=' '): """ Add a breakable separator to the output. This does not mean that it will automatically break here. If no breaking on this position takes place the `sep` is inserted which default to one space. """ width = len(sep) group = self.group_stack[-1] if group.want_break: self.flush() self.output.write(self.newline) self.output.write(' ' * self.indentation)
python
{ "resource": "" }
q279503
PrettyPrinter.end_group
test
def end_group(self, dedent=0, close=''): """End a group. See `begin_group` for more details.""" self.indentation -= dedent group = self.group_stack.pop()
python
{ "resource": "" }
q279504
PrettyPrinter.flush
test
def flush(self): """Flush data that is left in the buffer.""" for data in self.buffer:
python
{ "resource": "" }
q279505
RepresentationPrinter.pretty
test
def pretty(self, obj): """Pretty print the given object.""" obj_id = id(obj) cycle = obj_id in self.stack self.stack.append(obj_id) self.begin_group() try: obj_class = getattr(obj, '__class__', None) or type(obj) # First try to find registered singleton printers for the type. try: printer = self.singleton_pprinters[obj_id] except (TypeError, KeyError): pass else: return printer(obj, self, cycle) # Next walk the mro and check for either: # 1) a registered printer # 2) a _repr_pretty_ method for cls in _get_mro(obj_class):
python
{ "resource": "" }
q279506
exception_colors
test
def exception_colors(): """Return a color table with fields for exception reporting. The table is an instance of ColorSchemeTable with schemes added for 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled in. Examples: >>> ec = exception_colors() >>> ec.active_scheme_name '' >>> print ec.active_colors None Now we activate a color scheme: >>> ec.set_active_scheme('NoColor') >>> ec.active_scheme_name 'NoColor' >>> sorted(ec.active_colors.keys()) ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line', 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName', 'val', 'valEm'] """ ex_colors = ColorSchemeTable() # Populate it with color schemes C = TermColors # shorthand and local lookup ex_colors.add_scheme(ColorScheme( 'NoColor', # The color to be used for the top line topline = C.NoColor, # The colors to be used in the traceback filename = C.NoColor, lineno = C.NoColor, name = C.NoColor, vName = C.NoColor, val = C.NoColor, em = C.NoColor, # Emphasized colors for the last frame of the traceback normalEm = C.NoColor, filenameEm = C.NoColor, linenoEm = C.NoColor, nameEm = C.NoColor, valEm = C.NoColor, # Colors for printing the exception excName = C.NoColor, line = C.NoColor, caret = C.NoColor, Normal = C.NoColor )) # make some schemes as instances so we can copy them for modification easily ex_colors.add_scheme(ColorScheme( 'Linux', # The color to be used for the top line topline = C.LightRed, # The colors to be used in the traceback filename = C.Green, lineno = C.Green, name = C.Purple, vName = C.Cyan, val = C.Green, em = C.LightCyan, # Emphasized colors for the last frame of the traceback normalEm = C.LightCyan, filenameEm = C.LightGreen,
python
{ "resource": "" }
q279507
_write_row_into_ods
test
def _write_row_into_ods(ods, sheet_no, row_no, row): """ Write row with translations to ods file into specified sheet and row_no. """ ods.content.getSheet(sheet_no) for j, col in enumerate(row): cell = ods.content.getCell(j, row_no+1) cell.stringValue(_escape_apostrophe(col)) if j %
python
{ "resource": "" }
q279508
win32_clipboard_get
test
def win32_clipboard_get(): """ Get the current clipboard's text on Windows. Requires Mark Hammond's pywin32 extensions. """ try: import win32clipboard except ImportError: raise TryNext("Getting text from the clipboard requires the pywin32 " "extensions: http://sourceforge.net/projects/pywin32/")
python
{ "resource": "" }
q279509
osx_clipboard_get
test
def osx_clipboard_get(): """ Get the clipboard's text on OS X. """ p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'], stdout=subprocess.PIPE) text, stderr = p.communicate()
python
{ "resource": "" }
q279510
tkinter_clipboard_get
test
def tkinter_clipboard_get(): """ Get the clipboard's text using Tkinter. This is the default on systems that are not Windows or OS X. It may interfere with other UI toolkits and should be replaced with an implementation that uses that toolkit. """ try: import Tkinter except ImportError:
python
{ "resource": "" }
q279511
_get_build_prefix
test
def _get_build_prefix(): """ Returns a safe build_prefix """ path = os.path.join( tempfile.gettempdir(), 'pip_build_%s' % __get_username().replace(' ', '_') ) if WINDOWS: """ on windows(tested on 7) temp dirs are isolated """ return path try: os.mkdir(path) write_delete_marker_file(path) except OSError: file_uid = None try: # raises OSError for symlinks # https://github.com/pypa/pip/pull/935#discussion_r5307003 file_uid = get_path_uid(path) except OSError: file_uid = None if file_uid != os.geteuid():
python
{ "resource": "" }
q279512
rekey
test
def rekey(dikt): """Rekey a dict that has been forced to use str keys where there should be ints by json.""" for k in dikt.iterkeys(): if isinstance(k, basestring): ik=fk=None try: ik = int(k) except ValueError: try: fk = float(k) except ValueError:
python
{ "resource": "" }
q279513
extract_dates
test
def extract_dates(obj): """extract ISO8601 dates from unpacked JSON""" if isinstance(obj, dict): obj = dict(obj) # don't clobber for k,v in obj.iteritems(): obj[k] = extract_dates(v) elif isinstance(obj, (list, tuple)): obj = [ extract_dates(o) for
python
{ "resource": "" }
q279514
squash_dates
test
def squash_dates(obj): """squash datetime objects into ISO8601 strings""" if isinstance(obj, dict): obj = dict(obj) # don't clobber for k,v in obj.iteritems(): obj[k] = squash_dates(v) elif isinstance(obj, (list, tuple)): obj =
python
{ "resource": "" }
q279515
date_default
test
def date_default(obj): """default function for packing datetime objects in JSON.""" if isinstance(obj, datetime):
python
{ "resource": "" }
q279516
json_clean
test
def json_clean(obj): """Clean an object to ensure it's safe to encode in JSON. Atomic, immutable objects are returned unmodified. Sets and tuples are converted to lists, lists are copied and dicts are also copied. Note: dicts whose keys could cause collisions upon encoding (such as a dict with both the number 1 and the string '1' as keys) will cause a ValueError to be raised. Parameters ---------- obj : any python object Returns ------- out : object A version of the input which will not cause an encoding error when encoded as JSON. Note that this function does not *encode* its inputs, it simply sanitizes it so that there will be no encoding errors later. Examples -------- >>> json_clean(4) 4 >>> json_clean(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> sorted(json_clean(dict(x=1, y=2)).items()) [('x', 1), ('y', 2)] >>> sorted(json_clean(dict(x=1, y=2, z=[1,2,3])).items()) [('x', 1), ('y', 2), ('z', [1, 2, 3])] >>> json_clean(True) True """ # types that are 'atomic' and ok in json as-is. bool doesn't need to be # listed explicitly because bools pass as int instances atomic_ok = (unicode, int, types.NoneType) # containers that we need to convert into lists container_to_list = (tuple, set, types.GeneratorType) if isinstance(obj, float): # cast out-of-range floats to their reprs if math.isnan(obj) or math.isinf(obj): return repr(obj) return obj if isinstance(obj, atomic_ok): return obj if isinstance(obj, bytes):
python
{ "resource": "" }
q279517
easy_install.check_site_dir
test
def check_site_dir(self): """Verify that self.install_dir is .pth-capable dir, if needed""" instdir = normalize_path(self.install_dir) pth_file = os.path.join(instdir, 'easy-install.pth') # Is it a configured, PYTHONPATH, implicit, or explicit site dir? is_site_dir = instdir in self.all_site_dirs if not is_site_dir and not self.multi_version: # No? Then directly test whether it does .pth file processing is_site_dir = self.check_pth_processing() else: # make sure we can write to target dir testfile = self.pseudo_tempname() + '.write-test' test_exists = os.path.exists(testfile) try: if test_exists: os.unlink(testfile) open(testfile, 'w').close() os.unlink(testfile) except (OSError, IOError): self.cant_write_to_target() if not is_site_dir and not self.multi_version: # Can't install non-multi to non-site dir raise DistutilsError(self.no_default_version_msg())
python
{ "resource": "" }
q279518
install_scripts.write_script
test
def write_script(self, script_name, contents, mode="t", *ignored): """Write an executable file to the scripts directory""" from setuptools.command.easy_install import chmod, current_umask log.info("Installing %s script to %s", script_name, self.install_dir) target = os.path.join(self.install_dir, script_name) self.outfiles.append(target) mask =
python
{ "resource": "" }
q279519
sleep_here
test
def sleep_here(count, t): """simple function that takes args, prints a short message, sleeps for a time, and returns the same args""" import time,sys print("hi from
python
{ "resource": "" }
q279520
BaseCommand.create_parser
test
def create_parser(self, prog_name, subcommand): """ Create and return the ``ArgumentParser`` which will be used to parse the arguments to this command. """ parser = ArgumentParser(
python
{ "resource": "" }
q279521
Extension._convert_pyx_sources_to_c
test
def _convert_pyx_sources_to_c(self): "convert .pyx extensions to .c" def pyx_to_c(source):
python
{ "resource": "" }
q279522
main
test
def main(connection_file): """watch iopub channel, and print messages""" ctx = zmq.Context.instance() with open(connection_file) as f: cfg = json.loads(f.read()) location = cfg['location'] reg_url = cfg['url'] session = Session(key=str_to_bytes(cfg['exec_key'])) query = ctx.socket(zmq.DEALER) query.connect(disambiguate_url(cfg['url'], location)) session.send(query, "connection_request") idents,msg = session.recv(query, mode=0) c = msg['content'] iopub_url = disambiguate_url(c['iopub'], location) sub = ctx.socket(zmq.SUB) # This will subscribe to all messages: sub.setsockopt(zmq.SUBSCRIBE, b'') # replace with b'' with b'engine.1.stdout' to subscribe only to engine 1's stdout # 0MQ
python
{ "resource": "" }
q279523
InstallCommand._build_package_finder
test
def _build_package_finder(self, options, index_urls, session): """ Create a package finder appropriate to this install command. This method is meant to be overridden by subclasses, not called directly. """ return PackageFinder( find_links=options.find_links,
python
{ "resource": "" }
q279524
Application._log_level_changed
test
def _log_level_changed(self, name, old, new): """Adjust the log level when log_level is set.""" if isinstance(new, basestring):
python
{ "resource": "" }
q279525
Application._log_default
test
def _log_default(self): """Start logging for this application. The default is to log to stdout using a StreaHandler. The log level starts at loggin.WARN, but this can be adjusted by setting the ``log_level`` attribute. """ log = logging.getLogger(self.__class__.__name__) log.setLevel(self.log_level)
python
{ "resource": "" }
q279526
Application._flags_changed
test
def _flags_changed(self, name, old, new): """ensure flags dict is valid""" for key,value in new.iteritems(): assert len(value) == 2, "Bad flag: %r:%s"%(key,value) assert
python
{ "resource": "" }
q279527
Application.print_alias_help
test
def print_alias_help(self): """Print the alias part of the help.""" if not self.aliases: return lines = [] classdict = {} for cls in self.classes: # include all parents (up to, but excluding Configurable) in available names for c in cls.mro()[:-3]: classdict[c.__name__] = c for alias, longname in self.aliases.iteritems(): classname, traitname = longname.split('.',1) cls = classdict[classname] trait = cls.class_traits(config=True)[traitname] help = cls.class_get_trait_help(trait).splitlines()
python
{ "resource": "" }
q279528
Application.print_flag_help
test
def print_flag_help(self): """Print the flag part of the help.""" if not self.flags: return lines = [] for m, (cfg,help) in self.flags.iteritems(): prefix = '--' if len(m) > 1 else '-' lines.append(prefix+m)
python
{ "resource": "" }
q279529
Application.print_subcommands
test
def print_subcommands(self): """Print the subcommand part of the help.""" if not self.subcommands: return lines = ["Subcommands"] lines.append('-'*len(lines[0])) lines.append('') for p in wrap_paragraphs(self.subcommand_description): lines.append(p) lines.append('')
python
{ "resource": "" }
q279530
Application.print_help
test
def print_help(self, classes=False): """Print the help for each Configurable class in self.classes. If classes=False (the default), only flags and aliases are printed. """ self.print_subcommands() self.print_options() if classes: if self.classes: print "Class parameters" print "----------------" print for p in
python
{ "resource": "" }
q279531
Application.print_examples
test
def print_examples(self): """Print usage and examples. This usage string goes at the end of the command line help string and should contain examples of the application's usage. """ if self.examples:
python
{ "resource": "" }
q279532
Application.update_config
test
def update_config(self, config): """Fire the traits events when the config is updated.""" # Save a copy of the current config. newconfig = deepcopy(self.config)
python
{ "resource": "" }
q279533
Application.initialize_subcommand
test
def initialize_subcommand(self, subc, argv=None): """Initialize a subcommand with argv.""" subapp,help = self.subcommands.get(subc) if isinstance(subapp, basestring): subapp = import_item(subapp) # clear existing instances
python
{ "resource": "" }
q279534
Application.flatten_flags
test
def flatten_flags(self): """flatten flags and aliases, so cl-args override as expected. This prevents issues such as an alias pointing to InteractiveShell, but a config file setting the same trait in TerminalInteraciveShell getting inappropriate priority over the command-line arg. Only aliases with exactly one descendent in the class list will be promoted. """ # build a tree of classes in our list that inherit from a particular # it will be a dict by parent classname of classes in our list # that are descendents mro_tree = defaultdict(list) for cls in self.classes: clsname = cls.__name__ for parent in cls.mro()[1:-3]: # exclude cls itself and Configurable,HasTraits,object mro_tree[parent.__name__].append(clsname) # flatten aliases, which have the form: # { 'alias' : 'Class.trait' } aliases = {} for alias, cls_trait in self.aliases.iteritems(): cls,trait = cls_trait.split('.',1) children = mro_tree[cls] if len(children) == 1:
python
{ "resource": "" }
q279535
Application.parse_command_line
test
def parse_command_line(self, argv=None): """Parse the command line arguments.""" argv = sys.argv[1:] if argv is None else argv if argv and argv[0] == 'help': # turn `ipython help notebook` into `ipython notebook -h` argv = argv[1:] + ['-h'] if self.subcommands and len(argv) > 0: # we have subcommands, and one may have been specified subc, subargv = argv[0], argv[1:] if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands: # it's a subcommand, and *not* a flag or class parameter
python
{ "resource": "" }
q279536
Application.load_config_file
test
def load_config_file(self, filename, path=None): """Load a .py based config file by filename and path.""" loader = PyFileConfigLoader(filename, path=path) try: config = loader.load_config() except ConfigFileNotFound: # problem finding the file, raise raise except Exception: # try to get the full filename, but it will be empty in the # unlikely event that the error raised before filefind finished filename = loader.full_filename or filename
python
{ "resource": "" }
q279537
Application.generate_config_file
test
def generate_config_file(self): """generate default config file from Configurables""" lines = ["# Configuration file for %s."%self.name] lines.append('') lines.append('c = get_config()') lines.append('')
python
{ "resource": "" }
q279538
downsample
test
def downsample(array, k): """Choose k random elements of array.""" length = array.shape[0]
python
{ "resource": "" }
q279539
info_formatter
test
def info_formatter(info): """Produce a sequence of formatted lines from info. `info` is a sequence of pairs (label, data). The produced lines are nicely formatted, ready to print. """ label_len = max([len(l) for l, _d in info])
python
{ "resource": "" }
q279540
DebugControl.write
test
def write(self, msg): """Write a line of debug output.""" if self.should('pid'): msg = "pid %5d: %s" %
python
{ "resource": "" }
q279541
Configurable._config_changed
test
def _config_changed(self, name, old, new): """Update all the class traits having ``config=True`` as metadata. For any class trait with a ``config`` metadata attribute that is ``True``, we update the trait with the value of the corresponding config entry. """ # Get all traits with a config metadata entry that is True traits = self.traits(config=True) # We auto-load config section for this class as well as any parent # classes that are Configurable subclasses. This starts with Configurable # and works down the mro loading the config for each section. section_names = [cls.__name__ for cls in \ reversed(self.__class__.__mro__) if issubclass(cls, Configurable) and issubclass(self.__class__, cls)] for sname in section_names: # Don't do a blind getattr as that would cause the config to # dynamically create the section with name self.__class__.__name__. if new._has_section(sname): my_config = new[sname] for k, v in traits.iteritems(): # Don't allow traitlets with config=True to start with # uppercase. Otherwise, they are confused with Config # subsections. But, developers shouldn't have uppercase # attributes anyways! (PEP 6) if k[0].upper()==k[0] and not k.startswith('_'): raise ConfigurableError('Configurable traitlets with ' 'config=True must start with a lowercase so they are ' 'not confused with Config subsections: %s.%s' % \
python
{ "resource": "" }
q279542
Configurable.class_get_help
test
def class_get_help(cls, inst=None): """Get the help string for this class in ReST format. If `inst` is given, it's current trait values will be used in place of class defaults. """ assert inst is None or isinstance(inst, cls) cls_traits = cls.class_traits(config=True) final_help = [] final_help.append(u'%s options' % cls.__name__)
python
{ "resource": "" }
q279543
Configurable.class_get_trait_help
test
def class_get_trait_help(cls, trait, inst=None): """Get the help string for a single trait. If `inst` is given, it's current trait values will be used in place of the class default. """ assert inst is None or isinstance(inst, cls) lines = [] header = "--%s.%s=<%s>" % (cls.__name__, trait.name, trait.__class__.__name__) lines.append(header) if inst is not None: lines.append(indent('Current: %r' % getattr(inst, trait.name), 4)) else: try: dvr = repr(trait.get_default_value()) except Exception: dvr = None # ignore defaults we can't construct if dvr is not None: if len(dvr) > 64: dvr = dvr[:61]+'...'
python
{ "resource": "" }
q279544
Configurable.class_config_section
test
def class_config_section(cls): """Get the config class config section""" def c(s): """return a commented, wrapped block.""" s = '\n\n'.join(wrap_paragraphs(s, 78)) return '# ' + s.replace('\n', '\n# ') # section header breaker = '#' + '-'*78 s = "# %s configuration"%cls.__name__ lines = [breaker, s, breaker, ''] # get the description trait desc = cls.class_traits().get('description') if desc: desc = desc.default_value else: # no description trait, use __doc__ desc = getattr(cls, '__doc__', '') if desc: lines.append(c(desc)) lines.append('') parents = [] for parent in cls.mro(): # only include parents that are not base classes # and are not the class itself # and have some configurable traits to inherit if parent is not cls and issubclass(parent, Configurable) and \
python
{ "resource": "" }
q279545
SingletonConfigurable.clear_instance
test
def clear_instance(cls): """unset _instance for this class and singleton parents. """ if not cls.initialized(): return for subclass in cls._walk_mro(): if isinstance(subclass._instance, cls):
python
{ "resource": "" }
q279546
SingletonConfigurable.instance
test
def instance(cls, *args, **kwargs): """Returns a global instance of this class. This method create a new instance if none have previously been created and returns a previously created instance is one already exists. The arguments and keyword arguments passed to this method are passed on to the :meth:`__init__` method of the class upon instantiation. Examples -------- Create a singleton class using instance, and retrieve it:: >>> from IPython.config.configurable import SingletonConfigurable >>> class Foo(SingletonConfigurable): pass >>> foo = Foo.instance() >>> foo == Foo.instance() True Create a subclass that is retrived using the base class instance:: >>> class Bar(SingletonConfigurable): pass >>> class Bam(Bar): pass >>> bam = Bam.instance() >>> bam == Bar.instance() True
python
{ "resource": "" }
q279547
FailureDetail.formatFailure
test
def formatFailure(self, test, err): """Add detail from traceback inspection to error message of a failure.
python
{ "resource": "" }
q279548
crash_handler_lite
test
def crash_handler_lite(etype, evalue, tb): """a light excepthook, adding a small message to the usual traceback""" traceback.print_exception(etype, evalue, tb) from IPython.core.interactiveshell import InteractiveShell if InteractiveShell.initialized(): # we are in a Shell environment, give %magic example config = "%config
python
{ "resource": "" }
q279549
QtSubSocketChannel.flush
test
def flush(self): """ Reimplemented to ensure that signals are dispatched immediately. """ super(QtSubSocketChannel,
python
{ "resource": "" }
q279550
QtKernelManager.start_channels
test
def start_channels(self, *args, **kw): """ Reimplemented to emit signal. """ super(QtKernelManager,
python
{ "resource": "" }
q279551
NotebookReader.read
test
def read(self, fp, **kwargs): """Read a notebook from a file like object""" nbs = fp.read() if not py3compat.PY3 and not isinstance(nbs, unicode):
python
{ "resource": "" }
q279552
read_no_interrupt
test
def read_no_interrupt(p): """Read from a pipe ignoring EINTR errors. This is necessary because when reading from pipes with GUI event loops running in the background, often interrupts are raised that stop the command from completing."""
python
{ "resource": "" }
q279553
process_handler
test
def process_handler(cmd, callback, stderr=subprocess.PIPE): """Open a command in a shell subprocess and execute a callback. This function provides common scaffolding for creating subprocess.Popen() calls. It creates a Popen object and then calls the callback with it. Parameters ---------- cmd : str A string to be executed with the underlying system shell (by calling :func:`Popen` with ``shell=True``. callback : callable A one-argument function that will be called with the Popen object. stderr : file descriptor number, optional By default this is set to ``subprocess.PIPE``, but you can also pass the value ``subprocess.STDOUT`` to force the subprocess' stderr to go into the same file descriptor as its stdout. This is useful to read stdout and stderr combined in the order they are generated. Returns ------- The return value of the provided callback is returned. """ sys.stdout.flush() sys.stderr.flush() # On win32, close_fds can't be true when using pipes for stdin/out/err close_fds = sys.platform != 'win32' p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
python
{ "resource": "" }
q279554
arg_split
test
def arg_split(s, posix=False, strict=True): """Split a command line's arguments in a shell-like manner. This is a modified version of the standard library's shlex.split() function, but with a default of posix=False for splitting, so that quotes in inputs are respected. if strict=False, then any errors shlex.split would raise will result in the unparsed remainder being the last element of the list, rather than raising. This is because we sometimes use arg_split to parse things other than command-line args. """ # Unfortunately, python's shlex module is buggy with unicode input: # http://bugs.python.org/issue1170 # At least encoding the input when it's unicode seems to help, but there # may be more problems lurking. Apparently this is fixed in python3.
python
{ "resource": "" }
q279555
compress_dhist
test
def compress_dhist(dh): """Compress a directory history into a new one with at most 20 entries. Return a new list made from the first and last 10 elements of dhist after removal of duplicates. """ head, tail = dh[:-10], dh[-10:] newhead = [] done =
python
{ "resource": "" }
q279556
magics_class
test
def magics_class(cls): """Class decorator for all subclasses of the main Magics class. Any class that subclasses Magics *must* also apply this decorator, to ensure that all the methods that have been decorated as line/cell magics get correctly registered in the class instance. This is necessary because when method decorators run, the class does not exist yet, so they temporarily store their information into a module global. Application of this class decorator copies that global data to the class instance and clears the global. Obviously, this mechanism is not thread-safe, which means that the *creation* of subclasses of Magic should only be done in a single-thread context. Instantiation of the classes has no restrictions. Given that
python
{ "resource": "" }
q279557
record_magic
test
def record_magic(dct, magic_kind, magic_name, func): """Utility function to store a function as a magic of a specific kind. Parameters ---------- dct : dict A dictionary with 'line' and 'cell' subdicts. magic_kind : str Kind of magic to be stored. magic_name : str Key to
python
{ "resource": "" }
q279558
_method_magic_marker
test
def _method_magic_marker(magic_kind): """Decorator factory for methods in Magics subclasses. """ validate_type(magic_kind) # This is a closure to capture the magic_kind. We could also use a class, # but it's overkill for just that one bit of state. def magic_deco(arg): call = lambda f, *a, **k: f(*a, **k) if callable(arg): # "Naked" decorator call (just @foo, no args) func = arg name = func.func_name
python
{ "resource": "" }
q279559
_function_magic_marker
test
def _function_magic_marker(magic_kind): """Decorator factory for standalone functions. """ validate_type(magic_kind) # This is a closure to capture the magic_kind. We could also use a class, # but it's overkill for just that one bit of state. def magic_deco(arg): call = lambda f, *a, **k: f(*a, **k) # Find get_ipython() in the caller's namespace caller = sys._getframe(1) for ns in ['f_locals', 'f_globals', 'f_builtins']: get_ipython = getattr(caller, ns).get('get_ipython') if get_ipython is not None: break else: raise NameError('Decorator can only run in context where ' '`get_ipython` exists') ip = get_ipython() if callable(arg): # "Naked" decorator call (just @foo, no args) func = arg name = func.func_name ip.register_magic_function(func, magic_kind, name) retval = decorator(call, func) elif isinstance(arg, basestring): # Decorator called with arguments (@foo('bar')) name = arg def mark(func, *a, **kw): ip.register_magic_function(func, magic_kind, name)
python
{ "resource": "" }
q279560
MagicsManager.lsmagic_docs
test
def lsmagic_docs(self, brief=False, missing=''): """Return dict of documentation of magic functions. The return dict has the keys 'line' and 'cell', corresponding to the two types of magics we support. Each value is a dict keyed by magic name whose value is the function docstring. If a docstring is unavailable, the value of `missing` is used instead. If brief is True, only the first line of each docstring will be returned. """ docs = {} for m_type in self.magics: m_docs = {}
python
{ "resource": "" }
q279561
MagicsManager.register
test
def register(self, *magic_objects): """Register one or more instances of Magics. Take one or more classes or instances of classes that subclass the main `core.Magic` class, and register them with IPython to use the magic functions they provide. The registration process will then ensure that any methods that have decorated to provide line and/or cell magics will be recognized with the `%x`/`%%x` syntax as a line/cell magic respectively. If classes are given, they will be instantiated with the default constructor. If your classes need a custom constructor, you should instanitate them first and pass the instance. The provided arguments can be an arbitrary mix of classes and instances. Parameters ---------- magic_objects : one or more classes or instances """ # Start by validating them to ensure they have all had their magic # methods registered at the instance level for m in magic_objects: if not m.registered:
python
{ "resource": "" }
q279562
MagicsManager.register_function
test
def register_function(self, func, magic_kind='line', magic_name=None): """Expose a standalone function as magic function for IPython. This will create an IPython magic (line, cell or both) from a standalone function. The functions should have the following signatures: * For line magics: `def f(line)` * For cell magics: `def f(line, cell)` * For a function that does both: `def f(line, cell=None)` In the latter case, the function will be called with `cell==None` when
python
{ "resource": "" }
q279563
Magics.format_latex
test
def format_latex(self, strng): """Format a string for latex inclusion.""" # Characters that need to be escaped for latex: escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) # Magic command names as headers: cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, re.MULTILINE) # Magic commands cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, re.MULTILINE) # Paragraph continue par_re = re.compile(r'\\$',re.MULTILINE) # The "\n" symbol newline_re
python
{ "resource": "" }
q279564
Magics.parse_options
test
def parse_options(self, arg_str, opt_str, *long_opts, **kw): """Parse options passed to an argument string. The interface is similar to that of getopt(), but it returns back a Struct with the options as keys and the stripped argument string still as a string. arg_str is quoted as a true sys.argv vector by using shlex.split. This allows us to easily expand variables, glob files, quote arguments, etc. Options: -mode: default 'string'. If given as 'list', the argument string is returned as a list (split on whitespace) instead of a string. -list_all: put all option values in lists. Normally only options appearing more than once are put in a list. -posix (True): whether to split the input line in POSIX mode or not, as per the conventions outlined in the shlex module from the standard library.""" # inject default options at the beginning of the input line caller = sys._getframe(1).f_code.co_name arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) mode = kw.get('mode','string')
python
{ "resource": "" }
q279565
Magics.default_option
test
def default_option(self, fn, optstr): """Make an entry in the options_table for fn, with value optstr""" if fn not in self.lsmagic():
python
{ "resource": "" }
q279566
page_guiref
test
def page_guiref(arg_s=None): """Show a basic reference about the GUI Console.""" from IPython.core import
python
{ "resource": "" }
q279567
task_with_callable
test
def task_with_callable(the_callable, label=None, schedule=DEFAULT_SCHEDULE, userdata=None, pk_override=None): """Factory function to create a properly initialized task.""" task = Task() if isinstance(the_callable, str): if pk_override is not None: components = the_callable.split('.') info = dict( func_type='instancemethod', module_name='.'.join(components[:-2]), class_name=components[-2], class_path='.'.join(components[:-1]), model_pk=pk_override,
python
{ "resource": "" }
q279568
taskinfo_with_label
test
def taskinfo_with_label(label): """Return task info dictionary from task label. Internal function, pretty much
python
{ "resource": "" }
q279569
Task.func_from_info
test
def func_from_info(self): """Find and return a callable object from a task info dictionary""" info = self.funcinfo functype = info['func_type'] if functype in ['instancemethod', 'classmethod', 'staticmethod']: the_modelclass = get_module_member_by_dottedpath(info['class_path']) if functype == 'instancemethod': the_modelobject = the_modelclass.objects.get(pk=info['model_pk']) the_callable = get_member(the_modelobject, info['func_name']) else: the_callable = get_member(the_modelclass, info['func_name'])
python
{ "resource": "" }
q279570
Task.calc_next_run
test
def calc_next_run(self): """Calculate next run time of this task""" base_time = self.last_run if self.last_run == HAS_NOT_RUN: if self.wait_for_schedule is False: self.next_run = timezone.now()
python
{ "resource": "" }
q279571
Task.submit
test
def submit(self, timestamp): """Internal instance method to submit this task for running immediately. Does not handle any iteration, end-date, etc., processing."""
python
{ "resource": "" }
q279572
Task.run
test
def run(self, message): """Internal instance method run by worker process to actually run the task callable.""" the_callable = self.func_from_info() try: task_message = dict( task=self, channel_message=message, ) the_callable(task_message) finally: if self.end_running < self.next_run: self.enabled=False Channel(KILL_TASK_CHANNEL).send({'id': self.pk})
python
{ "resource": "" }
q279573
Task.run_asap
test
def run_asap(self): """Instance method to run this task immediately.""" now = timezone.now() self.last_run = now
python
{ "resource": "" }
q279574
Task.run_iterations
test
def run_iterations(cls, the_callable, iterations=1, label=None, schedule='* * * * * *', userdata = None, run_immediately=False, delay_until=None): """Class method to run a callable with a specified number of iterations""" task = task_with_callable(the_callable, label=label, schedule=schedule, userdata=userdata) task.iterations = iterations if delay_until is not None: if isinstance(delay_until, datetime): if delay_until > timezone.now(): task.start_running = delay_until
python
{ "resource": "" }
q279575
Task.run_once
test
def run_once(cls, the_callable, userdata=None, delay_until=None): """Class method to run a one-shot task, immediately."""
python
{ "resource": "" }
q279576
IPEngineApp.find_url_file
test
def find_url_file(self): """Set the url file. Here we don't try to actually see if it exists for is valid as that is hadled by the connection logic. """ config = self.config # Find the actual controller key file
python
{ "resource": "" }
q279577
IPEngineApp.bind_kernel
test
def bind_kernel(self, **kwargs): """Promote engine to listening kernel, accessible to frontends.""" if self.kernel_app is not None: return self.log.info("Opening ports for direct connections as an IPython kernel") kernel = self.kernel kwargs.setdefault('config', self.config) kwargs.setdefault('log', self.log) kwargs.setdefault('profile_dir', self.profile_dir) kwargs.setdefault('session', self.engine.session) app = self.kernel_app = IPKernelApp(**kwargs) # allow IPKernelApp.instance(): IPKernelApp._instance = app app.init_connection_file() # relevant contents of init_sockets: app.shell_port = app._bind_socket(kernel.shell_streams[0], app.shell_port)
python
{ "resource": "" }
q279578
timid
test
def timid(ctxt, test, key=None, check=False, exts=None): """ Execute a test described by a YAML file. :param ctxt: A ``timid.context.Context`` object. :param test: The name of a YAML file containing the test description. Note that the current working directory set up in ``ctxt.environment`` does not affect the resolution of this file. :param key: An optional key into the test description file. If not ``None``, the file named by ``test`` must be a YAML dictionary of lists of steps; otherwise, it must be a simple list of steps. :param check: If ``True``, only performs a syntax check of the test steps indicated by ``test`` and ``key``; the test itself is not run. :param exts: An instance of ``timid.extensions.ExtensionSet`` describing the extensions to be called while processing the test steps. """ # Normalize the extension set if exts is None: exts = extensions.ExtensionSet() # Begin by reading the steps and adding them to the list in the # context (which may already have elements thanks to the # extensions) ctxt.emit('Reading test steps from %s%s...' % (test, '[%s]' % key if key else ''), debug=True) ctxt.steps += exts.read_steps(ctxt, steps.Step.parse_file(ctxt, test, key)) # If all we were supposed to do was check, well, we've # accomplished that... if check: return None
python
{ "resource": "" }
q279579
ParentPollerWindows.create_interrupt_event
test
def create_interrupt_event(): """ Create an interrupt event handle. The parent process should use this static method for creating the interrupt event that is passed to the child process. It should store this handle and use it with ``send_interrupt`` to interrupt the child process. """ # Create a security attributes struct that permits inheritance of the # handle by new processes. # FIXME: We can clean up this mess by requiring pywin32 for IPython. class SECURITY_ATTRIBUTES(ctypes.Structure): _fields_ = [ ("nLength", ctypes.c_int), ("lpSecurityDescriptor", ctypes.c_void_p),
python
{ "resource": "" }
q279580
ParentPollerWindows.run
test
def run(self): """ Run the poll loop. This method never returns. """ try: from _winapi import WAIT_OBJECT_0, INFINITE except ImportError: from _subprocess import WAIT_OBJECT_0, INFINITE # Build the list of handle to listen on. handles = [] if self.interrupt_handle: handles.append(self.interrupt_handle) if self.parent_handle: handles.append(self.parent_handle) arch = platform.architecture()[0] c_int = ctypes.c_int64 if arch.startswith('64') else ctypes.c_int # Listen forever. while True: result = ctypes.windll.kernel32.WaitForMultipleObjects( len(handles), # nCount (c_int * len(handles))(*handles), # lpHandles False, # bWaitAll
python
{ "resource": "" }
q279581
filter_ns
test
def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True, show_all=True): """Filter a namespace dictionary by name pattern and item type.""" pattern = name_pattern.replace("*",".*").replace("?",".") if ignore_case: reg = re.compile(pattern+"$", re.I) else: reg = re.compile(pattern+"$") # Check each one matches regex; shouldn't be hidden;
python
{ "resource": "" }
q279582
list_namespace
test
def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False): """Return dictionary of all objects in a namespace dictionary that match type_pattern and filter.""" pattern_list=filter.split(".") if len(pattern_list) == 1: return filter_ns(namespace, name_pattern=pattern_list[0], type_pattern=type_pattern, ignore_case=ignore_case, show_all=show_all) else: # This is where we can change if all objects should be searched or
python
{ "resource": "" }
q279583
mutex_opts
test
def mutex_opts(dict,ex_op): """Check for presence of mutually exclusive keys in a dict. Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" for op1,op2 in ex_op: if op1 in dict and op2 in dict:
python
{ "resource": "" }
q279584
draw_if_interactive
test
def draw_if_interactive(): """ Is called after every pylab drawing command """ # signal that the current active figure should be sent at the end of # execution. Also sets the _draw_called flag, signaling that there will be # something to send. At the end of the code execution, a separate call to # flush_figures() will act upon these values fig = Gcf.get_active().canvas.figure # Hack: matplotlib FigureManager objects in interacive backends (at least # in some of them) monkeypatch the figure object and add a .show() method # to it. This applies the same monkeypatch in order to support user code # that might expect `.show()` to be part of the official API of figure # objects. # For further reference: # https://github.com/ipython/ipython/issues/1612 # https://github.com/matplotlib/matplotlib/issues/835 if not hasattr(fig, 'show'): # Queue up `fig` for display fig.show = lambda
python
{ "resource": "" }
q279585
flush_figures
test
def flush_figures(): """Send all figures that changed This is meant to be called automatically and will call show() if, during prior code execution, there had been any calls to draw_if_interactive. This function is meant to be used as a post_execute callback in IPython, so user-caused errors are handled with showtraceback() instead of being allowed to raise. If this function is not called from within IPython, then these exceptions will raise. """ if not show._draw_called: return if InlineBackend.instance().close_figures: # ignore the tracking, just draw and close all figures try: return show(True) except Exception as e: # safely show traceback if in IPython, else raise try: get_ipython except NameError: raise e else: get_ipython().showtraceback()
python
{ "resource": "" }
q279586
send_figure
test
def send_figure(fig): """Draw the given figure and send it as a PNG payload. """ fmt = InlineBackend.instance().figure_format data = print_figure(fig, fmt) # print_figure will return None if there's nothing to draw: if data is None: return mimetypes = { 'png' : 'image/png', 'svg' : 'image/svg+xml' } mime = mimetypes[fmt] # flush text streams before sending figures, helps a little with
python
{ "resource": "" }
q279587
ExtensionManager.load_extension
test
def load_extension(self, module_str): """Load an IPython extension by its module name. If :func:`load_ipython_extension` returns anything, this function will return that object. """ from IPython.utils.syspathcontext import prepended_to_syspath if module_str not in sys.modules:
python
{ "resource": "" }
q279588
ExtensionManager.unload_extension
test
def unload_extension(self, module_str): """Unload an IPython extension by its module name. This function looks up the extension's name in ``sys.modules`` and
python
{ "resource": "" }
q279589
random_ports
test
def random_ports(port, n): """Generate a list of n random ports near the given port. The first 5 ports will be sequential, and the remaining n-5 will be randomly selected in the range [port-2*n, port+2*n].
python
{ "resource": "" }
q279590
NotebookApp.init_webapp
test
def init_webapp(self): """initialize tornado webapp and httpserver""" self.web_app = NotebookWebApplication( self, self.kernel_manager, self.notebook_manager, self.cluster_manager, self.log, self.base_project_url, self.webapp_settings ) if self.certfile: ssl_options = dict(certfile=self.certfile) if self.keyfile: ssl_options['keyfile'] = self.keyfile else: ssl_options = None self.web_app.password = self.password self.http_server = httpserver.HTTPServer(self.web_app, ssl_options=ssl_options) if ssl_options is None and not self.ip and not (self.read_only and not self.password): self.log.critical('WARNING: the notebook server is listening on all IP addresses ' 'but not using any encryption or authentication. This is highly ' 'insecure and not recommended.') success = None for port in random_ports(self.port, self.port_retries+1): try:
python
{ "resource": "" }
q279591
NotebookApp._handle_sigint
test
def _handle_sigint(self, sig, frame): """SIGINT handler spawns confirmation dialog""" # register more forceful signal handler for ^C^C case signal.signal(signal.SIGINT, self._signal_stop) # request confirmation dialog in bg thread, to avoid
python
{ "resource": "" }
q279592
NotebookApp._confirm_exit
test
def _confirm_exit(self): """confirm shutdown on ^C A second ^C, or answering 'y' within 5s will cause shutdown, otherwise original SIGINT handler will be restored. This doesn't work on Windows. """ # FIXME: remove this delay when pyzmq dependency is >= 2.1.11 time.sleep(0.1) sys.stdout.write("Shutdown Notebook Server (y/[n])? ") sys.stdout.flush() r,w,x = select.select([sys.stdin], [], [], 5) if r: line = sys.stdin.readline() if line.lower().startswith('y'): self.log.critical("Shutdown confirmed")
python
{ "resource": "" }
q279593
NotebookApp.cleanup_kernels
test
def cleanup_kernels(self): """shutdown all kernels The kernels will shutdown themselves when this process no longer exists, but explicit shutdown allows the KernelManagers to cleanup the connection files. """ self.log.info('Shutting down kernels') km
python
{ "resource": "" }
q279594
price_options
test
def price_options(S=100.0, K=100.0, sigma=0.25, r=0.05, days=260, paths=10000): """ Price European and Asian options using a Monte Carlo method. Parameters ---------- S : float The initial price of the stock. K : float The strike price of the option. sigma : float The volatility of the stock. r : float The risk free interest rate. days : int The number of days until the option expires. paths : int The number of Monte Carlo paths used to price the option. Returns ------- A tuple of (E. call, E. put, A. call, A. put) option prices. """ import numpy as np from math import exp,sqrt h = 1.0/days const1 = exp((r-0.5*sigma**2)*h) const2 = sigma*sqrt(h) stock_price = S*np.ones(paths, dtype='float64') stock_price_sum = np.zeros(paths, dtype='float64') for j in range(days):
python
{ "resource": "" }
q279595
multiple_replace
test
def multiple_replace(dict, text): """ Replace in 'text' all occurences of any key in the given dictionary by its corresponding value. Returns the new string.""" # Function by Xavier Defrang, originally found at: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 # Create a regular expression from the
python
{ "resource": "" }
q279596
PromptManager._render
test
def _render(self, name, color=True, **kwargs): """Render but don't justify, or update the width or txtwidth attributes. """ if name == 'rewrite': return self._render_rewrite(color=color) if color: scheme = self.color_scheme_table.active_colors if name=='out': colors = color_lists['normal'] colors.number, colors.prompt, colors.normal = \ scheme.out_number, scheme.out_prompt, scheme.normal else: colors = color_lists['inp'] colors.number, colors.prompt, colors.normal = \ scheme.in_number, scheme.in_prompt, scheme.in_normal if name=='in2': colors.prompt = scheme.in_prompt2 else: # No color colors = color_lists['nocolor'] colors.number, colors.prompt, colors.normal = '', '', ''
python
{ "resource": "" }
q279597
base_launch_kernel
test
def base_launch_kernel(code, fname, stdin=None, stdout=None, stderr=None, executable=None, independent=False, extra_arguments=[], cwd=None): """ Launches a localhost kernel, binding to the specified ports. Parameters ---------- code : str, A string of Python code that imports and executes a kernel entry point. stdin, stdout, stderr : optional (default None) Standards streams, as defined in subprocess.Popen. fname : unicode, optional The JSON connector file, containing ip/port/hmac key information. key : str, optional The Session key used for HMAC authentication. executable : str, optional (default sys.executable) The Python executable to use for the kernel process. independent : bool, optional (default False) If set, the kernel process is guaranteed to survive if this process dies. If not set, an effort is made to ensure that the kernel is killed when this process dies. Note that in this case it is still good practice to kill kernels manually before exiting. extra_arguments : list, optional A list of extra arguments to pass when executing the launch code. cwd : path, optional The working dir of the kernel process (default: cwd of this process). Returns ------- A tuple of form: (kernel_process, shell_port, iopub_port, stdin_port, hb_port) where kernel_process is a Popen object and the ports are integers. """ # Build the kernel launch command. if executable is None: executable = sys.executable arguments = [ executable, '-c', code, '-f', fname ] arguments.extend(extra_arguments) # Popen will fail (sometimes with a deadlock) if stdin, stdout, and stderr # are invalid. Unfortunately, there is in general no way to detect whether # they are valid. The following two blocks redirect them to (temporary) # pipes in certain important cases. # If this process has been backgrounded, our stdin is invalid. Since there # is no compelling reason for the kernel to inherit our stdin anyway, we'll # place this one safe and always redirect. redirect_in = True _stdin = PIPE if stdin is None else stdin # If this process in running on pythonw, we know that stdin, stdout, and # stderr are all invalid. redirect_out = sys.executable.endswith('pythonw.exe') if redirect_out: _stdout = PIPE if stdout is None else stdout _stderr = PIPE if stderr is None else stderr else: _stdout, _stderr = stdout, stderr # Spawn a kernel. if sys.platform == 'win32': # Create a Win32 event for interrupting the kernel. interrupt_event = ParentPollerWindows.create_interrupt_event() arguments += [ '--interrupt=%i'%interrupt_event ] # If the kernel is running on pythonw and stdout/stderr are not been # re-directed, it will crash when more than 4KB of data is written to # stdout or stderr. This is a bug that has been with Python for a very # long time; see http://bugs.python.org/issue706263.
python
{ "resource": "" }
q279598
create_zipfile
test
def create_zipfile(context): """This is the actual zest.releaser entry point Relevant items in the context dict: name Name of the project being released tagdir Directory where the tag checkout is placed (*if* a tag checkout has been made) version Version we're releasing
python
{ "resource": "" }
q279599
fix_version
test
def fix_version(context): """Fix the version in metadata.txt Relevant context dict item for both prerelease and postrelease: ``new_version``. """ if not prerequisites_ok(): return lines = codecs.open('metadata.txt',
python
{ "resource": "" }