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 pull(self, project, run=None, entity=None): """Download files from W&B Args: project (str): The project to download run (str, optional): The run to upload to entity (str, optional): The entity to scope this project to. Defaults to wandb models Returns: The requests library response object """
project, run = self.parse_slug(project, run=run) urls = self.download_urls(project, run, entity) responses = [] for fileName in urls: _, response = self.download_write_file(urls[fileName]) if response: responses.append(response) return responses
<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, files, run=None, entity=None, project=None, description=None, force=True, progress=False): """Uploads multiple files to W&B Args: files (list or dict): The filenames to upload run (str, optional): The run to upload to entity (str, optional): The entity to scope this project to. Defaults to wandb models project (str, optional): The name of the project to upload to. Defaults to the one in settings. description (str, optional): The description of the changes force (bool, optional): Whether to prevent push if git has uncommitted changes progress (callable, or stream): If callable, will be called with (chunk_bytes, total_bytes) as argument else if True, renders a progress bar to stream. Returns: The requests library response object """
if project is None: project = self.get_project() if project is None: raise CommError("No project configured.") if run is None: run = self.current_run_id # TODO(adrian): we use a retriable version of self.upload_file() so # will never retry self.upload_urls() here. Instead, maybe we should # make push itself retriable. run_id, result = self.upload_urls( project, files, run, entity, description) responses = [] for file_name, file_info in result.items(): try: # To handle Windows paths # TODO: this doesn't handle absolute paths... normal_name = os.path.join(*file_name.split("/")) open_file = files[normal_name] if isinstance( files, dict) else open(normal_name, "rb") except IOError: print("%s does not exist" % file_name) continue if progress: if hasattr(progress, '__call__'): responses.append(self.upload_file_retry( file_info['url'], open_file, progress)) else: length = os.fstat(open_file.fileno()).st_size with click.progressbar(file=progress, length=length, label='Uploading file: %s' % (file_name), fill_char=click.style('&', fg='green')) as bar: responses.append(self.upload_file_retry( file_info['url'], open_file, lambda bites, _: bar.update(bites))) else: responses.append(self.upload_file_retry(file_info['url'], open_file)) open_file.close() return responses
<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_file_stream_api(self): """This creates a new file pusher thread. Call start to initiate the thread that talks to W&B"""
if not self._file_stream_api: if self._current_run_id is None: raise UsageError( 'Must have a current run to use file stream API.') self._file_stream_api = FileStreamApi(self, self._current_run_id) return self._file_stream_api
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _status_request(self, url, length): """Ask google how much we've uploaded"""
return requests.put( url=url, headers={'Content-Length': '0', 'Content-Range': 'bytes */%i' % length} )
<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_common_complete_suffix(document, completions): """ Return the common prefix for all completions. """
# Take only completions that don't change the text before the cursor. def doesnt_change_before_cursor(completion): end = completion.text[:-completion.start_position] return document.text_before_cursor.endswith(end) completions2 = [c for c in completions if doesnt_change_before_cursor(c)] # When there is at least one completion that changes the text before the # cursor, don't return any common part. if len(completions2) != len(completions): return '' # Return the common prefix. def get_suffix(completion): return completion.text[-completion.start_position:] return _commonprefix([get_suffix(c) for c in completions2])
<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_width(self, cli, ui_content): " Width to report to the `Window`. " # Take the width from the first line. text = token_list_to_text(self.get_prompt_tokens(cli)) return get_cwidth(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 prompt_for_project(ctx, entity): """Ask the user for a project, creating one if necessary."""
result = ctx.invoke(projects, entity=entity, display=False) try: if len(result) == 0: project = click.prompt("Enter a name for your first project") #description = editor() project = api.upsert_project(project, entity=entity)["name"] else: project_names = [project["name"] for project in result] question = { 'type': 'list', 'name': 'project_name', 'message': "Which project should we use?", 'choices': project_names + ["Create New"] } result = whaaaaat.prompt([question]) if result: project = result['project_name'] else: project = "Create New" # TODO: check with the server if the project exists if project == "Create New": project = click.prompt( "Enter a name for your new project", value_proc=api.format_project) #description = editor() project = api.upsert_project(project, entity=entity)["name"] except wandb.apis.CommError as e: raise ClickException(str(e)) return project
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx): """Weights & Biases. Run "wandb docs" for full documentation. """
wandb.try_to_set_up_global_logging() if ctx.invoked_subcommand is None: click.echo(ctx.get_help())
<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_values(self): """Load config.yaml from the run directory if available."""
path = self._config_path() if path is not None and os.path.isfile(path): self._load_file(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 load_json(self, json): """Loads existing config from JSON"""
for key in json: if key == "wandb_version": continue self._items[key] = json[key].get('value') self._descriptions[key] = json[key].get('desc')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def persist(self): """Stores the current configuration for pushing to W&B"""
# In dryrun mode, without wandb run, we don't # save config on initial load, because the run directory # may not be created yet (because we don't know if we're # being used in a run context, or as an API). # TODO: Defer saving somehow, maybe via an events system path = self._config_path() if path is None: return with open(path, "w") as conf_file: conf_file.write(str(self))
<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_upstream_fork_point(self): """Get the most recent ancestor of HEAD that occurs on an upstream branch. First looks at the current branch's tracking branch, if applicable. If that doesn't work, looks at every other branch to find the most recent ancestor of HEAD that occurs on a tracking branch. Returns: git.Commit object or None """
possible_relatives = [] try: if not self.repo: return None try: active_branch = self.repo.active_branch except (TypeError, ValueError): logger.debug("git is in a detached head state") return None # detached head else: tracking_branch = active_branch.tracking_branch() if tracking_branch: possible_relatives.append(tracking_branch.commit) if not possible_relatives: for branch in self.repo.branches: tracking_branch = branch.tracking_branch() if tracking_branch is not None: possible_relatives.append(tracking_branch.commit) head = self.repo.head most_recent_ancestor = None for possible_relative in possible_relatives: # at most one: for ancestor in self.repo.merge_base(head, possible_relative): if most_recent_ancestor is None: most_recent_ancestor = ancestor elif self.repo.is_ancestor(most_recent_ancestor, ancestor): most_recent_ancestor = ancestor return most_recent_ancestor except exc.GitCommandError as e: logger.debug("git remote upstream fork point could not be found") logger.debug(e.message) 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 create_text_object_decorator(registry): """ Create a decorator that can be used to register Vi text object implementations. """
assert isinstance(registry, BaseRegistry) operator_given = ViWaitingForTextObjectMode() navigation_mode = ViNavigationMode() selection_mode = ViSelectionMode() def text_object_decorator(*keys, **kw): """ Register a text object function. Usage:: @text_object('w', filter=..., no_move_handler=False) def handler(event): # Return a text object for this key. return TextObject(...) :param no_move_handler: Disable the move handler in navigation mode. (It's still active in selection mode.) """ filter = kw.pop('filter', Always()) no_move_handler = kw.pop('no_move_handler', False) no_selection_handler = kw.pop('no_selection_handler', False) eager = kw.pop('eager', False) assert not kw def decorator(text_object_func): assert callable(text_object_func) @registry.add_binding(*keys, filter=operator_given & filter, eager=eager) def _(event): # Arguments are multiplied. vi_state = event.cli.vi_state event._arg = (vi_state.operator_arg or 1) * (event.arg or 1) # Call the text object handler. text_obj = text_object_func(event) if text_obj is not None: assert isinstance(text_obj, TextObject) # Call the operator function with the text object. vi_state.operator_func(event, text_obj) # Clear operator. event.cli.vi_state.operator_func = None event.cli.vi_state.operator_arg = None # Register a move operation. (Doesn't need an operator.) if not no_move_handler: @registry.add_binding(*keys, filter=~operator_given & filter & navigation_mode, eager=eager) def _(event): " Move handler for navigation mode. " text_object = text_object_func(event) event.current_buffer.cursor_position += text_object.start # Register a move selection operation. if not no_selection_handler: @registry.add_binding(*keys, filter=~operator_given & filter & selection_mode, eager=eager) def _(event): " Move handler for selection mode. " text_object = text_object_func(event) buff = event.current_buffer # When the text object has both a start and end position, like 'i(' or 'iw', # Turn this into a selection, otherwise the cursor. if text_object.end: # Take selection positions from text object. start, end = text_object.operator_range(buff.document) start += buff.cursor_position end += buff.cursor_position buff.selection_state.original_cursor_position = start buff.cursor_position = end # Take selection type from text object. if text_object.type == TextObjectType.LINEWISE: buff.selection_state.type = SelectionType.LINES else: buff.selection_state.type = SelectionType.CHARACTERS else: event.current_buffer.cursor_position += text_object.start # Make it possible to chain @text_object decorators. return text_object_func return decorator return text_object_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 create_operator_decorator(registry): """ Create a decorator that can be used for registering Vi operators. """
assert isinstance(registry, BaseRegistry) operator_given = ViWaitingForTextObjectMode() navigation_mode = ViNavigationMode() selection_mode = ViSelectionMode() def operator_decorator(*keys, **kw): """ Register a Vi operator. Usage:: @operator('d', filter=...) def handler(cli, text_object): # Do something with the text object here. """ filter = kw.pop('filter', Always()) eager = kw.pop('eager', False) assert not kw def decorator(operator_func): @registry.add_binding(*keys, filter=~operator_given & filter & navigation_mode, eager=eager) def _(event): """ Handle operator in navigation mode. """ # When this key binding is matched, only set the operator # function in the ViState. We should execute it after a text # object has been received. event.cli.vi_state.operator_func = operator_func event.cli.vi_state.operator_arg = event.arg @registry.add_binding(*keys, filter=~operator_given & filter & selection_mode, eager=eager) def _(event): """ Handle operator in selection mode. """ buff = event.current_buffer selection_state = buff.selection_state # Create text object from selection. if selection_state.type == SelectionType.LINES: text_obj_type = TextObjectType.LINEWISE elif selection_state.type == SelectionType.BLOCK: text_obj_type = TextObjectType.BLOCK else: text_obj_type = TextObjectType.INCLUSIVE text_object = TextObject( selection_state.original_cursor_position - buff.cursor_position, type=text_obj_type) # Execute operator. operator_func(event, text_object) # Quit selection mode. buff.selection_state = None return operator_func return decorator return operator_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 load_vi_open_in_editor_bindings(): """ Pressing 'v' in navigation mode will open the buffer in an external editor. """
registry = Registry() navigation_mode = ViNavigationMode() registry.add_binding('v', filter=navigation_mode)( get_by_name('edit-and-execute-command')) 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 cut(self, buffer): """ Turn text object into `ClipboardData` instance. """
from_, to = self.operator_range(buffer.document) from_ += buffer.cursor_position to += buffer.cursor_position to -= 1 # SelectionState does not include the end position, `operator_range` does. document = Document(buffer.text, to, SelectionState( original_cursor_position=from_, type=self.selection_type)) new_document, clipboard_data = document.cut_selection() return new_document, clipboard_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 get_sync_start_position(self, document, lineno): " Scan backwards, and find a possible position to start. " pattern = self._compiled_pattern lines = document.lines # Scan upwards, until we find a point where we can start the syntax # synchronisation. for i in range(lineno, max(-1, lineno - self.MAX_BACKWARDS), -1): match = pattern.match(lines[i]) if match: return i, match.start() # No synchronisation point found. If we aren't that far from the # beginning, start at the very beginning, otherwise, just try to start # at the current line. if lineno < self.FROM_START_IF_NO_SYNC_POS_FOUND: return 0, 0 else: return lineno, 0
<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_filename(cls, filename, sync_from_start=True): """ Create a `Lexer` from a filename. """
# Inline imports: the Pygments dependency is optional! from pygments.util import ClassNotFound from pygments.lexers import get_lexer_for_filename try: pygments_lexer = get_lexer_for_filename(filename) except ClassNotFound: return SimpleLexer() else: return cls(pygments_lexer.__class__, sync_from_start=sync_from_start)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bisearch(ucs, table): """ Auxiliary function for binary search in interval table. :arg int ucs: Ordinal value of unicode character. :arg list table: List of starting and ending ranges of ordinal values, :rtype: int :returns: 1 if ordinal value ucs is found within lookup table, else 0. """
lbound = 0 ubound = len(table) - 1 if ucs < table[0][0] or ucs > table[ubound][1]: return 0 while ubound >= lbound: mid = (lbound + ubound) // 2 if ucs > table[mid][1]: lbound = mid + 1 elif ucs < table[mid][0]: ubound = mid - 1 else: return 1 return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wcwidth(wc): r""" Given one unicode character, return its printable length on a terminal. The wcwidth() function returns 0 if the wc argument has no printable effect on a terminal (such as NUL '\0'), -1 if wc is not printable, or has an indeterminate effect on the terminal, such as a control character. Otherwise, the number of column positions the character occupies on a graphic terminal (1 or 2) is returned. The following have a column width of -1: - C0 control characters (U+001 through U+01F). - C1 control characters and DEL (U+07F through U+0A0). The following have a column width of 0: - Non-spacing and enclosing combining characters (general category code Mn or Me in the Unicode database). - NULL (U+0000, 0). - COMBINING GRAPHEME JOINER (U+034F). - ZERO WIDTH SPACE (U+200B) through RIGHT-TO-LEFT MARK (U+200F). - LINE SEPERATOR (U+2028) and PARAGRAPH SEPERATOR (U+2029). - LEFT-TO-RIGHT EMBEDDING (U+202A) through RIGHT-TO-LEFT OVERRIDE (U+202E). - WORD JOINER (U+2060) through INVISIBLE SEPARATOR (U+2063). The following have a column width of 1: - SOFT HYPHEN (U+00AD) has a column width of 1. - All remaining characters (including all printable ISO 8859-1 and WGL4 characters, Unicode control characters, etc.) have a column width of 1. The following have a column width of 2: - Spacing characters in the East Asian Wide (W) or East Asian Full-width (F) category as defined in Unicode Technical Report #11 have a column width of 2. """
# pylint: disable=C0103 # Invalid argument name "wc" ucs = ord(wc) # NOTE: created by hand, there isn't anything identifiable other than # general Cf category code to identify these, and some characters in Cf # category code are of non-zero width. # pylint: disable=too-many-boolean-expressions # Too many boolean expressions in if statement (7/5) if (ucs == 0 or ucs == 0x034F or 0x200B <= ucs <= 0x200F or ucs == 0x2028 or ucs == 0x2029 or 0x202A <= ucs <= 0x202E or 0x2060 <= ucs <= 0x2063): return 0 # C0/C1 control characters if ucs < 32 or 0x07F <= ucs < 0x0A0: return -1 # combining characters with zero width if _bisearch(ucs, ZERO_WIDTH): return 0 return 1 + _bisearch(ucs, WIDE_EASTASIAN)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wcswidth(pwcs, n=None): """ Given a unicode string, return its printable length on a terminal. Return the width, in cells, necessary to display the first ``n`` characters of the unicode string ``pwcs``. When ``n`` is None (default), return the length of the entire string. Returns ``-1`` if a non-printable character is encountered. """
# pylint: disable=C0103 # Invalid argument name "n" end = len(pwcs) if n is None else n idx = slice(0, end) width = 0 for char in pwcs[idx]: wcw = wcwidth(char) if wcw < 0: return -1 else: width += wcw return width
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _per_file_event_handler(self): """Create a Watchdog file event handler that does different things for every file """
file_event_handler = PatternMatchingEventHandler() file_event_handler.on_created = self._on_file_created file_event_handler.on_modified = self._on_file_modified file_event_handler.on_moved = self._on_file_moved file_event_handler._patterns = [ os.path.join(self._watch_dir, os.path.normpath('*'))] # Ignore hidden files/folders and output.log because we stream it specially file_event_handler._ignore_patterns = [ '*/.*', '*.tmp', os.path.join(self._run.dir, OUTPUT_FNAME) ] for glob in self._api.settings("ignore_globs"): file_event_handler._ignore_patterns.append( os.path.join(self._run.dir, glob)) return file_event_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 _get_file_event_handler(self, file_path, save_name): """Get or create an event handler for a particular file. file_path: the file's actual path save_name: its path relative to the run directory (aka the watch directory) """
self._file_pusher.update_file(save_name, file_path) # track upload progress if save_name not in self._file_event_handlers: if save_name == 'wandb-history.jsonl': self._file_event_handlers['wandb-history.jsonl'] = FileEventHandlerTextStream( file_path, 'wandb-history.jsonl', self._api) elif save_name == 'wandb-events.jsonl': self._file_event_handlers['wandb-events.jsonl'] = FileEventHandlerTextStream( file_path, 'wandb-events.jsonl', self._api) elif 'tfevents' in save_name or 'graph.pbtxt' in save_name: # overwrite the tensorboard but not every reload -- just # frequently enough to resemble realtime self._file_event_handlers[save_name] = FileEventHandlerThrottledOverwrite( file_path, save_name, self._api, self._file_pusher) # Don't try to stream tensorboard files for now. # elif 'tfevents' in save_name: # # TODO: This is hard-coded, but we want to give users control # # over streaming files (or detect them). # self._api.get_file_stream_api().set_file_policy(save_name, # BinaryFilePolicy()) # self._file_event_handlers[save_name] = FileEventHandlerBinaryStream( # file_path, save_name, self._api) # Overwrite handler (non-deferred) has a bug, wherein if the file is truncated # during upload, the request to Google hangs (at least, this is my working # theory). So for now we defer uploading everything til the end of the run. # TODO: send wandb-summary during run. One option is to copy to a temporary # file before uploading. elif save_name == config.FNAME: self._file_event_handlers[save_name] = FileEventHandlerConfig( file_path, save_name, self._api, self._file_pusher, self._run) elif save_name == 'wandb-summary.json': # Load the summary into the syncer process for meta etc to work self._run.summary.load() self._api.get_file_stream_api().set_file_policy(save_name, OverwriteFilePolicy()) self._file_event_handlers[save_name] = FileEventHandlerSummary( file_path, save_name, self._api, self._file_pusher, self._run) elif save_name.startswith('media/'): # Save media files immediately self._file_event_handlers[save_name] = FileEventHandlerOverwrite( file_path, save_name, self._api, self._file_pusher) else: Handler = FileEventHandlerOverwriteDeferred for policy, globs in six.iteritems(self._user_file_policies): if policy == "end": continue for g in globs: if any(save_name in p for p in glob.glob(os.path.join(self._run.dir, g))): if policy == "live": Handler = FileEventHandlerThrottledOverwriteMinWait self._file_event_handlers[save_name] = Handler( file_path, save_name, self._api, self._file_pusher) return self._file_event_handlers[save_name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mirror_stdout_stderr(self): """Simple STDOUT and STDERR mirroring used by _init_jupyter"""
# TODO: Ideally we could start collecting logs without pushing fs_api = self._api.get_file_stream_api() io_wrap.SimpleTee(sys.stdout, streaming_log.TextStreamPusher( fs_api, OUTPUT_FNAME, prepend_timestamp=True)) io_wrap.SimpleTee(sys.stderr, streaming_log.TextStreamPusher( fs_api, OUTPUT_FNAME, prepend_timestamp=True, line_prepend='ERROR'))
<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_stdout_stderr_streams(self): """Sets up STDOUT and STDERR streams. Only call this once."""
if six.PY2 or not hasattr(sys.stdout, "buffer"): if hasattr(sys.stdout, "fileno") and sys.stdout.isatty(): try: stdout = os.fdopen(sys.stdout.fileno(), "w+", 0) stderr = os.fdopen(sys.stderr.fileno(), "w+", 0) # OSError [Errno 22] Invalid argument wandb except OSError: stdout = sys.stdout stderr = sys.stderr else: stdout = sys.stdout stderr = sys.stderr else: # we write binary so grab the raw I/O objects in python 3 try: stdout = sys.stdout.buffer.raw stderr = sys.stderr.buffer.raw except AttributeError: # The testing environment and potentially others may have screwed with their # io so we fallback to raw stdout / err stdout = sys.stdout.buffer stderr = sys.stderr.buffer output_log_path = os.path.join(self._run.dir, OUTPUT_FNAME) self._output_log = WriteSerializingFile(open(output_log_path, 'wb')) stdout_streams = [stdout, self._output_log] stderr_streams = [stderr, self._output_log] if self._cloud: # Tee stdout/stderr into our TextOutputStream, which will push lines to the cloud. fs_api = self._api.get_file_stream_api() self._stdout_stream = streaming_log.TextStreamPusher( fs_api, OUTPUT_FNAME, prepend_timestamp=True) self._stderr_stream = streaming_log.TextStreamPusher( fs_api, OUTPUT_FNAME, line_prepend='ERROR', prepend_timestamp=True) stdout_streams.append(self._stdout_stream) stderr_streams.append(self._stderr_stream) return stdout_streams, stderr_streams
<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_stdout_stderr_streams(self): """Close output-capturing stuff. This also flushes anything left in the buffers. """
# we don't have tee_file's in headless mode if self._stdout_tee.tee_file is not None: self._stdout_tee.tee_file.close() if self._stderr_tee.tee_file is not None: self._stderr_tee.tee_file.close() # TODO(adrian): we should close these even in headless mode # but in python 2 the read thread doesn't stop on its own # for some reason self._stdout_tee.close_join() self._stderr_tee.close_join() if self._cloud: # not set in dry run mode self._stdout_stream.close() self._stderr_stream.close() self._output_log.f.close() self._output_log = 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 shutdown(self, exitcode=0): """Stops system stats, streaming handlers, and uploads files without output, used by wandb.monitor"""
logger.info("shutting down system stats and metadata service") self._system_stats.shutdown() self._meta.shutdown() if self._cloud: logger.info("stopping streaming files and file change observer") self._stop_file_observer() self._end_file_syncing(exitcode) self._run.history.close()
<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_user_process(self, program, args, env): """Launch a user process, capture its output, and sync its files to the backend. This returns after the process has ended and syncing is done. Captures ctrl-c's, signals, etc. """
stdout_streams, stderr_streams = self._get_stdout_stderr_streams() if sys.platform == "win32": # PTYs don't work in windows so we use pipes. self._stdout_tee = io_wrap.Tee.pipe(*stdout_streams) self._stderr_tee = io_wrap.Tee.pipe(*stderr_streams) # Seems like the following actually isn't necessary on Windows # TODO(adrian): we may need to do the following if we use pipes instead of PTYs # because Python on Unix doesn't like writing UTF-8 to files # tell child python interpreters we accept utf-8 # env['PYTHONIOENCODING'] = 'UTF-8' else: self._stdout_tee = io_wrap.Tee.pty(*stdout_streams) self._stderr_tee = io_wrap.Tee.pty(*stderr_streams) command = [program] + list(args) runner = util.find_runner(program) if runner: command = runner + command command = ' '.join(six.moves.shlex_quote(arg) for arg in command) self._stdout_stream.write_string(command + "\n\n") try: self.proc = subprocess.Popen( command, env=env, stdout=self._stdout_tee.tee_file, stderr=self._stderr_tee.tee_file, shell=True, ) self._run.pid = self.proc.pid except (OSError, IOError): raise Exception('Could not find program: %s' % command) self._sync_etc()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_existing_process(self, pid, stdout_read_fd, stderr_read_fd, port=None): """Do syncing, etc. for an already-running process. This returns after the process has ended and syncing is done. Captures ctrl-c's, signals, etc. """
stdout_read_file = os.fdopen(stdout_read_fd, 'rb') stderr_read_file = os.fdopen(stderr_read_fd, 'rb') stdout_streams, stderr_streams = self._get_stdout_stderr_streams() self._stdout_tee = io_wrap.Tee(stdout_read_file, *stdout_streams) self._stderr_tee = io_wrap.Tee(stderr_read_file, *stderr_streams) self.proc = Process(pid) self._run.pid = pid logger.info("wrapping existing process %i" % pid) try: self.init_run() except LaunchError as e: logger.exception("catostrophic launch error") wandb.termerror(str(e)) util.sentry_exc(e) self._socket.launch_error() return if io_wrap.SIGWINCH_HANDLER is not None: # SIGWINCH_HANDLER (maybe) gets set in self.init_run() io_wrap.SIGWINCH_HANDLER.add_fd(stdout_read_fd) io_wrap.SIGWINCH_HANDLER.add_fd(stderr_read_fd) # Signal the main process that we're all hooked up logger.info("informing user process we are ready to proceed") self._socket.ready() self._sync_etc(headless=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 token_list_len(tokenlist): """ Return the amount of characters in this token list. :param tokenlist: List of (token, text) or (token, text, mouse_handler) tuples. """
ZeroWidthEscape = Token.ZeroWidthEscape return sum(len(item[1]) for item in tokenlist if item[0] != ZeroWidthEscape)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def token_list_to_text(tokenlist): """ Concatenate all the text parts again. """
ZeroWidthEscape = Token.ZeroWidthEscape return ''.join(item[1] for item in tokenlist if item[0] != ZeroWidthEscape)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_token_lines(tokenlist): """ Iterator that yields tokenlists for each line. """
line = [] for token, c in explode_tokens(tokenlist): line.append((token, c)) if c == '\n': yield line line = [] yield 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 _process(self): """ Coroutine implementing the key match algorithm. Key strokes are sent into this generator, and it calls the appropriate handlers. """
buffer = self.key_buffer retry = False while True: if retry: retry = False else: buffer.append((yield)) # If we have some key presses, check for matches. if buffer: is_prefix_of_longer_match = self._is_prefix_of_longer_match(buffer) matches = self._get_matches(buffer) # When eager matches were found, give priority to them and also # ignore all the longer matches. eager_matches = [m for m in matches if m.eager(self._cli_ref())] if eager_matches: matches = eager_matches is_prefix_of_longer_match = False # Exact matches found, call handler. if not is_prefix_of_longer_match and matches: self._call_handler(matches[-1], key_sequence=buffer[:]) del buffer[:] # Keep reference. # No match found. elif not is_prefix_of_longer_match and not matches: retry = True found = False # Loop over the input, try longest match first and shift. for i in range(len(buffer), 0, -1): matches = self._get_matches(buffer[:i]) if matches: self._call_handler(matches[-1], key_sequence=buffer[:i]) del buffer[:i] found = True break if not found: del buffer[: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 arg(self): """ Repetition argument. """
if self._arg == '-': return -1 result = int(self._arg or 1) # Don't exceed a million. if int(result) >= 1000000: result = 1 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 append_to_arg_count(self, data): """ Add digit to the input argument. :param data: the typed digit as string """
assert data in '-0123456789' current = self._arg if data == '-': assert current is None or current == '-' result = data elif current is None: result = data else: result = "%s%s" % (current, data) self.input_processor.arg = 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 _get_keys(self, read, input_records): """ Generator that yields `KeyPress` objects from the input records. """
for i in range(read.value): ir = input_records[i] # Get the right EventType from the EVENT_RECORD. # (For some reason the Windows console application 'cmder' # [http://gooseberrycreative.com/cmder/] can return '0' for # ir.EventType. -- Just ignore that.) if ir.EventType in EventTypes: ev = getattr(ir.Event, EventTypes[ir.EventType]) # Process if this is a key event. (We also have mouse, menu and # focus events.) if type(ev) == KEY_EVENT_RECORD and ev.KeyDown: for key_press in self._event_to_key_presses(ev): yield key_press elif type(ev) == MOUSE_EVENT_RECORD: for key_press in self._handle_mouse(ev): yield key_press
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _event_to_key_presses(self, ev): """ For this `KEY_EVENT_RECORD`, return a list of `KeyPress` instances. """
assert type(ev) == KEY_EVENT_RECORD and ev.KeyDown result = None u_char = ev.uChar.UnicodeChar ascii_char = u_char.encode('utf-8') # NOTE: We don't use `ev.uChar.AsciiChar`. That appears to be latin-1 # encoded. See also: # https://github.com/ipython/ipython/issues/10004 # https://github.com/jonathanslenders/python-prompt-toolkit/issues/389 if u_char == '\x00': if ev.VirtualKeyCode in self.keycodes: result = KeyPress(self.keycodes[ev.VirtualKeyCode], '') else: if ascii_char in self.mappings: if self.mappings[ascii_char] == Keys.ControlJ: u_char = '\n' # Windows sends \n, turn into \r for unix compatibility. result = KeyPress(self.mappings[ascii_char], u_char) else: result = KeyPress(u_char, u_char) # Correctly handle Control-Arrow keys. if (ev.ControlKeyState & self.LEFT_CTRL_PRESSED or ev.ControlKeyState & self.RIGHT_CTRL_PRESSED) and result: if result.key == Keys.Left: result.key = Keys.ControlLeft if result.key == Keys.Right: result.key = Keys.ControlRight if result.key == Keys.Up: result.key = Keys.ControlUp if result.key == Keys.Down: result.key = Keys.ControlDown # Turn 'Tab' into 'BackTab' when shift was pressed. if ev.ControlKeyState & self.SHIFT_PRESSED and result: if result.key == Keys.Tab: result.key = Keys.BackTab # Turn 'Space' into 'ControlSpace' when control was pressed. if (ev.ControlKeyState & self.LEFT_CTRL_PRESSED or ev.ControlKeyState & self.RIGHT_CTRL_PRESSED) and result and result.data == ' ': result = KeyPress(Keys.ControlSpace, ' ') # Turn Control-Enter into META-Enter. (On a vt100 terminal, we cannot # detect this combination. But it's really practical on Windows.) if (ev.ControlKeyState & self.LEFT_CTRL_PRESSED or ev.ControlKeyState & self.RIGHT_CTRL_PRESSED) and result and \ result.key == Keys.ControlJ: return [KeyPress(Keys.Escape, ''), result] # Return result. If alt was pressed, prefix the result with an # 'Escape' key, just like unix VT100 terminals do. # NOTE: Only replace the left alt with escape. The right alt key often # acts as altgr and is used in many non US keyboard layouts for # typing some special characters, like a backslash. We don't want # all backslashes to be prefixed with escape. (Esc-\ has a # meaning in E-macs, for instance.) if result: meta_pressed = ev.ControlKeyState & self.LEFT_ALT_PRESSED if meta_pressed: return [KeyPress(Keys.Escape, ''), result] else: return [result] else: 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 _handle_mouse(self, ev): """ Handle mouse events. Return a list of KeyPress instances. """
FROM_LEFT_1ST_BUTTON_PRESSED = 0x1 result = [] # Check event type. if ev.ButtonState == FROM_LEFT_1ST_BUTTON_PRESSED: # On a key press, generate both the mouse down and up event. for event_type in [MouseEventType.MOUSE_DOWN, MouseEventType.MOUSE_UP]: data = ';'.join([ event_type, str(ev.MousePosition.X), str(ev.MousePosition.Y) ]) result.append(KeyPress(Keys.WindowsMouseEvent, data)) 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 tokenize_regex(input): """ Takes a string, representing a regular expression as input, and tokenizes it. :param input: string, representing a regular expression. :returns: List of tokens. """
# Regular expression for tokenizing other regular expressions. p = re.compile(r'''^( \(\?P\<[a-zA-Z0-9_-]+\> | # Start of named group. \(\?#[^)]*\) | # Comment \(\?= | # Start of lookahead assertion \(\?! | # Start of negative lookahead assertion \(\?<= | # If preceded by. \(\?< | # If not preceded by. \(?: | # Start of group. (non capturing.) \( | # Start of group. \(?[iLmsux] | # Flags. \(?P=[a-zA-Z]+\) | # Back reference to named group \) | # End of group. \{[^{}]*\} | # Repetition \*\? | \+\? | \?\?\ | # Non greedy repetition. \* | \+ | \? | # Repetition \#.*\n | # Comment \\. | # Character group. \[ ( [^\]\\] | \\.)* \] | [^(){}] | . )''', re.VERBOSE) tokens = [] while input: m = p.match(input) if m: token, input = input[:m.end()], input[m.end():] if not token.isspace(): tokens.append(token) else: raise Exception('Could not tokenize input regex.') return tokens
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_regex(regex_tokens): """ Takes a list of tokens from the tokenizer, and returns a parse tree. """
# We add a closing brace because that represents the final pop of the stack. tokens = [')'] + regex_tokens[::-1] def wrap(lst): """ Turn list into sequence when it contains several items. """ if len(lst) == 1: return lst[0] else: return Sequence(lst) def _parse(): or_list = [] result = [] def wrapped_result(): if or_list == []: return wrap(result) else: or_list.append(result) return Any([wrap(i) for i in or_list]) while tokens: t = tokens.pop() if t.startswith('(?P<'): variable = Variable(_parse(), varname=t[4:-1]) result.append(variable) elif t in ('*', '*?'): greedy = (t == '*') result[-1] = Repeat(result[-1], greedy=greedy) elif t in ('+', '+?'): greedy = (t == '+') result[-1] = Repeat(result[-1], min_repeat=1, greedy=greedy) elif t in ('?', '??'): if result == []: raise Exception('Nothing to repeat.' + repr(tokens)) else: greedy = (t == '?') result[-1] = Repeat(result[-1], min_repeat=0, max_repeat=1, greedy=greedy) elif t == '|': or_list.append(result) result = [] elif t in ('(', '(?:'): result.append(_parse()) elif t == '(?!': result.append(Lookahead(_parse(), negative=True)) elif t == '(?=': result.append(Lookahead(_parse(), negative=False)) elif t == ')': return wrapped_result() elif t.startswith('#'): pass elif t.startswith('{'): # TODO: implement! raise Exception('{}-style repitition not yet supported' % t) elif t.startswith('(?'): raise Exception('%r not supported' % t) elif t.isspace(): pass else: result.append(Regex(t)) raise Exception("Expecting ')' token") result = _parse() if len(tokens) != 0: raise Exception("Unmatched parantheses.") else: 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 _divide_heigths(self, cli, write_position): """ Return the heights for all rows. Or None when there is not enough space. """
if not self.children: return [] # Calculate heights. given_dimensions = self.get_dimensions(cli) if self.get_dimensions else None def get_dimension_for_child(c, index): if given_dimensions and given_dimensions[index] is not None: return given_dimensions[index] else: return c.preferred_height(cli, write_position.width, write_position.extended_height) dimensions = [get_dimension_for_child(c, index) for index, c in enumerate(self.children)] # Sum dimensions sum_dimensions = sum_layout_dimensions(dimensions) # If there is not enough space for both. # Don't do anything. if sum_dimensions.min > write_position.extended_height: return # Find optimal sizes. (Start with minimal size, increase until we cover # the whole height.) sizes = [d.min for d in dimensions] child_generator = take_using_weights( items=list(range(len(dimensions))), weights=[d.weight for d in dimensions]) i = next(child_generator) while sum(sizes) < min(write_position.extended_height, sum_dimensions.preferred): # Increase until we meet at least the 'preferred' size. if sizes[i] < dimensions[i].preferred: sizes[i] += 1 i = next(child_generator) if not any([cli.is_returning, cli.is_exiting, cli.is_aborting]): while sum(sizes) < min(write_position.height, sum_dimensions.max): # Increase until we use all the available space. (or until "max") if sizes[i] < dimensions[i].max: sizes[i] += 1 i = next(child_generator) return sizes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _divide_widths(self, cli, width): """ Return the widths for all columns. Or None when there is not enough space. """
if not self.children: return [] # Calculate widths. given_dimensions = self.get_dimensions(cli) if self.get_dimensions else None def get_dimension_for_child(c, index): if given_dimensions and given_dimensions[index] is not None: return given_dimensions[index] else: return c.preferred_width(cli, width) dimensions = [get_dimension_for_child(c, index) for index, c in enumerate(self.children)] # Sum dimensions sum_dimensions = sum_layout_dimensions(dimensions) # If there is not enough space for both. # Don't do anything. if sum_dimensions.min > width: return # Find optimal sizes. (Start with minimal size, increase until we cover # the whole height.) sizes = [d.min for d in dimensions] child_generator = take_using_weights( items=list(range(len(dimensions))), weights=[d.weight for d in dimensions]) i = next(child_generator) while sum(sizes) < min(width, sum_dimensions.preferred): # Increase until we meet at least the 'preferred' size. if sizes[i] < dimensions[i].preferred: sizes[i] += 1 i = next(child_generator) while sum(sizes) < min(width, sum_dimensions.max): # Increase until we use all the available space. if sizes[i] < dimensions[i].max: sizes[i] += 1 i = next(child_generator) return sizes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def input_line_to_visible_line(self): """ Return the dictionary mapping the line numbers of the input buffer to the lines of the screen. When a line spans several rows at the screen, the first row appears in the dictionary. """
result = {} for k, v in self.visible_line_to_input_line.items(): if v in result: result[v] = min(result[v], k) else: result[v] = k 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 last_visible_line(self, before_scroll_offset=False): """ Like `first_visible_line`, but for the last visible line. """
if before_scroll_offset: return self.displayed_lines[-1 - self.applied_scroll_offsets.bottom] else: return self.displayed_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 center_visible_line(self, before_scroll_offset=False, after_scroll_offset=False): """ Like `first_visible_line`, but for the center visible line. """
return (self.first_visible_line(after_scroll_offset) + (self.last_visible_line(before_scroll_offset) - self.first_visible_line(after_scroll_offset)) // 2 )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_dimensions(dimension, preferred=None, dont_extend=False): """ Take the LayoutDimension from this `Window` class and the received preferred size from the `UIControl` and return a `LayoutDimension` to report to the parent container. """
dimension = dimension or LayoutDimension() # When a preferred dimension was explicitly given to the Window, # ignore the UIControl. if dimension.preferred_specified: preferred = dimension.preferred # When a 'preferred' dimension is given by the UIControl, make sure # that it stays within the bounds of the Window. if preferred is not None: if dimension.max: preferred = min(preferred, dimension.max) if dimension.min: preferred = max(preferred, dimension.min) # When a `dont_extend` flag has been given, use the preferred dimension # also as the max dimension. if dont_extend and preferred is not None: max_ = min(dimension.max, preferred) else: max_ = dimension.max return LayoutDimension( min=dimension.min, max=max_, preferred=preferred, weight=dimension.weight)
<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_ui_content(self, cli, width, height): """ Create a `UIContent` instance. """
def get_content(): return self.content.create_content(cli, width=width, height=height) key = (cli.render_counter, width, height) return self._ui_content_cache.get(key, get_content)
<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_digraph_char(self, cli): " Return `False`, or the Digraph symbol to be used. " if cli.quoted_insert: return '^' if cli.vi_state.waiting_for_digraph: if cli.vi_state.digraph_symbol1: return cli.vi_state.digraph_symbol1 return '?' 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 _highlight_digraph(self, cli, new_screen): """ When we are in Vi digraph mode, put a question mark underneath the cursor. """
digraph_char = self._get_digraph_char(cli) if digraph_char: cpos = new_screen.cursor_position new_screen.data_buffer[cpos.y][cpos.x] = \ _CHAR_CACHE[digraph_char, Token.Digraph]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _show_input_processor_key_buffer(self, cli, new_screen): """ When the user is typing a key binding that consists of several keys, display the last pressed key if the user is in insert mode and the key is meaningful to be displayed. E.g. Some people want to bind 'jj' to escape in Vi insert mode. But the first 'j' needs to be displayed in order to get some feedback. """
key_buffer = cli.input_processor.key_buffer if key_buffer and _in_insert_mode(cli) and not cli.is_done: # The textual data for the given key. (Can be a VT100 escape # sequence.) data = key_buffer[-1].data # Display only if this is a 1 cell width character. if get_cwidth(data) == 1: cpos = new_screen.cursor_position new_screen.data_buffer[cpos.y][cpos.x] = \ _CHAR_CACHE[data, Token.PartialKeyBinding]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _copy_margin(self, cli, lazy_screen, new_screen, write_position, move_x, width): """ Copy characters from the margin screen to the real screen. """
xpos = write_position.xpos + move_x ypos = write_position.ypos margin_write_position = WritePosition(xpos, ypos, width, write_position.height) self._copy_body(cli, lazy_screen, new_screen, margin_write_position, 0, width)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _mouse_handler(self, cli, mouse_event): """ Mouse handler. Called when the UI control doesn't handle this particular event. """
if mouse_event.event_type == MouseEventType.SCROLL_DOWN: self._scroll_down(cli) elif mouse_event.event_type == MouseEventType.SCROLL_UP: self._scroll_up(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 _scroll_up(self, cli): " Scroll window up. " info = self.render_info if info.vertical_scroll > 0: # TODO: not entirely correct yet in case of line wrapping and long lines. if info.cursor_position.y >= info.window_height - 1 - info.configured_scroll_offsets.bottom: self.content.move_cursor_up(cli) self.vertical_scroll -= 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 update(self, key_vals=None, overwrite=True): """Locked keys will be overwritten unless overwrite=False. Otherwise, written keys will be added to the "locked" list. """
if not key_vals: return write_items = self._update(key_vals, overwrite) self._root._root_set(self._path, write_items) self._root._write(commit=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 _encode(self, value, path_from_root): """Normalize, compress, and encode sub-objects for backend storage. value: Object to encode. path_from_root: `tuple` of key strings from the top-level summary to the current `value`. Returns: A new tree of dict's with large objects replaced with dictionaries with "_type" entries that say which type the original data was. """
# Constructs a new `dict` tree in `json_value` that discards and/or # encodes objects that aren't JSON serializable. if isinstance(value, dict): json_value = {} for key, value in six.iteritems(value): json_value[key] = self._encode(value, path_from_root + (key,)) return json_value else: path = ".".join(path_from_root) if util.is_pandas_data_frame(value): return util.encode_data_frame(path, value, self._run) else: friendly_value, converted = util.json_friendly(data_types.val_to_json(path, value)) json_value, compressed = util.maybe_compress_summary(friendly_value, util.get_h5_typename(value)) if compressed: self.write_h5(path_from_root, friendly_value) return json_value """ if isinstance(value, dict): json_child[key], converted = util.json_friendly( self._encode(value, path_from_root + [key])) else: """
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scroll_one_line_down(event): """ scroll_offset += 1 """
w = find_window_for_buffer_name(event.cli, event.cli.current_buffer_name) b = event.cli.current_buffer if w: # When the cursor is at the top, move to the next line. (Otherwise, only scroll.) if w.render_info: info = w.render_info if w.vertical_scroll < info.content_height - info.window_height: if info.cursor_position.y <= info.configured_scroll_offsets.top: b.cursor_position += b.document.get_cursor_down_position() w.vertical_scroll += 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 scroll_one_line_up(event): """ scroll_offset -= 1 """
w = find_window_for_buffer_name(event.cli, event.cli.current_buffer_name) b = event.cli.current_buffer if w: # When the cursor is at the bottom, move to the previous line. (Otherwise, only scroll.) if w.render_info: info = w.render_info if w.vertical_scroll > 0: first_line_height = info.get_height_for_line(info.first_visible_line()) cursor_up = info.cursor_position.y - (info.window_height - 1 - first_line_height - info.configured_scroll_offsets.bottom) # Move cursor up, as many steps as the height of the first line. # TODO: not entirely correct yet, in case of line wrapping and many long lines. for _ in range(max(0, cursor_up)): b.cursor_position += b.document.get_cursor_up_position() # Scroll window w.vertical_scroll -= 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 create_content(self, cli, width, height): """ Create a UIContent object for this control. """
complete_state = cli.current_buffer.complete_state if complete_state: completions = complete_state.current_completions index = complete_state.complete_index # Can be None! # Calculate width of completions menu. menu_width = self._get_menu_width(width, complete_state) menu_meta_width = self._get_menu_meta_width(width - menu_width, complete_state) show_meta = self._show_meta(complete_state) def get_line(i): c = completions[i] is_current_completion = (i == index) result = self._get_menu_item_tokens(c, is_current_completion, menu_width) if show_meta: result += self._get_menu_item_meta_tokens(c, is_current_completion, menu_meta_width) return result return UIContent(get_line=get_line, cursor_position=Point(x=0, y=index or 0), line_count=len(completions), default_char=Char(' ', self.token)) return UIContent()
<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_menu_width(self, max_width, complete_state): """ Return the width of the main column. """
return min(max_width, max(self.MIN_WIDTH, max(get_cwidth(c.display) for c in complete_state.current_completions) + 2))
<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_menu_meta_width(self, max_width, complete_state): """ Return the width of the meta column. """
if self._show_meta(complete_state): return min(max_width, max(get_cwidth(c.display_meta) for c in complete_state.current_completions) + 2) else: return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_content(self, cli, width, height): """ Create a UIContent object for this menu. """
complete_state = cli.current_buffer.complete_state column_width = self._get_column_width(complete_state) self._render_pos_to_completion = {} def grouper(n, iterable, fillvalue=None): " grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx " args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args) def is_current_completion(completion): " Returns True when this completion is the currently selected one. " return complete_state.complete_index is not None and c == complete_state.current_completion # Space required outside of the regular columns, for displaying the # left and right arrow. HORIZONTAL_MARGIN_REQUIRED = 3 if complete_state: # There should be at least one column, but it cannot be wider than # the available width. column_width = min(width - HORIZONTAL_MARGIN_REQUIRED, column_width) # However, when the columns tend to be very wide, because there are # some very wide entries, shrink it anyway. if column_width > self.suggested_max_column_width: # `column_width` can still be bigger that `suggested_max_column_width`, # but if there is place for two columns, we divide by two. column_width //= (column_width // self.suggested_max_column_width) visible_columns = max(1, (width - self._required_margin) // column_width) columns_ = list(grouper(height, complete_state.current_completions)) rows_ = list(zip(*columns_)) # Make sure the current completion is always visible: update scroll offset. selected_column = (complete_state.complete_index or 0) // height self.scroll = min(selected_column, max(self.scroll, selected_column - visible_columns + 1)) render_left_arrow = self.scroll > 0 render_right_arrow = self.scroll < len(rows_[0]) - visible_columns # Write completions to screen. tokens_for_line = [] for row_index, row in enumerate(rows_): tokens = [] middle_row = row_index == len(rows_) // 2 # Draw left arrow if we have hidden completions on the left. if render_left_arrow: tokens += [(Token.Scrollbar, '<' if middle_row else ' ')] # Draw row content. for column_index, c in enumerate(row[self.scroll:][:visible_columns]): if c is not None: tokens += self._get_menu_item_tokens(c, is_current_completion(c), column_width) # Remember render position for mouse click handler. for x in range(column_width): self._render_pos_to_completion[(column_index * column_width + x, row_index)] = c else: tokens += [(self.token.Completion, ' ' * column_width)] # Draw trailing padding. (_get_menu_item_tokens only returns padding on the left.) tokens += [(self.token.Completion, ' ')] # Draw right arrow if we have hidden completions on the right. if render_right_arrow: tokens += [(Token.Scrollbar, '>' if middle_row else ' ')] # Newline. tokens_for_line.append(tokens) else: tokens = [] self._rendered_rows = height self._rendered_columns = visible_columns self._total_columns = len(columns_) self._render_left_arrow = render_left_arrow self._render_right_arrow = render_right_arrow self._render_width = column_width * visible_columns + render_left_arrow + render_right_arrow + 1 def get_line(i): return tokens_for_line[i] return UIContent(get_line=get_line, line_count=len(rows_))
<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_column_width(self, complete_state): """ Return the width of each column. """
return max(get_cwidth(c.display) for c in complete_state.current_completions) + 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 mouse_handler(self, cli, mouse_event): """ Handle scoll and click events. """
b = cli.current_buffer def scroll_left(): b.complete_previous(count=self._rendered_rows, disable_wrap_around=True) self.scroll = max(0, self.scroll - 1) def scroll_right(): b.complete_next(count=self._rendered_rows, disable_wrap_around=True) self.scroll = min(self._total_columns - self._rendered_columns, self.scroll + 1) if mouse_event.event_type == MouseEventType.SCROLL_DOWN: scroll_right() elif mouse_event.event_type == MouseEventType.SCROLL_UP: scroll_left() elif mouse_event.event_type == MouseEventType.MOUSE_UP: x = mouse_event.position.x y = mouse_event.position.y # Mouse click on left arrow. if x == 0: if self._render_left_arrow: scroll_left() # Mouse click on right arrow. elif x == self._render_width - 1: if self._render_right_arrow: scroll_right() # Mouse click on completion. else: completion = self._render_pos_to_completion.get((x, y)) if completion: b.apply_completion(completion)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def preferred_width(self, cli, max_available_width): """ Report the width of the longest meta text as the preferred width of this control. It could be that we use less width, but this way, we're sure that the layout doesn't change when we select another completion (E.g. that completions are suddenly shown in more or fewer columns.) """
if cli.current_buffer.complete_state: state = cli.current_buffer.complete_state return 2 + max(get_cwidth(c.display_meta) for c in state.current_completions) else: return 0
<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_text(self, text): # Not abstract. """ Shortcut for setting plain text on clipboard. """
assert isinstance(text, six.string_types) self.set_data(ClipboardData(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 reset(self): """ Reset the timeout. Starts a new timer. """
self.counter += 1 local_counter = self.counter def timer_timeout(): if self.counter == local_counter and self.running: self.callback() self.loop.call_later(self.timeout, timer_timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sentry_reraise(exc): """Re-raise an exception after logging it to Sentry Use this for top-level exceptions when you want the user to see the traceback. Must be called from within an exception handler. """
sentry_exc(exc) # this will messily add this "reraise" function to the stack trace # but hopefully it's not too bad six.reraise(type(exc), exc, sys.exc_info()[2])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vendor_import(name): """This enables us to use the vendor directory for packages we don't depend on"""
parent_dir = os.path.abspath(os.path.dirname(__file__)) vendor_dir = os.path.join(parent_dir, 'vendor') sys.path.insert(1, vendor_dir) return import_module(name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_matplotlib_figure(obj): """Extract the current figure from a matplotlib object or return the object if it's a figure. raises ValueError if the object can't be converted. """
import matplotlib from matplotlib.figure import Figure if obj == matplotlib.pyplot: obj = obj.gcf() elif not isinstance(obj, Figure): if hasattr(obj, "figure"): obj = obj.figure # Some matplotlib objects have a figure function if not isinstance(obj, Figure): raise ValueError( "Only matplotlib.pyplot or matplotlib.pyplot.Figure objects are accepted.") if not obj.gca().has_data(): raise ValueError( "You attempted to log an empty plot, pass a figure directly or ensure the global plot isn't closed.") return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_friendly(obj): """Convert an object into something that's more becoming of JSON"""
converted = True typename = get_full_typename(obj) if is_tf_tensor_typename(typename): obj = obj.eval() elif is_pytorch_tensor_typename(typename): try: if obj.requires_grad: obj = obj.detach() except AttributeError: pass # before 0.4 is only present on variables try: obj = obj.data except RuntimeError: pass # happens for Tensors before 0.4 if obj.size(): obj = obj.numpy() else: return obj.item(), True if np and isinstance(obj, np.ndarray): if obj.size == 1: obj = obj.flatten()[0] elif obj.size <= 32: obj = obj.tolist() elif np and isinstance(obj, np.generic): obj = obj.item() elif isinstance(obj, bytes): obj = obj.decode('utf-8') elif isinstance(obj, (datetime, date)): obj = obj.isoformat() else: converted = False if getsizeof(obj) > VALUE_BYTES_LIMIT: logger.warning("Object %s is %i bytes", obj, getsizeof(obj)) return obj, converted
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def launch_browser(attempt_launch_browser=True): """Decide if we should launch a browser"""
_DISPLAY_VARIABLES = ['DISPLAY', 'WAYLAND_DISPLAY', 'MIR_SOCKET'] _WEBBROWSER_NAMES_BLACKLIST = [ 'www-browser', 'lynx', 'links', 'elinks', 'w3m'] import webbrowser launch_browser = attempt_launch_browser if launch_browser: if ('linux' in sys.platform and not any(os.getenv(var) for var in _DISPLAY_VARIABLES)): launch_browser = False try: browser = webbrowser.get() if (hasattr(browser, 'name') and browser.name in _WEBBROWSER_NAMES_BLACKLIST): launch_browser = False except webbrowser.Error: launch_browser = False return launch_browser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_tfjob_config(): """Attempts to parse TFJob config, returning False if it can't find it"""
if os.getenv("TF_CONFIG"): try: return json.loads(os.environ["TF_CONFIG"]) except ValueError: return False 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 parse_sm_config(): """Attempts to parse SageMaker configuration returning False if it can't find it"""
sagemaker_config = "/opt/ml/input/config/hyperparameters.json" if os.path.exists(sagemaker_config): conf = {} conf["sagemaker_training_job_name"] = os.getenv('TRAINING_JOB_NAME') # Hyper-parameter searchs quote configs... for k, v in six.iteritems(json.load(open(sagemaker_config))): cast = v.strip('"') if os.getenv("WANDB_API_KEY") is None and k == "wandb_api_key": os.environ["WANDB_API_KEY"] = cast else: if re.match(r'^[-\d]+$', cast): cast = int(cast) elif re.match(r'^[-.\d]+$', cast): cast = float(cast) conf[k] = cast return conf 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 write_netrc(host, entity, key): """Add our host and key to .netrc"""
if len(key) != 40: click.secho( 'API-key must be exactly 40 characters long: {} ({} chars)'.format(key, len(key))) return None try: normalized_host = host.split("/")[-1].split(":")[0] print("Appending key for %s to your netrc file: %s" % (normalized_host, os.path.expanduser('~/.netrc'))) machine_line = 'machine %s' % normalized_host path = os.path.expanduser('~/.netrc') orig_lines = None try: with open(path) as f: orig_lines = f.read().strip().split('\n') except (IOError, OSError) as e: pass with open(path, 'w') as f: if orig_lines: # delete this machine from the file if it's already there. skip = 0 for line in orig_lines: if machine_line in line: skip = 2 elif skip: skip -= 1 else: f.write('%s\n' % line) f.write(textwrap.dedent("""\ machine {host} login {entity} password {key} """).format(host=normalized_host, entity=entity, key=key)) os.chmod(os.path.expanduser('~/.netrc'), stat.S_IRUSR | stat.S_IWUSR) return True except IOError as e: click.secho("Unable to read ~/.netrc", fg="red") 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 request_with_retry(func, *args, **kwargs): """Perform a requests http call, retrying with exponential backoff. Args: func: An http-requesting function to call, like requests.post max_retries: Maximum retries before giving up. By default we retry 30 times in ~2 hours before dropping the chunk *args: passed through to func **kwargs: passed through to func """
max_retries = kwargs.pop('max_retries', 30) sleep = 2 retry_count = 0 while True: try: response = func(*args, **kwargs) response.raise_for_status() return response except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError, # XXX 500s aren't retryable requests.exceptions.Timeout) as e: if retry_count == max_retries: return e retry_count += 1 delay = sleep + random.random() * 0.25 * sleep if isinstance(e, requests.exceptions.HTTPError) and e.response.status_code == 429: logger.info( "Rate limit exceeded, retrying in %s seconds" % delay) else: logger.warning('requests_with_retry encountered retryable exception: %s. args: %s, kwargs: %s', e, args, kwargs) time.sleep(delay) sleep *= 2 if sleep > MAX_SLEEP_SECONDS: sleep = MAX_SLEEP_SECONDS except requests.exceptions.RequestException as e: logger.error(response.json()['error']) # XXX clean this up logger.exception( 'requests_with_retry encountered unretryable exception: %s', e) return e
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_runner(program): """Return a command that will run program. Args: program: The string name of the program to try to run. Returns: commandline list of strings to run the program (eg. with subprocess.call()) or None """
if os.path.isfile(program) and not os.access(program, os.X_OK): # program is a path to a non-executable file try: opened = open(program) except PermissionError: return None first_line = opened.readline().strip() if first_line.startswith('#!'): return shlex.split(first_line[2:]) if program.endswith('.py'): return [sys.executable] 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 downsample(values, target_length): """Downsamples 1d values to target_length, including start and end. Algorithm just rounds index down. Values can be any sequence, including a generator. """
assert target_length > 1 values = list(values) if len(values) < target_length: return values ratio = float(len(values) - 1) / (target_length - 1) result = [] for i in range(target_length): result.append(values[int(i * ratio)]) 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 image_from_docker_args(args): """This scans docker run args and attempts to find the most likely docker image argument. If excludes any argments that start with a dash, and the argument after it if it isn't a boolean switch. This can be improved, we currently fallback gracefully when this fails. """
bool_args = ["-t", "--tty", "--rm","--privileged", "--oom-kill-disable","--no-healthcheck", "-i", "--interactive", "--init", "--help", "--detach", "-d", "--sig-proxy", "-it", "-itd"] last_flag = -2 last_arg = "" possible_images = [] if len(args) > 0 and args[0] == "run": args.pop(0) for i, arg in enumerate(args): if arg.startswith("-"): last_flag = i last_arg = arg elif "@sha256:" in arg: # Because our regex doesn't match digests possible_images.append(arg) elif docker_image_regex(arg): if last_flag == i - 2: possible_images.append(arg) elif "=" in last_arg: possible_images.append(arg) elif last_arg in bool_args and last_flag == i - 1: possible_images.append(arg) most_likely = None for img in possible_images: if ":" in img or "@" in img or "/" in img: most_likely = img break if most_likely == None and len(possible_images) > 0: most_likely = possible_images[0] return most_likely
<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_yaml(file): """If pyyaml > 5.1 use full_load to avoid warning"""
if hasattr(yaml, "full_load"): return yaml.full_load(file) else: return yaml.load(file)
<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_k8s(): """Pings the k8s metadata service for the image id"""
token_path = "/var/run/secrets/kubernetes.io/serviceaccount/token" if os.path.exists(token_path): k8s_server = "https://{}:{}/api/v1/namespaces/default/pods/{}".format( os.getenv("KUBERNETES_SERVICE_HOST"), os.getenv( "KUBERNETES_PORT_443_TCP_PORT"), os.getenv("HOSTNAME") ) try: res = requests.get(k8s_server, verify="/var/run/secrets/kubernetes.io/serviceaccount/ca.crt", timeout=3, headers={"Authorization": "Bearer {}".format(open(token_path).read())}) res.raise_for_status() except requests.RequestException: return None try: return res.json()["status"]["containerStatuses"][0]["imageID"].strip("docker-pullable://") except (ValueError, KeyError, IndexError): logger.exception("Error checking kubernetes for image id") 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 stopwatch_now(): """Get a timevalue for interval comparisons When possible it is a monotonic clock to prevent backwards time issues. """
if six.PY2: now = time.time() else: now = time.monotonic() return now
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def focus(self, cli, buffer_name): """ Focus the buffer with the given name. """
assert isinstance(buffer_name, six.text_type) self.focus_stack = [buffer_name]
<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_focus(self, cli, buffer_name): """ Push buffer on the focus stack. """
assert isinstance(buffer_name, six.text_type) self.focus_stack.append(buffer_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop_focus(self, cli): """ Pop buffer from the focus stack. """
if len(self.focus_stack) > 1: self.focus_stack.pop() else: raise IndexError('Cannot pop last item from the focus stack.')
<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, size=-1): """Read bytes and call the callback"""
bites = self.file.read(size) self.bytes_read += len(bites) self.callback(len(bites), self.bytes_read) return bites
<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_train_begin(self, **kwargs): "Call watch method to log model topology, gradients & weights" # Set self.best, method inherited from "TrackerCallback" by "SaveModelCallback" super().on_train_begin() # Ensure we don't call "watch" multiple times if not WandbCallback.watch_called: WandbCallback.watch_called = True # Logs model topology and optionally gradients and weights wandb.watch(self.learn.model, log=self.log)
<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_epoch_end(self, epoch, smooth_loss, last_metrics, **kwargs): "Logs training loss, validation loss and custom metrics & log prediction samples & save model" if self.save_model: # Adapted from fast.ai "SaveModelCallback" current = self.get_monitor_value() if current is not None and self.operator(current, self.best): print( f'Better model found at epoch {epoch} with {self.monitor} value: {current}.' ) self.best = current # Section modified to save within wandb folder with self.model_path.open('wb') as model_file: self.learn.save(model_file) # Log sample predictions if self.show_results: self.learn.show_results() # pyplot display of sample predictions wandb.log({"Prediction Samples": plt}, commit=False) # Log losses & metrics # Adapted from fast.ai "CSVLogger" logs = { name: stat for name, stat in list( zip(self.learn.recorder.names, [epoch, smooth_loss] + last_metrics))[1:] } wandb.log(logs) # We can now close results figure if self.show_results: plt.close('all')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def column(self, key): """Iterator over a given column, skipping steps that don't have that key """
for row in self.rows: if key in row: yield row[key]
<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(self, row={}, step=None): """Adds or updates a history step. If row isn't specified, will write the current state of row. If step is specified, the row will be written only when add() is called with a different step value. run.history.row["duration"] = 1.0 run.history.add({"loss": 1}) => {"duration": 1.0, "loss": 1} """
if not isinstance(row, collections.Mapping): raise wandb.Error('history.add expects dict-like object') if step is None: self.update(row) if not self.batched: self._write() else: if not isinstance(step, numbers.Integral): raise wandb.Error( "Step must be an integer, not {}".format(step)) elif step < self._steps: warnings.warn( "Adding to old History rows isn't currently supported. Dropping.", wandb.WandbWarning) return elif step == self._steps: pass elif self.batched: raise wandb.Error( "Can't log to a particular History step ({}) while in batched mode.".format(step)) else: # step > self._steps self._write() self._steps = step self.update(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 update(self, new_vals): """Add a dictionary of values to the current step without writing it to disk. """
for k, v in six.iteritems(new_vals): k = k.strip() if k in self.row: warnings.warn("Adding history key ({}) that is already set in this step".format( k), wandb.WandbWarning) self.row[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 step(self, compute=True): """Context manager to gradually build a history row, then commit it at the end. To reduce the number of conditionals needed, code can check run.history.compute: with run.history.step(batch_idx % log_interval == 0): run.history.add({"nice": "ok"}) if run.history.compute: # Something expensive here """
if self.batched: # we're already in a context manager raise wandb.Error("Nested History step contexts aren't supported") self.batched = True self.compute = compute yield self if compute: self._write() compute = 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 _index(self, row): """Add a row to the internal list of rows without writing it to disk. This function should keep the data structure consistent so it's usable for both adding new rows, and loading pre-existing histories. """
self.rows.append(row) self._keys.update(row.keys()) self._steps += 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 wandb_pty(resize=True): """Get a PTY set to raw mode and registered to hear about window size changes. """
master_fd, slave_fd = pty.openpty() # raw mode so carriage returns etc. don't get added by the terminal driver, # bash for windows blows up on this so we catch the error and do nothing # TODO(adrian): (when) will this be called on windows? try: tty.setraw(master_fd) except termios.error: pass if resize: if SIGWINCH_HANDLER is not None: SIGWINCH_HANDLER.add_fd(master_fd) return master_fd, slave_fd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spawn_reader_writer(get_data_fn, put_data_fn): """Spawn a thread that reads from a data source and writes to a sink. The thread will terminate if it receives a Falsey value from the source. Args: get_data_fn: Data-reading function. Called repeatedly until it returns False-y to indicate that the thread should terminate. put_data_fn: Data-writing function. Returns: threading.Thread """
def _reader_thread(): while True: out = get_data_fn() put_data_fn(out) if not out: # EOF. # We've passed this on so things farther down the pipeline will # know to shut down. break t = threading.Thread(target=_reader_thread) t.daemon = True t.start() return t
<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(self): """Restore `self.redir_file` to its original state. """
# NOTE: dup2 makes `self._from_fd` inheritable unconditionally self.redir_file.flush() os.dup2(self.orig_file.fileno(), self._from_fd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def negotiate(self, data): """ Got negotiate data. """
command, payload = data[0:1], data[1:] assert isinstance(command, bytes) if command == NAWS: self.naws(payload) else: logger.info('Negotiate (%r got bytes)', len(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 _parse_coroutine(self): """ Parser state machine. Every 'yield' expression returns the next byte. """
while True: d = yield if d == int2byte(0): pass # NOP # Go to state escaped. elif d == IAC: d2 = yield if d2 == IAC: self.received_data(d2) # Handle simple commands. elif d2 in (NOP, DM, BRK, IP, AO, AYT, EC, EL, GA): self.command_received(d2, None) # Handle IAC-[DO/DONT/WILL/WONT] commands. elif d2 in (DO, DONT, WILL, WONT): d3 = yield self.command_received(d2, d3) # Subnegotiation elif d2 == SB: # Consume everything until next IAC-SE data = [] while True: d3 = yield if d3 == IAC: d4 = yield if d4 == SE: break else: data.append(d4) else: data.append(d3) self.negotiate(b''.join(data)) else: self.received_data(d)
<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(self, data): """ Feed data to the parser. """
assert isinstance(data, binary_type) for b in iterbytes(data): self._parser.send(int2byte(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 create(cls, api, run_id=None, project=None, username=None): """Create a run for the given project"""
run_id = run_id or util.generate_id() project = project or api.settings.get("project") mutation = gql(''' mutation upsertRun($project: String, $entity: String, $name: String!) { upsertBucket(input: {modelName: $project, entityName: $entity, name: $name}) { bucket { project { name entity { name } } id name } inserted } } ''') variables = {'entity': username, 'project': project, 'name': run_id} res = api.client.execute(mutation, variable_values=variables) res = res['upsertBucket']['bucket'] return Run(api.client, res["project"]["entity"]["name"], res["project"]["name"], res["name"], { "id": res["id"], "config": "{}", "systemMetrics": "{}", "summaryMetrics": "{}", "tags": [], "description": None, "state": "running" })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _exec(self, query, **kwargs): """Execute a query against the cloud backend"""
variables = {'entity': self.username, 'project': self.project, 'name': self.name} variables.update(kwargs) return self.client.execute(query, variable_values=variables)