code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if count < 0: return self.find_previous_word_beginning(count=-count, WORD=WORD) regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE iterator = regex.finditer(self.text_after_cursor) try: for i, match in enumerate(iterator): # Take first...
def find_next_word_beginning(self, count=1, WORD=False)
Return an index relative to the cursor position pointing to the start of the next word. Return `None` if nothing was found.
3.689782
3.493476
1.056192
if count < 0: return self.find_previous_word_ending(count=-count, WORD=WORD) if include_current_position: text = self.text_after_cursor else: text = self.text_after_cursor[1:] regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE iter...
def find_next_word_ending(self, include_current_position=False, count=1, WORD=False)
Return an index relative to the cursor position pointing to the end of the next word. Return `None` if nothing was found.
2.880383
2.743561
1.04987
if count < 0: return self.find_next_word_beginning(count=-count, WORD=WORD) regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE iterator = regex.finditer(self.text_before_cursor[::-1]) try: for i, match in enumerate(iterator): if i + 1 ...
def find_previous_word_beginning(self, count=1, WORD=False)
Return an index relative to the cursor position pointing to the start of the previous word. Return `None` if nothing was found.
3.809935
3.394311
1.122447
if count < 0: return self.find_next_word_ending(count=-count, WORD=WORD) text_before_cursor = self.text_after_cursor[:1] + self.text_before_cursor[::-1] regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE iterator = regex.finditer(text_before_cursor) try:...
def find_previous_word_ending(self, count=1, WORD=False)
Return an index relative to the cursor position pointing to the end of the previous word. Return `None` if nothing was found.
3.856042
3.696038
1.043291
result = None for index, line in enumerate(self.lines[self.cursor_position_row + 1:]): if match_func(line): result = 1 + index count -= 1 if count == 0: break return result
def find_next_matching_line(self, match_func, count=1)
Look downwards for empty lines. Return the line index, relative to the current line.
3.720164
3.175907
1.171371
if count < 0: return self.get_cursor_right_position(-count) return - min(self.cursor_position_col, count)
def get_cursor_left_position(self, count=1)
Relative position for cursor left.
5.701737
5.434639
1.049147
if count < 0: return self.get_cursor_left_position(-count) return min(count, len(self.current_line_after_cursor))
def get_cursor_right_position(self, count=1)
Relative position for cursor_right.
5.195759
4.888206
1.062917
assert count >= 1 column = self.cursor_position_col if preferred_column is None else preferred_column return self.translate_row_col_to_index( max(0, self.cursor_position_row - count), column) - self.cursor_position
def get_cursor_up_position(self, count=1, preferred_column=None)
Return the relative cursor position (character index) where we would be if the user pressed the arrow-up button. :param preferred_column: When given, go to this column instead of staying at the current column.
3.424197
4.025118
0.850707
assert count >= 1 column = self.cursor_position_col if preferred_column is None else preferred_column return self.translate_row_col_to_index( self.cursor_position_row + count, column) - self.cursor_position
def get_cursor_down_position(self, count=1, preferred_column=None)
Return the relative cursor position (character index) where we would be if the user pressed the arrow-down button. :param preferred_column: When given, go to this column instead of staying at the current column.
3.413859
3.981929
0.857338
if self.current_char == right_ch: return 0 if end_pos is None: end_pos = len(self.text) else: end_pos = min(len(self.text), end_pos) stack = 1 # Look forward. for i in range(self.cursor_position + 1, end_pos): c ...
def find_enclosing_bracket_right(self, left_ch, right_ch, end_pos=None)
Find the right bracket enclosing current position. Return the relative position to the cursor position. When `end_pos` is given, don't look past the position.
2.134119
2.005403
1.064185
if self.current_char == left_ch: return 0 if start_pos is None: start_pos = 0 else: start_pos = max(0, start_pos) stack = 1 # Look backward. for i in range(self.cursor_position - 1, start_pos - 1, -1): c = self.t...
def find_enclosing_bracket_left(self, left_ch, right_ch, start_pos=None)
Find the left bracket enclosing current position. Return the relative position to the cursor position. When `start_pos` is given, don't look past the position.
2.393769
2.254894
1.061588
# Look for a match. for A, B in '()', '[]', '{}', '<>': if self.current_char == A: return self.find_enclosing_bracket_right(A, B, end_pos=end_pos) or 0 elif self.current_char == B: return self.find_enclosing_bracket_left(A, B, start_pos=s...
def find_matching_bracket_position(self, start_pos=None, end_pos=None)
Return relative cursor position of matching [, (, { or < bracket. When `start_pos` or `end_pos` are given. Don't look past the positions.
3.555153
3.369244
1.055178
if after_whitespace: current_line = self.current_line return len(current_line) - len(current_line.lstrip()) - self.cursor_position_col else: return - len(self.current_line_before_cursor)
def get_start_of_line_position(self, after_whitespace=False)
Relative position for the start of this line.
3.378475
3.253572
1.03839
line_length = len(self.current_line) current_column = self.cursor_position_col column = max(0, min(line_length, column)) return column - current_column
def get_column_cursor_position(self, column)
Return the relative cursor position for this column at the current line. (It will stay between the boundaries of the line in case of a larger number.)
4.198048
3.462634
1.212386
from_, to = sorted([self.cursor_position, self.selection.original_cursor_position]) else: from_, to = self.cursor_position, self.cursor_position return from_, to
def selection_range(self): # XXX: shouldn't this return `None` if there is no selection??? if self.selection
Return (from, to) tuple of the selection. start and end position are included. This doesn't take the selection type into account. Use `selection_ranges` instead.
5.798335
5.962219
0.972513
if self.selection: from_, to = sorted([self.cursor_position, self.selection.original_cursor_position]) if self.selection.type == SelectionType.BLOCK: from_line, from_column = self.translate_index_to_position(from_) to_line, to_column = self.trans...
def selection_ranges(self)
Return a list of (from, to) tuples for the selection or none if nothing was selected. start and end position are always included in the selection. This will yield several (from, to) tuples in case of a BLOCK selection.
2.499095
2.381112
1.049549
if self.selection: row_start = self.translate_row_col_to_index(row, 0) row_end = self.translate_row_col_to_index(row, max(0, len(self.lines[row]) - 1)) from_, to = sorted([self.cursor_position, self.selection.original_cursor_position]) # Take the inters...
def selection_range_at_line(self, row)
If the selection spans a portion of the given line, return a (from, to) tuple. Otherwise, return None.
2.207979
2.068215
1.067577
if self.selection: cut_parts = [] remaining_parts = [] new_cursor_position = self.cursor_position last_to = 0 for from_, to in self.selection_ranges(): if last_to == 0: new_cursor_position = from_ ...
def cut_selection(self)
Return a (:class:`.Document`, :class:`.ClipboardData`) tuple, where the document represents the new document when the selection is cut, and the clipboard data, represents whatever has to be put on the clipboard.
2.857048
2.545688
1.122309
assert isinstance(data, ClipboardData) assert paste_mode in (PasteMode.VI_BEFORE, PasteMode.VI_AFTER, PasteMode.EMACS) before = (paste_mode == PasteMode.VI_BEFORE) after = (paste_mode == PasteMode.VI_AFTER) if data.type == SelectionType.CHARACTERS: if after...
def paste_clipboard_data(self, data, paste_mode=PasteMode.EMACS, count=1)
Return a new :class:`.Document` instance which contains the result if we would paste this data at the current cursor position. :param paste_mode: Where to paste. (Before/after/emacs.) :param count: When >1, Paste multiple times.
1.975575
1.942594
1.016978
count = 0 for line in self.lines[::-1]: if not line or line.isspace(): count += 1 else: break return count
def empty_line_count_at_the_end(self)
Return number of empty lines at the end of the document.
2.97589
2.541543
1.170899
def match_func(text): return not text or text.isspace() line_index = self.find_previous_matching_line(match_func=match_func, count=count) if line_index: add = 0 if before else 1 return min(0, self.get_cursor_up_position(count=-line_index) + add) ...
def start_of_paragraph(self, count=1, before=False)
Return the start of the current paragraph. (Relative cursor position.)
5.551106
5.130406
1.082001
def match_func(text): return not text or text.isspace() line_index = self.find_next_matching_line(match_func=match_func, count=count) if line_index: add = 0 if after else 1 return max(0, self.get_cursor_down_position(count=line_index) - add) ...
def end_of_paragraph(self, count=1, after=False)
Return the end of the current paragraph. (Relative cursor position.)
5.076111
4.71784
1.07594
return Document( text=self.text + text, cursor_position=self.cursor_position, selection=self.selection)
def insert_after(self, text)
Create a new document, with this text inserted after the buffer. It keeps selection ranges and cursor position in sync.
5.379672
3.955291
1.36012
selection_state = self.selection if selection_state: selection_state = SelectionState( original_cursor_position=selection_state.original_cursor_position + len(text), type=selection_state.type) return Document( text=text + sel...
def insert_before(self, text)
Create a new document, with this text inserted before the buffer. It keeps selection ranges and cursor position in sync.
3.531423
3.25365
1.085373
assert get_search_state is None or callable(get_search_state) # Accept both Filters and booleans as input. enable_abort_and_exit_bindings = to_cli_filter(enable_abort_and_exit_bindings) enable_system_bindings = to_cli_filter(enable_system_bindings) enable_search = to_cli_filter(enable_search)...
def load_key_bindings( get_search_state=None, enable_abort_and_exit_bindings=False, enable_system_bindings=False, enable_search=False, enable_open_in_editor=False, enable_extra_page_navigation=False, enable_auto_suggest_bindings=False)
Create a Registry object that contains the default key bindings. :param enable_abort_and_exit_bindings: Filter to enable Ctrl-C and Ctrl-D. :param enable_system_bindings: Filter to enable the system bindings (meta-! prompt and Control-Z suspension.) :param enable_search: Filter to enable the se...
2.051222
2.049133
1.00102
kw.setdefault('enable_abort_and_exit_bindings', True) kw.setdefault('enable_search', True) kw.setdefault('enable_auto_suggest_bindings', True) return load_key_bindings(**kw)
def load_key_bindings_for_prompt(**kw)
Create a ``Registry`` object with the defaults key bindings for an input prompt. This activates the key bindings for abort/exit (Ctrl-C/Ctrl-D), incremental search and auto suggestions. (Not for full screen applications.)
3.66153
3.332177
1.09884
if is_windows(): from prompt_toolkit.eventloop.win32 import Win32EventLoop as Loop return Loop(inputhook=inputhook, recognize_paste=recognize_win32_paste) else: from prompt_toolkit.eventloop.posix import PosixEventLoop as Loop return Loop(inputhook=inputhook)
def create_eventloop(inputhook=None, recognize_win32_paste=True)
Create and return an :class:`~prompt_toolkit.eventloop.base.EventLoop` instance for a :class:`~prompt_toolkit.interface.CommandLineInterface`.
2.299605
2.268549
1.01369
stdout = stdout or sys.__stdout__ true_color = to_simple_filter(true_color) if is_windows(): if is_conemu_ansi(): return ConEmuOutput(stdout) else: return Win32Output(stdout) else: term = os.environ.get('TERM', '') if PY2: term = ...
def create_output(stdout=None, true_color=False, ansi_colors_only=None)
Return an :class:`~prompt_toolkit.output.Output` instance for the command line. :param true_color: When True, use 24bit colors instead of 256 colors. (`bool` or :class:`~prompt_toolkit.filters.SimpleFilter`.) :param ansi_colors_only: When True, restrict to 16 ANSI colors only. (`bool` or :c...
3.936189
3.879672
1.014567
# Inline import, to make sure the rest doesn't break on Python 2. (Where # asyncio is not available.) if is_windows(): from prompt_toolkit.eventloop.asyncio_win32 import Win32AsyncioEventLoop as AsyncioEventLoop else: from prompt_toolkit.eventloop.asyncio_posix import PosixAsyncioEv...
def create_asyncio_eventloop(loop=None)
Returns an asyncio :class:`~prompt_toolkit.eventloop.EventLoop` instance for usage in a :class:`~prompt_toolkit.interface.CommandLineInterface`. It is a wrapper around an asyncio loop. :param loop: The asyncio eventloop (or `None` if the default asyncioloop should be used.)
5.046597
4.425034
1.140465
def has_before_tokens(cli): for token, char in get_prompt_tokens(cli): if '\n' in char: return True return False def before(cli): result = [] found_nl = False for token, char in reversed(explode_tokens(get_prompt_tokens(cli))): ...
def _split_multiline_prompt(get_prompt_tokens)
Take a `get_prompt_tokens` function and return three new functions instead. One that tells whether this prompt consists of multiple lines; one that returns the tokens to be shown on the lines above the input; and another one with the tokens to be shown at the first line of the input.
2.708334
2.496983
1.084643
patch_stdout = kwargs.pop('patch_stdout', False) return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine', False) true_color = kwargs.pop('true_color', False) refresh_interval = kwargs.pop('refresh_interval', 0) eventloop = kwargs.pop('eventloop', None) application = create_prompt_...
def prompt(message='', **kwargs)
Get input from the user and return it. This is a wrapper around a lot of ``prompt_toolkit`` functionality and can be a replacement for `raw_input`. (or GNU readline.) If you want to keep your history across several calls, create one :class:`~prompt_toolkit.history.History` instance and pass it every t...
2.506736
1.840977
1.361633
assert isinstance(application, Application) if return_asyncio_coroutine: eventloop = create_asyncio_eventloop() else: eventloop = eventloop or create_eventloop() # Create CommandLineInterface. cli = CommandLineInterface( application=application, eventloop=event...
def run_application( application, patch_stdout=False, return_asyncio_coroutine=False, true_color=False, refresh_interval=0, eventloop=None)
Run a prompt toolkit application. :param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that print statements from other threads won't destroy the prompt. (They will be printed above the prompt instead.) :param return_asyncio_coroutine: When True, return a asyncio coroutin...
3.018895
3.048639
0.990244
registry = Registry() @registry.add_binding('y') @registry.add_binding('Y') def _(event): event.cli.buffers[DEFAULT_BUFFER].text = 'y' event.cli.set_return_value(True) @registry.add_binding('n') @registry.add_binding('N') @registry.add_binding(Keys.ControlC) def _(...
def create_confirm_application(message)
Create a confirmation `Application` that returns True/False.
2.92984
2.889116
1.014096
assert isinstance(message, text_type) app = create_confirm_application(message) return run_application(app)
def confirm(message='Confirm (y or n) ')
Display a confirmation prompt.
11.197021
9.772213
1.145802
if style is None: style = DEFAULT_STYLE assert isinstance(style, Style) output = create_output(true_color=true_color, stdout=file) renderer_print_tokens(output, tokens, style)
def print_tokens(tokens, style=None, true_color=False, file=None)
Print a list of (Token, text) tuples in the given style to the output. E.g.:: style = style_from_dict({ Token.Hello: '#ff0066', Token.World: '#884444 italic', }) tokens = [ (Token.Hello, 'Hello'), (Token.World, 'World'), ] prin...
5.00331
7.598765
0.658437
" Create a table that maps the 16 named ansi colors to their Windows code. " return { 'ansidefault': color_cls.BLACK, 'ansiblack': color_cls.BLACK, 'ansidarkgray': color_cls.BLACK | color_cls.INTENSITY, 'ansilightgray': color_cls.GRAY, 'ansiwhite': color_cls.GR...
def _create_ansi_color_dict(color_cls)
Create a table that maps the 16 named ansi colors to their Windows code.
2.040518
1.800092
1.133563
self.flush() if _DEBUG_RENDER_OUTPUT: self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n') self.LOG.write(b' ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b'\n') self.LOG.write(b' ' + ', '.join(['%r' % type(i) for i in a]).encode('...
def _winapi(self, func, *a, **kw)
Flush and call win API function.
2.815962
2.68219
1.049874
# NOTE: We don't call the `GetConsoleScreenBufferInfo` API through # `self._winapi`. Doing so causes Python to crash on certain 64bit # Python versions. (Reproduced with 64bit Python 2.7.6, on Windows # 10). It is not clear why. Possibly, it has to do with passing ...
def get_win32_screen_buffer_info(self)
Return Screen buffer info.
5.365901
5.31709
1.00918
assert isinstance(title, six.text_type) self._winapi(windll.kernel32.SetConsoleTitleW, title)
def set_title(self, title)
Set terminal title.
5.80935
4.546999
1.277623
" Reset the console foreground/background color. " self._winapi(windll.kernel32.SetConsoleTextAttribute, self.hconsole, self.default_attrs)
def reset_attributes(self)
Reset the console foreground/background color.
14.078557
7.589896
1.854908
if not self._buffer: # Only flush stdout buffer. (It could be that Python still has # something in its buffer. -- We want to be sure to print that in # the correct color.) self.stdout.flush() return data = ''.join(self._buffer) ...
def flush(self)
Write to output stream and flush.
8.514157
8.372643
1.016902
# Get current window size info = self.get_win32_screen_buffer_info() sr = info.srWindow cursor_pos = info.dwCursorPosition result = SMALL_RECT() # Scroll to the left. result.Left = 0 result.Right = sr.Right - sr.Left # Scroll vertical ...
def scroll_buffer_to_prompt(self)
To be called before drawing the prompt. This should scroll the console to left, with the cursor at the bottom (if possible).
4.803418
4.524713
1.061596
if not self._in_alternate_screen: GENERIC_READ = 0x80000000 GENERIC_WRITE = 0x40000000 # Create a new console buffer and activate that one. handle = self._winapi(windll.kernel32.CreateConsoleScreenBuffer, GENERIC_READ|GENERIC_WRITE, ...
def enter_alternate_screen(self)
Go to alternate screen buffer.
3.920999
3.581328
1.094845
if self._in_alternate_screen: stdout = self._winapi(windll.kernel32.GetStdHandle, STD_OUTPUT_HANDLE) self._winapi(windll.kernel32.SetConsoleActiveScreenBuffer, stdout) self._winapi(windll.kernel32.CloseHandle, self.hconsole) self.hconsole = stdout ...
def quit_alternate_screen(self)
Make stdout again the active buffer.
3.690026
2.983948
1.236626
# Get console handle handle = windll.kernel32.GetConsoleWindow() RDW_INVALIDATE = 0x0001 windll.user32.RedrawWindow(handle, None, None, c_uint(RDW_INVALIDATE))
def win32_refresh_window(cls)
Call win32 API to refresh the whole Window. This is sometimes necessary when the application paints background for completion menus. When the menu disappears, it leaves traces due to a bug in the Windows Console. Sending a repaint request solves it.
5.420332
5.277958
1.026975
FG = FOREGROUND_COLOR BG = BACKROUND_COLOR return [ (0x00, 0x00, 0x00, FG.BLACK, BG.BLACK), (0x00, 0x00, 0xaa, FG.BLUE, BG.BLUE), (0x00, 0xaa, 0x00, FG.GREEN, BG.GREEN), (0x00, 0xaa, 0xaa, FG.CYAN, BG.CYAN), (0xaa, 0x00, 0x00,...
def _build_color_table()
Build an RGB-to-256 color conversion table
1.337616
1.334488
1.002344
# Foreground. if fg_color in FG_ANSI_COLORS: return FG_ANSI_COLORS[fg_color] else: return self._color_indexes(fg_color)[0]
def lookup_fg_color(self, fg_color)
Return the color for use in the `windll.kernel32.SetConsoleTextAttribute` API call. :param fg_color: Foreground as text. E.g. 'ffffff' or 'red'
4.780527
6.260621
0.763587
# Background. if bg_color in BG_ANSI_COLORS: return BG_ANSI_COLORS[bg_color] else: return self._color_indexes(bg_color)[1]
def lookup_bg_color(self, bg_color)
Return the color for use in the `windll.kernel32.SetConsoleTextAttribute` API call. :param bg_color: Background as text. E.g. 'ffffff' or 'red'
6.394527
7.544967
0.847522
if hasattr(array_or_tuple, 'size'): # pytorch tensors use V.size() to get size of tensor return list(array_or_tuple.size()) elif hasattr(array_or_tuple, 'get_shape'): # tensorflow uses V.get_shape() to get size of tensor return array_or_tuple.get_shape().as_list() elif h...
def nested_shape(array_or_tuple)
Figures out the shape of tensors possibly embedded in tuples i.e [0,0] returns (2) ([0,0], [0,0]) returns (2,2) (([0,0], [0,0]),[0,0]) returns ((2,2),2)
3.605197
3.650776
0.987515
log_track[LOG_TRACK_COUNT] += 1 if log_track[LOG_TRACK_COUNT] < log_track[LOG_TRACK_THRESHOLD]: return False log_track[LOG_TRACK_COUNT] = 0 return True
def log_track_update(log_track)
count (log_track[0]) up to threshold (log_track[1]), reset count (log_track[0]) and return true when reached
2.474734
2.017188
1.226824
if name is not None: prefix = prefix + name if log_parameters: def parameter_log_hook(module, input_, output, log_track): if not log_track_update(log_track): return for name, parameter in module.named_parameters(): ...
def add_log_hooks_to_pytorch_module(self, module, name=None, prefix='', log_parameters=True, log_gradients=True, log_freq=0)
This instuments hooks into the pytorch module log_parameters - log parameters after a forward pass log_gradients - log gradients after a backward pass log_freq - log gradients/parameters every N batches
2.952052
2.990913
0.987007
# TODO Handle the case of duplicate names. if (isinstance(tensor, tuple) or isinstance(tensor, list)): while (isinstance(tensor, tuple) or isinstance(tensor, list)) and (isinstance(tensor[0], tuple) or isinstance(tensor[0], list)): tensor = [item for sublist in tens...
def log_tensor_stats(self, tensor, name)
Add distribution statistics on a tensor's elements to the current History entry
4.301534
4.250516
1.012003
if not isinstance(var, torch.autograd.Variable): cls = type(var) raise TypeError('Expected torch.Variable, not {}.{}'.format( cls.__module__, cls.__name__)) handle = self._hook_handles.get(name) if handle is not None and self._torch_hook_handle_i...
def _hook_variable_gradient_stats(self, var, name, log_track)
Logs a Variable's gradient's distribution statistics next time backward() is called on it.
3.401676
3.469118
0.980559
try: return self._line_heights[lineno, width] except KeyError: text = token_list_to_text(self.get_line(lineno)) result = self.get_height_for_text(text, width) # Cache and return self._line_heights[lineno, width] = result r...
def get_height_for_line(self, lineno, width)
Return the height that a given line would need if it is rendered in a space with the given width.
3.326456
3.327628
0.999648
return self._token_cache.get( cli.render_counter, lambda: self.get_tokens(cli))
def _get_tokens_cached(self, cli)
Get tokens, but only retrieve tokens once during one render run. (This function is called several times during one rendering, because we also need those for calculating the dimensions.)
10.728631
5.646701
1.899982
text = token_list_to_text(self._get_tokens_cached(cli)) line_lengths = [get_cwidth(l) for l in text.split('\n')] return max(line_lengths)
def preferred_width(self, cli, max_available_width)
Return the preferred width for this control. That is the width of the longest line.
6.695579
5.943511
1.126536
if self._tokens: # Read the generator. tokens_for_line = list(split_lines(self._tokens)) try: tokens = tokens_for_line[mouse_event.position.y] except IndexError: return NotImplemented else: # Fi...
def mouse_handler(self, cli, mouse_event)
Handle mouse events. (When the token list contained mouse handlers and the user clicked on on any of these, the matching handler is called. This handler can still return `NotImplemented` in case we want the `Window` to handle this particular event.)
5.199069
4.474386
1.161963
# Cache using `document.text`. def get_tokens_for_line(): return self.lexer.lex_document(cli, document) return self._token_cache.get(document.text, get_tokens_for_line)
def _get_tokens_for_line_func(self, cli, document)
Create a function that returns the tokens for a given line.
5.019848
4.806815
1.044319
def transform(lineno, tokens): " Transform the tokens for a given line number. " source_to_display_functions = [] display_to_source_functions = [] # Get cursor position at this line. if document.cursor_position_row == lineno: ...
def _create_get_processed_line_func(self, cli, document)
Create a function that takes a line number of the current document and returns a _ProcessedLine(processed_tokens, source_to_display, display_to_source) tuple.
2.703934
2.512995
1.075981
buffer = self._buffer(cli) # Get the document to be shown. If we are currently searching (the # search buffer has focus, and the preview_search filter is enabled), # then use the search document, which has possibly a different # text/cursor position.) def previe...
def create_content(self, cli, width, height)
Create a UIContent.
4.961231
4.907465
1.010956
buffer = self._buffer(cli) position = mouse_event.position # Focus buffer when clicked. if self.has_focus(cli): if self._last_get_processed_line: processed_line = self._last_get_processed_line(position.y) # Translate coordinates back...
def mouse_handler(self, cli, mouse_event)
Mouse handler for this control.
4.74424
4.772035
0.994175
arg = cli.input_processor.arg return [ (Token.Prompt.Arg, '(arg: '), (Token.Prompt.Arg.Text, str(arg)), (Token.Prompt.Arg, ') '), ]
def _get_arg_tokens(cli)
Tokens for the arg-prompt.
7.329983
5.97858
1.226041
assert isinstance(message, text_type) def get_message_tokens(cli): return [(Token.Prompt, message)] return cls(get_message_tokens)
def from_message(cls, message='> ')
Create a default prompt with a static message text.
7.149564
5.627579
1.270451
if not isinstance(data, list): print('warning: malformed json data for file', fname) return with open(fname, 'w') as of: for row in data: # TODO: other malformed cases? if row.strip(): of.write('%s\n' % row.strip())
def write_jsonl_file(fname, data)
Writes a jsonl file. Args: data: list of json encoded data
4.953034
6.104834
0.81133
# Process signal asynchronously, because this handler can write to the # output, and doing this inside the signal handler causes easily # reentrant calls, giving runtime errors.. # Furthur, this has to be thread safe. When the CommandLineInterface # runs not in the main...
def received_winch(self)
Notify the event loop that SIGWINCH has been received
15.561491
14.49563
1.07353
# Wait until the main thread is idle. # We start the thread by using `call_from_executor`. The event loop # favours processing input over `calls_from_executor`, so the thread # will not start until there is no more input to process and the main # thread becomes idle for ...
def run_in_executor(self, callback)
Run a long running function in a background thread. (This is recommended for code that could block the event loop.) Similar to Twisted's ``deferToThread``.
13.033876
13.248477
0.983802
assert _max_postpone_until is None or isinstance(_max_postpone_until, float) self._calls_from_executor.append((callback, _max_postpone_until)) if self._schedule_pipe: try: os.write(self._schedule_pipe[1], b'x') except (AttributeError, IndexError,...
def call_from_executor(self, callback, _max_postpone_until=None)
Call this function in the main event loop. Similar to Twisted's ``callFromThread``. :param _max_postpone_until: `None` or `time.time` value. For interal use. If the eventloop is saturated, consider this task to be low priority and postpone maximum until this timestamp. (For inst...
4.684231
4.662602
1.004639
" Add read file descriptor to the event loop. " fd = fd_to_int(fd) self._read_fds[fd] = callback self.selector.register(fd)
def add_reader(self, fd, callback)
Add read file descriptor to the event loop.
7.624868
5.41471
1.408177
" Remove read file descriptor from the event loop. " fd = fd_to_int(fd) if fd in self._read_fds: del self._read_fds[fd] self.selector.unregister(fd)
def remove_reader(self, fd)
Remove read file descriptor from the event loop.
4.937876
4.063094
1.215299
cache = SimpleCache(maxsize=maxsize) def decorator(obj): @wraps(obj) def new_callable(*a, **kw): def create_new(): return obj(*a, **kw) key = (a, tuple(kw.items())) return cache.get(key, create_new) return new_callable return...
def memoized(maxsize=1024)
Momoization decorator for immutable classes and pure functions.
2.821535
2.744176
1.02819
# Look in cache first. try: return self._data[key] except KeyError: # Not found? Get it. value = getter_func() self._data[key] = value self._keys.append(key) # Remove the oldest key when the size is exceeded. ...
def get(self, key, getter_func)
Get object from the cache. If not found, call `getter_func` to resolve it, and put that on the top of the cache instead.
2.535686
2.485794
1.020071
filter = to_cli_filter(kwargs.pop('filter', True)) eager = to_cli_filter(kwargs.pop('eager', False)) save_before = kwargs.pop('save_before', lambda e: True) to_cli_filter(kwargs.pop('invalidate_ui', True)) # Deprecated! (ignored.) assert not kwargs assert keys ...
def add_binding(self, *keys, **kwargs)
Decorator for annotating key bindings. :param filter: :class:`~prompt_toolkit.filters.CLIFilter` to determine when this key binding is active. :param eager: :class:`~prompt_toolkit.filters.CLIFilter` or `bool`. When True, ignore potential longer matches when this key binding is ...
5.757151
4.6406
1.240605
assert callable(function) for b in self.key_bindings: if b.handler == function: self.key_bindings.remove(b) self._clear_cache() return # No key binding found for this function. Raise ValueError. raise ValueError('Bind...
def remove_binding(self, function)
Remove a key binding. This expects a function that was given to `add_binding` method as parameter. Raises `ValueError` when the given function was not registered before.
4.271869
3.857157
1.107517
def get(): result = [] for b in self.key_bindings: if len(keys) == len(b.keys): match = True any_count = 0 for i, j in zip(b.keys, keys): if i != j and i != Keys.Any: ...
def get_bindings_for_keys(self, keys)
Return a list of key bindings that can handle this key. (This return also inactive bindings, so the `filter` still has to be called, for checking it.) :param keys: tuple of keys.
3.231747
3.220073
1.003625
def get(): result = [] for b in self.key_bindings: if len(keys) < len(b.keys): match = True for i, j in zip(b.keys, keys): if i != j and i != Keys.Any: match = False ...
def get_bindings_starting_with_keys(self, keys)
Return a list of key bindings that handle a key sequence starting with `keys`. (It does only return bindings for which the sequences are longer than `keys`. And like `get_bindings_for_keys`, it also includes inactive bindings.) :param keys: tuple of keys.
2.882615
2.828036
1.019299
" If the original registry was changed. Update our copy version. " expected_version = (self.registry._version, self._extra_registry._version) if self._last_version != expected_version: registry2 = Registry() # Copy all bindings from `self.registry`, adding our condition...
def _update_cache(self)
If the original registry was changed. Update our copy version.
6.09332
4.576965
1.331301
expected_version = ( tuple(r._version for r in self.registries) + (self._extra_registry._version, )) if self._last_version != expected_version: registry2 = Registry() for reg in self.registries: registry2.key_bindings.extend(reg....
def _update_cache(self)
If one of the original registries was changed. Update our merged version.
4.274048
3.739888
1.142828
if not config_dict: config_file = find_config_file(config_path) if not config_file: return cls({}, credstore_env) try: with open(config_file) as f: config_dict = json.load(f) except (IOError, KeyError,...
def load_config(cls, config_path, config_dict, credstore_env=None)
Loads authentication data from a Docker configuration file in the given root directory or if config_path is passed use given path. Lookup priority: explicit config_path parameter > DOCKER_CONFIG environment variable > ~/.docker/config.json > ~/.dockercfg
2.952117
2.860577
1.032
tfutil = util.get_module('tensorflow.python.util') if tfutil: return tfutil.nest.flatten(thing) else: return [thing]
def nest(thing)
Use tensorflows nest function if available, otherwise just wrap object in an array
5.803381
3.349418
1.732654
converted = val typename = util.get_full_typename(val) if util.is_matplotlib_typename(typename): # This handles plots with images in it because plotly doesn't support it # TODO: should we handle a list of plots? val = util.ensure_matplotlib_figure(val) if any(len(ax.imag...
def val_to_json(key, val, mode="summary", step=None)
Converts a wandb datatype to its JSON representation
3.47979
3.405089
1.021938
for key, val in six.iteritems(payload): if isinstance(val, dict): payload[key] = to_json(val, mode) else: payload[key] = val_to_json( key, val, mode, step=payload.get("_step")) return payload
def to_json(payload, mode="history")
Converts all keys in a potentially nested array into their JSON representation
3.283061
3.095148
1.060712
# TODO: do we want to support dimensions being at the beginning of the array? if data.ndim == 2: return "L" elif data.shape[-1] == 3: return "RGB" elif data.shape[-1] == 4: return "RGBA" else: raise ValueError( ...
def guess_mode(self, data)
Guess what type of image the np.array is representing
4.376335
3.787055
1.155604
np = util.get_module( "numpy", required="wandb.Image requires numpy if not supplying PIL Images: pip install numpy") # I think it's better to check the image range vs the data type, since many # image libraries will return floats between 0 and 255 # some images hav...
def to_uint8(self, data)
Converts floating point image on the range [0,1] and integer images on the range [0,255] to uint8, clipping if necessary.
5.341881
5.328871
1.002441
from PIL import Image as PILImage base = os.path.join(out_dir, "media", "images") width, height = images[0].image.size num_images_to_log = len(images) if num_images_to_log > Image.MAX_IMAGES: logging.warn( "The maximum number of images to sto...
def transform(images, out_dir, fname)
Combines a list of images into a single sprite returning meta information
3.086898
3.024617
1.020591
kw.setdefault('enable_abort_and_exit_bindings', True) kw.setdefault('enable_search', True) kw.setdefault('enable_auto_suggest_bindings', True) return cls(**kw)
def for_prompt(cls, **kw)
Create a ``KeyBindingManager`` with the defaults for an input prompt. This activates the key bindings for abort/exit (Ctrl-C/Ctrl-D), incremental search and auto suggestions. (Not for full screen applications.)
5.592319
2.901961
1.927083
assert isinstance(app, Application) assert callback is None or callable(callback) self.cli = CommandLineInterface( application=app, eventloop=self.eventloop, output=self.vt100_output) self.callback = callback # Create a parser, and p...
def set_application(self, app, callback=None)
Set ``CommandLineInterface`` instance for this connection. (This can be replaced any time.) :param cli: CommandLineInterface instance. :param callback: Callable that takes the result of the CLI.
6.47427
6.502821
0.995609
assert isinstance(data, binary_type) self.parser.feed(data) # Render again. self.cli._redraw() # When a return value has been set (enter was pressed), handle command. if self.cli.is_returning: try: return_value = self.cli.return_val...
def feed(self, data)
Handler for incoming data. (Called by TelnetServer.)
6.322832
5.701617
1.108954
logger.info('Handle command %r', command) def in_executor(): self.handling_command = True try: if self.callback is not None: self.callback(self, command) finally: self.server.call_from_executor(done) ...
def _handle_command(self, command)
Handle command. This will run in a separate thread, in order not to block the event loop.
6.668609
6.458508
1.032531
self.vt100_output.erase_screen() self.vt100_output.cursor_goto(0, 0) self.vt100_output.flush()
def erase_screen(self)
Erase output screen.
3.366922
3.096891
1.087194
assert isinstance(data, text_type) # When data is send back to the client, we should replace the line # endings. (We didn't allocate a real pseudo terminal, and the telnet # connection is raw, so we are responsible for inserting \r.) self.stdout.write(data.replace('\n',...
def send(self, data)
Send text to the client.
10.158184
9.479552
1.071589
self.application.client_leaving(self) self.conn.close() self.closed = True
def close(self)
Close the connection.
12.858676
10.411287
1.235071
# Flush all the pipe content. os.read(self._schedule_pipe[0], 1024) # Process calls from executor. calls_from_executor, self._calls_from_executor = self._calls_from_executor, [] for c in calls_from_executor: c()
def _process_callbacks(self)
Process callbacks from `call_from_executor` in eventloop.
6.590851
5.266951
1.25136
listen_socket = self.create_socket(self.host, self.port) logger.info('Listening for telnet connections on %s port %r', self.host, self.port) try: while True: # Removed closed connections. self.connections = set([c for c in self.connections if...
def run(self)
Run the eventloop for the telnet server.
4.482738
4.221823
1.061801
conn, addr = listen_socket.accept() connection = TelnetConnection(conn, addr, self.application, self, encoding=self.encoding) self.connections.add(connection) logger.info('New connection %r %r', *addr)
def _accept(self, listen_socket)
Accept new incoming connection.
4.608796
4.155015
1.109213
connection = [c for c in self.connections if c.conn == conn][0] data = conn.recv(1024) if data: connection.feed(data) else: self.connections.remove(connection)
def _handle_incoming_data(self, conn)
Handle incoming data on socket.
2.860238
2.610377
1.095718
try: return self.client.execute(*args, **kwargs) except requests.exceptions.HTTPError as err: res = err.response logger.error("%s response executing GraphQL." % res.status_code) logger.error(res.text) self.display_gorilla_error_if_foun...
def execute(self, *args, **kwargs)
Wrapper around execute that logs in cases of failure.
5.066567
4.699701
1.078062
try: import pkg_resources installed_packages = [d for d in iter(pkg_resources.working_set)] installed_packages_list = sorted( ["%s==%s" % (i.key, i.version) for i in installed_packages] ) with open(os.path.join(out_dir, 'requi...
def save_pip(self, out_dir)
Saves the current working set of pip packages to requirements.txt
2.374821
2.27288
1.044851
if not self.git.enabled: return False try: root = self.git.root if self.git.dirty: patch_path = os.path.join(out_dir, 'diff.patch') if self.git.has_submodule_diff: with open(patch_path, 'wb') as patch: ...
def save_patches(self, out_dir)
Save the current state of this repository to one or more patches. Makes one patch against HEAD and another one against the most recent commit that occurs in an upstream branch. This way we can be robust to history editing as long as the user never does "push -f" to break history on an u...
2.162389
2.030055
1.065188
if not self._settings: self._settings = self.default_settings.copy() section = section or self._settings['section'] try: if section in self.settings_parser.sections(): for option in self.settings_parser.options(section): ...
def settings(self, key=None, section=None)
The settings overridden from the wandb/settings file. Args: key (str, optional): If provided only this setting is returned section (str, optional): If provided this section of the setting file is used, defaults to "default" Returns: A dict with the curre...
2.518799
2.299402
1.095415
query = gql(''' query Models($entity: String!) { models(first: 10, entityName: $entity) { edges { node { id name description } } ...
def list_projects(self, entity=None)
Lists projects in W&B scoped by entity. Args: entity (str, optional): The entity to scope this project to. Returns: [{"id","name","description"}]
4.55311
4.49929
1.011962