text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_closest_ansi_color(r, g, b, exclude=()): """ Find closest ANSI color. Return it by name. :param r: Red (Between 0 and 255.) :param g: Green (Between 0 and 255.) :param b: Blue (Between 0 and 255.) :param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.) """
assert isinstance(exclude, tuple) # When we have a bit of saturation, avoid the gray-like colors, otherwise, # too often the distance to the gray color is less. saturation = abs(r - g) + abs(g - b) + abs(b - r) # Between 0..510 if saturation > 30: exclude += ('ansilightgray', 'ansidarkgray', 'ansiwhite', 'ansiblack') # Take the closest color. # (Thanks to Pygments for this part.) distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff) match = 'ansidefault' for name, (r2, g2, b2) in ANSI_COLORS_TO_RGB.items(): if name != 'ansidefault' and name not in exclude: d = (r - r2) ** 2 + (g - g2) ** 2 + (b - b2) ** 2 if d < distance: match = name distance = d return match
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_size(fileno): # Thanks to fabric (fabfile.org), and # http://sqizit.bartletts.id.au/2011/02/14/pseudo-terminals-in-python/ """ Get the size of this pseudo terminal. :param fileno: stdout.fileno() :returns: A (rows, cols) tuple. """
# Inline imports, because these modules are not available on Windows. # (This file is used by ConEmuOutput, which is used on Windows.) import fcntl import termios # Buffer for the C call buf = array.array(b'h' if six.PY2 else u'h', [0, 0, 0, 0]) # Do TIOCGWINSZ (Get) # Note: We should not pass 'True' as a fourth parameter to 'ioctl'. (True # is the default.) This causes segmentation faults on some systems. # See: https://github.com/jonathanslenders/python-prompt-toolkit/pull/364 fcntl.ioctl(fileno, termios.TIOCGWINSZ, buf) # Return rows, cols return buf[0], buf[1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _colors_to_code(self, fg_color, bg_color): " Return a tuple with the vt100 values that represent this color. " # When requesting ANSI colors only, and both fg/bg color were converted # to ANSI, ensure that the foreground and background color are not the # same. (Unless they were explicitely defined to be the same color.) fg_ansi = [()] def get(color, bg): table = BG_ANSI_COLORS if bg else FG_ANSI_COLORS if color is None: return () # 16 ANSI colors. (Given by name.) elif color in table: return (table[color], ) # RGB colors. (Defined as 'ffffff'.) else: try: rgb = self._color_name_to_rgb(color) except ValueError: return () # When only 16 colors are supported, use that. if self.ansi_colors_only(): if bg: # Background. if fg_color != bg_color: exclude = (fg_ansi[0], ) else: exclude = () code, name = _16_bg_colors.get_code(rgb, exclude=exclude) return (code, ) else: # Foreground. code, name = _16_fg_colors.get_code(rgb) fg_ansi[0] = name return (code, ) # True colors. (Only when this feature is enabled.) elif self.true_color: r, g, b = rgb return (48 if bg else 38, 2, r, g, b) # 256 RGB colors. else: return (48 if bg else 38, 5, _256_colors[rgb]) result = [] result.extend(get(fg_color, False)) result.extend(get(bg_color, True)) return map(six.text_type, result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attributes(self, attrs): """ Create new style and output. :param attrs: `Attrs` instance. """
if self.true_color() and not self.ansi_colors_only(): self.write_raw(self._escape_code_cache_true_color[attrs]) else: self.write_raw(self._escape_code_cache[attrs])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def watch(models, criterion=None, log="gradients", log_freq=100): """ Hooks into the torch model to collect gradients and the topology. Should be extended to accept arbitrary ML models. :param (torch.Module) models: The model to hook, can be a tuple :param (torch.F) criterion: An optional loss value being optimized :param (str) log: One of "gradients", "parameters", "all", or None :param (int) log_freq: log gradients and parameters every N batches :return: (wandb.Graph) The graph object that will populate after the first backward pass """
global watch_called if run is None: raise ValueError( "You must call `wandb.init` before calling watch") if watch_called: raise ValueError( "You can only call `wandb.watch` once per process. If you want to watch multiple models, pass them in as a tuple." ) watch_called = True log_parameters = False log_gradients = True if log == "all": log_parameters = True elif log == "parameters": log_parameters = True log_gradients = False elif log is None: log_gradients = False if not isinstance(models, (tuple, list)): models = (models,) graphs = [] prefix = '' for idx, model in enumerate(models): if idx > 0: prefix = "graph_%i" % idx run.history.torch.add_log_hooks_to_pytorch_module( model, log_parameters=log_parameters, log_gradients=log_gradients, prefix=prefix, log_freq=log_freq) graph = wandb_torch.TorchGraph.hook_torch(model, criterion, graph_idx=idx) graphs.append(graph) # NOTE: the graph is set in run.summary by hook_torch on the backward pass return graphs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(name, run_path=None, replace=False, root="."): """ Downloads the specified file from cloud storage into the current run directory if it doesn exist. name: the name of the file run_path: optional path to a different run to pull files from replace: whether to download the file even if it already exists locally root: the directory to download the file to. Defaults to the current directory or the run directory if wandb.init was called. returns None if it can't find the file, otherwise a file object open for reading raises wandb.CommError if it can't find the run """
if run_path is None and run is None: raise ValueError( "You must call `wandb.init` before calling restore or specify a run_path") api = Api() api_run = api.run(run_path or run.path) root = run.dir if run else root path = os.path.exists(os.path.join(root, name)) if path and replace == False: return open(path, "r") files = api_run.files([name]) if len(files) == 0: return None return files[0].download(root=root, replace=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def monitor(options={}): """Starts syncing with W&B if you're in Jupyter. Displays your W&B charts live in a Jupyter notebook. It's currently a context manager for legacy reasons. """
try: from IPython.display import display except ImportError: def display(stuff): return None class Monitor(): def __init__(self, options={}): if os.getenv("WANDB_JUPYTER"): display(jupyter.Run()) else: self.rm = False termerror( "wandb.monitor is only functional in Jupyter notebooks") def __enter__(self): termlog( "DEPRECATED: with wandb.monitor(): is deprecated, just call wandb.monitor() to see live results.") pass def __exit__(self, *args): pass return Monitor(options)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(row=None, commit=True, *args, **kargs): """Log a dict to the global run's history. If commit is false, enables multiple calls before commiting. Eg. wandb.log({'train-loss': 0.5, 'accuracy': 0.9}) """
if run is None: raise ValueError( "You must call `wandb.init` in the same process before calling log") if row is None: row = {} if commit: run.history.add(row, *args, **kargs) else: run.history.update(row, *args, **kargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_env(exclude=[]): """Remove environment variables, used in Jupyter notebooks"""
if os.getenv(env.INITED): wandb_keys = [key for key in os.environ.keys() if key.startswith( 'WANDB_') and key not in exclude] for key in wandb_keys: del os.environ[key] return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def try_to_set_up_global_logging(): """Try to set up global W&B debug log that gets re-written by every W&B process. It may fail (and return False) eg. if the current directory isn't user-writable """
root = logging.getLogger() root.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(filename)s:%(funcName)s():%(lineno)s] %(message)s') if env.is_debug(): handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) handler.setFormatter(formatter) root.addHandler(handler) try: handler = logging.FileHandler(GLOBAL_LOG_FNAME, mode='w') handler.setLevel(logging.DEBUG) handler.setFormatter(formatter) root.addHandler(handler) except IOError as e: # eg. in case wandb directory isn't writable termerror('Failed to set up logging: {}'.format(e)) return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sagemaker_auth(overrides={}, path="."): """ Write a secrets.env file with the W&B ApiKey and any additional secrets passed. Args: overrides (dict, optional): Additional environment variables to write to secrets.env path (str, optional): The path to write the secrets file. """
api_key = overrides.get(env.API_KEY, Api().api_key) if api_key is None: raise ValueError( "Can't find W&B ApiKey, set the WANDB_API_KEY env variable or run `wandb login`") overrides[env.API_KEY] = api_key with open(os.path.join(path, "secrets.env"), "w") as file: for k, v in six.iteritems(overrides): file.write("{}={}\n".format(k, v))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
if old_save_name in self._files: del self._files[old_save_name] self.update_file(new_save_name, new_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(name): """ Store handler in the `_readline_commands` dictionary. """
assert isinstance(name, six.text_type) def decorator(handler): assert callable(handler) _readline_commands[name] = handler return handler return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def beginning_of_line(event): " 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def end_of_line(event): " Move to the end of the line. " buff = event.current_buffer buff.cursor_position += buff.document.get_end_of_line_position()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def forward_char(event): " Move forward a character. " buff = event.current_buffer buff.cursor_position += buff.document.get_cursor_right_position(count=event.arg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def backward_char(event): " Move back a character. " buff = event.current_buffer buff.cursor_position += buff.document.get_cursor_left_position(count=event.arg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward_word(event): """ Move forward to the end of the next word. Words are composed of letters and digits. """
buff = event.current_buffer pos = buff.document.find_next_word_ending(count=event.arg) if pos: buff.cursor_position += pos
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def backward_word(event): """ Move back to the start of the current or previous word. Words are composed of letters and digits. """
buff = event.current_buffer pos = buff.document.find_previous_word_beginning(count=event.arg) if pos: buff.cursor_position += pos
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def accept_line(event): " Accept the line regardless of where the cursor is. " b = event.current_buffer b.accept_action.validate_and_handle(event.cli, b)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def end_of_history(event): """ Move to the end of the input history, i.e., the line currently being entered. """
event.current_buffer.history_forward(count=10**100) buff = event.current_buffer buff.go_to_history(len(buff._working_lines) - 1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
event.cli.current_search_state.direction = IncrementalSearchDirection.BACKWARD event.cli.push_focus(SEARCH_BUFFER)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete_char(event): " Delete character before the cursor. " deleted = event.current_buffer.delete(count=event.arg) if not deleted: event.cli.output.bell()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def backward_delete_char(event): " 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.) """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unix_word_rubout(event, WORD=True): """ Kill the word behind point, using whitespace as a word boundary. Usually bound to ControlW. """
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete_horizontal_space(event): " 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unix_line_discard(event): """ Kill backward from the cursor to the beginning of the current line. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yank(event): """ Paste before cursor. """
event.current_buffer.paste_clipboard_data( event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yank_last_arg(event): """ Like `yank_nth_arg`, but if no argument has been given, yank the last word of each line. """
n = (event.arg if event.arg_present else None) event.current_buffer.yank_last_arg(n)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yank_pop(event): """ Rotate the kill ring, and yank the new top. Only works following yank or yank-pop. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def print_last_kbd_macro(event): " 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_comment(event): """ Without numeric argument, comment all lines. With numeric argument, uncomment all lines. In any case accept the input. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_and_execute(event): """ Invoke an editor on the current command line, and accept the result. """
buff = event.current_buffer buff.open_in_editor(event.cli) buff.accept_action.validate_and_handle(event.cli, buff)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_auto_suggestion_bindings(): """ Key bindings for accepting auto suggestion text. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_columns(self, types): """Set the column types args: types: iterable of (column_name, type) pairs. """
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]})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rows_above_layout(self): """ Return the number of rows visible in the terminal above the layout. """
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.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self): """ Clear screen and go to 0,0 """
# 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def close(self): " Close pipe fds. " os.close(self._r) os.close(self._w) self._r = None self._w = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_all_tokens(self, token): """ For all the characters in the screen. Set the token to the given `token`. """
b = self.data_buffer for y, row in b.items(): for x, char in row.items(): b[y][x] = _CHAR_CACHE[char.char, token]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_response(self, response): """Logs dropped chunks and updates dynamic settings"""
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"])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
self._queue.put(Chunk(filename, data))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finish(self, exitcode): """Cleans up. Anything pushed after finish will be dropped. Args: exitcode: The exitcode of the watched process. """
self._queue.put(self.Finish(exitcode)) self._thread.join()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def shell(cmd): "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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 """
# 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 {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image_id_from_registry(image_name): """Get the docker id from a public or private registry"""
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"]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def escape(self, varname, value): """ Escape `value` to fit in the place of this variable into the grammar. """
f = self.escape_funcs.get(varname) return f(value) if f else value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unescape(self, varname, value): """ Unescape `value`. """
f = self.unescape_funcs.get(varname) return f(value) if f else value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def end_nodes(self): """ Yields `MatchVariable` instances for all the nodes having their end position at the end of the input string. """
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]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self, mode=InputMode.INSERT): """ Reset state, go back to the given mode. INSERT by default. """
# Go back to insert mode. self.input_mode = mode self.waiting_for_digraph = False self.operator_func = None self.operator_arg = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_buffer(self, name, buffer, focus=False): """ Insert a new buffer. """
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(): """ Wrapper around the asynchronous completer and auto suggestion, that ensures that it's only called while typing if the `complete_while_typing` filter is enabled. """ 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(_): """ When the text in a buffer changes. (A paste event is also a change, but not an insert. So we don't want to do autocompletions in this case, but we want to propagate the on_buffer_changed event.) """ # Trigger on_buffer_changed. self.on_buffer_changed.fire() buffer.on_text_changed += buffer_changed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def terminal_title(self): """ Return the current title to be displayed in the terminal. When this in `None`, the terminal title remains the original. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
# 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invalidate(self): """ Thread safe way of sending a repaint trigger to the input event loop. """
# 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
# 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _pre_run(self, pre_run=None): " 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[:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exit(self): """ Set exit. When Control-D has been pressed. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def abort(self): """ Set abort. When Control-C has been pressed. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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`. """
# 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(): 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. """
# 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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`. """
return _PatchStdoutContext( self.stdout_proxy(raw=raw), patch_stdout=patch_stdout, patch_stderr=patch_stderr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _active_cli(self): """ Return the active `CommandLineInterface`. """
cli = self.cli # If there is a sub CLI. That one is always active. while cli._sub_cli: cli = cli._sub_cli return cli
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def feed_key(self, key_press): """ Feed a key press to the CommandLineInterface. """
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_mouse_handler_for_range(self, x_min, x_max, y_min, y_max, handler=None): """ Set mouse handler for a region. """
for x, y in product(range(x_min, x_max), range(y_min, y_max)): self.mouse_handlers[x,y] = handler
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 """
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")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_debug(self): """Uploads the debug log to cloud storage"""
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def display_completions_like_readline(event): """ Key binding handler for readline-style tab completion. This is meant to be as similar as possible to the way how readline displays completions. Generate the completions immediately (blocking) and display them above the prompt in columns. Usage:: # Call this handler when 'Tab' has been pressed. registry.add_binding(Keys.ControlI)(display_completions_like_readline) """
# Request completions. b = event.current_buffer if b.completer is None: return complete_event = CompleteEvent(completion_requested=True) completions = list(b.completer.get_completions(b.document, complete_event)) # Calculate the common suffix. common_suffix = get_common_complete_suffix(b.document, completions) # One completion: insert it. if len(completions) == 1: b.delete_before_cursor(-completions[0].start_position) b.insert_text(completions[0].text) # Multiple completions with common part. elif common_suffix: b.insert_text(common_suffix) # Otherwise: display all completions. elif completions: _display_completions_like_readline(event.cli, completions)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _display_completions_like_readline(cli, completions): """ Display the list of completions in columns above the prompt. This will ask for a confirmation if there are too many completions to fit on a single page and provide a paginator to walk through them. """
from prompt_toolkit.shortcuts import create_confirm_application assert isinstance(completions, list) # Get terminal dimensions. term_size = cli.output.get_size() term_width = term_size.columns term_height = term_size.rows # Calculate amount of required columns/rows for displaying the # completions. (Keep in mind that completions are displayed # alphabetically column-wise.) max_compl_width = min(term_width, max(get_cwidth(c.text) for c in completions) + 1) column_count = max(1, term_width // max_compl_width) completions_per_page = column_count * (term_height - 1) page_count = int(math.ceil(len(completions) / float(completions_per_page))) # Note: math.ceil can return float on Python2. def display(page): # Display completions. page_completions = completions[page * completions_per_page: (page+1) * completions_per_page] page_row_count = int(math.ceil(len(page_completions) / float(column_count))) page_columns = [page_completions[i * page_row_count:(i+1) * page_row_count] for i in range(column_count)] result = [] for r in range(page_row_count): for c in range(column_count): try: result.append(page_columns[c][r].text.ljust(max_compl_width)) except IndexError: pass result.append('\n') cli.output.write(''.join(result)) cli.output.flush() # User interaction through an application generator function. def run(): if len(completions) > completions_per_page: # Ask confirmation if it doesn't fit on the screen. message = 'Display all {} possibilities? (y on n) '.format(len(completions)) confirm = yield create_confirm_application(message) if confirm: # Display pages. for page in range(page_count): display(page) if page != page_count - 1: # Display --MORE-- and go to the next page. show_more = yield _create_more_application() if not show_more: return else: cli.output.write('\n'); cli.output.flush() else: # Display all completions. display(0) cli.run_application_generator(run, render_cli_done=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_simple_filter(bool_or_filter): """ Accept both booleans and CLIFilters as input and turn it into a SimpleFilter. """
if not isinstance(bool_or_filter, (bool, SimpleFilter)): raise TypeError('Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter) return { True: _always, False: _never, }.get(bool_or_filter, bool_or_filter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_cli_filter(bool_or_filter): """ Accept both booleans and CLIFilters as input and turn it into a CLIFilter. """
if not isinstance(bool_or_filter, (bool, CLIFilter)): raise TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter) return { True: _always, False: _never, }.get(bool_or_filter, bool_or_filter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, count=1024): # By default we choose a rather small chunk size, because reading # big amounts of input at once, causes the event loop to process # all these key bindings also at once without going back to the # loop. This will make the application feel unresponsive. """ Read the input and return it as a string. Return the text. Note that this can return an empty string, even when the input stream was not yet closed. This means that something went wrong during the decoding. """
if self.closed: return b'' # Note: the following works better than wrapping `self.stdin` like # `codecs.getreader('utf-8')(stdin)` and doing `read(1)`. # Somehow that causes some latency when the escape # character is pressed. (Especially on combination with the `select`.) try: data = os.read(self.stdin_fd, count) # Nothing more to read, stream is closed. if data == b'': self.closed = True return '' except OSError: # In case of SIGWINCH data = b'' return self._stdin_decoder.decode(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_string(self, data): """Process some data splitting it into complete lines and buffering the rest Args: data: A `str` in Python 2 or `bytes` in Python 3 Returns: list of complete lines ending with a carriage return (eg. a progress bar) or a newline. """
lines = [] while data: match = self._line_end_re.search(data) if match is None: chunk = data else: chunk = data[:match.end()] data = data[len(chunk):] if self._buf and self._buf[-1].endswith(b('\r')) and not chunk.startswith(b('\n')): # if we get a carriage return followed by something other than # a newline then we assume that we're overwriting the current # line (ie. a progress bar) # # We don't terminate lines that end with a carriage return until # we see what's coming next so we can distinguish between a # progress bar situation and a Windows line terminator. # # TODO(adrian): some day these hacks should be replaced with # real terminal emulation lines.append(self._finish_line()) self._buf.append(chunk) if chunk.endswith(b('\n')): lines.append(self._finish_line()) return lines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, message, cur_time=None): """Write some text to the pusher. Args: message: a string to push for this file. cur_time: used for unit testing. override line timestamp. """
if cur_time is None: cur_time = time.time() lines = self._line_buffer.add_string(message) for line in lines: #print('ts line', repr(line)) timestamp = '' if self._prepend_timestamp: timestamp = datetime.datetime.utcfromtimestamp( cur_time).isoformat() + ' ' line = u'{}{}{}'.format(self._line_prepend, timestamp, line) self._fsapi.push(self._filename, line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stream_tfevents(path, file_api, step=0): """Parses and streams a tfevents file to the server"""
last_step = 0 row = {} buffer = [] last_row = {} for summary in tf.train.summary_iterator(path): parsed = tf_summary_to_dict(summary) if last_step != parsed["tensorflow_step"]: step += 1 last_step = parsed["tensorflow_step"] # TODO: handle time if len(row) > 0: last_row = to_json(row) buffer.append(Chunk("wandb-history.jsonl", util.json_dumps_safer_history(to_json(row)))) row.update(parsed) file_api._send(buffer) return last_row
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def agent_run(args): """A version of `wandb run` that the agent uses to run things. """
run = wandb.wandb_run.Run.from_environment_or_defaults() run.enable_logging() api = wandb.apis.InternalApi() api.set_current_run_id(run.id) # TODO: better failure handling root = api.git.root # handle non-git directories if not root: root = os.path.abspath(os.getcwd()) host = socket.gethostname() remote_url = 'file://{}{}'.format(host, root) run.save(program=args['program'], api=api) env = dict(os.environ) run.set_environment(env) try: rm = wandb.run_manager.RunManager(api, run) except wandb.run_manager.Error: exc_type, exc_value, exc_traceback = sys.exc_info() wandb.termerror('An Exception was raised during setup, see %s for full traceback.' % util.get_log_file_path()) wandb.termerror(exc_value) if 'permission' in str(exc_value): wandb.termerror( 'Are you sure you provided the correct API key to "wandb login"?') lines = traceback.format_exception( exc_type, exc_value, exc_traceback) logging.error('\n'.join(lines)) else: rm.run_user_process(args['program'], args['args'], env)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch(save=True, tensorboardX=tensorboardX_loaded): """Monkeypatches tensorboard or tensorboardX so that all events are logged to tfevents files and wandb. We save the tfevents files and graphs to wandb by default. Arguments: save, default: True - Passing False will skip sending events. tensorboardX, default: True if module can be imported - You can override this when calling patch """
global Summary, Event if tensorboardX: tensorboard_module = "tensorboardX.writer" if tensorflow_loaded: wandb.termlog( "Found TensorboardX and tensorflow, pass tensorboardX=False to patch regular tensorboard.") from tensorboardX.proto.summary_pb2 import Summary from tensorboardX.proto.event_pb2 import Event else: tensorboard_module = "tensorflow.python.summary.writer.writer" from tensorflow.summary import Summary, Event writers = set() def _add_event(self, event, step, walltime=None): event.wall_time = time.time() if walltime is None else walltime if step is not None: event.step = int(step) try: # TensorboardX uses _file_name if hasattr(self.event_writer._ev_writer, "_file_name"): name = self.event_writer._ev_writer._file_name else: name = self.event_writer._ev_writer.FileName().decode("utf-8") writers.add(name) # This is a little hacky, there is a case where the log_dir changes. # Because the events files will have the same names in sub directories # we simply overwrite the previous symlink in wandb.save if the log_dir # changes. log_dir = os.path.dirname(os.path.commonprefix(list(writers))) filename = os.path.basename(name) # Tensorboard loads all tfevents files in a directory and prepends # their values with the path. Passing namespace to log allows us # to nest the values in wandb namespace = name.replace(filename, "").replace( log_dir, "").strip(os.sep) if save: wandb.save(name, base_path=log_dir) wandb.save(os.path.join(log_dir, "*.pbtxt"), base_path=log_dir) log(event, namespace=namespace, step=event.step) except Exception as e: wandb.termerror("Unable to log event %s" % e) # six.reraise(type(e), e, sys.exc_info()[2]) self.event_writer.add_event(event) writer = wandb.util.get_module(tensorboard_module) writer.SummaryToEventTransformer._add_event = _add_event
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tf_summary_to_dict(tf_summary_str_or_pb, namespace=""): """Convert a Tensorboard Summary to a dictionary Accepts either a tensorflow.summary.Summary or one encoded as a string. """
values = {} if isinstance(tf_summary_str_or_pb, Summary): summary_pb = tf_summary_str_or_pb elif isinstance(tf_summary_str_or_pb, Event): summary_pb = tf_summary_str_or_pb.summary values["global_step"] = tf_summary_str_or_pb.step values["_timestamp"] = tf_summary_str_or_pb.wall_time else: summary_pb = Summary() summary_pb.ParseFromString(tf_summary_str_or_pb) for value in summary_pb.value: kind = value.WhichOneof("value") if kind == "simple_value": values[namespaced_tag(value.tag, namespace)] = value.simple_value elif kind == "image": from PIL import Image image = wandb.Image(Image.open( six.BytesIO(value.image.encoded_image_string))) tag_idx = value.tag.rsplit('/', 1) if len(tag_idx) > 1 and tag_idx[1].isdigit(): tag, idx = tag_idx values.setdefault(history_image_key(tag), []).append(image) else: values[history_image_key(value.tag)] = image # Coming soon... # elif kind == "audio": # audio = wandb.Audio(six.BytesIO(value.audio.encoded_audio_string), # sample_rate=value.audio.sample_rate, content_type=value.audio.content_type) elif kind == "histo": first = value.histo.bucket_limit[0] + \ value.histo.bucket_limit[0] - value.histo.bucket_limit[1] last = value.histo.bucket_limit[-2] + \ value.histo.bucket_limit[-2] - value.histo.bucket_limit[-3] np_histogram = (list(value.histo.bucket), [ first] + value.histo.bucket_limit[:-1] + [last]) values[namespaced_tag(value.tag)] = wandb.Histogram( np_histogram=np_histogram) return values
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_search_text(self, cli): """ The text we are searching for. """
# When the search buffer has focus, take that text. if self.preview_search(cli) and cli.buffers[self.search_buffer_name].text: return cli.buffers[self.search_buffer_name].text # Otherwise, take the text of the last active search. else: return self.get_search_state(cli).text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listen(self, max_seconds=30): """Waits to receive up to two bytes for up to max_seconds"""
if not self.connection: self.connect() start = time.time() conn, _, err = select([self.connection], [], [ self.connection], max_seconds) try: if len(err) > 0: raise socket.error("Couldn't open socket") message = b'' while True: if time.time() - start > max_seconds: raise socket.error( "Timeout of %s seconds waiting for W&B process" % max_seconds) res = self.connection.recv(1024) term = res.find(b'\0') if term != -1: message += res[:term] break else: message += res message = json.loads(message.decode('utf8')) if message['status'] == 'done': return True, None elif message['status'] == 'ready': return True, message elif message['status'] == 'launch_error': return False, None else: raise socket.error("Invalid status: %s" % message['status']) except (socket.error, ValueError) as e: util.sentry_exc(e) return False, None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calc_adu(self): """Apply DAFs if existing for the buffer."""
res = super()._calc_adu() self.ensure_one() dafs_to_apply = self.env['ddmrp.adjustment'].search( self._daf_to_apply_domain()) if dafs_to_apply: daf = 1 values = dafs_to_apply.mapped('value') for val in values: daf *= val prev = self.adu self.adu *= daf _logger.debug( "DAF=%s applied to %s. ADU: %s -> %s" % (daf, self.name, prev, self.adu)) # Compute generated demand to be applied to components: dafs_to_explode = self.env['ddmrp.adjustment'].search( self._daf_to_apply_domain(False)) for daf in dafs_to_explode: prev = self.adu increased_demand = prev * daf.value - prev self.explode_demand_to_components( daf, increased_demand, self.product_uom) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cron_ddmrp_adu(self, automatic=False): """Apply extra demand originated by Demand Adjustment Factors to components after the cron update of all the buffers."""
self.env['ddmrp.adjustment.demand'].search([]).unlink() super().cron_ddmrp_adu(automatic) today = fields.Date.today() for op in self.search([]).filtered('extra_demand_ids'): to_add = sum(op.extra_demand_ids.filtered( lambda r: r.date_start <= today <= r.date_end ).mapped('extra_demand')) if to_add: op.adu += to_add _logger.debug( "DAFs-originated demand applied. %s: ADU += %s" % (op.name, to_add))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_dlt(self): """Apply Lead Time Adj Factor if existing"""
res = super()._compute_dlt() for rec in self: ltaf_to_apply = self.env['ddmrp.adjustment'].search( rec._ltaf_to_apply_domain()) if ltaf_to_apply: ltaf = 1 values = ltaf_to_apply.mapped('value') for val in values: ltaf *= val prev = rec.dlt rec.dlt *= ltaf _logger.debug( "LTAF=%s applied to %s. DLT: %s -> %s" % (ltaf, rec.name, prev, rec.dlt)) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten(nested_dict, separator="_", root_keys_to_ignore=set()): """ Flattens a dictionary with nested structure to a dictionary with no hierarchy Consider ignoring keys that you are not interested in to prevent unnecessary processing This is specially true for very deep objects :param nested_dict: dictionary we want to flatten :param separator: string to separate dictionary keys by :param root_keys_to_ignore: set of root keys to ignore from flattening :return: flattened dictionary """
assert isinstance(nested_dict, dict), "flatten requires a dictionary input" assert isinstance(separator, six.string_types), "separator must be string" # This global dictionary stores the flattened keys and values and is # ultimately returned flattened_dict = dict() def _flatten(object_, key): """ For dict, list and set objects_ calls itself on the elements and for other types assigns the object_ to the corresponding key in the global flattened_dict :param object_: object to flatten :param key: carries the concatenated key for the object_ :return: None """ # Empty object can't be iterated, take as is if not object_: flattened_dict[key] = object_ # These object types support iteration elif isinstance(object_, dict): for object_key in object_: if not (not key and object_key in root_keys_to_ignore): _flatten(object_[object_key], _construct_key(key, separator, object_key)) elif isinstance(object_, (list, set, tuple)): for index, item in enumerate(object_): _flatten(item, _construct_key(key, separator, index)) # Anything left take as is else: flattened_dict[key] = object_ _flatten(nested_dict, None) return flattened_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_if_numbers_are_consecutive(list_): """ Returns True if numbers in the list are consecutive :param list_: list of integers :return: Boolean """
return all((True if second - first == 1 else False for first, second in zip(list_[:-1], list_[1:])))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def strip( text ): ''' Strips all color codes from a text. ''' members = [attr for attr in Colors.__dict__.keys() if not attr.startswith( "__" ) and not attr == 'strip'] for c in members: text = text.replace( vars( Colors )[c], '' ) return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def vprintf(self, alevel, format, *args): ''' A verbosity-aware printf. ''' if self._verbosity and self._verbosity >= alevel: sys.stdout.write(format % args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def density(a_M, *args, **kwargs): """ ARGS a_M matrix to analyze *args[0] optional mask matrix; if passed, calculate density of a_M using non-zero elements of args[0] as a mask. DESC Determine the "density" of a passed matrix. Two densities are returned: o f_actualDensity -- density of the matrix using matrix values as "mass" o f_binaryDensity -- density of the matrix irrespective of actual matrix values If the passed matrix contains only "ones", the f_binaryDensity will be equal to the f_actualDensity. """
rows, cols = a_M.shape a_Mmask = ones( (rows, cols) ) if len(args): a_Mmask = args[0] a_M *= a_Mmask # The "binary" density determines the density of nonzero elements, # irrespective of their actual value f_binaryMass = float(size(nonzero(a_M)[0])) f_actualMass = a_M.sum() f_area = float(size(nonzero(a_Mmask)[0])) f_binaryDensity = f_binaryMass / f_area; f_actualDensity = f_actualMass / f_area; return f_actualDensity, f_binaryDensity
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cdf(arr, **kwargs): """ ARGS arr array to calculate cumulative distribution function **kwargs Passed directly to numpy.histogram. Typical options include: bins = <num_bins> normed = True|False DESC Determines the cumulative distribution function. """
counts, bin_edges = histogram(arr, **kwargs) cdf = cumsum(counts) return cdf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def array2DIndices_enumerate(arr): """ DESC Given a 2D array defined by arr, prepare an explicit list of the indices. ARGS arr in 2 element array with the first element the rows and the second the cols RET A list of explicit 2D coordinates. """
rows = arr[0] cols = arr[1] arr_index = zeros((rows * cols, 2)) count = 0 for row in arange(0, rows): for col in arange(0, cols): arr_index[count] = array([row, col]) count = count + 1 return arr_index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toc(*args, **kwargs): """ Port of the MatLAB function of same name Behaviour is controllable to some extent by the keyword args: """
global Gtic_start f_elapsedTime = time.time() - Gtic_start for key, value in kwargs.items(): if key == 'sysprint': return value % f_elapsedTime if key == 'default': return "Elapsed time = %f seconds." % f_elapsedTime return f_elapsedTime
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def base10toN(num, n): """Change a num to a base-n number. Up to base-36 is supported without special notation."""
num_rep = {10:'a', 11:'b', 12:'c', 13:'d', 14:'e', 15:'f', 16:'g', 17:'h', 18:'i', 19:'j', 20:'k', 21:'l', 22:'m', 23:'n', 24:'o', 25:'p', 26:'q', 27:'r', 28:'s', 29:'t', 30:'u', 31:'v', 32:'w', 33:'x', 34:'y', 35:'z'} new_num_string = '' new_num_arr = array(()) current = num while current != 0: remainder = current % n if 36 > remainder > 9: remainder_string = num_rep[remainder] elif remainder >= 36: remainder_string = '(' + str(remainder) + ')' else: remainder_string = str(remainder) new_num_string = remainder_string + new_num_string new_num_arr = r_[remainder, new_num_arr] current = current / n print(new_num_arr) return new_num_string