_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q280100
FrontendWidget._prompt_finished_hook
test
def _prompt_finished_hook(self): """ Called immediately after a prompt is finished, i.e. when some input will be processed and a new prompt displayed. """ # Flush all state from the input splitter so the next round of # reading input starts with a clean buffer. self._input_splitter.reset() if not self._reading: self._highlighter.highlighting_on = False
python
{ "resource": "" }
q280101
FrontendWidget._tab_pressed
test
def _tab_pressed(self): """ Called when the tab key is pressed. Returns whether to continue processing the event. """ # Perform tab completion if: # 1) The cursor is in the input buffer. # 2) There is a non-whitespace character before the cursor. text = self._get_input_buffer_cursor_line() if text is None: return False complete = bool(text[:self._get_input_buffer_cursor_column()].strip()) if complete: self._complete() return not complete
python
{ "resource": "" }
q280102
FrontendWidget._context_menu_make
test
def _context_menu_make(self, pos): """ Reimplemented to add an action for raw copy. """ menu = super(FrontendWidget, self)._context_menu_make(pos) for before_action in menu.actions(): if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \ QtGui.QKeySequence.ExactMatch: menu.insertAction(before_action, self._copy_raw_action) break return menu
python
{ "resource": "" }
q280103
FrontendWidget._event_filter_console_keypress
test
def _event_filter_console_keypress(self, event): """ Reimplemented for execution interruption and smart backspace. """ key = event.key() if self._control_key_down(event.modifiers(), include_command=False): if key == QtCore.Qt.Key_C and self._executing: self.request_interrupt_kernel() return True elif key == QtCore.Qt.Key_Period: self.request_restart_kernel() return True elif not event.modifiers() & QtCore.Qt.AltModifier: # Smart backspace: remove four characters in one backspace if: # 1) everything left of the cursor is whitespace # 2) the four characters immediately left of the cursor are spaces if key == QtCore.Qt.Key_Backspace: col = self._get_input_buffer_cursor_column() cursor = self._control.textCursor() if col > 3 and not cursor.hasSelection(): text = self._get_input_buffer_cursor_line()[:col] if text.endswith(' ') and not text.strip(): cursor.movePosition(QtGui.QTextCursor.Left, QtGui.QTextCursor.KeepAnchor, 4) cursor.removeSelectedText() return True return super(FrontendWidget, self)._event_filter_console_keypress(event)
python
{ "resource": "" }
q280104
FrontendWidget._insert_continuation_prompt
test
def _insert_continuation_prompt(self, cursor): """ Reimplemented for auto-indentation. """ super(FrontendWidget, self)._insert_continuation_prompt(cursor) cursor.insertText(' ' * self._input_splitter.indent_spaces)
python
{ "resource": "" }
q280105
FrontendWidget._handle_complete_reply
test
def _handle_complete_reply(self, rep): """ Handle replies for tab completion. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): text = '.'.join(self._get_context()) cursor.movePosition(QtGui.QTextCursor.Left, n=len(text)) self._complete_with_items(cursor, rep['content']['matches'])
python
{ "resource": "" }
q280106
FrontendWidget._silent_exec_callback
test
def _silent_exec_callback(self, expr, callback): """Silently execute `expr` in the kernel and call `callback` with reply the `expr` is evaluated silently in the kernel (without) output in the frontend. Call `callback` with the `repr <http://docs.python.org/library/functions.html#repr> `_ as first argument Parameters ---------- expr : string valid string to be executed by the kernel. callback : function function accepting one argument, as a string. The string will be the `repr` of the result of evaluating `expr` The `callback` is called with the `repr()` of the result of `expr` as first argument. To get the object, do `eval()` on the passed value. See Also -------- _handle_exec_callback : private method, deal with calling callback with reply """ # generate uuid, which would be used as an indication of whether or # not the unique request originated from here (can use msg id ?) local_uuid = str(uuid.uuid1()) msg_id = self.kernel_manager.shell_channel.execute('', silent=True, user_expressions={ local_uuid:expr }) self._callback_dict[local_uuid] = callback self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'silent_exec_callback')
python
{ "resource": "" }
q280107
FrontendWidget._handle_exec_callback
test
def _handle_exec_callback(self, msg): """Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback`` Parameters ---------- msg : raw message send by the kernel containing an `user_expressions` and having a 'silent_exec_callback' kind. Notes ----- This function will look for a `callback` associated with the corresponding message id. Association has been made by `_silent_exec_callback`. `callback` is then called with the `repr()` of the value of corresponding `user_expressions` as argument. `callback` is then removed from the known list so that any message coming again with the same id won't trigger it. """ user_exp = msg['content'].get('user_expressions') if not user_exp: return for expression in user_exp: if expression in self._callback_dict: self._callback_dict.pop(expression)(user_exp[expression])
python
{ "resource": "" }
q280108
FrontendWidget._handle_execute_reply
test
def _handle_execute_reply(self, msg): """ Handles replies for code execution. """ self.log.debug("execute: %s", msg.get('content', '')) msg_id = msg['parent_header']['msg_id'] info = self._request_info['execute'].get(msg_id) # unset reading flag, because if execute finished, raw_input can't # still be pending. self._reading = False if info and info.kind == 'user' and not self._hidden: # Make sure that all output from the SUB channel has been processed # before writing a new prompt. self.kernel_manager.sub_channel.flush() # Reset the ANSI style information to prevent bad text in stdout # from messing up our colors. We're not a true terminal so we're # allowed to do this. if self.ansi_codes: self._ansi_processor.reset_sgr() content = msg['content'] status = content['status'] if status == 'ok': self._process_execute_ok(msg) elif status == 'error': self._process_execute_error(msg) elif status == 'aborted': self._process_execute_abort(msg) self._show_interpreter_prompt_for_reply(msg) self.executed.emit(msg) self._request_info['execute'].pop(msg_id) elif info and info.kind == 'silent_exec_callback' and not self._hidden: self._handle_exec_callback(msg) self._request_info['execute'].pop(msg_id) else: super(FrontendWidget, self)._handle_execute_reply(msg)
python
{ "resource": "" }
q280109
FrontendWidget._handle_input_request
test
def _handle_input_request(self, msg): """ Handle requests for raw_input. """ self.log.debug("input: %s", msg.get('content', '')) if self._hidden: raise RuntimeError('Request for raw input during hidden execution.') # Make sure that all output from the SUB channel has been processed # before entering readline mode. self.kernel_manager.sub_channel.flush() def callback(line): self.kernel_manager.stdin_channel.input(line) if self._reading: self.log.debug("Got second input request, assuming first was interrupted.") self._reading = False self._readline(msg['content']['prompt'], callback=callback)
python
{ "resource": "" }
q280110
FrontendWidget._handle_kernel_died
test
def _handle_kernel_died(self, since_last_heartbeat): """ Handle the kernel's death by asking if the user wants to restart. """ self.log.debug("kernel died: %s", since_last_heartbeat) if self.custom_restart: self.custom_restart_kernel_died.emit(since_last_heartbeat) else: message = 'The kernel heartbeat has been inactive for %.2f ' \ 'seconds. Do you want to restart the kernel? You may ' \ 'first want to check the network connection.' % \ since_last_heartbeat self.restart_kernel(message, now=True)
python
{ "resource": "" }
q280111
FrontendWidget._handle_object_info_reply
test
def _handle_object_info_reply(self, rep): """ Handle replies for call tips. """ self.log.debug("oinfo: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('call_tip') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): # Get the information for a call tip. For now we format the call # line as string, later we can pass False to format_call and # syntax-highlight it ourselves for nicer formatting in the # calltip. content = rep['content'] # if this is from pykernel, 'docstring' will be the only key if content.get('ismagic', False): # Don't generate a call-tip for magics. Ideally, we should # generate a tooltip, but not on ( like we do for actual # callables. call_info, doc = None, None else: call_info, doc = call_tip(content, format_call=True) if call_info or doc: self._call_tip_widget.show_call_info(call_info, doc)
python
{ "resource": "" }
q280112
FrontendWidget._handle_pyout
test
def _handle_pyout(self, msg): """ Handle display hook output. """ self.log.debug("pyout: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): text = msg['content']['data'] self._append_plain_text(text + '\n', before_prompt=True)
python
{ "resource": "" }
q280113
FrontendWidget._handle_stream
test
def _handle_stream(self, msg): """ Handle stdout, stderr, and stdin. """ self.log.debug("stream: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): # Most consoles treat tabs as being 8 space characters. Convert tabs # to spaces so that output looks as expected regardless of this # widget's tab width. text = msg['content']['data'].expandtabs(8) self._append_plain_text(text, before_prompt=True) self._control.moveCursor(QtGui.QTextCursor.End)
python
{ "resource": "" }
q280114
FrontendWidget._handle_shutdown_reply
test
def _handle_shutdown_reply(self, msg): """ Handle shutdown signal, only if from other console. """ self.log.debug("shutdown: %s", msg.get('content', '')) if not self._hidden and not self._is_from_this_session(msg): if self._local_kernel: if not msg['content']['restart']: self.exit_requested.emit(self) else: # we just got notified of a restart! time.sleep(0.25) # wait 1/4 sec to reset # lest the request for a new prompt # goes to the old kernel self.reset() else: # remote kernel, prompt on Kernel shutdown/reset title = self.window().windowTitle() if not msg['content']['restart']: reply = QtGui.QMessageBox.question(self, title, "Kernel has been shutdown permanently. " "Close the Console?", QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: self.exit_requested.emit(self) else: # XXX: remove message box in favor of using the # clear_on_kernel_restart setting? reply = QtGui.QMessageBox.question(self, title, "Kernel has been reset. Clear the Console?", QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: time.sleep(0.25) # wait 1/4 sec to reset # lest the request for a new prompt # goes to the old kernel self.reset()
python
{ "resource": "" }
q280115
FrontendWidget.execute_file
test
def execute_file(self, path, hidden=False): """ Attempts to execute file with 'path'. If 'hidden', no output is shown. """ self.execute('execfile(%r)' % path, hidden=hidden)
python
{ "resource": "" }
q280116
FrontendWidget.interrupt_kernel
test
def interrupt_kernel(self): """ Attempts to interrupt the running kernel. Also unsets _reading flag, to avoid runtime errors if raw_input is called again. """ if self.custom_interrupt: self._reading = False self.custom_interrupt_requested.emit() elif self.kernel_manager.has_kernel: self._reading = False self.kernel_manager.interrupt_kernel() else: self._append_plain_text('Kernel process is either remote or ' 'unspecified. Cannot interrupt.\n')
python
{ "resource": "" }
q280117
FrontendWidget.reset
test
def reset(self, clear=False): """ Resets the widget to its initial state if ``clear`` parameter or ``clear_on_kernel_restart`` configuration setting is True, otherwise prints a visual indication of the fact that the kernel restarted, but does not clear the traces from previous usage of the kernel before it was restarted. With ``clear=True``, it is similar to ``%clear``, but also re-writes the banner and aborts execution if necessary. """ if self._executing: self._executing = False self._request_info['execute'] = {} self._reading = False self._highlighter.highlighting_on = False if self.clear_on_kernel_restart or clear: self._control.clear() self._append_plain_text(self.banner) else: self._append_plain_text("# restarting kernel...") self._append_html("<hr><br>") # XXX: Reprinting the full banner may be too much, but once #1680 is # addressed, that will mitigate it. #self._append_plain_text(self.banner) # update output marker for stdout/stderr, so that startup # messages appear after banner: self._append_before_prompt_pos = self._get_cursor().position() self._show_interpreter_prompt()
python
{ "resource": "" }
q280118
FrontendWidget.restart_kernel
test
def restart_kernel(self, message, now=False): """ Attempts to restart the running kernel. """ # FIXME: now should be configurable via a checkbox in the dialog. Right # now at least the heartbeat path sets it to True and the manual restart # to False. But those should just be the pre-selected states of a # checkbox that the user could override if so desired. But I don't know # enough Qt to go implementing the checkbox now. if self.custom_restart: self.custom_restart_requested.emit() elif self.kernel_manager.has_kernel: # Pause the heart beat channel to prevent further warnings. self.kernel_manager.hb_channel.pause() # Prompt the user to restart the kernel. Un-pause the heartbeat if # they decline. (If they accept, the heartbeat will be un-paused # automatically when the kernel is restarted.) if self.confirm_restart: buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No result = QtGui.QMessageBox.question(self, 'Restart kernel?', message, buttons) do_restart = result == QtGui.QMessageBox.Yes else: # confirm_restart is False, so we don't need to ask user # anything, just do the restart do_restart = True if do_restart: try: self.kernel_manager.restart_kernel(now=now) except RuntimeError: self._append_plain_text('Kernel started externally. ' 'Cannot restart.\n', before_prompt=True ) else: self.reset() else: self.kernel_manager.hb_channel.unpause() else: self._append_plain_text('Kernel process is either remote or ' 'unspecified. Cannot restart.\n', before_prompt=True )
python
{ "resource": "" }
q280119
FrontendWidget._call_tip
test
def _call_tip(self): """ Shows a call tip, if appropriate, at the current cursor location. """ # Decide if it makes sense to show a call tip if not self.enable_calltips: return False cursor = self._get_cursor() cursor.movePosition(QtGui.QTextCursor.Left) if cursor.document().characterAt(cursor.position()) != '(': return False context = self._get_context(cursor) if not context: return False # Send the metadata request to the kernel name = '.'.join(context) msg_id = self.kernel_manager.shell_channel.object_info(name) pos = self._get_cursor().position() self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos) return True
python
{ "resource": "" }
q280120
FrontendWidget._complete
test
def _complete(self): """ Performs completion at the current cursor location. """ context = self._get_context() if context: # Send the completion request to the kernel msg_id = self.kernel_manager.shell_channel.complete( '.'.join(context), # text self._get_input_buffer_cursor_line(), # line self._get_input_buffer_cursor_column(), # cursor_pos self.input_buffer) # block pos = self._get_cursor().position() info = self._CompletionRequest(msg_id, pos) self._request_info['complete'] = info
python
{ "resource": "" }
q280121
FrontendWidget._process_execute_error
test
def _process_execute_error(self, msg): """ Process a reply for an execution request that resulted in an error. """ content = msg['content'] # If a SystemExit is passed along, this means exit() was called - also # all the ipython %exit magic syntax of '-k' to be used to keep # the kernel running if content['ename']=='SystemExit': keepkernel = content['evalue']=='-k' or content['evalue']=='True' self._keep_kernel_on_exit = keepkernel self.exit_requested.emit(self) else: traceback = ''.join(content['traceback']) self._append_plain_text(traceback)
python
{ "resource": "" }
q280122
FrontendWidget._process_execute_ok
test
def _process_execute_ok(self, msg): """ Process a reply for a successful execution request. """ payload = msg['content']['payload'] for item in payload: if not self._process_execute_payload(item): warning = 'Warning: received unknown payload of type %s' print(warning % repr(item['source']))
python
{ "resource": "" }
q280123
FrontendWidget._document_contents_change
test
def _document_contents_change(self, position, removed, added): """ Called whenever the document's content changes. Display a call tip if appropriate. """ # Calculate where the cursor should be *after* the change: position += added document = self._control.document() if position == self._get_cursor().position(): self._call_tip()
python
{ "resource": "" }
q280124
PluginProxy.addPlugin
test
def addPlugin(self, plugin, call): """Add plugin to my list of plugins to call, if it has the attribute I'm bound to. """ meth = getattr(plugin, call, None) if meth is not None: if call == 'loadTestsFromModule' and \ len(inspect.getargspec(meth)[0]) == 2: orig_meth = meth meth = lambda module, path, **kwargs: orig_meth(module) self.plugins.append((plugin, meth))
python
{ "resource": "" }
q280125
PluginProxy.chain
test
def chain(self, *arg, **kw): """Call plugins in a chain, where the result of each plugin call is sent to the next plugin as input. The final output result is returned. """ result = None # extract the static arguments (if any) from arg so they can # be passed to each plugin call in the chain static = [a for (static, a) in zip(getattr(self.method, 'static_args', []), arg) if static] for p, meth in self.plugins: result = meth(*arg, **kw) arg = static[:] arg.append(result) return result
python
{ "resource": "" }
q280126
PluginProxy.generate
test
def generate(self, *arg, **kw): """Call all plugins, yielding each item in each non-None result. """ for p, meth in self.plugins: result = None try: result = meth(*arg, **kw) if result is not None: for r in result: yield r except (KeyboardInterrupt, SystemExit): raise except: exc = sys.exc_info() yield Failure(*exc) continue
python
{ "resource": "" }
q280127
PluginProxy.simple
test
def simple(self, *arg, **kw): """Call all plugins, returning the first non-None result. """ for p, meth in self.plugins: result = meth(*arg, **kw) if result is not None: return result
python
{ "resource": "" }
q280128
PluginManager.configure
test
def configure(self, options, config): """Configure the set of plugins with the given options and config instance. After configuration, disabled plugins are removed from the plugins list. """ log.debug("Configuring plugins") self.config = config cfg = PluginProxy('configure', self._plugins) cfg(options, config) enabled = [plug for plug in self._plugins if plug.enabled] self.plugins = enabled self.sort() log.debug("Plugins enabled: %s", enabled)
python
{ "resource": "" }
q280129
EntryPointPluginManager.loadPlugins
test
def loadPlugins(self): """Load plugins by iterating the `nose.plugins` entry point. """ from pkg_resources import iter_entry_points loaded = {} for entry_point, adapt in self.entry_points: for ep in iter_entry_points(entry_point): if ep.name in loaded: continue loaded[ep.name] = True log.debug('%s load plugin %s', self.__class__.__name__, ep) try: plugcls = ep.load() except KeyboardInterrupt: raise except Exception, e: # never want a plugin load to kill the test run # but we can't log here because the logger is not yet # configured warn("Unable to load plugin %s: %s" % (ep, e), RuntimeWarning) continue if adapt: plug = adapt(plugcls()) else: plug = plugcls() self.addPlugin(plug) super(EntryPointPluginManager, self).loadPlugins()
python
{ "resource": "" }
q280130
BuiltinPluginManager.loadPlugins
test
def loadPlugins(self): """Load plugins in nose.plugins.builtin """ from nose.plugins import builtin for plug in builtin.plugins: self.addPlugin(plug()) super(BuiltinPluginManager, self).loadPlugins()
python
{ "resource": "" }
q280131
latex_to_png
test
def latex_to_png(s, encode=False, backend='mpl'): """Render a LaTeX string to PNG. Parameters ---------- s : str The raw string containing valid inline LaTeX. encode : bool, optional Should the PNG data bebase64 encoded to make it JSON'able. backend : {mpl, dvipng} Backend for producing PNG data. None is returned when the backend cannot be used. """ if backend == 'mpl': f = latex_to_png_mpl elif backend == 'dvipng': f = latex_to_png_dvipng else: raise ValueError('No such backend {0}'.format(backend)) bin_data = f(s) if encode and bin_data: bin_data = encodestring(bin_data) return bin_data
python
{ "resource": "" }
q280132
latex_to_html
test
def latex_to_html(s, alt='image'): """Render LaTeX to HTML with embedded PNG data using data URIs. Parameters ---------- s : str The raw string containing valid inline LateX. alt : str The alt text to use for the HTML. """ base64_data = latex_to_png(s, encode=True) if base64_data: return _data_uri_template_png % (base64_data, alt)
python
{ "resource": "" }
q280133
math_to_image
test
def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None): """ Given a math expression, renders it in a closely-clipped bounding box to an image file. *s* A math expression. The math portion should be enclosed in dollar signs. *filename_or_obj* A filepath or writable file-like object to write the image data to. *prop* If provided, a FontProperties() object describing the size and style of the text. *dpi* Override the output dpi, otherwise use the default associated with the output format. *format* The output format, eg. 'svg', 'pdf', 'ps' or 'png'. If not provided, will be deduced from the filename. """ from matplotlib import figure # backend_agg supports all of the core output formats from matplotlib.backends import backend_agg from matplotlib.font_manager import FontProperties from matplotlib.mathtext import MathTextParser if prop is None: prop = FontProperties() parser = MathTextParser('path') width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop) fig = figure.Figure(figsize=(width / 72.0, height / 72.0)) fig.text(0, depth/height, s, fontproperties=prop) backend_agg.FigureCanvasAgg(fig) fig.savefig(filename_or_obj, dpi=dpi, format=format) return depth
python
{ "resource": "" }
q280134
InstallRequirement.check_if_exists
test
def check_if_exists(self): """Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.conflicts_with appropriately.""" if self.req is None: return False try: self.satisfied_by = pkg_resources.get_distribution(self.req) except pkg_resources.DistributionNotFound: return False except pkg_resources.VersionConflict: existing_dist = pkg_resources.get_distribution(self.req.project_name) if self.use_user_site: if dist_in_usersite(existing_dist): self.conflicts_with = existing_dist elif running_under_virtualenv() and dist_in_site_packages(existing_dist): raise InstallationError("Will not install to the user site because it will lack sys.path precedence to %s in %s" %(existing_dist.project_name, existing_dist.location)) else: self.conflicts_with = existing_dist return True
python
{ "resource": "" }
q280135
process_iter
test
def process_iter(): """Return a generator yielding a Process class instance for all running processes on the local machine. Every new Process instance is only created once and then cached into an internal table which is updated every time this is used. The sorting order in which processes are yielded is based on their PIDs. """ def add(pid): proc = Process(pid) _pmap[proc.pid] = proc return proc def remove(pid): _pmap.pop(pid, None) a = set(get_pid_list()) b = set(_pmap.keys()) new_pids = a - b gone_pids = b - a for pid in gone_pids: remove(pid) for pid, proc in sorted(list(_pmap.items()) + \ list(dict.fromkeys(new_pids).items())): try: if proc is None: # new process yield add(pid) else: # use is_running() to check whether PID has been reused by # another process in which case yield a new Process instance if proc.is_running(): yield proc else: yield add(pid) except NoSuchProcess: remove(pid) except AccessDenied: # Process creation time can't be determined hence there's # no way to tell whether the pid of the cached process # has been reused. Just return the cached version. yield proc
python
{ "resource": "" }
q280136
cpu_percent
test
def cpu_percent(interval=0.1, percpu=False): """Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls. """ global _last_cpu_times global _last_per_cpu_times blocking = interval is not None and interval > 0.0 def calculate(t1, t2): t1_all = sum(t1) t1_busy = t1_all - t1.idle t2_all = sum(t2) t2_busy = t2_all - t2.idle # this usually indicates a float precision issue if t2_busy <= t1_busy: return 0.0 busy_delta = t2_busy - t1_busy all_delta = t2_all - t1_all busy_perc = (busy_delta / all_delta) * 100 return round(busy_perc, 1) # system-wide usage if not percpu: if blocking: t1 = cpu_times() time.sleep(interval) else: t1 = _last_cpu_times _last_cpu_times = cpu_times() return calculate(t1, _last_cpu_times) # per-cpu usage else: ret = [] if blocking: tot1 = cpu_times(percpu=True) time.sleep(interval) else: tot1 = _last_per_cpu_times _last_per_cpu_times = cpu_times(percpu=True) for t1, t2 in zip(tot1, _last_per_cpu_times): ret.append(calculate(t1, t2)) return ret
python
{ "resource": "" }
q280137
Process.as_dict
test
def as_dict(self, attrs=[], ad_value=None): """Utility method returning process information as a hashable dictionary. If 'attrs' is specified it must be a list of strings reflecting available Process class's attribute names (e.g. ['get_cpu_times', 'name']) else all public (read only) attributes are assumed. 'ad_value' is the value which gets assigned to a dict key in case AccessDenied exception is raised when retrieving that particular process information. """ excluded_names = set(['send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait', 'is_running', 'as_dict', 'parent', 'get_children', 'nice']) retdict = dict() for name in set(attrs or dir(self)): if name.startswith('_'): continue if name.startswith('set_'): continue if name in excluded_names: continue try: attr = getattr(self, name) if callable(attr): if name == 'get_cpu_percent': ret = attr(interval=0) else: ret = attr() else: ret = attr except AccessDenied: ret = ad_value except NotImplementedError: # in case of not implemented functionality (may happen # on old or exotic systems) we want to crash only if # the user explicitly asked for that particular attr if attrs: raise continue if name.startswith('get'): if name[3] == '_': name = name[4:] elif name == 'getcwd': name = 'cwd' retdict[name] = ret return retdict
python
{ "resource": "" }
q280138
Process.name
test
def name(self): """The process name.""" name = self._platform_impl.get_process_name() if os.name == 'posix': # On UNIX the name gets truncated to the first 15 characters. # If it matches the first part of the cmdline we return that # one instead because it's usually more explicative. # Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon". try: cmdline = self.cmdline except AccessDenied: pass else: if cmdline: extended_name = os.path.basename(cmdline[0]) if extended_name.startswith(name): name = extended_name # XXX - perhaps needs refactoring self._platform_impl._process_name = name return name
python
{ "resource": "" }
q280139
Process.exe
test
def exe(self): """The process executable path. May also be an empty string.""" def guess_it(fallback): # try to guess exe from cmdline[0] in absence of a native # exe representation cmdline = self.cmdline if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'): exe = cmdline[0] # the possible exe rexe = os.path.realpath(exe) # ...in case it's a symlink if os.path.isabs(rexe) and os.path.isfile(rexe) \ and os.access(rexe, os.X_OK): return exe if isinstance(fallback, AccessDenied): raise fallback return fallback try: exe = self._platform_impl.get_process_exe() except AccessDenied: err = sys.exc_info()[1] return guess_it(fallback=err) else: if not exe: # underlying implementation can legitimately return an # empty string; if that's the case we don't want to # raise AD while guessing from the cmdline try: exe = guess_it(fallback=exe) except AccessDenied: pass return exe
python
{ "resource": "" }
q280140
Process.get_children
test
def get_children(self, recursive=False): """Return the children of this process as a list of Process objects. If recursive is True return all the parent descendants. Example (A == this process): A ─┐ │ ├─ B (child) ─┐ │ └─ X (grandchild) ─┐ │ └─ Y (great grandchild) ├─ C (child) └─ D (child) >>> p.get_children() B, C, D >>> p.get_children(recursive=True) B, X, Y, C, D Note that in the example above if process X disappears process Y won't be returned either as the reference to process A is lost. """ if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) ret = [] if not recursive: for p in process_iter(): try: if p.ppid == self.pid: # if child happens to be older than its parent # (self) it means child's PID has been reused if self.create_time <= p.create_time: ret.append(p) except NoSuchProcess: pass else: # construct a dict where 'values' are all the processes # having 'key' as their parent table = defaultdict(list) for p in process_iter(): try: table[p.ppid].append(p) except NoSuchProcess: pass # At this point we have a mapping table where table[self.pid] # are the current process's children. # Below, we look for all descendants recursively, similarly # to a recursive function call. checkpids = [self.pid] for pid in checkpids: for child in table[pid]: try: # if child happens to be older than its parent # (self) it means child's PID has been reused intime = self.create_time <= child.create_time except NoSuchProcess: pass else: if intime: ret.append(child) if child.pid not in checkpids: checkpids.append(child.pid) return ret
python
{ "resource": "" }
q280141
Process.get_cpu_percent
test
def get_cpu_percent(self, interval=0.1): """Return a float representing the current process CPU utilization as a percentage. When interval is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. """ blocking = interval is not None and interval > 0.0 if blocking: st1 = sum(cpu_times()) pt1 = self._platform_impl.get_cpu_times() time.sleep(interval) st2 = sum(cpu_times()) pt2 = self._platform_impl.get_cpu_times() else: st1 = self._last_sys_cpu_times pt1 = self._last_proc_cpu_times st2 = sum(cpu_times()) pt2 = self._platform_impl.get_cpu_times() if st1 is None or pt1 is None: self._last_sys_cpu_times = st2 self._last_proc_cpu_times = pt2 return 0.0 delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system) delta_time = st2 - st1 # reset values for next call in case of interval == None self._last_sys_cpu_times = st2 self._last_proc_cpu_times = pt2 try: # the utilization split between all CPUs overall_percent = (delta_proc / delta_time) * 100 except ZeroDivisionError: # interval was too low return 0.0 # the utilization of a single CPU single_cpu_percent = overall_percent * NUM_CPUS # on posix a percentage > 100 is legitimate # http://stackoverflow.com/questions/1032357/comprehending-top-cpu-usage # on windows we use this ugly hack to avoid troubles with float # precision issues if os.name != 'posix': if single_cpu_percent > 100.0: return 100.0 return round(single_cpu_percent, 1)
python
{ "resource": "" }
q280142
Process.get_memory_percent
test
def get_memory_percent(self): """Compare physical system memory to process resident memory and calculate process memory utilization as a percentage. """ rss = self._platform_impl.get_memory_info()[0] try: return (rss / float(TOTAL_PHYMEM)) * 100 except ZeroDivisionError: return 0.0
python
{ "resource": "" }
q280143
Process.get_memory_maps
test
def get_memory_maps(self, grouped=True): """Return process's mapped memory regions as a list of nameduples whose fields are variable depending on the platform. If 'grouped' is True the mapped regions with the same 'path' are grouped together and the different memory fields are summed. If 'grouped' is False every mapped region is shown as a single entity and the namedtuple will also include the mapped region's address space ('addr') and permission set ('perms'). """ it = self._platform_impl.get_memory_maps() if grouped: d = {} for tupl in it: path = tupl[2] nums = tupl[3:] try: d[path] = map(lambda x, y: x+y, d[path], nums) except KeyError: d[path] = nums nt = self._platform_impl.nt_mmap_grouped return [nt(path, *d[path]) for path in d] else: nt = self._platform_impl.nt_mmap_ext return [nt(*x) for x in it]
python
{ "resource": "" }
q280144
Process.is_running
test
def is_running(self): """Return whether this process is running.""" if self._gone: return False try: # Checking if pid is alive is not enough as the pid might # have been reused by another process. # pid + creation time, on the other hand, is supposed to # identify a process univocally. return self.create_time == \ self._platform_impl.get_process_create_time() except NoSuchProcess: self._gone = True return False
python
{ "resource": "" }
q280145
Process.suspend
test
def suspend(self): """Suspend process execution.""" # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) # windows if hasattr(self._platform_impl, "suspend_process"): self._platform_impl.suspend_process() else: # posix self.send_signal(signal.SIGSTOP)
python
{ "resource": "" }
q280146
Process.resume
test
def resume(self): """Resume process execution.""" # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) # windows if hasattr(self._platform_impl, "resume_process"): self._platform_impl.resume_process() else: # posix self.send_signal(signal.SIGCONT)
python
{ "resource": "" }
q280147
Process.kill
test
def kill(self): """Kill the current process.""" # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) if os.name == 'posix': self.send_signal(signal.SIGKILL) else: self._platform_impl.kill_process()
python
{ "resource": "" }
q280148
Process.wait
test
def wait(self, timeout=None): """Wait for process to terminate and, if process is a children of the current one also return its exit code, else None. """ if timeout is not None and not timeout >= 0: raise ValueError("timeout must be a positive integer") return self._platform_impl.process_wait(timeout)
python
{ "resource": "" }
q280149
GTKEmbed._wire_kernel
test
def _wire_kernel(self): """Initializes the kernel inside GTK. This is meant to run only once at startup, so it does its job and returns False to ensure it doesn't get run again by GTK. """ self.gtk_main, self.gtk_main_quit = self._hijack_gtk() gobject.timeout_add(int(1000*self.kernel._poll_interval), self.iterate_kernel) return False
python
{ "resource": "" }
q280150
GTKEmbed._hijack_gtk
test
def _hijack_gtk(self): """Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt to start or stop Returns ------- The original functions that have been hijacked: - gtk.main - gtk.main_quit """ def dummy(*args, **kw): pass # save and trap main and main_quit from gtk orig_main, gtk.main = gtk.main, dummy orig_main_quit, gtk.main_quit = gtk.main_quit, dummy return orig_main, orig_main_quit
python
{ "resource": "" }
q280151
is_shadowed
test
def is_shadowed(identifier, ip): """Is the given identifier defined in one of the namespaces which shadow the alias and magic namespaces? Note that an identifier is different than ifun, because it can not contain a '.' character.""" # This is much safer than calling ofind, which can change state return (identifier in ip.user_ns \ or identifier in ip.user_global_ns \ or identifier in ip.ns_table['builtin'])
python
{ "resource": "" }
q280152
PrefilterManager.init_transformers
test
def init_transformers(self): """Create the default transformers.""" self._transformers = [] for transformer_cls in _default_transformers: transformer_cls( shell=self.shell, prefilter_manager=self, config=self.config )
python
{ "resource": "" }
q280153
PrefilterManager.register_transformer
test
def register_transformer(self, transformer): """Register a transformer instance.""" if transformer not in self._transformers: self._transformers.append(transformer) self.sort_transformers()
python
{ "resource": "" }
q280154
PrefilterManager.unregister_transformer
test
def unregister_transformer(self, transformer): """Unregister a transformer instance.""" if transformer in self._transformers: self._transformers.remove(transformer)
python
{ "resource": "" }
q280155
PrefilterManager.init_checkers
test
def init_checkers(self): """Create the default checkers.""" self._checkers = [] for checker in _default_checkers: checker( shell=self.shell, prefilter_manager=self, config=self.config )
python
{ "resource": "" }
q280156
PrefilterManager.register_checker
test
def register_checker(self, checker): """Register a checker instance.""" if checker not in self._checkers: self._checkers.append(checker) self.sort_checkers()
python
{ "resource": "" }
q280157
PrefilterManager.unregister_checker
test
def unregister_checker(self, checker): """Unregister a checker instance.""" if checker in self._checkers: self._checkers.remove(checker)
python
{ "resource": "" }
q280158
PrefilterManager.init_handlers
test
def init_handlers(self): """Create the default handlers.""" self._handlers = {} self._esc_handlers = {} for handler in _default_handlers: handler( shell=self.shell, prefilter_manager=self, config=self.config )
python
{ "resource": "" }
q280159
PrefilterManager.register_handler
test
def register_handler(self, name, handler, esc_strings): """Register a handler instance by name with esc_strings.""" self._handlers[name] = handler for esc_str in esc_strings: self._esc_handlers[esc_str] = handler
python
{ "resource": "" }
q280160
PrefilterManager.unregister_handler
test
def unregister_handler(self, name, handler, esc_strings): """Unregister a handler instance by name with esc_strings.""" try: del self._handlers[name] except KeyError: pass for esc_str in esc_strings: h = self._esc_handlers.get(esc_str) if h is handler: del self._esc_handlers[esc_str]
python
{ "resource": "" }
q280161
PrefilterManager.prefilter_line_info
test
def prefilter_line_info(self, line_info): """Prefilter a line that has been converted to a LineInfo object. This implements the checker/handler part of the prefilter pipe. """ # print "prefilter_line_info: ", line_info handler = self.find_handler(line_info) return handler.handle(line_info)
python
{ "resource": "" }
q280162
PrefilterManager.find_handler
test
def find_handler(self, line_info): """Find a handler for the line_info by trying checkers.""" for checker in self.checkers: if checker.enabled: handler = checker.check(line_info) if handler: return handler return self.get_handler_by_name('normal')
python
{ "resource": "" }
q280163
PrefilterManager.transform_line
test
def transform_line(self, line, continue_prompt): """Calls the enabled transformers in order of increasing priority.""" for transformer in self.transformers: if transformer.enabled: line = transformer.transform(line, continue_prompt) return line
python
{ "resource": "" }
q280164
PrefilterManager.prefilter_line
test
def prefilter_line(self, line, continue_prompt=False): """Prefilter a single input line as text. This method prefilters a single line of text by calling the transformers and then the checkers/handlers. """ # print "prefilter_line: ", line, continue_prompt # All handlers *must* return a value, even if it's blank (''). # save the line away in case we crash, so the post-mortem handler can # record it self.shell._last_input_line = line if not line: # Return immediately on purely empty lines, so that if the user # previously typed some whitespace that started a continuation # prompt, he can break out of that loop with just an empty line. # This is how the default python prompt works. return '' # At this point, we invoke our transformers. if not continue_prompt or (continue_prompt and self.multi_line_specials): line = self.transform_line(line, continue_prompt) # Now we compute line_info for the checkers and handlers line_info = LineInfo(line, continue_prompt) # the input history needs to track even empty lines stripped = line.strip() normal_handler = self.get_handler_by_name('normal') if not stripped: if not continue_prompt: self.shell.displayhook.prompt_count -= 1 return normal_handler.handle(line_info) # special handlers are only allowed for single line statements if continue_prompt and not self.multi_line_specials: return normal_handler.handle(line_info) prefiltered = self.prefilter_line_info(line_info) # print "prefiltered line: %r" % prefiltered return prefiltered
python
{ "resource": "" }
q280165
PrefilterManager.prefilter_lines
test
def prefilter_lines(self, lines, continue_prompt=False): """Prefilter multiple input lines of text. This is the main entry point for prefiltering multiple lines of input. This simply calls :meth:`prefilter_line` for each line of input. This covers cases where there are multiple lines in the user entry, which is the case when the user goes back to a multiline history entry and presses enter. """ llines = lines.rstrip('\n').split('\n') # We can get multiple lines in one shot, where multiline input 'blends' # into one line, in cases like recalling from the readline history # buffer. We need to make sure that in such cases, we correctly # communicate downstream which line is first and which are continuation # ones. if len(llines) > 1: out = '\n'.join([self.prefilter_line(line, lnum>0) for lnum, line in enumerate(llines) ]) else: out = self.prefilter_line(llines[0], continue_prompt) return out
python
{ "resource": "" }
q280166
IPyAutocallChecker.check
test
def check(self, line_info): "Instances of IPyAutocall in user_ns get autocalled immediately" obj = self.shell.user_ns.get(line_info.ifun, None) if isinstance(obj, IPyAutocall): obj.set_ip(self.shell) return self.prefilter_manager.get_handler_by_name('auto') else: return None
python
{ "resource": "" }
q280167
MultiLineMagicChecker.check
test
def check(self, line_info): "Allow ! and !! in multi-line statements if multi_line_specials is on" # Note that this one of the only places we check the first character of # ifun and *not* the pre_char. Also note that the below test matches # both ! and !!. if line_info.continue_prompt \ and self.prefilter_manager.multi_line_specials: if line_info.esc == ESC_MAGIC: return self.prefilter_manager.get_handler_by_name('magic') else: return None
python
{ "resource": "" }
q280168
EscCharsChecker.check
test
def check(self, line_info): """Check for escape character and return either a handler to handle it, or None if there is no escape char.""" if line_info.line[-1] == ESC_HELP \ and line_info.esc != ESC_SHELL \ and line_info.esc != ESC_SH_CAP: # the ? can be at the end, but *not* for either kind of shell escape, # because a ? can be a vaild final char in a shell cmd return self.prefilter_manager.get_handler_by_name('help') else: if line_info.pre: return None # This returns None like it should if no handler exists return self.prefilter_manager.get_handler_by_esc(line_info.esc)
python
{ "resource": "" }
q280169
AliasChecker.check
test
def check(self, line_info): "Check if the initital identifier on the line is an alias." # Note: aliases can not contain '.' head = line_info.ifun.split('.',1)[0] if line_info.ifun not in self.shell.alias_manager \ or head not in self.shell.alias_manager \ or is_shadowed(head, self.shell): return None return self.prefilter_manager.get_handler_by_name('alias')
python
{ "resource": "" }
q280170
PrefilterHandler.handle
test
def handle(self, line_info): # print "normal: ", line_info """Handle normal input lines. Use as a template for handlers.""" # With autoindent on, we need some way to exit the input loop, and I # don't want to force the user to have to backspace all the way to # clear the line. The rule will be in this case, that either two # lines of pure whitespace in a row, or a line of pure whitespace but # of a size different to the indent level, will exit the input loop. line = line_info.line continue_prompt = line_info.continue_prompt if (continue_prompt and self.shell.autoindent and line.isspace() and 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2): line = '' return line
python
{ "resource": "" }
q280171
AliasHandler.handle
test
def handle(self, line_info): """Handle alias input lines. """ transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) # pre is needed, because it carries the leading whitespace. Otherwise # aliases won't work in indented sections. line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, transformed) return line_out
python
{ "resource": "" }
q280172
ShellEscapeHandler.handle
test
def handle(self, line_info): """Execute the line in a shell, empty return value""" magic_handler = self.prefilter_manager.get_handler_by_name('magic') line = line_info.line if line.lstrip().startswith(ESC_SH_CAP): # rewrite LineInfo's line, ifun and the_rest to properly hold the # call to %sx and the actual command to be executed, so # handle_magic can work correctly. Note that this works even if # the line is indented, so it handles multi_line_specials # properly. new_rest = line.lstrip()[2:] line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest) line_info.ifun = 'sx' line_info.the_rest = new_rest return magic_handler.handle(line_info) else: cmd = line.lstrip().lstrip(ESC_SHELL) line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, cmd) return line_out
python
{ "resource": "" }
q280173
MagicHandler.handle
test
def handle(self, line_info): """Execute magic functions.""" ifun = line_info.ifun the_rest = line_info.the_rest cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace, (ifun + " " + the_rest)) return cmd
python
{ "resource": "" }
q280174
AutoHandler.handle
test
def handle(self, line_info): """Handle lines which can be auto-executed, quoting if requested.""" line = line_info.line ifun = line_info.ifun the_rest = line_info.the_rest pre = line_info.pre esc = line_info.esc continue_prompt = line_info.continue_prompt obj = line_info.ofind(self.shell)['obj'] #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg # This should only be active for single-line input! if continue_prompt: return line force_auto = isinstance(obj, IPyAutocall) # User objects sometimes raise exceptions on attribute access other # than AttributeError (we've seen it in the past), so it's safest to be # ultra-conservative here and catch all. try: auto_rewrite = obj.rewrite except Exception: auto_rewrite = True if esc == ESC_QUOTE: # Auto-quote splitting on whitespace newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) elif esc == ESC_QUOTE2: # Auto-quote whole string newcmd = '%s("%s")' % (ifun,the_rest) elif esc == ESC_PAREN: newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) else: # Auto-paren. if force_auto: # Don't rewrite if it is already a call. do_rewrite = not the_rest.startswith('(') else: if not the_rest: # We only apply it to argument-less calls if the autocall # parameter is set to 2. do_rewrite = (self.shell.autocall >= 2) elif the_rest.startswith('[') and hasattr(obj, '__getitem__'): # Don't autocall in this case: item access for an object # which is BOTH callable and implements __getitem__. do_rewrite = False else: do_rewrite = True # Figure out the rewritten command if do_rewrite: if the_rest.endswith(';'): newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) else: newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) else: normal_handler = self.prefilter_manager.get_handler_by_name('normal') return normal_handler.handle(line_info) # Display the rewritten call if auto_rewrite: self.shell.auto_rewrite_input(newcmd) return newcmd
python
{ "resource": "" }
q280175
HelpHandler.handle
test
def handle(self, line_info): """Try to get some help for the object. obj? or ?obj -> basic information. obj?? or ??obj -> more details. """ normal_handler = self.prefilter_manager.get_handler_by_name('normal') line = line_info.line # We need to make sure that we don't process lines which would be # otherwise valid python, such as "x=1 # what?" try: codeop.compile_command(line) except SyntaxError: # We should only handle as help stuff which is NOT valid syntax if line[0]==ESC_HELP: line = line[1:] elif line[-1]==ESC_HELP: line = line[:-1] if line: #print 'line:<%r>' % line # dbg self.shell.magic('pinfo %s' % line_info.ifun) else: self.shell.show_usage() return '' # Empty string is needed here! except: raise # Pass any other exceptions through to the normal handler return normal_handler.handle(line_info) else: # If the code compiles ok, we should handle it normally return normal_handler.handle(line_info)
python
{ "resource": "" }
q280176
CallTipWidget.eventFilter
test
def eventFilter(self, obj, event): """ Reimplemented to hide on certain key presses and on text edit focus changes. """ if obj == self._text_edit: etype = event.type() if etype == QtCore.QEvent.KeyPress: key = event.key() if key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return): self.hide() elif key == QtCore.Qt.Key_Escape: self.hide() return True elif etype == QtCore.QEvent.FocusOut: self.hide() elif etype == QtCore.QEvent.Enter: self._hide_timer.stop() elif etype == QtCore.QEvent.Leave: self._leave_event_hide() return super(CallTipWidget, self).eventFilter(obj, event)
python
{ "resource": "" }
q280177
CallTipWidget.enterEvent
test
def enterEvent(self, event): """ Reimplemented to cancel the hide timer. """ super(CallTipWidget, self).enterEvent(event) self._hide_timer.stop()
python
{ "resource": "" }
q280178
CallTipWidget.paintEvent
test
def paintEvent(self, event): """ Reimplemented to paint the background panel. """ painter = QtGui.QStylePainter(self) option = QtGui.QStyleOptionFrame() option.initFrom(self) painter.drawPrimitive(QtGui.QStyle.PE_PanelTipLabel, option) painter.end() super(CallTipWidget, self).paintEvent(event)
python
{ "resource": "" }
q280179
CallTipWidget.show_call_info
test
def show_call_info(self, call_line=None, doc=None, maxlines=20): """ Attempts to show the specified call line and docstring at the current cursor location. The docstring is possibly truncated for length. """ if doc: match = re.match("(?:[^\n]*\n){%i}" % maxlines, doc) if match: doc = doc[:match.end()] + '\n[Documentation continues...]' else: doc = '' if call_line: doc = '\n\n'.join([call_line, doc]) return self.show_tip(doc)
python
{ "resource": "" }
q280180
CallTipWidget.show_tip
test
def show_tip(self, tip): """ Attempts to show the specified tip at the current cursor location. """ # Attempt to find the cursor position at which to show the call tip. text_edit = self._text_edit document = text_edit.document() cursor = text_edit.textCursor() search_pos = cursor.position() - 1 self._start_position, _ = self._find_parenthesis(search_pos, forward=False) if self._start_position == -1: return False # Set the text and resize the widget accordingly. self.setText(tip) self.resize(self.sizeHint()) # Locate and show the widget. Place the tip below the current line # unless it would be off the screen. In that case, decide the best # location based trying to minimize the area that goes off-screen. padding = 3 # Distance in pixels between cursor bounds and tip box. cursor_rect = text_edit.cursorRect(cursor) screen_rect = QtGui.qApp.desktop().screenGeometry(text_edit) point = text_edit.mapToGlobal(cursor_rect.bottomRight()) point.setY(point.y() + padding) tip_height = self.size().height() tip_width = self.size().width() vertical = 'bottom' horizontal = 'Right' if point.y() + tip_height > screen_rect.height(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off screen, check if point is in top or bottom # half of screen. if point_.y() - tip_height < padding: # If point is in upper half of screen, show tip below it. # otherwise above it. if 2*point.y() < screen_rect.height(): vertical = 'bottom' else: vertical = 'top' else: vertical = 'top' if point.x() + tip_width > screen_rect.width(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off-screen, check if point is in the right or # left half of the screen. if point_.x() - tip_width < padding: if 2*point.x() < screen_rect.width(): horizontal = 'Right' else: horizontal = 'Left' else: horizontal = 'Left' pos = getattr(cursor_rect, '%s%s' %(vertical, horizontal)) point = text_edit.mapToGlobal(pos()) if vertical == 'top': point.setY(point.y() - tip_height - padding) if horizontal == 'Left': point.setX(point.x() - tip_width - padding) self.move(point) self.show() return True
python
{ "resource": "" }
q280181
CallTipWidget._cursor_position_changed
test
def _cursor_position_changed(self): """ Updates the tip based on user cursor movement. """ cursor = self._text_edit.textCursor() if cursor.position() <= self._start_position: self.hide() else: position, commas = self._find_parenthesis(self._start_position + 1) if position != -1: self.hide()
python
{ "resource": "" }
q280182
proxied_attribute
test
def proxied_attribute(local_attr, proxied_attr, doc): """Create a property that proxies attribute ``proxied_attr`` through the local attribute ``local_attr``. """ def fget(self): return getattr(getattr(self, local_attr), proxied_attr) def fset(self, value): setattr(getattr(self, local_attr), proxied_attr, value) def fdel(self): delattr(getattr(self, local_attr), proxied_attr) return property(fget, fset, fdel, doc)
python
{ "resource": "" }
q280183
canonicalize_path
test
def canonicalize_path(cwd, path): """ Canonicalizes a path relative to a given working directory. That is, the path, if not absolute, is interpreted relative to the working directory, then converted to absolute form. :param cwd: The working directory. :param path: The path to canonicalize. :returns: The absolute path. """ if not os.path.isabs(path): path = os.path.join(cwd, path) return os.path.abspath(path)
python
{ "resource": "" }
q280184
schema_validate
test
def schema_validate(instance, schema, exc_class, *prefix, **kwargs): """ Schema validation helper. Performs JSONSchema validation. If a schema validation error is encountered, an exception of the designated class is raised with the validation error message appropriately simplified and passed as the sole positional argument. :param instance: The object to schema validate. :param schema: The schema to use for validation. :param exc_class: The exception class to raise instead of the ``jsonschema.ValidationError`` exception. :param prefix: Positional arguments are interpreted as a list of keys to prefix to the path contained in the validation error. :param kwargs: Keyword arguments to pass to the exception constructor. """ try: # Do the validation jsonschema.validate(instance, schema) except jsonschema.ValidationError as exc: # Assemble the path path = '/'.join((a if isinstance(a, six.string_types) else '[%d]' % a) for a in itertools.chain(prefix, exc.path)) # Construct the message message = 'Failed to validate "%s": %s' % (path, exc.message) # Raise the target exception raise exc_class(message, **kwargs)
python
{ "resource": "" }
q280185
SensitiveDict.masked
test
def masked(self): """ Retrieve a read-only subordinate mapping. All values are stringified, and sensitive values are masked. The subordinate mapping implements the context manager protocol for convenience. """ if self._masked is None: self._masked = MaskedDict(self) return self._masked
python
{ "resource": "" }
q280186
virtualenv_no_global
test
def virtualenv_no_global(): """ Return True if in a venv and no system site packages. """ #this mirrors the logic in virtualenv.py for locating the no-global-site-packages.txt file site_mod_dir = os.path.dirname(os.path.abspath(site.__file__)) no_global_file = os.path.join(site_mod_dir, 'no-global-site-packages.txt') if running_under_virtualenv() and os.path.isfile(no_global_file): return True
python
{ "resource": "" }
q280187
pwordfreq
test
def pwordfreq(view, fnames): """Parallel word frequency counter. view - An IPython DirectView fnames - The filenames containing the split data. """ assert len(fnames) == len(view.targets) view.scatter('fname', fnames, flatten=True) ar = view.apply(wordfreq, Reference('fname')) freqs_list = ar.get() word_set = set() for f in freqs_list: word_set.update(f.keys()) freqs = dict(zip(word_set, repeat(0))) for f in freqs_list: for word, count in f.iteritems(): freqs[word] += count return freqs
python
{ "resource": "" }
q280188
view_decorator
test
def view_decorator(function_decorator): """Convert a function based decorator into a class based decorator usable on class based Views. Can't subclass the `View` as it breaks inheritance (super in particular), so we monkey-patch instead. Based on http://stackoverflow.com/a/8429311 """ def simple_decorator(View): View.dispatch = method_decorator(function_decorator)(View.dispatch) return View return simple_decorator
python
{ "resource": "" }
q280189
default_aliases
test
def default_aliases(): """Return list of shell aliases to auto-define. """ # Note: the aliases defined here should be safe to use on a kernel # regardless of what frontend it is attached to. Frontends that use a # kernel in-process can define additional aliases that will only work in # their case. For example, things like 'less' or 'clear' that manipulate # the terminal should NOT be declared here, as they will only work if the # kernel is running inside a true terminal, and not over the network. if os.name == 'posix': default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'), ('mv', 'mv -i'), ('rm', 'rm -i'), ('cp', 'cp -i'), ('cat', 'cat'), ] # Useful set of ls aliases. The GNU and BSD options are a little # different, so we make aliases that provide as similar as possible # behavior in ipython, by passing the right flags for each platform if sys.platform.startswith('linux'): ls_aliases = [('ls', 'ls -F --color'), # long ls ('ll', 'ls -F -o --color'), # ls normal files only ('lf', 'ls -F -o --color %l | grep ^-'), # ls symbolic links ('lk', 'ls -F -o --color %l | grep ^l'), # directories or links to directories, ('ldir', 'ls -F -o --color %l | grep /$'), # things which are executable ('lx', 'ls -F -o --color %l | grep ^-..x'), ] else: # BSD, OSX, etc. ls_aliases = [('ls', 'ls -F'), # long ls ('ll', 'ls -F -l'), # ls normal files only ('lf', 'ls -F -l %l | grep ^-'), # ls symbolic links ('lk', 'ls -F -l %l | grep ^l'), # directories or links to directories, ('ldir', 'ls -F -l %l | grep /$'), # things which are executable ('lx', 'ls -F -l %l | grep ^-..x'), ] default_aliases = default_aliases + ls_aliases elif os.name in ['nt', 'dos']: default_aliases = [('ls', 'dir /on'), ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'), ('mkdir', 'mkdir'), ('rmdir', 'rmdir'), ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'), ] else: default_aliases = [] return default_aliases
python
{ "resource": "" }
q280190
AliasManager.soft_define_alias
test
def soft_define_alias(self, name, cmd): """Define an alias, but don't raise on an AliasError.""" try: self.define_alias(name, cmd) except AliasError, e: error("Invalid alias: %s" % e)
python
{ "resource": "" }
q280191
AliasManager.define_alias
test
def define_alias(self, name, cmd): """Define a new alias after validating it. This will raise an :exc:`AliasError` if there are validation problems. """ nargs = self.validate_alias(name, cmd) self.alias_table[name] = (nargs, cmd)
python
{ "resource": "" }
q280192
AliasManager.validate_alias
test
def validate_alias(self, name, cmd): """Validate an alias and return the its number of arguments.""" if name in self.no_alias: raise InvalidAliasError("The name %s can't be aliased " "because it is a keyword or builtin." % name) if not (isinstance(cmd, basestring)): raise InvalidAliasError("An alias command must be a string, " "got: %r" % cmd) nargs = cmd.count('%s') if nargs>0 and cmd.find('%l')>=0: raise InvalidAliasError('The %s and %l specifiers are mutually ' 'exclusive in alias definitions.') return nargs
python
{ "resource": "" }
q280193
AliasManager.call_alias
test
def call_alias(self, alias, rest=''): """Call an alias given its name and the rest of the line.""" cmd = self.transform_alias(alias, rest) try: self.shell.system(cmd) except: self.shell.showtraceback()
python
{ "resource": "" }
q280194
AliasManager.transform_alias
test
def transform_alias(self, alias,rest=''): """Transform alias to system command string.""" nargs, cmd = self.alias_table[alias] if ' ' in cmd and os.path.isfile(cmd): cmd = '"%s"' % cmd # Expand the %l special to be the user's input line if cmd.find('%l') >= 0: cmd = cmd.replace('%l', rest) rest = '' if nargs==0: # Simple, argument-less aliases cmd = '%s %s' % (cmd, rest) else: # Handle aliases with positional arguments args = rest.split(None, nargs) if len(args) < nargs: raise AliasError('Alias <%s> requires %s arguments, %s given.' % (alias, nargs, len(args))) cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) return cmd
python
{ "resource": "" }
q280195
AliasManager.expand_alias
test
def expand_alias(self, line): """ Expand an alias in the command line Returns the provided command line, possibly with the first word (command) translated according to alias expansion rules. [ipython]|16> _ip.expand_aliases("np myfile.txt") <16> 'q:/opt/np/notepad++.exe myfile.txt' """ pre,_,fn,rest = split_user_input(line) res = pre + self.expand_aliases(fn, rest) return res
python
{ "resource": "" }
q280196
autohelp_directive
test
def autohelp_directive(dirname, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """produces rst from nose help""" config = Config(parserClass=OptBucket, plugins=BuiltinPluginManager()) parser = config.getParser(TestProgram.usage()) rst = ViewList() for line in parser.format_help().split('\n'): rst.append(line, '<autodoc>') rst.append('Options', '<autodoc>') rst.append('-------', '<autodoc>') rst.append('', '<autodoc>') for opt in parser: rst.append(opt.options(), '<autodoc>') rst.append(' \n', '<autodoc>') rst.append(' ' + opt.help + '\n', '<autodoc>') rst.append('\n', '<autodoc>') node = nodes.section() node.document = state.document surrounding_title_styles = state.memo.title_styles surrounding_section_level = state.memo.section_level state.memo.title_styles = [] state.memo.section_level = 0 state.nested_parse(rst, 0, node, match_titles=1) state.memo.title_styles = surrounding_title_styles state.memo.section_level = surrounding_section_level return node.children
python
{ "resource": "" }
q280197
AnsiCodeProcessor.reset_sgr
test
def reset_sgr(self): """ Reset graphics attributs to their default values. """ self.intensity = 0 self.italic = False self.bold = False self.underline = False self.foreground_color = None self.background_color = None
python
{ "resource": "" }
q280198
AnsiCodeProcessor.split_string
test
def split_string(self, string): """ Yields substrings for which the same escape code applies. """ self.actions = [] start = 0 # strings ending with \r are assumed to be ending in \r\n since # \n is appended to output strings automatically. Accounting # for that, here. last_char = '\n' if len(string) > 0 and string[-1] == '\n' else None string = string[:-1] if last_char is not None else string for match in ANSI_OR_SPECIAL_PATTERN.finditer(string): raw = string[start:match.start()] substring = SPECIAL_PATTERN.sub(self._replace_special, raw) if substring or self.actions: yield substring self.actions = [] start = match.end() groups = filter(lambda x: x is not None, match.groups()) g0 = groups[0] if g0 == '\a': self.actions.append(BeepAction('beep')) yield None self.actions = [] elif g0 == '\r': self.actions.append(CarriageReturnAction('carriage-return')) yield None self.actions = [] elif g0 == '\b': self.actions.append(BackSpaceAction('backspace')) yield None self.actions = [] elif g0 == '\n' or g0 == '\r\n': self.actions.append(NewLineAction('newline')) yield g0 self.actions = [] else: params = [ param for param in groups[1].split(';') if param ] if g0.startswith('['): # Case 1: CSI code. try: params = map(int, params) except ValueError: # Silently discard badly formed codes. pass else: self.set_csi_code(groups[2], params) elif g0.startswith(']'): # Case 2: OSC code. self.set_osc_code(params) raw = string[start:] substring = SPECIAL_PATTERN.sub(self._replace_special, raw) if substring or self.actions: yield substring if last_char is not None: self.actions.append(NewLineAction('newline')) yield last_char
python
{ "resource": "" }
q280199
QtAnsiCodeProcessor.get_color
test
def get_color(self, color, intensity=0): """ Returns a QColor for a given color code, or None if one cannot be constructed. """ if color is None: return None # Adjust for intensity, if possible. if color < 8 and intensity > 0: color += 8 constructor = self.color_map.get(color, None) if isinstance(constructor, basestring): # If this is an X11 color name, we just hope there is a close SVG # color name. We could use QColor's static method # 'setAllowX11ColorNames()', but this is global and only available # on X11. It seems cleaner to aim for uniformity of behavior. return QtGui.QColor(constructor) elif isinstance(constructor, (tuple, list)): return QtGui.QColor(*constructor) return None
python
{ "resource": "" }