text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Reads given URL as JSON and returns data as loaded python object. <END_TASK> <USER_TASK:> Description: def read_url(url): """Reads given URL as JSON and returns data as loaded python object."""
logging.debug('reading {url} ...'.format(url=url)) token = os.environ.get("BOKEH_GITHUB_API_TOKEN") headers = {} if token: headers['Authorization'] = 'token %s' % token request = Request(url, headers=headers) response = urlopen(request).read() return json.loads(response.decode("UTF-8"))
<SYSTEM_TASK:> Hits the github API for all closed issues after the given date, returns the data. <END_TASK> <USER_TASK:> Description: def query_all_issues(after): """Hits the github API for all closed issues after the given date, returns the data."""
page = count(1) data = [] while True: page_data = query_issues(next(page), after) if not page_data: break data.extend(page_data) return data
<SYSTEM_TASK:> Given a list of tags, returns the datetime of the tag with the given name; Otherwise None. <END_TASK> <USER_TASK:> Description: def dateof(tag_name, tags): """Given a list of tags, returns the datetime of the tag with the given name; Otherwise None."""
for tag in tags: if tag['name'] == tag_name: commit = read_url(tag['commit']['url']) return parse_timestamp(commit['commit']['committer']['date']) return None
<SYSTEM_TASK:> Gets data from query_func, optionally saving that data to a file; or loads data from a file. <END_TASK> <USER_TASK:> Description: def get_data(query_func, load_data=False, save_data=False): """Gets data from query_func, optionally saving that data to a file; or loads data from a file."""
if hasattr(query_func, '__name__'): func_name = query_func.__name__ elif hasattr(query_func, 'func'): func_name = query_func.func.__name__ pickle_file = '{}.pickle'.format(func_name) if load_data: data = load_object(pickle_file) else: data = query_func() if save_data: save_object(pickle_file, data) return data
<SYSTEM_TASK:> Returns log line for given issue. <END_TASK> <USER_TASK:> Description: def issue_line(issue): """Returns log line for given issue."""
template = '#{number} {tags}{title}' tags = issue_tags(issue) params = { 'title': issue['title'].capitalize().rstrip('.'), 'number': issue['number'], 'tags': ' '.join('[{}]'.format(tag) for tag in tags) + (' ' if tags else '') } return template.format(**params)
<SYSTEM_TASK:> Converts result into a Future by collapsing any futures inside result. <END_TASK> <USER_TASK:> Description: def yield_for_all_futures(result): """ Converts result into a Future by collapsing any futures inside result. If result is a Future we yield until it's done, then if the value inside the Future is another Future we yield until it's done as well, and so on. """
while True: # This is needed for Tornado >= 4.5 where convert_yielded will no # longer raise BadYieldError on None if result is None: break try: future = gen.convert_yielded(result) except gen.BadYieldError: # result is not a yieldable thing, we are done break else: result = yield future raise gen.Return(result)
<SYSTEM_TASK:> Adds a callback to be run on the next tick. <END_TASK> <USER_TASK:> Description: def add_next_tick_callback(self, callback, callback_id=None): """ Adds a callback to be run on the next tick. Returns an ID that can be used with remove_next_tick_callback."""
def wrapper(*args, **kwargs): # this 'removed' flag is a hack because Tornado has no way # to remove a "next tick" callback added with # IOLoop.add_callback. So instead we make our wrapper skip # invoking the callback. if not wrapper.removed: self.remove_next_tick_callback(callback_id) return callback(*args, **kwargs) else: return None wrapper.removed = False def remover(): wrapper.removed = True callback_id = self._assign_remover(callback, callback_id, self._next_tick_callback_removers, remover) self._loop.add_callback(wrapper) return callback_id
<SYSTEM_TASK:> Adds a callback to be run once after timeout_milliseconds. <END_TASK> <USER_TASK:> Description: def add_timeout_callback(self, callback, timeout_milliseconds, callback_id=None): """ Adds a callback to be run once after timeout_milliseconds. Returns an ID that can be used with remove_timeout_callback."""
def wrapper(*args, **kwargs): self.remove_timeout_callback(callback_id) return callback(*args, **kwargs) handle = None def remover(): if handle is not None: self._loop.remove_timeout(handle) callback_id = self._assign_remover(callback, callback_id, self._timeout_callback_removers, remover) handle = self._loop.call_later(timeout_milliseconds / 1000.0, wrapper) return callback_id
<SYSTEM_TASK:> Adds a callback to be run every period_milliseconds until it is removed. <END_TASK> <USER_TASK:> Description: def add_periodic_callback(self, callback, period_milliseconds, callback_id=None): """ Adds a callback to be run every period_milliseconds until it is removed. Returns an ID that can be used with remove_periodic_callback."""
cb = _AsyncPeriodic(callback, period_milliseconds, io_loop=self._loop) callback_id = self._assign_remover(callback, callback_id, self._periodic_callback_removers, cb.stop) cb.start() return callback_id
<SYSTEM_TASK:> this is copied from sphinx.directives.code.CodeBlock.run <END_TASK> <USER_TASK:> Description: def get_codeblock_node(self, code, language): """this is copied from sphinx.directives.code.CodeBlock.run it has been changed to accept code and language as an arguments instead of reading from self """
# type: () -> List[nodes.Node] document = self.state.document location = self.state_machine.get_source_and_line(self.lineno) linespec = self.options.get('emphasize-lines') if linespec: try: nlines = len(code.split('\n')) hl_lines = parselinenos(linespec, nlines) if any(i >= nlines for i in hl_lines): log.warning(__('line number spec is out of range(1-%d): %r') % (nlines, self.options['emphasize-lines']), location=location) hl_lines = [x + 1 for x in hl_lines if x < nlines] except ValueError as err: return [document.reporter.warning(str(err), line=self.lineno)] else: hl_lines = None if 'dedent' in self.options: location = self.state_machine.get_source_and_line(self.lineno) lines = code.split('\n') lines = dedent_lines(lines, self.options['dedent'], location=location) code = '\n'.join(lines) literal = nodes.literal_block(code, code) literal['language'] = language literal['linenos'] = 'linenos' in self.options or \ 'lineno-start' in self.options literal['classes'] += self.options.get('class', []) extra_args = literal['highlight_args'] = {} if hl_lines is not None: extra_args['hl_lines'] = hl_lines if 'lineno-start' in self.options: extra_args['linenostart'] = self.options['lineno-start'] set_source_info(self, literal) caption = self.options.get('caption') if caption: try: literal = container_wrapper(self, literal, caption) except ValueError as exc: return [document.reporter.warning(text_type(exc), line=self.lineno)] # literal will be note_implicit_target that is linked from caption and numref. # when options['name'] is provided, it should be primary ID. self.add_name(literal) return [literal]
<SYSTEM_TASK:> This is largely copied from bokeh.sphinxext.bokeh_plot.run <END_TASK> <USER_TASK:> Description: def get_code_language(self): """ This is largely copied from bokeh.sphinxext.bokeh_plot.run """
js_source = self.get_js_source() if self.options.get("include_html", False): resources = get_sphinx_resources(include_bokehjs_api=True) html_source = BJS_HTML.render( css_files=resources.css_files, js_files=resources.js_files, bjs_script=js_source) return [html_source, "html"] else: return [js_source, "javascript"]
<SYSTEM_TASK:> Returns the compiled implementation of supplied `models`. <END_TASK> <USER_TASK:> Description: def _compile_models(custom_models): """Returns the compiled implementation of supplied `models`. """
ordered_models = sorted(custom_models.values(), key=lambda model: model.full_name) custom_impls = {} dependencies = [] for model in ordered_models: dependencies.extend(list(model.dependencies.items())) if dependencies: dependencies = sorted(dependencies, key=lambda name_version: name_version[0]) _run_npmjs(["install", "--no-progress"] + [ name + "@" + version for (name, version) in dependencies ]) for model in ordered_models: impl = model.implementation compiled = _CACHING_IMPLEMENTATION(model, impl) if compiled is None: compiled = nodejs_compile(impl.code, lang=impl.lang, file=impl.file) if "error" in compiled: raise CompilationError(compiled.error) custom_impls[model.full_name] = compiled return custom_impls
<SYSTEM_TASK:> Given a kwargs dict, a prefix, and a default value, looks for different <END_TASK> <USER_TASK:> Description: def _pop_colors_and_alpha(glyphclass, kwargs, prefix="", default_alpha=1.0): """ Given a kwargs dict, a prefix, and a default value, looks for different color and alpha fields of the given prefix, and fills in the default value if it doesn't exist. """
result = dict() # TODO: The need to do this and the complexity of managing this kind of # thing throughout the codebase really suggests that we need to have # a real stylesheet class, where defaults and Types can declaratively # substitute for this kind of imperative logic. color = kwargs.pop(prefix + "color", get_default_color()) for argname in ("fill_color", "line_color"): if argname not in glyphclass.properties(): continue result[argname] = kwargs.pop(prefix + argname, color) # NOTE: text fill color should really always default to black, hard coding # this here now until the stylesheet solution exists if "text_color" in glyphclass.properties(): result["text_color"] = kwargs.pop(prefix + "text_color", "black") alpha = kwargs.pop(prefix + "alpha", default_alpha) for argname in ("fill_alpha", "line_alpha", "text_alpha"): if argname not in glyphclass.properties(): continue result[argname] = kwargs.pop(prefix + argname, alpha) return result
<SYSTEM_TASK:> Takes a string and returns a corresponding `Tool` instance. <END_TASK> <USER_TASK:> Description: def _tool_from_string(name): """ Takes a string and returns a corresponding `Tool` instance. """
known_tools = sorted(_known_tools.keys()) if name in known_tools: tool_fn = _known_tools[name] if isinstance(tool_fn, string_types): tool_fn = _known_tools[tool_fn] return tool_fn() else: matches, text = difflib.get_close_matches(name.lower(), known_tools), "similar" if not matches: matches, text = known_tools, "possible" raise ValueError("unexpected tool name '%s', %s tools are %s" % (name, text, nice_join(matches)))
<SYSTEM_TASK:> Create a ``CustomJS`` instance from a Python function. The <END_TASK> <USER_TASK:> Description: def from_py_func(cls, func): """ Create a ``CustomJS`` instance from a Python function. The function is translated to JavaScript using PScript. """
from bokeh.util.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. " "Use CustomJS directly instead.") if not isinstance(func, FunctionType): raise ValueError('CustomJS.from_py_func needs function object.') pscript = import_required('pscript', 'To use Python functions for CustomJS, you need PScript ' + '("conda install -c conda-forge pscript" or "pip install pscript")') # Collect default values default_values = func.__defaults__ # Python 2.6+ default_names = func.__code__.co_varnames[:len(default_values)] args = dict(zip(default_names, default_values)) args.pop('window', None) # Clear window, so we use the global window object # Get JS code, we could rip out the function def, or just # call the function. We do the latter. code = pscript.py2js(func, 'cb') + 'cb(%s);\n' % ', '.join(default_names) return cls(code=code, args=args)
<SYSTEM_TASK:> Allow flexible selector syntax. <END_TASK> <USER_TASK:> Description: def _select_helper(args, kwargs): """ Allow flexible selector syntax. Returns: dict """
if len(args) > 1: raise TypeError("select accepts at most ONE positional argument.") if len(args) > 0 and len(kwargs) > 0: raise TypeError("select accepts EITHER a positional argument, OR keyword arguments (not both).") if len(args) == 0 and len(kwargs) == 0: raise TypeError("select requires EITHER a positional argument, OR keyword arguments.") if args: arg = args[0] if isinstance(arg, dict): selector = arg elif isinstance(arg, string_types): selector = dict(name=arg) elif isinstance(arg, type) and issubclass(arg, Model): selector = {"type": arg} else: raise TypeError("selector must be a dictionary, string or plot object.") elif 'selector' in kwargs: if len(kwargs) == 1: selector = kwargs['selector'] else: raise TypeError("when passing 'selector' keyword arg, not other keyword args may be present") else: selector = kwargs return selector
<SYSTEM_TASK:> Create a grid-based arrangement of Bokeh Layout objects. <END_TASK> <USER_TASK:> Description: def layout(*args, **kwargs): """ Create a grid-based arrangement of Bokeh Layout objects. Args: children (list of lists of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of lists of instances for a grid layout. Can be any of the following - :class:`~bokeh.models.plots.Plot`, :class:`~bokeh.models.widgets.widget.Widget`, :class:`~bokeh.models.layouts.Row`, :class:`~bokeh.models.layouts.Column`, :class:`~bokeh.models.tools.ToolbarBox`, :class:`~bokeh.models.layouts.Spacer`. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: Column: A column of ``Row`` layouts of the children, all with the same sizing_mode. Examples: >>> layout([[plot_1, plot_2], [plot_3, plot_4]]) >>> layout( children=[ [widget_1, plot_1], [slider], [widget_2, plot_2, plot_3] ], sizing_mode='fixed', ) """
sizing_mode = kwargs.pop('sizing_mode', None) children = kwargs.pop('children', None) children = _handle_children(*args, children=children) # Make the grid return _create_grid(children, sizing_mode)
<SYSTEM_TASK:> Yield successive n-sized chunks from list, l. <END_TASK> <USER_TASK:> Description: def _chunks(l, ncols): """Yield successive n-sized chunks from list, l."""
assert isinstance(ncols, int), "ncols must be an integer" for i in range(0, len(l), ncols): yield l[i: i+ncols]
<SYSTEM_TASK:> Get the location of the server subpackage <END_TASK> <USER_TASK:> Description: def serverdir(): """ Get the location of the server subpackage """
path = join(ROOT_DIR, 'server') path = normpath(path) if sys.platform == 'cygwin': path = realpath(path) return path
<SYSTEM_TASK:> Generate a random session ID. <END_TASK> <USER_TASK:> Description: def generate_session_id(secret_key=settings.secret_key_bytes(), signed=settings.sign_sessions()): """Generate a random session ID. Typically, each browser tab connected to a Bokeh application has its own session ID. In production deployments of a Bokeh app, session IDs should be random and unguessable - otherwise users of the app could interfere with one another. If session IDs are signed with a secret key, the server can verify that the generator of the session ID was "authorized" (the generator had to know the secret key). This can be used to have a separate process, such as another web application, which generates new sessions on a Bokeh server. This other process may require users to log in before redirecting them to the Bokeh server with a valid session ID, for example. Args: secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var) signed (bool, optional) : Whether to sign the session ID (default: value of 'BOKEH_SIGN_SESSIONS' env var) """
secret_key = _ensure_bytes(secret_key) if signed: # note: '-' can also be in the base64 encoded signature base_id = _get_random_string(secret_key=secret_key) return base_id + '-' + _signature(base_id, secret_key) else: return _get_random_string(secret_key=secret_key)
<SYSTEM_TASK:> Check the signature of a session ID, returning True if it's valid. <END_TASK> <USER_TASK:> Description: def check_session_id_signature(session_id, secret_key=settings.secret_key_bytes(), signed=settings.sign_sessions()): """Check the signature of a session ID, returning True if it's valid. The server uses this function to check whether a session ID was generated with the correct secret key. If signed sessions are disabled, this function always returns True. Args: session_id (str) : The session ID to check secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var) signed (bool, optional) : Whether to check anything (default: value of 'BOKEH_SIGN_SESSIONS' env var) """
secret_key = _ensure_bytes(secret_key) if signed: pieces = session_id.split('-', 1) if len(pieces) != 2: return False base_id = pieces[0] provided_signature = pieces[1] expected_signature = _signature(base_id, secret_key) # hmac.compare_digest() uses a string compare algorithm that doesn't # short-circuit so we don't allow timing analysis # encode_utf8 is used to ensure that strings have same encoding return hmac.compare_digest(encode_utf8(expected_signature), encode_utf8(provided_signature)) else: return True
<SYSTEM_TASK:> Create a ``CustomJSTransform`` instance from a pair of Python <END_TASK> <USER_TASK:> Description: def from_py_func(cls, func, v_func): ''' Create a ``CustomJSTransform`` instance from a pair of Python functions. The function is translated to JavaScript using PScript. The python functions must have no positional arguments. It's possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword arguments to the functions. The ``func`` function namespace will contain the variable ``x`` (the untransformed value) at render time. The ``v_func`` function namespace will contain the variable ``xs`` (the untransformed vector) at render time. .. warning:: The vectorized function, ``v_func``, must return an array of the same length as the input ``xs`` array. Example: .. code-block:: python def transform(): from pscript.stubs import Math return Math.cos(x) def v_transform(): from pscript.stubs import Math return [Math.cos(x) for x in xs] customjs_transform = CustomJSTransform.from_py_func(transform, v_transform) Args: func (function) : a scalar function to transform a single ``x`` value v_func (function) : a vectorized function to transform a vector ``xs`` Returns: CustomJSTransform ''' from bokeh.util.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. " "Use CustomJSTransform directly instead.") if not isinstance(func, FunctionType) or not isinstance(v_func, FunctionType): raise ValueError('CustomJSTransform.from_py_func only accepts function objects.') pscript = import_required( 'pscript', dedent("""\ To use Python functions for CustomJSTransform, you need PScript '("conda install -c conda-forge pscript" or "pip install pscript")"""
) ) def pscript_compile(func): sig = signature(func) all_names, default_values = get_param_info(sig) if len(all_names) - len(default_values) != 0: raise ValueError("Function may only contain keyword arguments.") if default_values and not any(isinstance(value, Model) for value in default_values): raise ValueError("Default value must be a Bokeh Model.") func_kwargs = dict(zip(all_names, default_values)) # Wrap the code attr in a function named `formatter` and call it # with arguments that match the `args` attr code = pscript.py2js(func, 'transformer') + 'return transformer(%s);\n' % ', '.join(all_names) return code, func_kwargs jsfunc, func_kwargs = pscript_compile(func) v_jsfunc, v_func_kwargs = pscript_compile(v_func) # Have to merge the function arguments func_kwargs.update(v_func_kwargs) return cls(func=jsfunc, v_func=v_jsfunc, args=func_kwargs)
<SYSTEM_TASK:> Issue a nicely formatted deprecation warning. <END_TASK> <USER_TASK:> Description: def deprecated(since_or_msg, old=None, new=None, extra=None): """ Issue a nicely formatted deprecation warning. """
if isinstance(since_or_msg, tuple): if old is None or new is None: raise ValueError("deprecated entity and a replacement are required") if len(since_or_msg) != 3 or not all(isinstance(x, int) and x >=0 for x in since_or_msg): raise ValueError("invalid version tuple: %r" % (since_or_msg,)) since = "%d.%d.%d" % since_or_msg message = "%(old)s was deprecated in Bokeh %(since)s and will be removed, use %(new)s instead." message = message % dict(old=old, since=since, new=new) if extra is not None: message += " " + extra.strip() elif isinstance(since_or_msg, six.string_types): if not (old is None and new is None and extra is None): raise ValueError("deprecated(message) signature doesn't allow extra arguments") message = since_or_msg else: raise ValueError("expected a version tuple or string message") warn(message)
<SYSTEM_TASK:> Allow the session to be discarded and don't get change notifications from it anymore <END_TASK> <USER_TASK:> Description: def detach_session(self): """Allow the session to be discarded and don't get change notifications from it anymore"""
if self._session is not None: self._session.unsubscribe(self) self._session = None
<SYSTEM_TASK:> Sends a PATCH-DOC message, returning a Future that's completed when it's written out. <END_TASK> <USER_TASK:> Description: def send_patch_document(self, event): """ Sends a PATCH-DOC message, returning a Future that's completed when it's written out. """
msg = self.protocol.create('PATCH-DOC', [event]) return self._socket.send_message(msg)
<SYSTEM_TASK:> Create a ``CustomJSFilter`` instance from a Python function. The <END_TASK> <USER_TASK:> Description: def from_py_func(cls, func): ''' Create a ``CustomJSFilter`` instance from a Python function. The function is translated to JavaScript using PScript. The ``func`` function namespace will contain the variable ``source`` at render time. This will be the data source associated with the ``CDSView`` that this filter is added to. ''' from bokeh.util.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. " "Use CustomJSFilter directly instead.") if not isinstance(func, FunctionType): raise ValueError('CustomJSFilter.from_py_func only accepts function objects.') pscript = import_required( 'pscript', dedent("""\ To use Python functions for CustomJSFilter, you need PScript '("conda install -c conda-forge pscript" or "pip install pscript")"""
) ) argspec = inspect.getargspec(func) default_names = argspec.args default_values = argspec.defaults or [] if len(default_names) - len(default_values) != 0: raise ValueError("Function may only contain keyword arguments.") # should the following be all of the values need to be Models? if default_values and not any(isinstance(value, Model) for value in default_values): raise ValueError("Default value must be a plot object.") func_kwargs = dict(zip(default_names, default_values)) code = pscript.py2js(func, 'filter') + 'return filter(%s);\n' % ', '.join(default_names) return cls(code=code, args=func_kwargs)
<SYSTEM_TASK:> Function that returns a Python callback to pretty print the events. <END_TASK> <USER_TASK:> Description: def print_event(attributes=[]): """ Function that returns a Python callback to pretty print the events. """
def python_callback(event): cls_name = event.__class__.__name__ attrs = ', '.join(['{attr}={val}'.format(attr=attr, val=event.__dict__[attr]) for attr in attributes]) print('{cls_name}({attrs})'.format(cls_name=cls_name, attrs=attrs)) return python_callback
<SYSTEM_TASK:> Extracts a zip file to its containing directory. <END_TASK> <USER_TASK:> Description: def extract_zip(zip_name, exclude_term=None): """Extracts a zip file to its containing directory."""
zip_dir = os.path.dirname(os.path.abspath(zip_name)) try: with zipfile.ZipFile(zip_name) as z: # write each zipped file out if it isn't a directory files = [zip_file for zip_file in z.namelist() if not zip_file.endswith('/')] print('Extracting %i files from %r.' % (len(files), zip_name)) for zip_file in files: # remove any provided extra directory term from zip file if exclude_term: dest_file = zip_file.replace(exclude_term, '') else: dest_file = zip_file dest_file = os.path.normpath(os.path.join(zip_dir, dest_file)) dest_dir = os.path.dirname(dest_file) # make directory if it does not exist if not os.path.isdir(dest_dir): os.makedirs(dest_dir) # read file from zip, then write to new directory data = z.read(zip_file) with open(dest_file, 'wb') as f: f.write(encode_utf8(data)) except zipfile.error as e: print("Bad zipfile (%r): %s" % (zip_name, e)) raise e
<SYSTEM_TASK:> This should only be called by ``ServerConnection.unsubscribe_session`` or our book-keeping will be broken <END_TASK> <USER_TASK:> Description: def unsubscribe(self, connection): """This should only be called by ``ServerConnection.unsubscribe_session`` or our book-keeping will be broken"""
self._subscribed_connections.discard(connection) self._last_unsubscribe_time = current_time()
<SYSTEM_TASK:> Set shell current working directory. <END_TASK> <USER_TASK:> Description: def set_cwd(self, dirname): """Set shell current working directory."""
# Replace single for double backslashes on Windows if os.name == 'nt': dirname = dirname.replace(u"\\", u"\\\\") if not self.external_kernel: code = u"get_ipython().kernel.set_cwd(u'''{}''')".format(dirname) if self._reading: self.kernel_client.input(u'!' + code) else: self.silent_execute(code) self._cwd = dirname
<SYSTEM_TASK:> Set color scheme for matched parentheses. <END_TASK> <USER_TASK:> Description: def set_bracket_matcher_color_scheme(self, color_scheme): """Set color scheme for matched parentheses."""
bsh = sh.BaseSH(parent=self, color_scheme=color_scheme) mpcolor = bsh.get_matched_p_color() self._bracket_matcher.format.setBackground(mpcolor)
<SYSTEM_TASK:> Set color scheme of the shell. <END_TASK> <USER_TASK:> Description: def set_color_scheme(self, color_scheme, reset=True): """Set color scheme of the shell."""
self.set_bracket_matcher_color_scheme(color_scheme) self.style_sheet, dark_color = create_qss_style(color_scheme) self.syntax_style = color_scheme self._style_sheet_changed() self._syntax_style_changed() if reset: self.reset(clear=True) if not dark_color: self.silent_execute("%colors linux") else: self.silent_execute("%colors lightbg")
<SYSTEM_TASK:> Banner for IPython widgets with pylab message <END_TASK> <USER_TASK:> Description: def long_banner(self): """Banner for IPython widgets with pylab message"""
# Default banner try: from IPython.core.usage import quick_guide except Exception: quick_guide = '' banner_parts = [ 'Python %s\n' % self.interpreter_versions['python_version'], 'Type "copyright", "credits" or "license" for more information.\n\n', 'IPython %s -- An enhanced Interactive Python.\n' % \ self.interpreter_versions['ipython_version'], quick_guide ] banner = ''.join(banner_parts) # Pylab additions pylab_o = self.additional_options['pylab'] autoload_pylab_o = self.additional_options['autoload_pylab'] mpl_installed = programs.is_module_installed('matplotlib') if mpl_installed and (pylab_o and autoload_pylab_o): pylab_message = ("\nPopulating the interactive namespace from " "numpy and matplotlib\n") banner = banner + pylab_message # Sympy additions sympy_o = self.additional_options['sympy'] if sympy_o: lines = """ These commands were executed: >>> from __future__ import division >>> from sympy import * >>> x, y, z, t = symbols('x y z t') >>> k, m, n = symbols('k m n', integer=True) >>> f, g, h = symbols('f g h', cls=Function) """ banner = banner + lines if (pylab_o and sympy_o): lines = """ Warning: pylab (numpy and matplotlib) and symbolic math (sympy) are both enabled at the same time. Some pylab functions are going to be overrided by the sympy module (e.g. plot) """ banner = banner + lines return banner
<SYSTEM_TASK:> Reset the namespace by removing all names defined by the user. <END_TASK> <USER_TASK:> Description: def reset_namespace(self, warning=False, message=False): """Reset the namespace by removing all names defined by the user."""
reset_str = _("Remove all variables") warn_str = _("All user-defined variables will be removed. " "Are you sure you want to proceed?") kernel_env = self.kernel_manager._kernel_spec.env if warning: box = MessageCheckBox(icon=QMessageBox.Warning, parent=self) box.setWindowTitle(reset_str) box.set_checkbox_text(_("Don't show again.")) box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) box.setDefaultButton(QMessageBox.Yes) box.set_checked(False) box.set_check_visible(True) box.setText(warn_str) answer = box.exec_() # Update checkbox based on user interaction CONF.set('ipython_console', 'show_reset_namespace_warning', not box.is_checked()) self.ipyclient.reset_warning = not box.is_checked() if answer != QMessageBox.Yes: return try: if self._reading: self.dbg_exec_magic('reset', '-f') else: if message: self.reset() self._append_html(_("<br><br>Removing all variables..." "\n<hr>"), before_prompt=False) self.silent_execute("%reset -f") if kernel_env.get('SPY_AUTOLOAD_PYLAB_O') == 'True': self.silent_execute("from pylab import *") if kernel_env.get('SPY_SYMPY_O') == 'True': sympy_init = """ from __future__ import division from sympy import * x, y, z, t = symbols('x y z t') k, m, n = symbols('k m n', integer=True) f, g, h = symbols('f g h', cls=Function) init_printing()""" self.silent_execute(dedent(sympy_init)) if kernel_env.get('SPY_RUN_CYTHON') == 'True': self.silent_execute("%reload_ext Cython") self.refresh_namespacebrowser() if not self.external_kernel: self.silent_execute( 'get_ipython().kernel.close_all_mpl_figures()') except AttributeError: pass
<SYSTEM_TASK:> Create shortcuts for ipyconsole. <END_TASK> <USER_TASK:> Description: def create_shortcuts(self): """Create shortcuts for ipyconsole."""
inspect = config_shortcut(self._control.inspect_current_object, context='Console', name='Inspect current object', parent=self) clear_console = config_shortcut(self.clear_console, context='Console', name='Clear shell', parent=self) restart_kernel = config_shortcut(self.ipyclient.restart_kernel, context='ipython_console', name='Restart kernel', parent=self) new_tab = config_shortcut(lambda: self.new_client.emit(), context='ipython_console', name='new tab', parent=self) reset_namespace = config_shortcut(lambda: self._reset_namespace(), context='ipython_console', name='reset namespace', parent=self) array_inline = config_shortcut(self._control.enter_array_inline, context='array_builder', name='enter array inline', parent=self) array_table = config_shortcut(self._control.enter_array_table, context='array_builder', name='enter array table', parent=self) clear_line = config_shortcut(self.ipyclient.clear_line, context='console', name='clear line', parent=self) return [inspect, clear_console, restart_kernel, new_tab, reset_namespace, array_inline, array_table, clear_line]
<SYSTEM_TASK:> Execute code in the kernel without increasing the prompt <END_TASK> <USER_TASK:> Description: def silent_execute(self, code): """Execute code in the kernel without increasing the prompt"""
try: self.kernel_client.execute(to_text_string(code), silent=True) except AttributeError: pass
<SYSTEM_TASK:> Silently execute a kernel method and save its reply <END_TASK> <USER_TASK:> Description: def silent_exec_method(self, code): """Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a variable but instead replies that can be handled by ast.literal_eval. To get a value see `get_value` Parameters ---------- code : string Code that contains the kernel method as part of its string See Also -------- handle_exec_method : Method that deals with the reply Note ---- This is based on the _silent_exec_callback method of RichJupyterWidget. Therefore this is licensed BSD """
# Generate uuid, which would be used as an indication of whether or # not the unique request originated from here local_uuid = to_text_string(uuid.uuid1()) code = to_text_string(code) if self.kernel_client is None: return msg_id = self.kernel_client.execute('', silent=True, user_expressions={ local_uuid:code }) self._kernel_methods[local_uuid] = code self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'silent_exec_method')
<SYSTEM_TASK:> Handle data returned by silent executions of kernel methods <END_TASK> <USER_TASK:> Description: def handle_exec_method(self, msg): """ Handle data returned by silent executions of kernel methods This is based on the _handle_exec_callback of RichJupyterWidget. Therefore this is licensed BSD. """
user_exp = msg['content'].get('user_expressions') if not user_exp: return for expression in user_exp: if expression in self._kernel_methods: # Process kernel reply method = self._kernel_methods[expression] reply = user_exp[expression] data = reply.get('data') if 'get_namespace_view' in method: if data is not None and 'text/plain' in data: literal = ast.literal_eval(data['text/plain']) view = ast.literal_eval(literal) else: view = None self.sig_namespace_view.emit(view) elif 'get_var_properties' in method: if data is not None and 'text/plain' in data: literal = ast.literal_eval(data['text/plain']) properties = ast.literal_eval(literal) else: properties = None self.sig_var_properties.emit(properties) elif 'get_cwd' in method: if data is not None and 'text/plain' in data: self._cwd = ast.literal_eval(data['text/plain']) if PY2: self._cwd = encoding.to_unicode_from_fs(self._cwd) else: self._cwd = '' self.sig_change_cwd.emit(self._cwd) elif 'get_syspath' in method: if data is not None and 'text/plain' in data: syspath = ast.literal_eval(data['text/plain']) else: syspath = None self.sig_show_syspath.emit(syspath) elif 'get_env' in method: if data is not None and 'text/plain' in data: env = ast.literal_eval(data['text/plain']) else: env = None self.sig_show_env.emit(env) elif 'getattr' in method: if data is not None and 'text/plain' in data: is_spyder_kernel = data['text/plain'] if 'SpyderKernel' in is_spyder_kernel: self.sig_is_spykernel.emit(self) else: if data is not None and 'text/plain' in data: self._kernel_reply = ast.literal_eval(data['text/plain']) else: self._kernel_reply = None self.sig_got_reply.emit() # Remove method after being processed self._kernel_methods.pop(expression)
<SYSTEM_TASK:> Mayavi plots require the Qt backend, so we try to detect if one is <END_TASK> <USER_TASK:> Description: def set_backend_for_mayavi(self, command): """ Mayavi plots require the Qt backend, so we try to detect if one is generated to change backends """
calling_mayavi = False lines = command.splitlines() for l in lines: if not l.startswith('#'): if 'import mayavi' in l or 'from mayavi' in l: calling_mayavi = True break if calling_mayavi: message = _("Changing backend to Qt for Mayavi") self._append_plain_text(message + '\n') self.silent_execute("%gui inline\n%gui qt")
<SYSTEM_TASK:> If the user is trying to change Matplotlib backends with <END_TASK> <USER_TASK:> Description: def change_mpl_backend(self, command): """ If the user is trying to change Matplotlib backends with %matplotlib, send the same command again to the kernel to correctly change it. Fixes issue 4002 """
if command.startswith('%matplotlib') and \ len(command.splitlines()) == 1: if not 'inline' in command: self.silent_execute(command)
<SYSTEM_TASK:> Reimplement banner creation to let the user decide if he wants a <END_TASK> <USER_TASK:> Description: def _banner_default(self): """ Reimplement banner creation to let the user decide if he wants a banner or not """
# Don't change banner for external kernels if self.external_kernel: return '' show_banner_o = self.additional_options['show_banner'] if show_banner_o: return self.long_banner() else: return self.short_banner()
<SYSTEM_TASK:> Refresh the highlighting with the current syntax style by class. <END_TASK> <USER_TASK:> Description: def _syntax_style_changed(self): """Refresh the highlighting with the current syntax style by class."""
if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter._style = create_style_class(self.syntax_style) self._highlighter._clear_caches() else: self._highlighter.set_style_sheet(self.style_sheet)
<SYSTEM_TASK:> Emit a signal when the prompt is ready. <END_TASK> <USER_TASK:> Description: def _prompt_started_hook(self): """Emit a signal when the prompt is ready."""
if not self._reading: self._highlighter.highlighting_on = True self.sig_prompt_ready.emit()
<SYSTEM_TASK:> Removes all panel from the CodeEditor. <END_TASK> <USER_TASK:> Description: def clear(self): """Removes all panel from the CodeEditor."""
for i in range(4): while len(self._panels[i]): key = sorted(list(self._panels[i].keys()))[0] panel = self.remove(key) panel.setParent(None) panel.deleteLater()
<SYSTEM_TASK:> Find the definition of an object within a source closest to a given line <END_TASK> <USER_TASK:> Description: def get_definition_with_regex(source, token, start_line=-1): """ Find the definition of an object within a source closest to a given line """
if not token: return None if DEBUG_EDITOR: t0 = time.time() patterns = [ # python / cython keyword definitions r'^c?import.*\W{0}{1}', r'from.*\W{0}\W.*c?import ', r'from .* c?import.*\W{0}{1}', r'class\s*{0}{1}', r'c?p?def[^=]*\W{0}{1}', r'cdef.*\[.*\].*\W{0}{1}', # enaml keyword definitions r'enamldef.*\W{0}{1}', r'attr.*\W{0}{1}', r'event.*\W{0}{1}', r'id\s*:.*\W{0}{1}'] matches = get_matches(patterns, source, token, start_line) if not matches: patterns = [r'.*\Wself.{0}{1}[^=!<>]*=[^=]', r'.*\W{0}{1}[^=!<>]*=[^=]', r'self.{0}{1}[^=!<>]*=[^=]', r'{0}{1}[^=!<>]*=[^=]'] matches = get_matches(patterns, source, token, start_line) # find the one closest to the start line (prefer before the start line) if matches: min_dist = len(source.splitlines()) best_ind = 0 for match in matches: dist = abs(start_line - match) if match <= start_line or not best_ind: if dist < min_dist: min_dist = dist best_ind = match if matches: if DEBUG_EDITOR: log_dt(LOG_FILENAME, 'regex definition match', t0) return best_ind else: if DEBUG_EDITOR: log_dt(LOG_FILENAME, 'regex definition failed match', t0) return None
<SYSTEM_TASK:> Return a list of all python-like extensions <END_TASK> <USER_TASK:> Description: def python_like_exts(): """Return a list of all python-like extensions"""
exts = [] for lang in languages.PYTHON_LIKE_LANGUAGES: exts.extend(list(languages.ALL_LANGUAGES[lang])) return ['.' + ext for ext in exts]
<SYSTEM_TASK:> Get a formatted calltip and docstring from Fallback <END_TASK> <USER_TASK:> Description: def get_info(self, info): """Get a formatted calltip and docstring from Fallback"""
if info['docstring']: if info['filename']: filename = os.path.basename(info['filename']) filename = os.path.splitext(filename)[0] else: filename = '<module>' resp = dict(docstring=info['docstring'], name=filename, note='', argspec='', calltip=None) return resp else: return default_info_response()
<SYSTEM_TASK:> Return a sorted list of all the children items of 'item'. <END_TASK> <USER_TASK:> Description: def get_item_children(item): """Return a sorted list of all the children items of 'item'."""
children = [item.child(index) for index in range(item.childCount())] for child in children[:]: others = get_item_children(child) if others is not None: children += others return sorted(children, key=lambda child: child.line)
<SYSTEM_TASK:> Find and return the item of the outline explorer under which is located <END_TASK> <USER_TASK:> Description: def item_at_line(root_item, line): """ Find and return the item of the outline explorer under which is located the specified 'line' of the editor. """
previous_item = root_item item = root_item for item in get_item_children(root_item): if item.line > line: return previous_item previous_item = item else: return item
<SYSTEM_TASK:> File was renamed, updating outline explorer tree <END_TASK> <USER_TASK:> Description: def file_renamed(self, editor, new_filename): """File was renamed, updating outline explorer tree"""
if editor is None: # This is needed when we can't find an editor to attach # the outline explorer to. # Fix issue 8813 return editor_id = editor.get_id() if editor_id in list(self.editor_ids.values()): root_item = self.editor_items[editor_id] root_item.set_path(new_filename, fullpath=self.show_fullpath) self.__sort_toplevel_items()
<SYSTEM_TASK:> Order the root file items in the Outline Explorer following the <END_TASK> <USER_TASK:> Description: def set_editor_ids_order(self, ordered_editor_ids): """ Order the root file items in the Outline Explorer following the provided list of editor ids. """
if self.ordered_editor_ids != ordered_editor_ids: self.ordered_editor_ids = ordered_editor_ids if self.sort_files_alphabetically is False: self.__sort_toplevel_items()
<SYSTEM_TASK:> Sort the root file items in alphabetical order if <END_TASK> <USER_TASK:> Description: def __sort_toplevel_items(self): """ Sort the root file items in alphabetical order if 'sort_files_alphabetically' is True, else order the items as specified in the 'self.ordered_editor_ids' list. """
if self.show_all_files is False: return current_ordered_items = [self.topLevelItem(index) for index in range(self.topLevelItemCount())] if self.sort_files_alphabetically: new_ordered_items = sorted( current_ordered_items, key=lambda item: osp.basename(item.path.lower())) else: new_ordered_items = [ self.editor_items.get(e_id) for e_id in self.ordered_editor_ids if self.editor_items.get(e_id) is not None] if current_ordered_items != new_ordered_items: selected_items = self.selectedItems() self.save_expanded_state() for index in range(self.topLevelItemCount()): self.takeTopLevelItem(0) for index, item in enumerate(new_ordered_items): self.insertTopLevelItem(index, item) self.restore_expanded_state() self.clearSelection() if selected_items: selected_items[-1].setSelected(True)
<SYSTEM_TASK:> Return the root item of the specified item. <END_TASK> <USER_TASK:> Description: def get_root_item(self, item): """Return the root item of the specified item."""
root_item = item while isinstance(root_item.parent(), QTreeWidgetItem): root_item = root_item.parent() return root_item
<SYSTEM_TASK:> Return a list of all visible items in the treewidget. <END_TASK> <USER_TASK:> Description: def get_visible_items(self): """Return a list of all visible items in the treewidget."""
items = [] iterator = QTreeWidgetItemIterator(self) while iterator.value(): item = iterator.value() if not item.isHidden(): if item.parent(): if item.parent().isExpanded(): items.append(item) else: items.append(item) iterator += 1 return items
<SYSTEM_TASK:> Setup the buttons of the outline explorer widget toolbar. <END_TASK> <USER_TASK:> Description: def setup_buttons(self): """Setup the buttons of the outline explorer widget toolbar."""
self.fromcursor_btn = create_toolbutton( self, icon=ima.icon('fromcursor'), tip=_('Go to cursor position'), triggered=self.treewidget.go_to_cursor_position) buttons = [self.fromcursor_btn] for action in [self.treewidget.collapse_all_action, self.treewidget.expand_all_action, self.treewidget.restore_action, self.treewidget.collapse_selection_action, self.treewidget.expand_selection_action]: buttons.append(create_toolbutton(self)) buttons[-1].setDefaultAction(action) return buttons
<SYSTEM_TASK:> Uninstalls the editor extension from the editor. <END_TASK> <USER_TASK:> Description: def on_uninstall(self): """Uninstalls the editor extension from the editor."""
self._on_close = True self.enabled = False self._editor = None
<SYSTEM_TASK:> Get version information for components used by Spyder <END_TASK> <USER_TASK:> Description: def get_versions(reporev=True): """Get version information for components used by Spyder"""
import sys import platform import qtpy import qtpy.QtCore revision = None if reporev: from spyder.utils import vcs revision, branch = vcs.get_git_revision(os.path.dirname(__dir__)) if not sys.platform == 'darwin': # To avoid a crash with our Mac app system = platform.system() else: system = 'Darwin' return { 'spyder': __version__, 'python': platform.python_version(), # "2.7.3" 'bitness': 64 if sys.maxsize > 2**32 else 32, 'qt': qtpy.QtCore.__version__, 'qt_api': qtpy.API_NAME, # PyQt5 'qt_api_ver': qtpy.PYQT_VERSION, 'system': system, # Linux, Windows, ... 'release': platform.release(), # XP, 10.6, 2.2.0, etc. 'revision': revision, # '9fdf926eccce' }
<SYSTEM_TASK:> Return True is datatype dtype is a number kind <END_TASK> <USER_TASK:> Description: def is_number(dtype): """Return True is datatype dtype is a number kind"""
return is_float(dtype) or ('int' in dtype.name) or ('long' in dtype.name) \ or ('short' in dtype.name)
<SYSTEM_TASK:> Extract the boundaries from a list of indexes <END_TASK> <USER_TASK:> Description: def get_idx_rect(index_list): """Extract the boundaries from a list of indexes"""
rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list])) return ( min(rows), max(rows), min(cols), max(cols) )
<SYSTEM_TASK:> Create editor widget <END_TASK> <USER_TASK:> Description: def createEditor(self, parent, option, index): """Create editor widget"""
model = index.model() value = model.get_value(index) if model._data.dtype.name == "bool": value = not value model.setData(index, to_qvariant(value)) return elif value is not np.ma.masked: editor = QLineEdit(parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignCenter) if is_number(self.dtype): validator = QDoubleValidator(editor) validator.setLocale(QLocale('C')) editor.setValidator(validator) editor.returnPressed.connect(self.commitAndCloseEditor) return editor
<SYSTEM_TASK:> Commit and close editor <END_TASK> <USER_TASK:> Description: def commitAndCloseEditor(self): """Commit and close editor"""
editor = self.sender() # Avoid a segfault with PyQt5. Variable value won't be changed # but at least Spyder won't crash. It seems generated by a bug in sip. try: self.commitData.emit(editor) except AttributeError: pass self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint)
<SYSTEM_TASK:> Copy an array portion to a unicode string <END_TASK> <USER_TASK:> Description: def _sel_to_text(self, cell_range): """Copy an array portion to a unicode string"""
if not cell_range: return row_min, row_max, col_min, col_max = get_idx_rect(cell_range) if col_min == 0 and col_max == (self.model().cols_loaded-1): # we've selected a whole column. It isn't possible to # select only the first part of a column without loading more, # so we can treat it as intentional and copy the whole thing col_max = self.model().total_cols-1 if row_min == 0 and row_max == (self.model().rows_loaded-1): row_max = self.model().total_rows-1 _data = self.model().get_data() if PY3: output = io.BytesIO() else: output = io.StringIO() try: np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1], delimiter='\t', fmt=self.model().get_format()) except: QMessageBox.warning(self, _("Warning"), _("It was not possible to copy values for " "this array")) return contents = output.getvalue().decode('utf-8') output.close() return contents
<SYSTEM_TASK:> This is implemented for handling negative values in index for <END_TASK> <USER_TASK:> Description: def change_active_widget(self, index): """ This is implemented for handling negative values in index for 3d arrays, to give the same behavior as slicing """
string_index = [':']*3 string_index[self.last_dim] = '<font color=red>%i</font>' self.slicing_label.setText((r"Slicing: [" + ", ".join(string_index) + "]") % index) if index < 0: data_index = self.data.shape[self.last_dim] + index else: data_index = index slice_index = [slice(None)]*3 slice_index[self.last_dim] = data_index stack_index = self.dim_indexes[self.last_dim].get(data_index) if stack_index is None: stack_index = self.stack.count() try: self.stack.addWidget(ArrayEditorWidget( self, self.data[tuple(slice_index)])) except IndexError: # Handle arrays of size 0 in one axis self.stack.addWidget(ArrayEditorWidget(self, self.data)) self.dim_indexes[self.last_dim][data_index] = stack_index self.stack.update() self.stack.setCurrentIndex(stack_index)
<SYSTEM_TASK:> This change the active axis the array editor is plotting over <END_TASK> <USER_TASK:> Description: def current_dim_changed(self, index): """ This change the active axis the array editor is plotting over in 3D """
self.last_dim = index string_size = ['%i']*3 string_size[index] = '<font color=red>%i</font>' self.shape_label.setText(('Shape: (' + ', '.join(string_size) + ') ') % self.data.shape) if self.index_spin.value() != 0: self.index_spin.setValue(0) else: # this is done since if the value is currently 0 it does not emit # currentIndexChanged(int) self.change_active_widget(0) self.index_spin.setRange(-self.data.shape[index], self.data.shape[index]-1)
<SYSTEM_TASK:> An error occured, closing the dialog box <END_TASK> <USER_TASK:> Description: def error(self, message): """An error occured, closing the dialog box"""
QMessageBox.critical(self, _("Array editor"), message) self.setAttribute(Qt.WA_DeleteOnClose) self.reject()
<SYSTEM_TASK:> Get the keywords for a given lexer. <END_TASK> <USER_TASK:> Description: def get_keywords(lexer): """Get the keywords for a given lexer. """
if not hasattr(lexer, 'tokens'): return [] if 'keywords' in lexer.tokens: try: return lexer.tokens['keywords'][0][0].words except: pass keywords = [] for vals in lexer.tokens.values(): for val in vals: try: if isinstance(val[0], words): keywords.extend(val[0].words) else: ini_val = val[0] if ')\\b' in val[0] or ')(\\s+)' in val[0]: val = re.sub(r'\\.', '', val[0]) val = re.sub(r'[^0-9a-zA-Z|]+', '', val) if '|' in ini_val: keywords.extend(val.split('|')) else: keywords.append(val) except Exception: continue return keywords
<SYSTEM_TASK:> Extract all words from a source code file to be used in code completion. <END_TASK> <USER_TASK:> Description: def get_words(file_path=None, content=None, extension=None): """ Extract all words from a source code file to be used in code completion. Extract the list of words that contains the file in the editor, to carry out the inline completion similar to VSCode. """
if (file_path is None and (content is None or extension is None) or file_path and content and extension): error_msg = ('Must provide `file_path` or `content` and `extension`') raise Exception(error_msg) if file_path and content is None and extension is None: extension = os.path.splitext(file_path)[1] with open(file_path) as infile: content = infile.read() if extension in ['.css']: regex = re.compile(r'([^a-zA-Z-])') elif extension in ['.R', '.c', '.md', '.cpp', '.java', '.py']: regex = re.compile(r'([^a-zA-Z_])') else: regex = re.compile(r'([^a-zA-Z])') words = sorted(set(regex.sub(r' ', content).split())) return words
<SYSTEM_TASK:> Given a file path, determine the full module path. <END_TASK> <USER_TASK:> Description: def get_parent_until(path): """ Given a file path, determine the full module path. e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields 'numpy.core' """
dirname = osp.dirname(path) try: mod = osp.basename(path) mod = osp.splitext(mod)[0] imp.find_module(mod, [dirname]) except ImportError: return items = [mod] while 1: items.append(osp.basename(dirname)) try: dirname = osp.dirname(dirname) imp.find_module('__init__', [dirname + os.sep]) except ImportError: break return '.'.join(reversed(items))
<SYSTEM_TASK:> Load the user's previously-saved kernel connection settings. <END_TASK> <USER_TASK:> Description: def load_connection_settings(self): """Load the user's previously-saved kernel connection settings."""
existing_kernel = CONF.get("existing-kernel", "settings", {}) connection_file_path = existing_kernel.get("json_file_path", "") is_remote = existing_kernel.get("is_remote", False) username = existing_kernel.get("username", "") hostname = existing_kernel.get("hostname", "") port = str(existing_kernel.get("port", 22)) is_ssh_kf = existing_kernel.get("is_ssh_keyfile", False) ssh_kf = existing_kernel.get("ssh_key_file_path", "") if connection_file_path != "": self.cf.setText(connection_file_path) if username != "": self.un.setText(username) if hostname != "": self.hn.setText(hostname) if ssh_kf != "": self.kf.setText(ssh_kf) self.rm_group.setChecked(is_remote) self.pn.setText(port) self.kf_radio.setChecked(is_ssh_kf) self.pw_radio.setChecked(not is_ssh_kf) try: import keyring ssh_passphrase = keyring.get_password("spyder_remote_kernel", "ssh_key_passphrase") ssh_password = keyring.get_password("spyder_remote_kernel", "ssh_password") if ssh_passphrase: self.kfp.setText(ssh_passphrase) if ssh_password: self.pw.setText(ssh_password) except Exception: pass
<SYSTEM_TASK:> Save user's kernel connection settings. <END_TASK> <USER_TASK:> Description: def save_connection_settings(self): """Save user's kernel connection settings."""
if not self.save_layout.isChecked(): return is_ssh_key = bool(self.kf_radio.isChecked()) connection_settings = { "json_file_path": self.cf.text(), "is_remote": self.rm_group.isChecked(), "username": self.un.text(), "hostname": self.hn.text(), "port": self.pn.text(), "is_ssh_keyfile": is_ssh_key, "ssh_key_file_path": self.kf.text() } CONF.set("existing-kernel", "settings", connection_settings) try: import keyring if is_ssh_key: keyring.set_password("spyder_remote_kernel", "ssh_key_passphrase", self.kfp.text()) else: keyring.set_password("spyder_remote_kernel", "ssh_password", self.pw.text()) except Exception: pass
<SYSTEM_TASK:> Return color depending on value type <END_TASK> <USER_TASK:> Description: def get_color(value, alpha): """Return color depending on value type"""
color = QColor() for typ in COLORS: if isinstance(value, typ): color = QColor(COLORS[typ]) color.setAlphaF(alpha) return color
<SYSTEM_TASK:> Return the column separator <END_TASK> <USER_TASK:> Description: def get_col_sep(self): """Return the column separator"""
if self.tab_btn.isChecked(): return u"\t" elif self.ws_btn.isChecked(): return None return to_text_string(self.line_edt.text())
<SYSTEM_TASK:> Parse a type to an other type <END_TASK> <USER_TASK:> Description: def parse_data_type(self, index, **kwargs): """Parse a type to an other type"""
if not index.isValid(): return False try: if kwargs['atype'] == "date": self._data[index.row()][index.column()] = \ datestr_to_datetime(self._data[index.row()][index.column()], kwargs['dayfirst']).date() elif kwargs['atype'] == "perc": _tmp = self._data[index.row()][index.column()].replace("%", "") self._data[index.row()][index.column()] = eval(_tmp)/100. elif kwargs['atype'] == "account": _tmp = self._data[index.row()][index.column()].replace(",", "") self._data[index.row()][index.column()] = eval(_tmp) elif kwargs['atype'] == "unicode": self._data[index.row()][index.column()] = to_text_string( self._data[index.row()][index.column()]) elif kwargs['atype'] == "int": self._data[index.row()][index.column()] = int( self._data[index.row()][index.column()]) elif kwargs['atype'] == "float": self._data[index.row()][index.column()] = float( self._data[index.row()][index.column()]) self.dataChanged.emit(index, index) except Exception as instance: print(instance)
<SYSTEM_TASK:> Decode the shape of the given text <END_TASK> <USER_TASK:> Description: def _shape_text(self, text, colsep=u"\t", rowsep=u"\n", transpose=False, skiprows=0, comments='#'): """Decode the shape of the given text"""
assert colsep != rowsep out = [] text_rows = text.split(rowsep)[skiprows:] for row in text_rows: stripped = to_text_string(row).strip() if len(stripped) == 0 or stripped.startswith(comments): continue line = to_text_string(row).split(colsep) line = [try_to_parse(to_text_string(x)) for x in line] out.append(line) # Replace missing elements with np.nan's or None's if programs.is_module_installed('numpy'): from numpy import nan out = list(zip_longest(*out, fillvalue=nan)) else: out = list(zip_longest(*out, fillvalue=None)) # Tranpose the last result to get the expected one out = [[r[col] for r in out] for col in range(len(out[0]))] if transpose: return [[r[col] for r in out] for col in range(len(out[0]))] return out
<SYSTEM_TASK:> Put data into table model <END_TASK> <USER_TASK:> Description: def process_data(self, text, colsep=u"\t", rowsep=u"\n", transpose=False, skiprows=0, comments='#'): """Put data into table model"""
data = self._shape_text(text, colsep, rowsep, transpose, skiprows, comments) self._model = PreviewTableModel(data) self.setModel(self._model)
<SYSTEM_TASK:> Parse to a given type <END_TASK> <USER_TASK:> Description: def parse_to_type(self,**kwargs): """Parse to a given type"""
indexes = self.selectedIndexes() if not indexes: return for index in indexes: self.model().parse_data_type(index, **kwargs)
<SYSTEM_TASK:> Open clipboard text as table <END_TASK> <USER_TASK:> Description: def open_data(self, text, colsep=u"\t", rowsep=u"\n", transpose=False, skiprows=0, comments='#'): """Open clipboard text as table"""
if pd: self.pd_text = text self.pd_info = dict(sep=colsep, lineterminator=rowsep, skiprows=skiprows, comment=comments) if colsep is None: self.pd_info = dict(lineterminator=rowsep, skiprows=skiprows, comment=comments, delim_whitespace=True) self._table_view.process_data(text, colsep, rowsep, transpose, skiprows, comments)
<SYSTEM_TASK:> Reduce the alist dimension if needed <END_TASK> <USER_TASK:> Description: def _simplify_shape(self, alist, rec=0): """Reduce the alist dimension if needed"""
if rec != 0: if len(alist) == 1: return alist[-1] return alist if len(alist) == 1: return self._simplify_shape(alist[-1], 1) return [self._simplify_shape(al, 1) for al in alist]
<SYSTEM_TASK:> Set Spyder breakpoints into a debugging session <END_TASK> <USER_TASK:> Description: def set_spyder_breakpoints(self, force=False): """Set Spyder breakpoints into a debugging session"""
if self._reading or force: breakpoints_dict = CONF.get('run', 'breakpoints', {}) # We need to enclose pickled values in a list to be able to # send them to the kernel in Python 2 serialiazed_breakpoints = [pickle.dumps(breakpoints_dict, protocol=PICKLE_PROTOCOL)] breakpoints = to_text_string(serialiazed_breakpoints) cmd = u"!get_ipython().kernel._set_spyder_breakpoints({})" self.kernel_client.input(cmd.format(breakpoints))
<SYSTEM_TASK:> Refresh Variable Explorer and Editor from a Pdb session, <END_TASK> <USER_TASK:> Description: def refresh_from_pdb(self, pdb_state): """ Refresh Variable Explorer and Editor from a Pdb session, after running any pdb command. See publish_pdb_state and notify_spyder in spyder_kernels """
if 'step' in pdb_state and 'fname' in pdb_state['step']: fname = pdb_state['step']['fname'] lineno = pdb_state['step']['lineno'] self.sig_pdb_step.emit(fname, lineno) if 'namespace_view' in pdb_state: self.sig_namespace_view.emit(ast.literal_eval( pdb_state['namespace_view'])) if 'var_properties' in pdb_state: self.sig_var_properties.emit(ast.literal_eval( pdb_state['var_properties']))
<SYSTEM_TASK:> Returns the global maximum and minimum. <END_TASK> <USER_TASK:> Description: def global_max(col_vals, index): """Returns the global maximum and minimum."""
col_vals_without_None = [x for x in col_vals if x is not None] max_col, min_col = zip(*col_vals_without_None) return max(max_col), min(min_col)
<SYSTEM_TASK:> Return the values of the labels for the header of columns or rows. <END_TASK> <USER_TASK:> Description: def header(self, axis, x, level=0): """ Return the values of the labels for the header of columns or rows. The value corresponds to the header of column or row x in the given level. """
ax = self._axis(axis) return ax.values[x] if not hasattr(ax, 'levels') \ else ax.values[x][level]
<SYSTEM_TASK:> Background color depending on value. <END_TASK> <USER_TASK:> Description: def get_bgcolor(self, index): """Background color depending on value."""
column = index.column() if not self.bgcolor_enabled: return value = self.get_value(index.row(), column) if self.max_min_col[column] is None or isna(value): color = QColor(BACKGROUND_NONNUMBER_COLOR) if is_text_string(value): color.setAlphaF(BACKGROUND_STRING_ALPHA) else: color.setAlphaF(BACKGROUND_MISC_ALPHA) else: if isinstance(value, COMPLEX_NUMBER_TYPES): color_func = abs else: color_func = float vmax, vmin = self.return_max(self.max_min_col, column) hue = (BACKGROUND_NUMBER_MINHUE + BACKGROUND_NUMBER_HUERANGE * (vmax - color_func(value)) / (vmax - vmin)) hue = float(abs(hue)) if hue > 1: hue = 1 color = QColor.fromHsvF(hue, BACKGROUND_NUMBER_SATURATION, BACKGROUND_NUMBER_VALUE, BACKGROUND_NUMBER_ALPHA) return color
<SYSTEM_TASK:> Load more rows and columns to display. <END_TASK> <USER_TASK:> Description: def load_more_data(self, value, rows=False, columns=False): """Load more rows and columns to display."""
try: if rows and value == self.verticalScrollBar().maximum(): self.model().fetch_more(rows=rows) self.sig_fetch_more_rows.emit() if columns and value == self.horizontalScrollBar().maximum(): self.model().fetch_more(columns=columns) self.sig_fetch_more_columns.emit() except NameError: # Needed to handle a NameError while fetching data when closing # See issue 7880 pass
<SYSTEM_TASK:> A function that changes types of cells. <END_TASK> <USER_TASK:> Description: def change_type(self, func): """A function that changes types of cells."""
model = self.model() index_list = self.selectedIndexes() [model.setData(i, '', change_type=func) for i in index_list]
<SYSTEM_TASK:> Get number of rows in the header. <END_TASK> <USER_TASK:> Description: def rowCount(self, index=None): """Get number of rows in the header."""
if self.axis == 0: return max(1, self._shape[0]) else: if self.total_rows <= self.rows_loaded: return self.total_rows else: return self.rows_loaded
<SYSTEM_TASK:> Get the data for the header. <END_TASK> <USER_TASK:> Description: def data(self, index, role): """ Get the data for the header. This is used when a header has levels. """
if not index.isValid() or \ index.row() >= self._shape[0] or \ index.column() >= self._shape[1]: return None row, col = ((index.row(), index.column()) if self.axis == 0 else (index.column(), index.row())) if role != Qt.DisplayRole: return None if self.axis == 0 and self._shape[0] <= 1: return None header = self.model.header(self.axis, col, row) # Don't perform any conversion on strings # because it leads to differences between # the data present in the dataframe and # what is shown by Spyder if not is_type_text_string(header): header = to_text_string(header) return header
<SYSTEM_TASK:> Get the text to put in the header of the levels of the indexes. <END_TASK> <USER_TASK:> Description: def headerData(self, section, orientation, role): """ Get the text to put in the header of the levels of the indexes. By default it returns 'Index i', where i is the section in the index """
if role == Qt.TextAlignmentRole: if orientation == Qt.Horizontal: return Qt.AlignCenter | Qt.AlignBottom else: return Qt.AlignRight | Qt.AlignVCenter if role != Qt.DisplayRole and role != Qt.ToolTipRole: return None if self.model.header_shape[0] <= 1 and orientation == Qt.Horizontal: if self.model.name(1,section): return self.model.name(1,section) return _('Index') elif self.model.header_shape[0] <= 1: return None elif self.model.header_shape[1] <= 1 and orientation == Qt.Vertical: return None return _('Index') + ' ' + to_text_string(section)
<SYSTEM_TASK:> Get the information of the levels. <END_TASK> <USER_TASK:> Description: def data(self, index, role): """Get the information of the levels."""
if not index.isValid(): return None if role == Qt.FontRole: return self._font label = '' if index.column() == self.model.header_shape[1] - 1: label = str(self.model.name(0, index.row())) elif index.row() == self.model.header_shape[0] - 1: label = str(self.model.name(1, index.column())) if role == Qt.DisplayRole and label: return label elif role == Qt.ForegroundRole: return self._foreground elif role == Qt.BackgroundRole: return self._background elif role == Qt.BackgroundRole: return self._palette.window() return None
<SYSTEM_TASK:> Create the QTableView that will hold the level model. <END_TASK> <USER_TASK:> Description: def create_table_level(self): """Create the QTableView that will hold the level model."""
self.table_level = QTableView() self.table_level.setEditTriggers(QTableWidget.NoEditTriggers) self.table_level.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.table_level.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.table_level.setFrameStyle(QFrame.Plain) self.table_level.horizontalHeader().sectionResized.connect( self._index_resized) self.table_level.verticalHeader().sectionResized.connect( self._header_resized) self.table_level.setItemDelegate(QItemDelegate()) self.layout.addWidget(self.table_level, 0, 0) self.table_level.setContentsMargins(0, 0, 0, 0) self.table_level.horizontalHeader().sectionClicked.connect( self.sortByIndex)
<SYSTEM_TASK:> Create the QTableView that will hold the header model. <END_TASK> <USER_TASK:> Description: def create_table_header(self): """Create the QTableView that will hold the header model."""
self.table_header = QTableView() self.table_header.verticalHeader().hide() self.table_header.setEditTriggers(QTableWidget.NoEditTriggers) self.table_header.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.table_header.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.table_header.setHorizontalScrollMode(QTableView.ScrollPerPixel) self.table_header.setHorizontalScrollBar(self.hscroll) self.table_header.setFrameStyle(QFrame.Plain) self.table_header.horizontalHeader().sectionResized.connect( self._column_resized) self.table_header.setItemDelegate(QItemDelegate()) self.layout.addWidget(self.table_header, 0, 1)
<SYSTEM_TASK:> Create the QTableView that will hold the index model. <END_TASK> <USER_TASK:> Description: def create_table_index(self): """Create the QTableView that will hold the index model."""
self.table_index = QTableView() self.table_index.horizontalHeader().hide() self.table_index.setEditTriggers(QTableWidget.NoEditTriggers) self.table_index.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.table_index.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.table_index.setVerticalScrollMode(QTableView.ScrollPerPixel) self.table_index.setVerticalScrollBar(self.vscroll) self.table_index.setFrameStyle(QFrame.Plain) self.table_index.verticalHeader().sectionResized.connect( self._row_resized) self.table_index.setItemDelegate(QItemDelegate()) self.layout.addWidget(self.table_index, 1, 0) self.table_index.setContentsMargins(0, 0, 0, 0)
<SYSTEM_TASK:> Create the QTableView that will hold the data model. <END_TASK> <USER_TASK:> Description: def create_data_table(self): """Create the QTableView that will hold the data model."""
self.dataTable = DataFrameView(self, self.dataModel, self.table_header.horizontalHeader(), self.hscroll, self.vscroll) self.dataTable.verticalHeader().hide() self.dataTable.horizontalHeader().hide() self.dataTable.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.dataTable.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.dataTable.setHorizontalScrollMode(QTableView.ScrollPerPixel) self.dataTable.setVerticalScrollMode(QTableView.ScrollPerPixel) self.dataTable.setFrameStyle(QFrame.Plain) self.dataTable.setItemDelegate(QItemDelegate()) self.layout.addWidget(self.dataTable, 1, 1) self.setFocusProxy(self.dataTable) self.dataTable.sig_sort_by_column.connect(self._sort_update) self.dataTable.sig_fetch_more_columns.connect(self._fetch_more_columns) self.dataTable.sig_fetch_more_rows.connect(self._fetch_more_rows)
<SYSTEM_TASK:> Update the column width. <END_TASK> <USER_TASK:> Description: def _column_resized(self, col, old_width, new_width): """Update the column width."""
self.dataTable.setColumnWidth(col, new_width) self._update_layout()
<SYSTEM_TASK:> Update the row height. <END_TASK> <USER_TASK:> Description: def _row_resized(self, row, old_height, new_height): """Update the row height."""
self.dataTable.setRowHeight(row, new_height) self._update_layout()
<SYSTEM_TASK:> Resize the corresponding column of the index section selected. <END_TASK> <USER_TASK:> Description: def _index_resized(self, col, old_width, new_width): """Resize the corresponding column of the index section selected."""
self.table_index.setColumnWidth(col, new_width) self._update_layout()
<SYSTEM_TASK:> Resize the corresponding row of the header section selected. <END_TASK> <USER_TASK:> Description: def _header_resized(self, row, old_height, new_height): """Resize the corresponding row of the header section selected."""
self.table_header.setRowHeight(row, new_height) self._update_layout()
<SYSTEM_TASK:> Resize a column by its contents. <END_TASK> <USER_TASK:> Description: def _resizeColumnToContents(self, header, data, col, limit_ms): """Resize a column by its contents."""
hdr_width = self._sizeHintForColumn(header, col, limit_ms) data_width = self._sizeHintForColumn(data, col, limit_ms) if data_width > hdr_width: width = min(self.max_width, data_width) elif hdr_width > data_width * 2: width = max(min(hdr_width, self.min_trunc), min(self.max_width, data_width)) else: width = max(min(self.max_width, hdr_width), self.min_trunc) header.setColumnWidth(col, width)
<SYSTEM_TASK:> Resize all the colummns to its contents. <END_TASK> <USER_TASK:> Description: def _resizeColumnsToContents(self, header, data, limit_ms): """Resize all the colummns to its contents."""
max_col = data.model().columnCount() if limit_ms is None: max_col_ms = None else: max_col_ms = limit_ms / max(1, max_col) for col in range(max_col): self._resizeColumnToContents(header, data, col, max_col_ms)
<SYSTEM_TASK:> Override eventFilter to catch resize event. <END_TASK> <USER_TASK:> Description: def eventFilter(self, obj, event): """Override eventFilter to catch resize event."""
if obj == self.dataTable and event.type() == QEvent.Resize: self._resizeVisibleColumnsToContents() return False