code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
assert isinstance(style_dict, Mapping)
if include_defaults:
s2 = {}
s2.update(DEFAULT_STYLE_EXTENSIONS)
s2.update(style_dict)
style_dict = s2
# Expand token inheritance and turn style description into Attrs.
token_to_attrs = {}
# (Loop through the tokens in order. Sorting makes sure that
# we process the parent first.)
for ttype, styledef in sorted(style_dict.items()):
# Start from parent Attrs or default Attrs.
attrs = DEFAULT_ATTRS
if 'noinherit' not in styledef:
for i in range(1, len(ttype) + 1):
try:
attrs = token_to_attrs[ttype[:-i]]
except KeyError:
pass
else:
break
# Now update with the given attributes.
for part in styledef.split():
if part == 'noinherit':
pass
elif part == 'bold':
attrs = attrs._replace(bold=True)
elif part == 'nobold':
attrs = attrs._replace(bold=False)
elif part == 'italic':
attrs = attrs._replace(italic=True)
elif part == 'noitalic':
attrs = attrs._replace(italic=False)
elif part == 'underline':
attrs = attrs._replace(underline=True)
elif part == 'nounderline':
attrs = attrs._replace(underline=False)
# prompt_toolkit extensions. Not in Pygments.
elif part == 'blink':
attrs = attrs._replace(blink=True)
elif part == 'noblink':
attrs = attrs._replace(blink=False)
elif part == 'reverse':
attrs = attrs._replace(reverse=True)
elif part == 'noreverse':
attrs = attrs._replace(reverse=False)
# Pygments properties that we ignore.
elif part in ('roman', 'sans', 'mono'):
pass
elif part.startswith('border:'):
pass
# Colors.
elif part.startswith('bg:'):
attrs = attrs._replace(bgcolor=_colorformat(part[3:]))
else:
attrs = attrs._replace(color=_colorformat(part))
token_to_attrs[ttype] = attrs
return _StyleFromDict(token_to_attrs) | def style_from_dict(style_dict, include_defaults=True) | Create a ``Style`` instance from a dictionary or other mapping.
The dictionary is equivalent to the ``Style.styles`` dictionary from
pygments, with a few additions: it supports 'reverse' and 'blink'.
Usage::
style_from_dict({
Token: '#ff0000 bold underline',
Token.Title: 'blink',
Token.SomethingElse: 'reverse',
})
:param include_defaults: Include the defaults (built-in) styling for
selected text, etc...) | 2.894098 | 2.903279 | 0.996838 |
self._input_is_ready = input_is_ready_func
# Start thread that activates this pipe when there is input to process.
def thread():
input_is_ready_func(wait=True)
os.write(self._w, b'x')
threading.Thread(target=thread).start()
# Call inputhook.
self.inputhook(self)
# Flush the read end of the pipe.
try:
# Before calling 'os.read', call select.select. This is required
# when the gevent monkey patch has been applied. 'os.read' is never
# monkey patched and won't be cooperative, so that would block all
# other select() calls otherwise.
# See: http://www.gevent.org/gevent.os.html
# Note: On Windows, this is apparently not an issue.
# However, if we would ever want to add a select call, it
# should use `windll.kernel32.WaitForMultipleObjects`,
# because `select.select` can't wait for a pipe on Windows.
if not is_windows():
select_fds([self._r], timeout=None)
os.read(self._r, 1024)
except OSError:
# This happens when the window resizes and a SIGWINCH was received.
# We get 'Error: [Errno 4] Interrupted system call'
# Just ignore.
pass
self._input_is_ready = None | def call_inputhook(self, input_is_ready_func) | Call the inputhook. (Called by a prompt-toolkit eventloop.) | 6.045929 | 5.882236 | 1.027828 |
if old_save_name in self._files:
del self._files[old_save_name]
self.update_file(new_save_name, new_path) | def rename_file(self, old_save_name, new_save_name, new_path) | This only updates the name and path we use to track the file's size
and upload progress. Doesn't rename it on the back end or make us
upload from anywhere else. | 2.751559 | 2.635463 | 1.044051 |
assert isinstance(name, six.text_type)
def decorator(handler):
assert callable(handler)
_readline_commands[name] = handler
return handler
return decorator | def register(name) | Store handler in the `_readline_commands` dictionary. | 5.777639 | 3.242865 | 1.781647 |
" Move to the start of the current line. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_start_of_line_position(after_whitespace=False) | def beginning_of_line(event) | Move to the start of the current line. | 6.544274 | 5.926404 | 1.104257 |
" Move to the end of the line. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_end_of_line_position() | def end_of_line(event) | Move to the end of the line. | 5.818261 | 5.71389 | 1.018266 |
" Move forward a character. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_cursor_right_position(count=event.arg) | def forward_char(event) | Move forward a character. | 9.90514 | 8.931607 | 1.108999 |
" Move back a character. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_cursor_left_position(count=event.arg) | def backward_char(event) | Move back a character. | 10.897798 | 9.385726 | 1.161103 |
buff = event.current_buffer
pos = buff.document.find_next_word_ending(count=event.arg)
if pos:
buff.cursor_position += pos | def forward_word(event) | Move forward to the end of the next word. Words are composed of letters and
digits. | 6.909036 | 6.384621 | 1.082137 |
buff = event.current_buffer
pos = buff.document.find_previous_word_beginning(count=event.arg)
if pos:
buff.cursor_position += pos | def backward_word(event) | Move back to the start of the current or previous word. Words are composed
of letters and digits. | 6.20278 | 6.29273 | 0.985706 |
" Accept the line regardless of where the cursor is. "
b = event.current_buffer
b.accept_action.validate_and_handle(event.cli, b) | def accept_line(event) | Accept the line regardless of where the cursor is. | 13.396447 | 9.319421 | 1.437476 |
event.current_buffer.history_forward(count=10**100)
buff = event.current_buffer
buff.go_to_history(len(buff._working_lines) - 1) | def end_of_history(event) | Move to the end of the input history, i.e., the line currently being entered. | 8.628324 | 7.863553 | 1.097255 |
event.cli.current_search_state.direction = IncrementalSearchDirection.BACKWARD
event.cli.push_focus(SEARCH_BUFFER) | def reverse_search_history(event) | Search backward starting at the current line and moving `up` through
the history as necessary. This is an incremental search. | 15.198153 | 12.245718 | 1.241099 |
" Delete character before the cursor. "
deleted = event.current_buffer.delete(count=event.arg)
if not deleted:
event.cli.output.bell() | def delete_char(event) | Delete character before the cursor. | 14.641534 | 12.392042 | 1.181527 |
" Delete the character behind the cursor. "
if event.arg < 0:
# When a negative argument has been given, this should delete in front
# of the cursor.
deleted = event.current_buffer.delete(count=-event.arg)
else:
deleted = event.current_buffer.delete_before_cursor(count=event.arg)
if not deleted:
event.cli.output.bell() | def backward_delete_char(event) | Delete the character behind the cursor. | 5.923587 | 5.962358 | 0.993497 |
b = event.current_buffer
p = b.cursor_position
if p == 0:
return
elif p == len(b.text) or b.text[p] == '\n':
b.swap_characters_before_cursor()
else:
b.cursor_position += b.document.get_cursor_right_position()
b.swap_characters_before_cursor() | def transpose_chars(event) | Emulate Emacs transpose-char behavior: at the beginning of the buffer,
do nothing. At the end of a line or buffer, swap the characters before
the cursor. Otherwise, move the cursor right, and then swap the
characters before the cursor. | 3.679931 | 2.727214 | 1.349337 |
buff = event.current_buffer
for i in range(event.arg):
pos = buff.document.find_next_word_ending()
words = buff.document.text_after_cursor[:pos]
buff.insert_text(words.upper(), overwrite=True) | def uppercase_word(event) | Uppercase the current (or following) word. | 4.732701 | 4.852629 | 0.975286 |
buff = event.current_buffer
for i in range(event.arg): # XXX: not DRY: see meta_c and meta_u!!
pos = buff.document.find_next_word_ending()
words = buff.document.text_after_cursor[:pos]
buff.insert_text(words.lower(), overwrite=True) | def downcase_word(event) | Lowercase the current (or following) word. | 9.149322 | 9.153893 | 0.999501 |
buff = event.current_buffer
for i in range(event.arg):
pos = buff.document.find_next_word_ending()
words = buff.document.text_after_cursor[:pos]
buff.insert_text(words.title(), overwrite=True) | def capitalize_word(event) | Capitalize the current (or following) word. | 4.994778 | 5.081646 | 0.982906 |
buff = event.current_buffer
if event.arg < 0:
deleted = buff.delete_before_cursor(count=-buff.document.get_start_of_line_position())
else:
if buff.document.current_char == '\n':
deleted = buff.delete(1)
else:
deleted = buff.delete(count=buff.document.get_end_of_line_position())
event.cli.clipboard.set_text(deleted) | def kill_line(event) | Kill the text from the cursor to the end of the line.
If we are at the end of the line, this should remove the newline.
(That way, it is possible to delete multiple lines by executing this
command multiple times.) | 3.45164 | 3.416716 | 1.010222 |
buff = event.current_buffer
pos = buff.document.find_next_word_ending(count=event.arg)
if pos:
deleted = buff.delete(count=pos)
event.cli.clipboard.set_text(deleted) | def kill_word(event) | Kill from point to the end of the current word, or if between words, to the
end of the next word. Word boundaries are the same as forward-word. | 6.69561 | 6.924092 | 0.967002 |
buff = event.current_buffer
pos = buff.document.find_start_of_previous_word(count=event.arg, WORD=WORD)
if pos is None:
# Nothing found? delete until the start of the document. (The
# input starts with whitespace and no words were found before the
# cursor.)
pos = - buff.cursor_position
if pos:
deleted = buff.delete_before_cursor(count=-pos)
# If the previous key press was also Control-W, concatenate deleted
# text.
if event.is_repeat:
deleted += event.cli.clipboard.get_data().text
event.cli.clipboard.set_text(deleted)
else:
# Nothing to delete. Bell.
event.cli.output.bell() | def unix_word_rubout(event, WORD=True) | Kill the word behind point, using whitespace as a word boundary.
Usually bound to ControlW. | 7.237689 | 6.966417 | 1.03894 |
" Delete all spaces and tabs around point. "
buff = event.current_buffer
text_before_cursor = buff.document.text_before_cursor
text_after_cursor = buff.document.text_after_cursor
delete_before = len(text_before_cursor) - len(text_before_cursor.rstrip('\t '))
delete_after = len(text_after_cursor) - len(text_after_cursor.lstrip('\t '))
buff.delete_before_cursor(count=delete_before)
buff.delete(count=delete_after) | def delete_horizontal_space(event) | Delete all spaces and tabs around point. | 2.864866 | 2.432177 | 1.177902 |
buff = event.current_buffer
if buff.document.cursor_position_col == 0 and buff.document.cursor_position > 0:
buff.delete_before_cursor(count=1)
else:
deleted = buff.delete_before_cursor(count=-buff.document.get_start_of_line_position())
event.cli.clipboard.set_text(deleted) | def unix_line_discard(event) | Kill backward from the cursor to the beginning of the current line. | 3.549893 | 3.487542 | 1.017878 |
event.current_buffer.paste_clipboard_data(
event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS) | def yank(event) | Paste before cursor. | 11.257033 | 9.695685 | 1.161035 |
n = (event.arg if event.arg_present else None)
event.current_buffer.yank_nth_arg(n) | def yank_nth_arg(event) | Insert the first argument of the previous command. With an argument, insert
the nth word from the previous command (start counting at 0). | 8.641669 | 8.650799 | 0.998945 |
n = (event.arg if event.arg_present else None)
event.current_buffer.yank_last_arg(n) | def yank_last_arg(event) | Like `yank_nth_arg`, but if no argument has been given, yank the last word
of each line. | 10.207816 | 8.842802 | 1.154364 |
buff = event.current_buffer
doc_before_paste = buff.document_before_paste
clipboard = event.cli.clipboard
if doc_before_paste is not None:
buff.document = doc_before_paste
clipboard.rotate()
buff.paste_clipboard_data(
clipboard.get_data(), paste_mode=PasteMode.EMACS) | def yank_pop(event) | Rotate the kill ring, and yank the new top. Only works following yank or
yank-pop. | 6.383201 | 6.66303 | 0.958003 |
" Print the last keboard macro. "
# TODO: Make the format suitable for the inputrc file.
def print_macro():
for k in event.cli.input_processor.macro:
print(k)
event.cli.run_in_terminal(print_macro) | def print_last_kbd_macro(event) | Print the last keboard macro. | 13.976393 | 12.211041 | 1.14457 |
buff = event.current_buffer
# Transform all lines.
if event.arg != 1:
def change(line):
return line[1:] if line.startswith('#') else line
else:
def change(line):
return '#' + line
buff.document = Document(
text='\n'.join(map(change, buff.text.splitlines())),
cursor_position=0)
# Accept input.
buff.accept_action.validate_and_handle(event.cli, buff) | def insert_comment(event) | Without numeric argument, comment all lines.
With numeric argument, uncomment all lines.
In any case accept the input. | 5.25282 | 4.574603 | 1.148257 |
buff = event.current_buffer
new_index = buff.working_index + 1
# Accept the current input. (This will also redraw the interface in the
# 'done' state.)
buff.accept_action.validate_and_handle(event.cli, buff)
# Set the new index at the start of the next run.
def set_working_index():
if new_index < len(buff._working_lines):
buff.working_index = new_index
event.cli.pre_run_callables.append(set_working_index) | def operate_and_get_next(event) | Accept the current line for execution and fetch the next line relative to
the current line from the history for editing. | 6.179977 | 6.050249 | 1.021442 |
buff = event.current_buffer
buff.open_in_editor(event.cli)
buff.accept_action.validate_and_handle(event.cli, buff) | def edit_and_execute(event) | Invoke an editor on the current command line, and accept the result. | 8.860176 | 8.482147 | 1.044568 |
registry = Registry()
@registry.add_binding(Keys.Vt100MouseEvent)
def _(event):
# Typical: "Esc[MaB*"
# Urxvt: "Esc[96;14;13M"
# Xterm SGR: "Esc[<64;85;12M"
# Parse incoming packet.
if event.data[2] == 'M':
# Typical.
mouse_event, x, y = map(ord, event.data[3:])
mouse_event = {
32: MouseEventType.MOUSE_DOWN,
35: MouseEventType.MOUSE_UP,
96: MouseEventType.SCROLL_UP,
97: MouseEventType.SCROLL_DOWN,
}.get(mouse_event)
# Handle situations where `PosixStdinReader` used surrogateescapes.
if x >= 0xdc00: x-= 0xdc00
if y >= 0xdc00: y-= 0xdc00
x -= 32
y -= 32
else:
# Urxvt and Xterm SGR.
# When the '<' is not present, we are not using the Xterm SGR mode,
# but Urxvt instead.
data = event.data[2:]
if data[:1] == '<':
sgr = True
data = data[1:]
else:
sgr = False
# Extract coordinates.
mouse_event, x, y = map(int, data[:-1].split(';'))
m = data[-1]
# Parse event type.
if sgr:
mouse_event = {
(0, 'M'): MouseEventType.MOUSE_DOWN,
(0, 'm'): MouseEventType.MOUSE_UP,
(64, 'M'): MouseEventType.SCROLL_UP,
(65, 'M'): MouseEventType.SCROLL_DOWN,
}.get((mouse_event, m))
else:
mouse_event = {
32: MouseEventType.MOUSE_DOWN,
35: MouseEventType.MOUSE_UP,
96: MouseEventType.SCROLL_UP,
97: MouseEventType.SCROLL_DOWN,
}.get(mouse_event)
x -= 1
y -= 1
# Only handle mouse events when we know the window height.
if event.cli.renderer.height_is_known and mouse_event is not None:
# Take region above the layout into account. The reported
# coordinates are absolute to the visible part of the terminal.
try:
y -= event.cli.renderer.rows_above_layout
except HeightIsUnknownError:
return
# Call the mouse handler from the renderer.
handler = event.cli.renderer.mouse_handlers.mouse_handlers[x,y]
handler(event.cli, MouseEvent(position=Point(x=x, y=y),
event_type=mouse_event))
@registry.add_binding(Keys.WindowsMouseEvent)
def _(event):
assert is_windows() # This key binding should only exist for Windows.
# Parse data.
event_type, x, y = event.data.split(';')
x = int(x)
y = int(y)
# Make coordinates absolute to the visible part of the terminal.
screen_buffer_info = event.cli.renderer.output.get_win32_screen_buffer_info()
rows_above_cursor = screen_buffer_info.dwCursorPosition.Y - event.cli.renderer._cursor_pos.y
y -= rows_above_cursor
# Call the mouse event handler.
handler = event.cli.renderer.mouse_handlers.mouse_handlers[x,y]
handler(event.cli, MouseEvent(position=Point(x=x, y=y),
event_type=event_type))
return registry | def load_mouse_bindings() | Key bindings, required for mouse support.
(Mouse events enter through the key binding system.) | 3.503095 | 3.489494 | 1.003898 |
registry = Registry()
handle = registry.add_binding
@handle(Keys.ControlC)
def _(event):
" Abort when Control-C has been pressed. "
event.cli.abort()
@Condition
def ctrl_d_condition(cli):
return (cli.current_buffer_name == DEFAULT_BUFFER and
not cli.current_buffer.text)
handle(Keys.ControlD, filter=ctrl_d_condition)(get_by_name('end-of-file'))
return registry | def load_abort_and_exit_bindings() | Basic bindings for abort (Ctrl-C) and exit (Ctrl-D). | 6.261919 | 5.616439 | 1.114927 |
registry = Registry()
suspend_supported = Condition(
lambda cli: suspend_to_background_supported())
@registry.add_binding(Keys.ControlZ, filter=suspend_supported)
def _(event):
event.cli.suspend_to_background()
return registry | def load_basic_system_bindings() | Basic system bindings (For both Emacs and Vi mode.) | 12.124744 | 10.561912 | 1.147969 |
registry = Registry()
handle = registry.add_binding
suggestion_available = Condition(
lambda cli:
cli.current_buffer.suggestion is not None and
cli.current_buffer.document.is_cursor_at_the_end)
@handle(Keys.ControlF, filter=suggestion_available)
@handle(Keys.ControlE, filter=suggestion_available)
@handle(Keys.Right, filter=suggestion_available)
def _(event):
" Accept suggestion. "
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
return registry | def load_auto_suggestion_bindings() | Key bindings for accepting auto suggestion text. | 3.938348 | 3.750916 | 1.04997 |
if self._types:
raise wandb.Error('TypedTable.set_columns called more than once.')
try:
for key, type_ in types:
if type_ not in TYPE_TO_TYPESTRING:
raise wandb.Error('TypedTable.set_columns received invalid type ({}) for key "{}".\n Valid types: {}'.format(
type_, key, '[%s]' % ', '.join(VALID_TYPE_NAMES)))
except TypeError:
raise wandb.Error(
'TypedTable.set_columns requires iterable of (column_name, type) pairs.')
self._types = dict(types)
self._output.add({
'typemap': {k: TYPE_TO_TYPESTRING[type_] for k, type_ in types},
'columns': [t[0] for t in types]}) | def set_columns(self, types) | Set the column types
args:
types: iterable of (column_name, type) pairs. | 3.634313 | 3.415246 | 1.064144 |
if not self._types:
raise wandb.Error(
'TypedTable.set_columns must be called before add.')
mapped_row = {}
for key, val in row.items():
try:
typed_val = self._types[key](val)
if hasattr(typed_val, 'encode'):
typed_val = typed_val.encode()
mapped_row[key] = typed_val
except KeyError:
raise wandb.Error(
'TypedTable.add received key ("%s") which wasn\'t provided to set_columns' % key)
except:
raise wandb.Error('TypedTable.add couldn\'t convert and encode ("{}") provided for key ("{}") to type ({})'.format(
val, key, self._types[key]))
self._output.add(mapped_row)
self._count += 1 | def add(self, row) | Add a row to the table.
Args:
row: A dict whose keys match the keys added in set_columns, and whose
values can be cast to the types added in set_columns. | 3.557717 | 3.321941 | 1.070976 |
assert isinstance(output, Output)
assert isinstance(style, Style)
# Reset first.
output.reset_attributes()
output.enable_autowrap()
# Print all (token, text) tuples.
attrs_for_token = _TokenToAttrsCache(style.get_attrs_for_token)
for token, text in tokens:
attrs = attrs_for_token[token]
if attrs:
output.set_attributes(attrs)
else:
output.reset_attributes()
output.write(text)
# Reset again.
output.reset_attributes()
output.flush() | def print_tokens(output, tokens, style) | Print a list of (Token, text) tuples in the given style to the output. | 3.831968 | 3.432197 | 1.116476 |
if self._in_alternate_screen:
return 0
elif self._min_available_height > 0:
total_rows = self.output.get_size().rows
last_screen_height = self._last_screen.height if self._last_screen else 0
return total_rows - max(self._min_available_height, last_screen_height)
else:
raise HeightIsUnknownError('Rows above layout is unknown.') | def rows_above_layout(self) | Return the number of rows visible in the terminal above the layout. | 5.561067 | 4.60648 | 1.207227 |
# Only do this request when the cursor is at the top row. (after a
# clear or reset). We will rely on that in `report_absolute_cursor_row`.
assert self._cursor_pos.y == 0
# For Win32, we have an API call to get the number of rows below the
# cursor.
if is_windows():
self._min_available_height = self.output.get_rows_below_cursor_position()
else:
if self.use_alternate_screen:
self._min_available_height = self.output.get_size().rows
else:
# Asks for a cursor position report (CPR).
self.waiting_for_cpr = True
self.output.ask_for_cpr() | def request_absolute_cursor_position(self) | Get current cursor position.
For vt100: Do CPR request. (answer will arrive later.)
For win32: Do API call. (Answer comes immediately.) | 7.689784 | 6.751935 | 1.138901 |
# Calculate the amount of rows from the cursor position until the
# bottom of the terminal.
total_rows = self.output.get_size().rows
rows_below_cursor = total_rows - row + 1
# Set the
self._min_available_height = rows_below_cursor
self.waiting_for_cpr = False | def report_absolute_cursor_row(self, row) | To be called when we know the absolute cursor position.
(As an answer of a "Cursor Position Request" response.) | 7.745963 | 7.507104 | 1.031818 |
output = self.output
# Enter alternate screen.
if self.use_alternate_screen and not self._in_alternate_screen:
self._in_alternate_screen = True
output.enter_alternate_screen()
# Enable bracketed paste.
if not self._bracketed_paste_enabled:
self.output.enable_bracketed_paste()
self._bracketed_paste_enabled = True
# Enable/disable mouse support.
needs_mouse_support = self.mouse_support(cli)
if needs_mouse_support and not self._mouse_support_enabled:
output.enable_mouse_support()
self._mouse_support_enabled = True
elif not needs_mouse_support and self._mouse_support_enabled:
output.disable_mouse_support()
self._mouse_support_enabled = False
# Create screen and write layout to it.
size = output.get_size()
screen = Screen()
screen.show_cursor = False # Hide cursor by default, unless one of the
# containers decides to display it.
mouse_handlers = MouseHandlers()
if is_done:
height = 0 # When we are done, we don't necessary want to fill up until the bottom.
else:
height = self._last_screen.height if self._last_screen else 0
height = max(self._min_available_height, height)
# When te size changes, don't consider the previous screen.
if self._last_size != size:
self._last_screen = None
# When we render using another style, do a full repaint. (Forget about
# the previous rendered screen.)
# (But note that we still use _last_screen to calculate the height.)
if self.style.invalidation_hash() != self._last_style_hash:
self._last_screen = None
self._attrs_for_token = None
if self._attrs_for_token is None:
self._attrs_for_token = _TokenToAttrsCache(self.style.get_attrs_for_token)
self._last_style_hash = self.style.invalidation_hash()
layout.write_to_screen(cli, screen, mouse_handlers, WritePosition(
xpos=0,
ypos=0,
width=size.columns,
height=(size.rows if self.use_alternate_screen else height),
extended_height=size.rows,
))
# When grayed. Replace all tokens in the new screen.
if cli.is_aborting or cli.is_exiting:
screen.replace_all_tokens(Token.Aborted)
# Process diff and write to output.
self._cursor_pos, self._last_token = _output_screen_diff(
output, screen, self._cursor_pos,
self._last_screen, self._last_token, is_done,
use_alternate_screen=self.use_alternate_screen,
attrs_for_token=self._attrs_for_token,
size=size,
previous_width=(self._last_size.columns if self._last_size else 0))
self._last_screen = screen
self._last_size = size
self.mouse_handlers = mouse_handlers
# Write title if it changed.
new_title = cli.terminal_title
if new_title != self._last_title:
if new_title is None:
self.output.clear_title()
else:
self.output.set_title(new_title)
self._last_title = new_title
output.flush() | def render(self, cli, layout, is_done=False) | Render the current interface to the output.
:param is_done: When True, put the cursor at the end of the interface. We
won't print any changes to this part. | 3.821527 | 3.755556 | 1.017566 |
output = self.output
output.cursor_backward(self._cursor_pos.x)
output.cursor_up(self._cursor_pos.y)
output.erase_down()
output.reset_attributes()
output.enable_autowrap()
output.flush()
# Erase title.
if self._last_title and erase_title:
output.clear_title()
self.reset(leave_alternate_screen=leave_alternate_screen) | def erase(self, leave_alternate_screen=True, erase_title=True) | Hide all output and put the cursor back at the first line. This is for
instance used for running a system command (while hiding the CLI) and
later resuming the same CLI.)
:param leave_alternate_screen: When True, and when inside an alternate
screen buffer, quit the alternate screen.
:param erase_title: When True, clear the title from the title bar. | 4.148077 | 4.298321 | 0.965046 |
# Erase current output first.
self.erase()
# Send "Erase Screen" command and go to (0, 0).
output = self.output
output.erase_screen()
output.cursor_goto(0, 0)
output.flush()
self.request_absolute_cursor_position() | def clear(self) | Clear screen and go to 0,0 | 9.150588 | 8.56835 | 1.067952 |
" Close pipe fds. "
os.close(self._r)
os.close(self._w)
self._r = None
self._w = None | def close(self) | Close pipe fds. | 5.406184 | 3.673659 | 1.471608 |
b = self.data_buffer
for y, row in b.items():
for x, char in row.items():
b[y][x] = _CHAR_CACHE[char.char, token] | def replace_all_tokens(self, token) | For all the characters in the screen. Set the token to the given `token`. | 9.005152 | 6.429527 | 1.400593 |
if isinstance(response, Exception):
logging.error("dropped chunk %s" % response)
elif response.json().get("limits"):
parsed = response.json()
self._api.dynamic_settings.update(parsed["limits"]) | def _handle_response(self, response) | Logs dropped chunks and updates dynamic settings | 10.876776 | 5.591838 | 1.945116 |
self._queue.put(Chunk(filename, data)) | def push(self, filename, data) | Push a chunk of a file to the streaming endpoint.
Args:
filename: Name of file that this is a chunk of.
chunk_id: TODO: change to 'offset'
chunk: File data. | 11.07969 | 14.179086 | 0.781411 |
self._queue.put(self.Finish(exitcode))
self._thread.join() | def finish(self, exitcode) | Cleans up.
Anything pushed after finish will be dropped.
Args:
exitcode: The exitcode of the watched process. | 6.693519 | 8.184562 | 0.817823 |
"Simple wrapper for calling docker, returning None on error and the output on success"
try:
return subprocess.check_output(['docker'] + cmd, stderr=subprocess.STDOUT).decode('utf8').strip()
except subprocess.CalledProcessError:
return None | def shell(cmd) | Simple wrapper for calling docker, returning None on error and the output on success | 4.604271 | 2.790627 | 1.649906 |
# TODO: Cache tokens?
auth_info = auth_config.resolve_authconfig(registry)
if auth_info:
normalized = {k.lower(): v for k, v in six.iteritems(auth_info)}
auth_info = (normalized.get("username"), normalized.get("password"))
response = requests.get("https://{}/v2/".format(registry), timeout=3)
if response.headers.get("www-authenticate"):
try:
info = www_authenticate.parse(response.headers['www-authenticate'])
except ValueError:
info = {}
else:
log.error("Received {} when attempting to authenticate with {}".format(
response, registry))
info = {}
if info.get("bearer"):
res = requests.get(info["bearer"]["realm"] +
"?service={}&scope=repository:{}:pull".format(
info["bearer"]["service"], repo), auth=auth_info, timeout=3)
res.raise_for_status()
return res.json()
return {} | def auth_token(registry, repo) | Makes a request to the root of a v2 docker registry to get the auth url.
Always returns a dictionary, if there's no token key we couldn't authenticate | 3.644653 | 3.54632 | 1.027728 |
registry, repository, tag = parse(image_name)
try:
token = auth_token(registry, repository).get("token")
# dockerhub is crazy
if registry == "index.docker.io":
registry = "registry-1.docker.io"
res = requests.head("https://{}/v2/{}/manifests/{}".format(registry, repository, tag), headers={
"Authorization": "Bearer {}".format(token),
"Accept": "application/vnd.docker.distribution.manifest.v2+json"
}, timeout=5)
res.raise_for_status()
except requests.RequestException:
log.error("Received {} when attempting to get digest for {}".format(
res, image_name))
return None
return "@".join([registry+"/"+repository, res.headers["Docker-Content-Digest"]]) | def image_id_from_registry(image_name) | Get the docker id from a public or private registry | 3.032373 | 3.031487 | 1.000292 |
return _compile_from_parse_tree(
parse_regex(tokenize_regex(expression)),
escape_funcs=escape_funcs,
unescape_funcs=unescape_funcs) | def compile(expression, escape_funcs=None, unescape_funcs=None) | Compile grammar (given as regex string), returning a `CompiledGrammar`
instance. | 4.207072 | 4.328527 | 0.971941 |
f = self.escape_funcs.get(varname)
return f(value) if f else value | def escape(self, varname, value) | Escape `value` to fit in the place of this variable into the grammar. | 4.719005 | 4.726834 | 0.998344 |
f = self.unescape_funcs.get(varname)
return f(value) if f else value | def unescape(self, varname, value) | Unescape `value`. | 4.238269 | 4.290419 | 0.987845 |
def transform(node):
# Turn `Any` into an OR.
if isinstance(node, Any):
return '(?:%s)' % '|'.join(transform(c) for c in node.children)
# Concatenate a `Sequence`
elif isinstance(node, Sequence):
return ''.join(transform(c) for c in node.children)
# For Regex and Lookahead nodes, just insert them literally.
elif isinstance(node, Regex):
return node.regex
elif isinstance(node, Lookahead):
before = ('(?!' if node.negative else '(=')
return before + transform(node.childnode) + ')'
# A `Variable` wraps the children into a named group.
elif isinstance(node, Variable):
return '(?P<%s>%s)' % (create_group_func(node), transform(node.childnode))
# `Repeat`.
elif isinstance(node, Repeat):
return '(?:%s){%i,%s}%s' % (
transform(node.childnode), node.min_repeat,
('' if node.max_repeat is None else str(node.max_repeat)),
('' if node.greedy else '?')
)
else:
raise TypeError('Got %r' % (node, ))
return transform(root_node) | def _transform(cls, root_node, create_group_func) | Turn a :class:`Node` object into a regular expression.
:param root_node: The :class:`Node` instance for which we generate the grammar.
:param create_group_func: A callable which takes a `Node` and returns the next
free name for this node. | 3.701642 | 3.348266 | 1.10554 |
def transform(node):
# Generate regexes for all permutations of this OR. Each node
# should be in front once.
if isinstance(node, Any):
for c in node.children:
for r in transform(c):
yield '(?:%s)?' % r
# For a sequence. We can either have a match for the sequence
# of all the children, or for an exact match of the first X
# children, followed by a partial match of the next children.
elif isinstance(node, Sequence):
for i in range(len(node.children)):
a = [cls._transform(c, create_group_func) for c in node.children[:i]]
for c in transform(node.children[i]):
yield '(?:%s)' % (''.join(a) + c)
elif isinstance(node, Regex):
yield '(?:%s)?' % node.regex
elif isinstance(node, Lookahead):
if node.negative:
yield '(?!%s)' % cls._transform(node.childnode, create_group_func)
else:
# Not sure what the correct semantics are in this case.
# (Probably it's not worth implementing this.)
raise Exception('Positive lookahead not yet supported.')
elif isinstance(node, Variable):
# (Note that we should not append a '?' here. the 'transform'
# method will already recursively do that.)
for c in transform(node.childnode):
yield '(?P<%s>%s)' % (create_group_func(node), c)
elif isinstance(node, Repeat):
# If we have a repetition of 8 times. That would mean that the
# current input could have for instance 7 times a complete
# match, followed by a partial match.
prefix = cls._transform(node.childnode, create_group_func)
for c in transform(node.childnode):
if node.max_repeat:
repeat_sign = '{,%i}' % (node.max_repeat - 1)
else:
repeat_sign = '*'
yield '(?:%s)%s%s(?:%s)?' % (
prefix,
repeat_sign,
('' if node.greedy else '?'),
c)
else:
raise TypeError('Got %r' % node)
for r in transform(root_node):
yield '^%s$' % r | def _transform_prefix(cls, root_node, create_group_func) | Yield all the regular expressions matching a prefix of the grammar
defined by the `Node` instance.
This can yield multiple expressions, because in the case of on OR
operation in the grammar, we can have another outcome depending on
which clause would appear first. E.g. "(A|B)C" is not the same as
"(B|A)C" because the regex engine is lazy and takes the first match.
However, because we the current input is actually a prefix of the
grammar which meight not yet contain the data for "C", we need to know
both intermediate states, in order to call the appropriate
autocompletion for both cases.
:param root_node: The :class:`Node` instance for which we generate the grammar.
:param create_group_func: A callable which takes a `Node` and returns the next
free name for this node. | 4.363824 | 4.142957 | 1.053311 |
m = self._re.match(string)
if m:
return Match(string, [(self._re, m)], self._group_names_to_nodes, self.unescape_funcs) | def match(self, string) | Match the string with the grammar.
Returns a :class:`Match` instance or `None` when the input doesn't match the grammar.
:param string: The input string. | 10.224014 | 9.704805 | 1.0535 |
# First try to match using `_re_prefix`. If nothing is found, use the patterns that
# also accept trailing characters.
for patterns in [self._re_prefix, self._re_prefix_with_trailing_input]:
matches = [(r, r.match(string)) for r in patterns]
matches = [(r, m) for r, m in matches if m]
if matches != []:
return Match(string, matches, self._group_names_to_nodes, self.unescape_funcs) | def match_prefix(self, string) | Do a partial match of the string with the grammar. The returned
:class:`Match` instance can contain multiple representations of the
match. This will never return `None`. If it doesn't match at all, the "trailing input"
part will capture all of the input.
:param string: The input string. | 6.932838 | 6.35489 | 1.090945 |
def get_tuples():
for r, re_match in self._re_matches:
for group_name, group_index in r.groupindex.items():
if group_name != _INVALID_TRAILING_INPUT:
reg = re_match.regs[group_index]
node = self._group_names_to_nodes[group_name]
yield (node, reg)
return list(get_tuples()) | def _nodes_to_regs(self) | Return a list of (varname, reg) tuples. | 5.607038 | 5.369198 | 1.044297 |
def is_none(slice):
return slice[0] == -1 and slice[1] == -1
def get(slice):
return self.string[slice[0]:slice[1]]
return [(varname, get(slice), slice) for varname, slice in self._nodes_to_regs() if not is_none(slice)] | def _nodes_to_values(self) | Returns list of list of (Node, string_value) tuples. | 5.17077 | 5.119046 | 1.010104 |
return Variables([(k, self._unescape(k, v), sl) for k, v, sl in self._nodes_to_values()]) | def variables(self) | Returns :class:`Variables` instance. | 16.985922 | 14.908155 | 1.139371 |
slices = []
# Find all regex group for the name _INVALID_TRAILING_INPUT.
for r, re_match in self._re_matches:
for group_name, group_index in r.groupindex.items():
if group_name == _INVALID_TRAILING_INPUT:
slices.append(re_match.regs[group_index])
# Take the smallest part. (Smaller trailing text means that a larger input has
# been matched, so that is better.)
if slices:
slice = [max(i[0] for i in slices), max(i[1] for i in slices)]
value = self.string[slice[0]:slice[1]]
return MatchVariable('<trailing_input>', value, slice) | def trailing_input(self) | Get the `MatchVariable` instance, representing trailing input, if there is any.
"Trailing input" is input at the end that does not match the grammar anymore, but
when this is removed from the end of the input, the input would be a valid string. | 6.751851 | 5.733919 | 1.177528 |
for varname, reg in self._nodes_to_regs():
# If this part goes until the end of the input string.
if reg[1] == len(self.string):
value = self._unescape(varname, self.string[reg[0]: reg[1]])
yield MatchVariable(varname, value, (reg[0], reg[1])) | def end_nodes(self) | Yields `MatchVariable` instances for all the nodes having their end
position at the end of the input string. | 8.851457 | 5.580702 | 1.586083 |
# Go back to insert mode.
self.input_mode = mode
self.waiting_for_digraph = False
self.operator_func = None
self.operator_arg = None | def reset(self, mode=InputMode.INSERT) | Reset state, go back to the given mode. INSERT by default. | 7.741894 | 6.763706 | 1.144623 |
assert isinstance(buffer, Buffer)
self.buffers[name] = buffer
if focus:
self.buffers.focus(name)
# Create asynchronous completer / auto suggestion.
auto_suggest_function = self._create_auto_suggest_function(buffer)
completer_function = self._create_async_completer(buffer)
self._async_completers[name] = completer_function
# Complete/suggest on text insert.
def create_on_insert_handler():
def on_text_insert(_):
# Only complete when "complete_while_typing" is enabled.
if buffer.completer and buffer.complete_while_typing():
completer_function()
# Call auto_suggest.
if buffer.auto_suggest:
auto_suggest_function()
return on_text_insert
buffer.on_text_insert += create_on_insert_handler()
def buffer_changed(_):
# Trigger on_buffer_changed.
self.on_buffer_changed.fire()
buffer.on_text_changed += buffer_changed | def add_buffer(self, name, buffer, focus=False) | Insert a new buffer. | 3.535241 | 3.526305 | 1.002534 |
buffer_name = buffer_name or self.current_buffer_name
completer = self._async_completers.get(buffer_name)
if completer:
completer(select_first=select_first,
select_last=select_last,
insert_common_part=insert_common_part,
complete_event=CompleteEvent(completion_requested=True)) | def start_completion(self, buffer_name=None, select_first=False,
select_last=False, insert_common_part=False,
complete_event=None) | Start asynchronous autocompletion of this buffer.
(This will do nothing if a previous completion was still in progress.) | 2.397326 | 2.314768 | 1.035666 |
result = self.application.get_title()
# Make sure that this function returns a unicode object,
# and not a byte string.
assert result is None or isinstance(result, six.text_type)
return result | def terminal_title(self) | Return the current title to be displayed in the terminal.
When this in `None`, the terminal title remains the original. | 6.515398 | 5.676799 | 1.147724 |
# Notice that we don't reset the buffers. (This happens just before
# returning, and when we have multiple buffers, we clearly want the
# content in the other buffers to remain unchanged between several
# calls of `run`. (And the same is true for the focus stack.)
self._exit_flag = False
self._abort_flag = False
self._return_value = None
self.renderer.reset()
self.input_processor.reset()
self.layout.reset()
self.vi_state.reset()
# Search new search state. (Does also remember what has to be
# highlighted.)
self.search_state = SearchState(ignore_case=Condition(lambda: self.is_ignoring_case))
# Trigger reset event.
self.on_reset.fire() | def reset(self, reset_current_buffer=False) | Reset everything, for reading the next input.
:param reset_current_buffer: XXX: not used anymore. The reason for
having this option in the past was when this CommandLineInterface
is run multiple times, that we could reset the buffer content from
the previous run. This is now handled in the AcceptAction. | 10.578671 | 10.035121 | 1.054165 |
# Never schedule a second redraw, when a previous one has not yet been
# executed. (This should protect against other threads calling
# 'invalidate' many times, resulting in 100% CPU.)
if self._invalidated:
return
else:
self._invalidated = True
# Trigger event.
self.on_invalidate.fire()
if self.eventloop is not None:
def redraw():
self._invalidated = False
self._redraw()
# Call redraw in the eventloop (thread safe).
# Usually with the high priority, in order to make the application
# feel responsive, but this can be tuned by changing the value of
# `max_render_postpone_time`.
if self.max_render_postpone_time:
_max_postpone_until = time.time() + self.max_render_postpone_time
else:
_max_postpone_until = None
self.eventloop.call_from_executor(
redraw, _max_postpone_until=_max_postpone_until) | def invalidate(self) | Thread safe way of sending a repaint trigger to the input event loop. | 5.255307 | 4.994662 | 1.052185 |
# Only draw when no sub application was started.
if self._is_running and self._sub_cli is None:
self.render_counter += 1
self.renderer.render(self, self.layout, is_done=self.is_done)
# Fire render event.
self.on_render.fire() | def _redraw(self) | Render the command line again. (Not thread safe!) (From other threads,
or if unsure, use :meth:`.CommandLineInterface.invalidate`.) | 10.118367 | 8.731987 | 1.15877 |
# Erase, request position (when cursor is at the start position)
# and redraw again. -- The order is important.
self.renderer.erase(leave_alternate_screen=False, erase_title=False)
self.renderer.request_absolute_cursor_position()
self._redraw() | def _on_resize(self) | When the window size changes, we erase the current output and request
again the cursor position. When the CPR answer arrives, the output is
drawn again. | 17.642513 | 11.651824 | 1.514142 |
" Called during `run`. "
if pre_run:
pre_run()
# Process registered "pre_run_callables" and clear list.
for c in self.pre_run_callables:
c()
del self.pre_run_callables[:] | def _pre_run(self, pre_run=None) | Called during `run`. | 6.815167 | 5.968699 | 1.141818 |
assert pre_run is None or callable(pre_run)
try:
self._is_running = True
self.on_start.fire()
self.reset()
# Call pre_run.
self._pre_run(pre_run)
# Run eventloop in raw mode.
with self.input.raw_mode():
self.renderer.request_absolute_cursor_position()
self._redraw()
self.eventloop.run(self.input, self.create_eventloop_callbacks())
finally:
# Clean up renderer. (This will leave the alternate screen, if we use
# that.)
# If exit/abort haven't been called set, but another exception was
# thrown instead for some reason, make sure that we redraw in exit
# mode.
if not self.is_done:
self._exit_flag = True
self._redraw()
self.renderer.reset()
self.on_stop.fire()
self._is_running = False
# Return result.
return self.return_value() | def run(self, reset_current_buffer=False, pre_run=None) | Read input from the command line.
This runs the eventloop until a return value has been set.
:param reset_current_buffer: XXX: Not used anymore.
:param pre_run: Callable that is called right after the reset has taken
place. This allows custom initialisation. | 7.010015 | 6.695743 | 1.046936 |
# `erase_when_done` is deprecated, set Application.erase_when_done instead.
assert isinstance(application, Application)
assert done_callback is None or callable(done_callback)
if self._sub_cli is not None:
raise RuntimeError('Another sub application started already.')
# Erase current application.
if not _from_application_generator:
self.renderer.erase()
# Callback when the sub app is done.
def done():
# Redraw sub app in done state.
# and reset the renderer. (This reset will also quit the alternate
# screen, if the sub application used that.)
sub_cli._redraw()
if erase_when_done or application.erase_when_done:
sub_cli.renderer.erase()
sub_cli.renderer.reset()
sub_cli._is_running = False # Don't render anymore.
self._sub_cli = None
# Restore main application.
if not _from_application_generator:
self.renderer.request_absolute_cursor_position()
self._redraw()
# Deliver result.
if done_callback:
done_callback(sub_cli.return_value())
# Create sub CommandLineInterface.
sub_cli = CommandLineInterface(
application=application,
eventloop=_SubApplicationEventLoop(self, done),
input=self.input,
output=self.output)
sub_cli._is_running = True # Allow rendering of sub app.
sub_cli._redraw()
self._sub_cli = sub_cli | def run_sub_application(self, application, done_callback=None, erase_when_done=False,
_from_application_generator=False) | Run a sub :class:`~prompt_toolkit.application.Application`.
This will suspend the main application and display the sub application
until that one returns a value. The value is returned by calling
`done_callback` with the result.
The sub application will share the same I/O of the main application.
That means, it uses the same input and output channels and it shares
the same event loop.
.. note:: Technically, it gets another Eventloop instance, but that is
only a proxy to our main event loop. The reason is that calling
'stop' --which returns the result of an application when it's
done-- is handled differently. | 4.702709 | 4.71679 | 0.997015 |
on_exit = self.application.on_exit
self._exit_flag = True
self._redraw()
if on_exit == AbortAction.RAISE_EXCEPTION:
def eof_error():
raise EOFError()
self._set_return_callable(eof_error)
elif on_exit == AbortAction.RETRY:
self.reset()
self.renderer.request_absolute_cursor_position()
self.current_buffer.reset()
elif on_exit == AbortAction.RETURN_NONE:
self.set_return_value(None) | def exit(self) | Set exit. When Control-D has been pressed. | 5.804247 | 5.358978 | 1.083088 |
on_abort = self.application.on_abort
self._abort_flag = True
self._redraw()
if on_abort == AbortAction.RAISE_EXCEPTION:
def keyboard_interrupt():
raise KeyboardInterrupt()
self._set_return_callable(keyboard_interrupt)
elif on_abort == AbortAction.RETRY:
self.reset()
self.renderer.request_absolute_cursor_position()
self.current_buffer.reset()
elif on_abort == AbortAction.RETURN_NONE:
self.set_return_value(None) | def abort(self) | Set abort. When Control-C has been pressed. | 5.295358 | 4.837267 | 1.0947 |
# Draw interface in 'done' state, or erase.
if render_cli_done:
self._return_value = True
self._redraw()
self.renderer.reset() # Make sure to disable mouse mode, etc...
else:
self.renderer.erase()
self._return_value = None
# Run system command.
if cooked_mode:
with self.input.cooked_mode():
result = func()
else:
result = func()
# Redraw interface again.
self.renderer.reset()
self.renderer.request_absolute_cursor_position()
self._redraw()
return result | def run_in_terminal(self, func, render_cli_done=False, cooked_mode=True) | Run function on the terminal above the prompt.
What this does is first hiding the prompt, then running this callable
(which can safely output to the terminal), and then again rendering the
prompt which causes the output of this function to scroll above the
prompt.
:param func: The callable to execute.
:param render_cli_done: When True, render the interface in the
'Done' state first, then execute the function. If False,
erase the interface first.
:param cooked_mode: When True (the default), switch the input to
cooked mode while executing the function.
:returns: the result of `func`. | 5.855911 | 5.324953 | 1.099711 |
# Draw interface in 'done' state, or erase.
if render_cli_done:
self._return_value = True
self._redraw()
self.renderer.reset() # Make sure to disable mouse mode, etc...
else:
self.renderer.erase()
self._return_value = None
# Loop through the generator.
g = coroutine()
assert isinstance(g, types.GeneratorType)
def step_next(send_value=None):
" Execute next step of the coroutine."
try:
# Run until next yield, in cooked mode.
with self.input.cooked_mode():
result = g.send(send_value)
except StopIteration:
done()
except:
done()
raise
else:
# Process yielded value from coroutine.
assert isinstance(result, Application)
self.run_sub_application(result, done_callback=step_next,
_from_application_generator=True)
def done():
# Redraw interface again.
self.renderer.reset()
self.renderer.request_absolute_cursor_position()
self._redraw()
# Start processing coroutine.
step_next() | def run_application_generator(self, coroutine, render_cli_done=False) | EXPERIMENTAL
Like `run_in_terminal`, but takes a generator that can yield Application instances.
Example:
def f():
yield Application1(...)
print('...')
yield Application2(...)
cli.run_in_terminal_async(f)
The values which are yielded by the given coroutine are supposed to be
`Application` instances that run in the current CLI, all other code is
supposed to be CPU bound, so except for yielding the applications,
there should not be any user interaction or I/O in the given function. | 5.881136 | 6.144833 | 0.957087 |
def wait_for_enter():
from .shortcuts import create_prompt_application
registry = Registry()
@registry.add_binding(Keys.ControlJ)
@registry.add_binding(Keys.ControlM)
def _(event):
event.cli.set_return_value(None)
application = create_prompt_application(
message='Press ENTER to continue...',
key_bindings_registry=registry)
self.run_sub_application(application)
def run():
# Try to use the same input/output file descriptors as the one,
# used to run this application.
try:
input_fd = self.input.fileno()
except AttributeError:
input_fd = sys.stdin.fileno()
try:
output_fd = self.output.fileno()
except AttributeError:
output_fd = sys.stdout.fileno()
# Run sub process.
# XXX: This will still block the event loop.
p = Popen(command, shell=True,
stdin=input_fd, stdout=output_fd)
p.wait()
# Wait for the user to press enter.
wait_for_enter()
self.run_in_terminal(run) | def run_system_command(self, command) | Run system command (While hiding the prompt. When finished, all the
output will scroll above the prompt.)
:param command: Shell command to be executed. | 3.727048 | 4.066478 | 0.91653 |
# Only suspend when the opperating system supports it.
# (Not on Windows.)
if hasattr(signal, 'SIGTSTP'):
def run():
# Send `SIGSTP` to own process.
# This will cause it to suspend.
# Usually we want the whole process group to be suspended. This
# handles the case when input is piped from another process.
if suspend_group:
os.kill(0, signal.SIGTSTP)
else:
os.kill(os.getpid(), signal.SIGTSTP)
self.run_in_terminal(run) | def suspend_to_background(self, suspend_group=True) | (Not thread safe -- to be called from inside the key bindings.)
Suspend process.
:param suspend_group: When true, suspend the whole process group.
(This is the default, and probably what you want.) | 5.628445 | 5.804073 | 0.96974 |
print_tokens(self.output, tokens, style or self.application.style) | def print_tokens(self, tokens, style=None) | Print a list of (Token, text) tuples to the output.
(When the UI is running, this method has to be called through
`run_in_terminal`, otherwise it will destroy the UI.)
:param style: Style class to use. Defaults to the active style in the CLI. | 13.728294 | 21.05003 | 0.652175 |
complete_thread_running = [False] # By ref.
def completion_does_nothing(document, completion):
text_before_cursor = document.text_before_cursor
replaced_text = text_before_cursor[
len(text_before_cursor) + completion.start_position:]
return replaced_text == completion.text
def async_completer(select_first=False, select_last=False,
insert_common_part=False, complete_event=None):
document = buffer.document
complete_event = complete_event or CompleteEvent(text_inserted=True)
# Don't start two threads at the same time.
if complete_thread_running[0]:
return
# Don't complete when we already have completions.
if buffer.complete_state or not buffer.completer:
return
# Otherwise, get completions in other thread.
complete_thread_running[0] = True
def run():
completions = list(buffer.completer.get_completions(document, complete_event))
def callback():
complete_thread_running[0] = False
# When there is only one completion, which has nothing to add, ignore it.
if (len(completions) == 1 and
completion_does_nothing(document, completions[0])):
del completions[:]
# Set completions if the text was not yet changed.
if buffer.text == document.text and \
buffer.cursor_position == document.cursor_position and \
not buffer.complete_state:
set_completions = True
select_first_anyway = False
# When the common part has to be inserted, and there
# is a common part.
if insert_common_part:
common_part = get_common_complete_suffix(document, completions)
if common_part:
# Insert the common part, update completions.
buffer.insert_text(common_part)
if len(completions) > 1:
# (Don't call `async_completer` again, but
# recalculate completions. See:
# https://github.com/ipython/ipython/issues/9658)
completions[:] = [
c.new_completion_from_position(len(common_part))
for c in completions]
else:
set_completions = False
else:
# When we were asked to insert the "common"
# prefix, but there was no common suffix but
# still exactly one match, then select the
# first. (It could be that we have a completion
# which does * expansion, like '*.py', with
# exactly one match.)
if len(completions) == 1:
select_first_anyway = True
if set_completions:
buffer.set_completions(
completions=completions,
go_to_first=select_first or select_first_anyway,
go_to_last=select_last)
self.invalidate()
elif not buffer.complete_state:
# Otherwise, restart thread.
async_completer()
if self.eventloop:
self.eventloop.call_from_executor(callback)
self.eventloop.run_in_executor(run)
return async_completer | def _create_async_completer(self, buffer) | Create function for asynchronous autocompletion.
(Autocomplete in other thread.) | 3.916412 | 3.912624 | 1.000968 |
suggest_thread_running = [False] # By ref.
def async_suggestor():
document = buffer.document
# Don't start two threads at the same time.
if suggest_thread_running[0]:
return
# Don't suggest when we already have a suggestion.
if buffer.suggestion or not buffer.auto_suggest:
return
# Otherwise, get completions in other thread.
suggest_thread_running[0] = True
def run():
suggestion = buffer.auto_suggest.get_suggestion(self, buffer, document)
def callback():
suggest_thread_running[0] = False
# Set suggestion only if the text was not yet changed.
if buffer.text == document.text and \
buffer.cursor_position == document.cursor_position:
# Set suggestion and redraw interface.
buffer.suggestion = suggestion
self.invalidate()
else:
# Otherwise, restart thread.
async_suggestor()
if self.eventloop:
self.eventloop.call_from_executor(callback)
self.eventloop.run_in_executor(run)
return async_suggestor | def _create_auto_suggest_function(self, buffer) | Create function for asynchronous auto suggestion.
(AutoSuggest in other thread.) | 4.368209 | 4.228885 | 1.032946 |
return _PatchStdoutContext(
self.stdout_proxy(raw=raw),
patch_stdout=patch_stdout, patch_stderr=patch_stderr) | def patch_stdout_context(self, raw=False, patch_stdout=True, patch_stderr=True) | Return a context manager that will replace ``sys.stdout`` with a proxy
that makes sure that all printed text will appear above the prompt, and
that it doesn't destroy the output from the renderer.
:param patch_stdout: Replace `sys.stdout`.
:param patch_stderr: Replace `sys.stderr`. | 5.073921 | 5.998412 | 0.845877 |
cli = self.cli
# If there is a sub CLI. That one is always active.
while cli._sub_cli:
cli = cli._sub_cli
return cli | def _active_cli(self) | Return the active `CommandLineInterface`. | 9.538987 | 7.149147 | 1.334283 |
assert isinstance(key_press, KeyPress)
cli = self._active_cli
# Feed the key and redraw.
# (When the CLI is in 'done' state, it should return to the event loop
# as soon as possible. Ignore all key presses beyond this point.)
if not cli.is_done:
cli.input_processor.feed(key_press)
cli.input_processor.process_keys() | def feed_key(self, key_press) | Feed a key press to the CommandLineInterface. | 7.491251 | 6.985342 | 1.072424 |
if '\n' in data:
# When there is a newline in the data, write everything before the
# newline, including the newline itself.
before, after = data.rsplit('\n', 1)
to_write = self._buffer + [before, '\n']
self._buffer = [after]
def run():
for s in to_write:
if self._raw:
self._cli.output.write_raw(s)
else:
self._cli.output.write(s)
self._do(run)
else:
# Otherwise, cache in buffer.
self._buffer.append(data) | def _write(self, data) | Note: print()-statements cause to multiple write calls.
(write('line') and write('\n')). Of course we don't want to call
`run_in_terminal` for every individual call, because that's too
expensive, and as long as the newline hasn't been written, the
text itself is again overwritter by the rendering of the input
command line. Therefor, we have a little buffer which holds the
text until a newline is written to stdout. | 3.944934 | 3.596308 | 1.09694 |
u
series = [ float(i) for i in series ]
minimum = min(series)
maximum = max(series)
data_range = maximum - minimum
if data_range == 0.0:
# Graph a baseline if every input value is equal.
return u''.join([ spark_chars[0] for i in series ])
coefficient = (len(spark_chars) - 1.0) / data_range
return u''.join([
spark_chars[
int(round((x - minimum) * coefficient))
] for x in series
]) | def sparkify(series) | u"""Converts <series> to a sparkline string.
Example:
>>> sparkify([ 0.5, 1.2, 3.5, 7.3, 8.0, 12.5, 13.2, 15.0, 14.2, 11.8, 6.1,
... 1.9 ])
u'▁▁▂▄▅▇▇██▆▄▂'
>>> sparkify([1, 1, -2, 3, -5, 8, -13])
u'▆▆▅▆▄█▁'
Raises ValueError if input data cannot be converted to float.
Raises TypeError if series is not an iterable. | 4.158086 | 4.179896 | 0.994782 |
min = sum([d.min for d in dimensions if d.min is not None])
max = sum([d.max for d in dimensions if d.max is not None])
preferred = sum([d.preferred for d in dimensions])
return LayoutDimension(min=min, max=max, preferred=preferred) | def sum_layout_dimensions(dimensions) | Sum a list of :class:`.LayoutDimension` instances. | 2.457278 | 2.19856 | 1.117676 |
min_ = max([d.min for d in dimensions if d.min is not None])
max_ = max([d.max for d in dimensions if d.max is not None])
preferred = max([d.preferred for d in dimensions])
return LayoutDimension(min=min_, max=max_, preferred=preferred) | def max_layout_dimensions(dimensions) | Take the maximum of a list of :class:`.LayoutDimension` instances. | 2.744915 | 2.390896 | 1.14807 |
return cls(min=amount, max=amount, preferred=amount) | def exact(cls, amount) | Return a :class:`.LayoutDimension` with an exact size. (min, max and
preferred set to ``amount``). | 10.904038 | 3.771797 | 2.89094 |
for x, y in product(range(x_min, x_max), range(y_min, y_max)):
self.mouse_handlers[x,y] = handler | def set_mouse_handler_for_range(self, x_min, x_max, y_min, y_max, handler=None) | Set mouse handler for a region. | 2.524867 | 2.416484 | 1.044852 |
if not options.get("save_policy"):
raise ValueError("Only configuring save_policy is supported")
if self.socket:
self.socket.send(options)
elif self._jupyter_agent:
self._jupyter_agent.start()
self._jupyter_agent.rm.update_user_file_policy(
options["save_policy"])
else:
wandb.termerror(
"wandb.init hasn't been called, can't configure run") | def send_message(self, options) | Sends a message to the wandb process changing the policy
of saved files. This is primarily used internally by wandb.save | 8.386666 | 6.773765 | 1.23811 |
if environment is None:
environment = os.environ
run_id = environment.get(env.RUN_ID)
resume = environment.get(env.RESUME)
storage_id = environment.get(env.RUN_STORAGE_ID)
mode = environment.get(env.MODE)
disabled = InternalApi().disabled()
if not mode and disabled:
mode = "dryrun"
elif disabled and mode != "dryrun":
wandb.termlog(
"WARNING: WANDB_MODE is set to run, but W&B was disabled. Run `wandb on` to remove this message")
elif disabled:
wandb.termlog(
'W&B is disabled in this directory. Run `wandb on` to enable cloud syncing.')
group = environment.get(env.RUN_GROUP)
job_type = environment.get(env.JOB_TYPE)
run_dir = environment.get(env.RUN_DIR)
sweep_id = environment.get(env.SWEEP_ID)
program = environment.get(env.PROGRAM)
description = environment.get(env.DESCRIPTION)
args = env.get_args()
wandb_dir = env.get_dir()
tags = env.get_tags()
config = Config.from_environment_or_defaults()
run = cls(run_id, mode, run_dir,
group, job_type, config,
sweep_id, storage_id, program=program, description=description,
args=args, wandb_dir=wandb_dir, tags=tags,
resume=resume)
return run | def from_environment_or_defaults(cls, environment=None) | Create a Run object taking values from the local environment where possible.
The run ID comes from WANDB_RUN_ID or is randomly generated.
The run mode ("dryrun", or "run") comes from WANDB_MODE or defaults to "dryrun".
The run directory comes from WANDB_RUN_DIR or is generated from the run ID.
The Run will have a .config attribute but its run directory won't be set by
default. | 3.121308 | 2.932349 | 1.064439 |
if environment is None:
environment = os.environ
environment[env.RUN_ID] = self.id
environment[env.RESUME] = self.resume
if self.storage_id:
environment[env.RUN_STORAGE_ID] = self.storage_id
environment[env.MODE] = self.mode
environment[env.RUN_DIR] = self.dir
if self.group:
environment[env.RUN_GROUP] = self.group
if self.job_type:
environment[env.JOB_TYPE] = self.job_type
if self.wandb_dir:
environment[env.DIR] = self.wandb_dir
if self.sweep_id is not None:
environment[env.SWEEP_ID] = self.sweep_id
if self.program is not None:
environment[env.PROGRAM] = self.program
if self.args is not None:
environment[env.ARGS] = json.dumps(self.args)
if self.name_and_description is not None:
environment[env.DESCRIPTION] = self.name_and_description
if len(self.tags) > 0:
environment[env.TAGS] = ",".join(self.tags) | def set_environment(self, environment=None) | Set environment variables needed to reconstruct this object inside
a user scripts (eg. in `wandb.init()`). | 2.150532 | 2.007817 | 1.07108 |
if os.path.exists(self.log_fname):
api = InternalApi()
api.set_current_run_id(self.id)
pusher = FilePusher(api)
pusher.update_file("wandb-debug.log", self.log_fname)
pusher.file_changed("wandb-debug.log", self.log_fname)
pusher.finish() | def upload_debug(self) | Uploads the debug log to cloud storage | 4.83571 | 4.74236 | 1.019684 |
handler = logging.FileHandler(self.log_fname)
handler.setLevel(logging.INFO)
run_id = self.id
class WBFilter(logging.Filter):
def filter(self, record):
record.run_id = run_id
return True
formatter = logging.Formatter(
'%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(run_id)s:%(filename)s:%(funcName)s():%(lineno)s] %(message)s')
handler.setFormatter(formatter)
handler.addFilter(WBFilter())
root = logging.getLogger()
root.addHandler(handler) | def enable_logging(self) | Enable logging to the global debug log. This adds a run_id to the log,
in case of muliple processes on the same machine.
Currently no way to disable logging after it's enabled. | 2.534568 | 2.437946 | 1.039633 |
if self._events is not None:
self._events.close()
self._events = None
if self._history is not None:
self._history.close()
self._history = None | def close_files(self) | Close open files to avoid Python warnings on termination:
Exception ignored in: <_io.FileIO name='wandb/dryrun-20180130_144602-9vmqjhgy/wandb-history.jsonl' mode='wb' closefd=True>
ResourceWarning: unclosed file <_io.TextIOWrapper name='wandb/dryrun-20180130_144602-9vmqjhgy/wandb-history.jsonl' mode='w' encoding='UTF-8'> | 2.589839 | 2.383822 | 1.086423 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.