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 or...
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: '...
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. ...
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....
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_...
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 = - bu...
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...
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.E...
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.sp...
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(): ...
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. mous...
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 ...
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.Co...
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 ...
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'): ...
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_f...
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...
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_window...
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 =...
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: ...
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...
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....
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), t...
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, ...
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...
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 ...
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 t...
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...
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...
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...
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_...
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, ...
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....
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...
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 ...
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(): ...
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....
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 a...
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: ...
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_abo...
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 ...
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: ...
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 ...
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...
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...
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...
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:] ...
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. ...
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....
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 ...
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 a...
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...
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 TypeE...
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...
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...
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. ...
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[en...
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.fin...
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( ...
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...
2.589839
2.383822
1.086423