code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
query = gql(''' query Models($entity: String, $project: String!) { model(name: $project, entityName: $entity) { id name repo dockerImage description } } ''') return se...
def project(self, project, entity=None)
Retrive project Args: project (str): The project to get details for entity (str, optional): The entity to scope this project to. Returns: [{"id","name","repo","dockerImage","description"}]
4.581565
3.371146
1.359053
query = gql(''' query Buckets($model: String!, $entity: String!) { model(name: $model, entityName: $entity) { buckets(first: 10) { edges { node { id name ...
def list_runs(self, project, entity=None)
Lists runs in W&B scoped by project. Args: project (str): The project to scope the runs to entity (str, optional): The entity to scope this project to. Defaults to public models Returns: [{"id",name","description"}]
3.795146
3.719423
1.020359
query = gql(''' mutation launchRun( $entity: String $model: String $runId: String $image: String $command: String $patch: String $cwd: String $datasets: [String] ) { launchRun(inp...
def launch_run(self, command, project=None, entity=None, run_id=None)
Launch a run in the cloud. Args: command (str): The command to run program (str): The file to run project (str): The project to scope the runs to entity (str, optional): The entity to scope this project to. Defaults to public models run_id (str, opti...
3.205234
3.097093
1.034917
query = gql(''' query Model($name: String!, $entity: String!, $run: String!) { model(name: $name, entityName: $entity) { bucket(name: $run) { config commit patch files(names: ["wandb-meta...
def run_config(self, project, run=None, entity=None)
Get the relevant configs for a run Args: project (str): The project to download, (can include bucket) run (str, optional): The run to download entity (str, optional): The entity to scope this project to.
2.860418
2.999764
0.953548
query = gql(''' query Model($project: String!, $entity: String, $name: String!) { model(name: $project, entityName: $entity) { id name entity { id name } bucket(n...
def run_resume_status(self, entity, project_name, name)
Check if a run exists and get resume information. Args: entity (str, optional): The entity to scope this project to. project_name (str): The project to download, (can include bucket) run (str, optional): The run to download
3.559478
3.697014
0.962798
mutation = gql(''' mutation UpsertModel($name: String!, $id: String, $entity: String!, $description: String, $repo: String) { upsertModel(input: { id: $id, name: $name, entityName: $entity, description: $description, repo: $repo }) { model { name...
def upsert_project(self, project, id=None, description=None, entity=None)
Create a new project Args: project (str): The project to create description (str, optional): A description of this project entity (str, optional): The entity to scope this project to.
3.088653
3.314883
0.931753
mutation = gql(''' mutation UpsertBucket( $id: String, $name: String, $project: String, $entity: String!, $groupName: String, $description: String, $commit: String, $config: JSONString, $host: String...
def upsert_run(self, id=None, name=None, project=None, host=None, group=None, tags=None, config=None, description=None, entity=None, state=None, repo=None, job_type=None, program_path=None, commit=None, sweep_name=None, summary_metrics=None, nu...
Update a run Args: id (str, optional): The existing run to update name (str, optional): The name of the run to create group (str, optional): Name of the group this run is a part of project (str, optional): The name of the project config (dict, optiona...
2.11062
2.14878
0.982241
query = gql(''' query Model($name: String!, $files: [String]!, $entity: String!, $run: String!, $description: String) { model(name: $name, entityName: $entity) { bucket(name: $run, desc: $description) { id files(names: $files) ...
def upload_urls(self, project, files, run=None, entity=None, description=None)
Generate temporary resumeable upload urls Args: project (str): The project to download 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 ...
3.207458
2.943001
1.08986
query = gql(''' query Model($name: String!, $entity: String!, $run: String!) { model(name: $name, entityName: $entity) { bucket(name: $run) { files { edges { node { ...
def download_urls(self, project, run=None, entity=None)
Generate download urls 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: A dict of extensions and urls {...
3.264751
3.01954
1.081208
query = gql(''' query Model($name: String!, $fileName: String!, $entity: String!, $run: String!) { model(name: $name, entityName: $entity) { bucket(name: $run) { files(names: [$fileName]) { edges { ...
def download_url(self, project, file_name, run=None, entity=None)
Generate download urls Args: project (str): The project to download file_name (str): The name of the file 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...
3.004167
2.812737
1.068058
response = requests.get(url, stream=True) response.raise_for_status() return (int(response.headers.get('content-length', 0)), response)
def download_file(self, url)
Initiate a streaming download Args: url (str): The url to download Returns: A tuple of the content length and the streaming response
2.715919
2.563857
1.05931
fileName = metadata['name'] path = os.path.join(out_dir or wandb_dir(), fileName) if self.file_current(fileName, metadata['md5']): return path, None size, response = self.download_file(metadata['url']) with open(path, "wb") as file: for data in ...
def download_write_file(self, metadata, out_dir=None)
Download a file from a run and write it to wandb/ Args: metadata (obj): The metadata object for the file to download. Comes from Api.download_urls(). Returns: A tuple of the file's local path and the streaming response. The streaming response is None if the file already existed...
3.832367
3.100505
1.236046
extra_headers = extra_headers.copy() response = None if os.stat(file.name).st_size == 0: raise CommError("%s is an empty file" % file.name) try: progress = Progress(file, callback=callback) response = requests.put( url, data=pr...
def upload_file(self, url, file, callback=None, extra_headers={})
Uploads a file to W&B with failure resumption Args: url (str): The url to download file (str): The path to the file you want to upload callback (:obj:`func`, optional): A callback which is passed the number of bytes uploaded since the last time it was called, use...
4.416202
4.748238
0.930072
mutation = gql(''' mutation CreateAgent( $host: String! $projectName: String!, $entityName: String!, $sweep: String! ) { createAgent(input: { host: $host, projectName: $projectName, ...
def register_agent(self, host, sweep_id=None, project_name=None)
Register a new agent Args: host (str): hostname persistent (bool): long running or oneoff sweep (str): sweep id project_name: (str): model that contains sweep
2.719577
2.847856
0.954956
mutation = gql(''' mutation Heartbeat( $id: ID!, $metrics: JSONString, $runState: JSONString ) { agentHeartbeat(input: { id: $id, metrics: $metrics, runState: $runState }) { ...
def agent_heartbeat(self, agent_id, metrics, run_states)
Notify server about agent state, receive commands. Args: agent_id (str): agent_id metrics (dict): system metrics run_states (dict): run_id: state mapping Returns: List of commands to execute.
3.092976
2.976754
1.039043
mutation = gql(''' mutation UpsertSweep( $config: String, $description: String, $entityName: String!, $projectName: String! ) { upsertSweep(input: { config: $config, description: $description, ...
def upsert_sweep(self, config)
Upsert a sweep object. Args: config (str): sweep config (will be converted to yaml)
3.043361
3.036304
1.002324
return os.path.isfile(fname) and util.md5_file(fname) == md5
def file_current(self, fname, md5)
Checksum a file and compare the md5 with the known md5
4.08961
4.101719
0.997048
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) r...
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
4.830217
5.389893
0.896162
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 ...
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 ...
3.683974
3.563096
1.033925
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
def get_file_stream_api(self)
This creates a new file pusher thread. Call start to initiate the thread that talks to W&B
3.132192
2.724233
1.149752
return requests.put( url=url, headers={'Content-Length': '0', 'Content-Range': 'bytes */%i' % length} )
def _status_request(self, url, length)
Ask google how much we've uploaded
4.568961
3.803866
1.201136
# 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...
def get_common_complete_suffix(document, completions)
Return the common prefix for all completions.
3.704953
3.65213
1.014464
assert isinstance(position, int) and position - self.start_position >= 0 return Completion( text=self.text[position - self.start_position:], display=self.display, display_meta=self._display_meta, get_display_meta=self._get_display_meta)
def new_completion_from_position(self, position)
(Only for internal use!) Get a new completion by splitting this one. Used by `CommandLineInterface` when it needs to have a list of new completions after inserting the common prefix.
3.829539
3.750624
1.021041
" 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)
def get_width(self, cli, ui_content)
Width to report to the `Window`.
20.156954
11.780832
1.710996
@wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except wandb.Error as e: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception( exc_type, exc_value, exc_traceback) l...
def display_error(func)
Function decorator for catching common errors and re-raising as wandb.Error
2.124898
1.976596
1.075029
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: pro...
def prompt_for_project(ctx, entity)
Ask the user for a project, creating one if necessary.
3.617868
3.555406
1.017568
wandb.try_to_set_up_global_logging() if ctx.invoked_subcommand is None: click.echo(ctx.get_help())
def cli(ctx)
Weights & Biases. Run "wandb docs" for full documentation.
5.943052
5.097263
1.16593
args = list(docker_run_args) if len(args) > 0 and args[0] == "run": args.pop(0) if help or len(args) == 0: wandb.termlog("This commands adds wandb env variables to your docker run calls") subprocess.call(['docker', 'run'] + args + ['--help']) exit() #TODO: is this wh...
def docker_run(ctx, docker_run_args, help)
Simple docker wrapper that adds WANDB_API_KEY and WANDB_DOCKER to any docker run command. This will also set the runtime to nvidia if the nvidia-docker executable is present on the system and --runtime wasn't set.
3.777434
3.463964
1.090495
path = self._config_path() if path is not None and os.path.isfile(path): self._load_file(path)
def _load_values(self)
Load config.yaml from the run directory if available.
4.439068
3.02422
1.467839
for key in json: if key == "wandb_version": continue self._items[key] = json[key].get('value') self._descriptions[key] = json[key].get('desc')
def load_json(self, json)
Loads existing config from JSON
5.089104
5.056859
1.006376
# 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 ...
def persist(self)
Stores the current configuration for pushing to W&B
11.101476
10.120296
1.096952
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...
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: ...
2.639169
2.573261
1.025613
# Map to ensure that we return the objects that were passed in originally. # Whether they are a fd integer or an object that has a fileno(). # (The 'poll' implementation for instance, returns always integers.) fd_map = dict((fd_to_int(fd), fd) for fd in read_fds) # Wait, using selector. se...
def select_fds(read_fds, timeout, selector=AutoSelector)
Wait for a list of file descriptors (`read_fds`) to become ready for reading. This chooses the most appropriate select-tool for use in prompt-toolkit.
6.132438
5.95566
1.029682
assert isinstance(registry, BaseRegistry) operator_given = ViWaitingForTextObjectMode() navigation_mode = ViNavigationMode() selection_mode = ViSelectionMode() def text_object_decorator(*keys, **kw): filter = kw.pop('filter', Always()) no_move_handler = kw.pop('no_mov...
def create_text_object_decorator(registry)
Create a decorator that can be used to register Vi text object implementations.
3.57315
3.508795
1.018341
assert isinstance(registry, BaseRegistry) operator_given = ViWaitingForTextObjectMode() navigation_mode = ViNavigationMode() selection_mode = ViSelectionMode() def operator_decorator(*keys, **kw): filter = kw.pop('filter', Always()) eager = kw.pop('eager', False) ...
def create_operator_decorator(registry)
Create a decorator that can be used for registering Vi operators.
4.331109
4.238286
1.021901
registry = Registry() navigation_mode = ViNavigationMode() registry.add_binding('v', filter=navigation_mode)( get_by_name('edit-and-execute-command')) return registry
def load_vi_open_in_editor_bindings()
Pressing 'v' in navigation mode will open the buffer in an external editor.
16.818085
12.867383
1.307032
registry = ConditionalRegistry(Registry(), ViMode()) handle = registry.add_binding handle(Keys.ControlF)(scroll_forward) handle(Keys.ControlB)(scroll_backward) handle(Keys.ControlD)(scroll_half_page_down) handle(Keys.ControlU)(scroll_half_page_up) handle(Keys.ControlE)(scroll_one_line_...
def load_extra_vi_page_navigation_bindings()
Key bindings, for scrolling up and down through pages. This are separate bindings, because GNU readline doesn't have them.
2.860945
2.814846
1.016377
if self.start < self.end: return self.start, self.end else: return self.end, self.start
def sorted(self)
Return a (start, end) tuple where start <= end.
2.95715
2.106377
1.403904
start, end = self.sorted() doc = document if (self.type == TextObjectType.EXCLUSIVE and doc.translate_index_to_position(end + doc.cursor_position)[1] == 0): # If the motion is exclusive and the end of motion is on the first # column, the end posi...
def operator_range(self, document)
Return a (start, end) tuple with start <= end that indicates the range operators should operate on. `buffer` is used to get start and end of line positions.
3.840037
3.615628
1.062066
# Get absolute cursor positions from the text object. from_, to = self.operator_range(buffer.document) from_ += buffer.cursor_position to += buffer.cursor_position # Take the start of the lines. from_, _ = buffer.document.translate_index_to_position(from_) ...
def get_line_numbers(self, buffer)
Return a (start_line, end_line) pair.
4.897135
4.462611
1.09737
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_c...
def cut(self, buffer)
Turn text object into `ClipboardData` instance.
8.776269
7.515104
1.167817
" 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): ...
def get_sync_start_position(self, document, lineno)
Scan backwards, and find a possible position to start.
5.799985
4.862469
1.192807
patterns = { # For Python, start highlighting at any class/def block. 'Python': r'^\s*(class|def)\s+', 'Python 3': r'^\s*(class|def)\s+', # For HTML, start at any open/close tag definition. 'HTML': r'<[/a-zA-Z]', # For javascri...
def from_pygments_lexer_cls(cls, lexer_cls)
Create a :class:`.RegexSync` instance for this Pygments lexer class.
6.823475
6.730292
1.013845
# 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() ...
def from_filename(cls, filename, sync_from_start=True)
Create a `Lexer` from a filename.
3.917817
3.589659
1.091417
# Cache of already lexed lines. cache = {} # Pygments generators that are currently lexing. line_generators = {} # Map lexer generator to the line number. def get_syntax_sync(): " The Syntax synchronisation objcet that we currently use. " if se...
def lex_document(self, cli, document)
Create a lexer function that takes a line number and returns the list of (Token, text) tuples as the Pygments lexer returns for that line.
5.50414
5.404008
1.018529
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:...
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, in form of ``[(start, end), ...]``. :rtype: int :returns: 1 if ordinal value ucs is found within lookup table, else 0.
1.868571
1.795844
1.040498
r # 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-b...
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. Otherwis...
4.539029
4.19597
1.081759
# 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
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 encounter...
3.653822
3.76614
0.970177
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(se...
def _per_file_event_handler(self)
Create a Watchdog file event handler that does different things for every file
3.43283
3.331043
1.030557
# TODO: there was a case where _file_event_handlers was getting modified in the loop. for handler in list(self._file_event_handlers.values()): handler.finish() self._file_pusher.finish() self._api.get_file_stream_api().finish(exitcode) # In Jupyter notebooks...
def _end_file_syncing(self, exitcode)
Stops file syncing/streaming but doesn't actually wait for everything to finish. We print progress info later.
9.286333
8.902004
1.043173
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...
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)
3.9811
3.966103
1.003781
# 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.TextStream...
def mirror_stdout_stderr(self)
Simple STDOUT and STDERR mirroring used by _init_jupyter
7.796471
7.142776
1.091518
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...
def _get_stdout_stderr_streams(self)
Sets up STDOUT and STDERR streams. Only call this once.
3.584313
3.56638
1.005029
# 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 mo...
def _close_stdout_stderr_streams(self)
Close output-capturing stuff. This also flushes anything left in the buffers.
4.821187
4.836948
0.996741
io_wrap.init_sigwinch_handler() self._check_update_available(__version__) if self._output: wandb.termlog("Local directory: %s" % os.path.relpath(self._run.dir)) self._system_stats.start() self._meta.start() logger.info("system metrics and metadata ...
def init_run(self, env=None)
Ensure we create a Run (Bucket) object We either create it now or, if the API call fails for some reason (eg. the network is down), we do it from a thread that we start. We hold off file syncing and streaming until it succeeds. Returns the initial step of the run, or None if we didn't ...
5.748455
5.698616
1.008746
if retry: num_retries = None else: num_retries = 0 # no retries because we want to let the user process run even if the backend is down try: upsert_result = self._run.save( id=storage_id, num_retries=num_retries, api=self._api) ...
def _upsert_run(self, retry, storage_id, env)
Upsert the Run (ie. for the first time with all its attributes) Arguments: retry: (bool) Whether to retry if the connection fails (ie. if the backend is down). False is useful so we can start running the user process even when the W&B backend is down, and let syncing...
5.524308
5.327266
1.036987
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_sync...
def shutdown(self, exitcode=0)
Stops system stats, streaming handlers, and uploads files without output, used by wandb.monitor
10.987575
8.16978
1.344905
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) ...
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.
4.297207
4.293925
1.000764
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(stder...
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.
4.210299
4.227098
0.996026
ZeroWidthEscape = Token.ZeroWidthEscape return sum(len(item[1]) for item in tokenlist if item[0] != ZeroWidthEscape)
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.
6.873692
7.899019
0.870196
ZeroWidthEscape = Token.ZeroWidthEscape return sum(get_cwidth(c) for item in tokenlist for c in item[1] if item[0] != ZeroWidthEscape)
def token_list_width(tokenlist)
Return the character width of this token list. (Take double width characters into account.) :param tokenlist: List of (token, text) or (token, text, mouse_handler) tuples.
7.5911
9.308548
0.815498
ZeroWidthEscape = Token.ZeroWidthEscape return ''.join(item[1] for item in tokenlist if item[0] != ZeroWidthEscape)
def token_list_to_text(tokenlist)
Concatenate all the text parts again.
6.549732
5.941524
1.102366
line = [] for token, c in explode_tokens(tokenlist): line.append((token, c)) if c == '\n': yield line line = [] yield line
def iter_token_lines(tokenlist)
Iterator that yields tokenlists for each line.
4.385359
4.144465
1.058124
line = [] for item in tokenlist: # For (token, text) tuples. if len(item) == 2: token, string = item parts = string.split('\n') for part in parts[:-1]: if part: line.append((token, part)) yield line ...
def split_lines(tokenlist)
Take a single list of (Token, text) tuples and yield one such list for each line. Just like str.split, this will yield at least one item. :param tokenlist: List of (token, text) or (token, text, mouse_handler) tuples.
4.491429
3.918302
1.146269
# When the tokenlist is already exploded, don't explode again. if getattr(tokenlist, 'exploded', False): return tokenlist result = [] for token, string in tokenlist: for c in string: result.append((token, c)) return _ExplodedList(result)
def explode_tokens(tokenlist)
Turn a list of (token, text) tuples into another list where each string is exactly one character. It should be fine to call this function several times. Calling this on a list that is already exploded, is a null operation. :param tokenlist: List of (token, text) tuples.
4.278244
4.362813
0.980616
from prompt_toolkit.interface import CommandLineInterface assert isinstance(cli, CommandLineInterface) from .containers import Window from .controls import BufferControl for l in cli.layout.walk(cli): if isinstance(l, Window) and isinstance(l.content, BufferControl): if l....
def find_window_for_buffer_name(cli, buffer_name)
Look for a :class:`~prompt_toolkit.layout.containers.Window` in the Layout that contains the :class:`~prompt_toolkit.layout.controls.BufferControl` for the given buffer and return it. If no such Window is found, return None.
4.131888
3.147969
1.312557
keys = tuple(k.key for k in key_presses) cli = self._cli_ref() # Try match, with mode flag return [b for b in self._registry.get_bindings_for_keys(keys) if b.filter(cli)]
def _get_matches(self, key_presses)
For a list of :class:`KeyPress` instances. Give the matching handlers that would handle this.
10.302949
9.233513
1.115821
keys = tuple(k.key for k in key_presses) cli = self._cli_ref() # Get the filters for all the key bindings that have a longer match. # Note that we transform it into a `set`, because we don't care about # the actual bindings and executing it more than once doesn't make ...
def _is_prefix_of_longer_match(self, key_presses)
For a list of :class:`KeyPress` instances. Return True if there is any handler that is bound to a suffix of this keys.
8.00103
7.485163
1.068919
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_matc...
def _process(self)
Coroutine implementing the key match algorithm. Key strokes are sent into this generator, and it calls the appropriate handlers.
4.11939
3.845937
1.071102
assert isinstance(key_press, KeyPress) self.input_queue.append(key_press)
def feed(self, key_press)
Add a new :class:`KeyPress` to the input queue. (Don't forget to call `process_keys` in order to process the queue.)
4.201684
2.836139
1.48148
while self.input_queue: key_press = self.input_queue.popleft() if key_press.key != Keys.CPRResponse: self.beforeKeyPress.fire() self._process_coroutine.send(key_press) if key_press.key != Keys.CPRResponse: self.afterKeyP...
def process_keys(self)
Process all the keys in the `input_queue`. (To be called after `feed`.) Note: because of the `feed`/`process_keys` separation, it is possible to call `feed` from inside a key binding. This function keeps looping until the queue is empty.
6.393485
5.742589
1.113345
cli = self._cli_ref() if cli: buff = cli.current_buffer preferred_column = buff.preferred_column if (ViNavigationMode()(event.cli) and buff.document.is_cursor_at_the_end_of_line and len(buff.document.current_line) > 0)...
def _fix_vi_cursor_position(self, event)
After every command, make sure that if we are in Vi navigation mode, we never put the cursor after the last character of a line. (Unless it's an empty line.)
7.072863
6.050201
1.169029
if self._arg == '-': return -1 result = int(self._arg or 1) # Don't exceed a million. if int(result) >= 1000000: result = 1 return result
def arg(self)
Repetition argument.
6.813803
5.828009
1.169148
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_proces...
def append_to_arg_count(self, data)
Add digit to the input argument. :param data: the typed digit as string
4.439879
4.487628
0.98936
max_count = 2048 # Max events to read at the same time. read = DWORD(0) arrtype = INPUT_RECORD * max_count input_records = arrtype() # Get next batch of input event. windll.kernel32.ReadConsoleInputW( self.handle, pointer(input_records), max_count,...
def read(self)
Return a list of `KeyPress` instances. It won't return anything when there was nothing to read. (This function doesn't block.) http://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx
5.282822
4.746474
1.112999
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 ...
def _get_keys(self, read, input_records)
Generator that yields `KeyPress` objects from the input records.
8.060422
7.254147
1.111147
# Consider paste when it contains at least one newline and at least one # other character. text_count = 0 newline_count = 0 for k in keys: if isinstance(k.key, six.text_type): text_count += 1 if k.key == Keys.ControlJ: ...
def _is_paste(keys)
Return `True` when we should consider this list of keys as a paste event. Pasted text on windows will be turned into a `Keys.BracketedPaste` event. (It's not 100% correct, but it is probably the best possible way to detect pasting of text and handle that correctly.)
4.271563
3.528548
1.210572
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/ipy...
def _event_to_key_presses(self, ev)
For this `KEY_EVENT_RECORD`, return a list of `KeyPress` instances.
4.009305
3.897771
1.028615
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]: ...
def _handle_mouse(self, ev)
Handle mouse events. Return a list of KeyPress instances.
6.405595
5.43341
1.178927
# 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 negati...
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.
5.274118
5.27577
0.999687
# We add a closing brace because that represents the final pop of the stack. tokens = [')'] + regex_tokens[::-1] def wrap(lst): if len(lst) == 1: return lst[0] else: return Sequence(lst) def _parse(): or_list = [] result = [] ...
def parse_regex(regex_tokens)
Takes a list of tokens from the tokenizer, and returns a parse tree.
3.118237
3.057618
1.019826
assert isinstance(items, list) assert isinstance(weights, list) assert all(isinstance(i, int) for i in weights) assert len(items) == len(weights) assert len(items) > 0 already_taken = [0 for i in items] item_count = len(items) max_weight = max(weights) i = 0 while True: ...
def take_using_weights(items, weights)
Generator that keeps yielding items from the items list, in proportion to their weight. For instance:: # Getting the first 70 items from this generator should have yielded 10 # times A, 20 times B and 40 times C, all distributed equally.. take_using_weights(['A', 'B', 'C'], [5, 10, 20]) ...
3.241044
3.169855
1.022458
sizes = self._divide_heigths(cli, write_position) if self.report_dimensions_callback: self.report_dimensions_callback(cli, sizes) if sizes is None: self.window_too_small.write_to_screen( cli, screen, mouse_handlers, write_position) else:...
def write_to_screen(self, cli, screen, mouse_handlers, write_position)
Render the prompt to a `Screen` instance. :param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class to which the output has to be written.
3.702988
3.936105
0.940775
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 ...
def _divide_heigths(self, cli, write_position)
Return the heights for all rows. Or None when there is not enough space.
3.871595
3.735192
1.036518
yield self for c in self.children: for i in c.walk(cli): yield i
def walk(self, cli)
Walk through children.
4.710085
3.426615
1.374559
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 g...
def _divide_widths(self, cli, width)
Return the widths for all columns. Or None when there is not enough space.
3.544057
3.429598
1.033374
if not self.children: return sizes = self._divide_widths(cli, write_position.width) if self.report_dimensions_callback: self.report_dimensions_callback(cli, sizes) # If there is not enough space. if sizes is None: self.window_too_sm...
def write_to_screen(self, cli, screen, mouse_handlers, write_position)
Render the prompt to a `Screen` instance. :param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class to which the output has to be written.
3.834072
3.91923
0.978272
return self.content.preferred_height(cli, width, max_available_height)
def preferred_height(self, cli, width, max_available_height)
Return the preferred height of the float container. (We don't care about the height of the floats, they should always fit into the dimensions provided by the container.)
4.275869
3.17057
1.348612
wp = write_position Transparent = Token.Transparent for y in range(wp.ypos, wp.ypos + wp.height): if y in screen.data_buffer: row = screen.data_buffer[y] for x in range(wp.xpos, wp.xpos + wp.width): c = row[x] ...
def _area_is_empty(self, screen, write_position)
Return True when the area below the write position is still empty. (For floats that should not hide content underneath.)
3.778948
3.607246
1.047599
yield self for i in self.content.walk(cli): yield i for f in self.floats: for i in f.content.walk(cli): yield i
def walk(self, cli)
Walk through children.
5.247584
4.619984
1.135845
cpos = self.ui_content.cursor_position y, x = self._rowcol_to_yx[cpos.y, cpos.x] return Point(x=x - self._x_offset, y=y - self._y_offset)
def cursor_position(self)
Return the cursor position coordinates, relative to the left/top corner of the rendered screen.
5.0339
4.677788
1.076128
if self.displayed_lines[0] == 0: top = 0 else: # Get row where the cursor is displayed. y = self.input_line_to_visible_line[self.ui_content.cursor_position.y] top = min(y, self.configured_scroll_offsets.top) return ScrollOffsets( ...
def applied_scroll_offsets(self)
Return a :class:`.ScrollOffsets` instance that indicates the actual offset. This can be less than or equal to what's configured. E.g, when the cursor is completely at the top, the top offset will be zero rather than what's configured.
5.571109
4.924162
1.131382
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
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.
2.745841
2.255114
1.217606
if after_scroll_offset: return self.displayed_lines[self.applied_scroll_offsets.top] else: return self.displayed_lines[0]
def first_visible_line(self, after_scroll_offset=False)
Return the line number (0 based) of the input document that corresponds with the first visible line.
4.334514
3.991215
1.086014
if before_scroll_offset: return self.displayed_lines[-1 - self.applied_scroll_offsets.bottom] else: return self.displayed_lines[-1]
def last_visible_line(self, before_scroll_offset=False)
Like `first_visible_line`, but for the last visible line.
4.85085
4.303362
1.127223
return (self.first_visible_line(after_scroll_offset) + (self.last_visible_line(before_scroll_offset) - self.first_visible_line(after_scroll_offset)) // 2 )
def center_visible_line(self, before_scroll_offset=False, after_scroll_offset=False)
Like `first_visible_line`, but for the center visible line.
2.825039
2.223119
1.270755
if self.wrap_lines: return self.ui_content.get_height_for_line(lineno, self.window_width) else: return 1
def get_height_for_line(self, lineno)
Return the height of the given line. (The height that it would take, if this line became visible.)
5.411123
5.102141
1.060559
# Margin.get_width, needs to have a UIContent instance. def get_ui_content(): return self._get_ui_content(cli, width=0, height=0) def get_width(): return margin.get_width(cli, get_ui_content) key = (margin, cli.render_counter) return self._margi...
def _get_margin_width(self, cli, margin)
Return the width for this margin. (Calculate only once per render time.)
6.247931
5.098926
1.225343
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, m...
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.
3.850726
3.342227
1.152144
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)
def _get_ui_content(self, cli, width, height)
Create a `UIContent` instance.
5.008636
4.683606
1.069397