repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
wandb/client | wandb/util.py | json_friendly | 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 | python | 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 | [
"def",
"json_friendly",
"(",
"obj",
")",
":",
"converted",
"=",
"True",
"typename",
"=",
"get_full_typename",
"(",
"obj",
")",
"if",
"is_tf_tensor_typename",
"(",
"typename",
")",
":",
"obj",
"=",
"obj",
".",
"eval",
"(",
")",
"elif",
"is_pytorch_tensor_type... | Convert an object into something that's more becoming of JSON | [
"Convert",
"an",
"object",
"into",
"something",
"that",
"s",
"more",
"becoming",
"of",
"JSON"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/util.py#L243-L283 | train | 207,400 |
wandb/client | wandb/util.py | launch_browser | 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 | python | 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 | [
"def",
"launch_browser",
"(",
"attempt_launch_browser",
"=",
"True",
")",
":",
"_DISPLAY_VARIABLES",
"=",
"[",
"'DISPLAY'",
",",
"'WAYLAND_DISPLAY'",
",",
"'MIR_SOCKET'",
"]",
"_WEBBROWSER_NAMES_BLACKLIST",
"=",
"[",
"'www-browser'",
",",
"'lynx'",
",",
"'links'",
"... | Decide if we should launch a browser | [
"Decide",
"if",
"we",
"should",
"launch",
"a",
"browser"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/util.py#L323-L344 | train | 207,401 |
wandb/client | wandb/util.py | parse_tfjob_config | 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 | python | 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 | [
"def",
"parse_tfjob_config",
"(",
")",
":",
"if",
"os",
".",
"getenv",
"(",
"\"TF_CONFIG\"",
")",
":",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"os",
".",
"environ",
"[",
"\"TF_CONFIG\"",
"]",
")",
"except",
"ValueError",
":",
"return",
"False",
... | Attempts to parse TFJob config, returning False if it can't find it | [
"Attempts",
"to",
"parse",
"TFJob",
"config",
"returning",
"False",
"if",
"it",
"can",
"t",
"find",
"it"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/util.py#L354-L362 | train | 207,402 |
wandb/client | wandb/util.py | parse_sm_config | 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 | python | 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 | [
"def",
"parse_sm_config",
"(",
")",
":",
"sagemaker_config",
"=",
"\"/opt/ml/input/config/hyperparameters.json\"",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"sagemaker_config",
")",
":",
"conf",
"=",
"{",
"}",
"conf",
"[",
"\"sagemaker_training_job_name\"",
"]",
... | Attempts to parse SageMaker configuration returning False if it can't find it | [
"Attempts",
"to",
"parse",
"SageMaker",
"configuration",
"returning",
"False",
"if",
"it",
"can",
"t",
"find",
"it"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/util.py#L365-L384 | train | 207,403 |
wandb/client | wandb/util.py | write_netrc | 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 | python | 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 | [
"def",
"write_netrc",
"(",
"host",
",",
"entity",
",",
"key",
")",
":",
"if",
"len",
"(",
"key",
")",
"!=",
"40",
":",
"click",
".",
"secho",
"(",
"'API-key must be exactly 40 characters long: {} ({} chars)'",
".",
"format",
"(",
"key",
",",
"len",
"(",
"k... | Add our host and key to .netrc | [
"Add",
"our",
"host",
"and",
"key",
"to",
".",
"netrc"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/util.py#L532-L571 | train | 207,404 |
wandb/client | wandb/util.py | request_with_retry | 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 | python | 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 | [
"def",
"request_with_retry",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"max_retries",
"=",
"kwargs",
".",
"pop",
"(",
"'max_retries'",
",",
"30",
")",
"sleep",
"=",
"2",
"retry_count",
"=",
"0",
"while",
"True",
":",
"try",
":... | 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 | [
"Perform",
"a",
"requests",
"http",
"call",
"retrying",
"with",
"exponential",
"backoff",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/util.py#L574-L612 | train | 207,405 |
wandb/client | wandb/util.py | find_runner | 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 | python | 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 | [
"def",
"find_runner",
"(",
"program",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"program",
")",
"and",
"not",
"os",
".",
"access",
"(",
"program",
",",
"os",
".",
"X_OK",
")",
":",
"# program is a path to a non-executable file",
"try",
":",
... | 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 | [
"Return",
"a",
"command",
"that",
"will",
"run",
"program",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/util.py#L615-L634 | train | 207,406 |
wandb/client | wandb/util.py | downsample | 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 | python | 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 | [
"def",
"downsample",
"(",
"values",
",",
"target_length",
")",
":",
"assert",
"target_length",
">",
"1",
"values",
"=",
"list",
"(",
"values",
")",
"if",
"len",
"(",
"values",
")",
"<",
"target_length",
":",
"return",
"values",
"ratio",
"=",
"float",
"("... | Downsamples 1d values to target_length, including start and end.
Algorithm just rounds index down.
Values can be any sequence, including a generator. | [
"Downsamples",
"1d",
"values",
"to",
"target_length",
"including",
"start",
"and",
"end",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/util.py#L637-L652 | train | 207,407 |
wandb/client | wandb/util.py | image_from_docker_args | 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 | python | 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 | [
"def",
"image_from_docker_args",
"(",
"args",
")",
":",
"bool_args",
"=",
"[",
"\"-t\"",
",",
"\"--tty\"",
",",
"\"--rm\"",
",",
"\"--privileged\"",
",",
"\"--oom-kill-disable\"",
",",
"\"--no-healthcheck\"",
",",
"\"-i\"",
",",
"\"--interactive\"",
",",
"\"--init\"... | 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. | [
"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"... | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/util.py#L679-L712 | train | 207,408 |
wandb/client | wandb/util.py | load_yaml | 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) | python | 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) | [
"def",
"load_yaml",
"(",
"file",
")",
":",
"if",
"hasattr",
"(",
"yaml",
",",
"\"full_load\"",
")",
":",
"return",
"yaml",
".",
"full_load",
"(",
"file",
")",
"else",
":",
"return",
"yaml",
".",
"load",
"(",
"file",
")"
] | If pyyaml > 5.1 use full_load to avoid warning | [
"If",
"pyyaml",
">",
"5",
".",
"1",
"use",
"full_load",
"to",
"avoid",
"warning"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/util.py#L715-L720 | train | 207,409 |
wandb/client | wandb/util.py | image_id_from_k8s | 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 | python | 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 | [
"def",
"image_id_from_k8s",
"(",
")",
":",
"token_path",
"=",
"\"/var/run/secrets/kubernetes.io/serviceaccount/token\"",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"token_path",
")",
":",
"k8s_server",
"=",
"\"https://{}:{}/api/v1/namespaces/default/pods/{}\"",
".",
"fo... | Pings the k8s metadata service for the image id | [
"Pings",
"the",
"k8s",
"metadata",
"service",
"for",
"the",
"image",
"id"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/util.py#L722-L740 | train | 207,410 |
wandb/client | wandb/util.py | stopwatch_now | 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 | python | 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 | [
"def",
"stopwatch_now",
"(",
")",
":",
"if",
"six",
".",
"PY2",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"else",
":",
"now",
"=",
"time",
".",
"monotonic",
"(",
")",
"return",
"now"
] | Get a timevalue for interval comparisons
When possible it is a monotonic clock to prevent backwards time issues. | [
"Get",
"a",
"timevalue",
"for",
"interval",
"comparisons"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/util.py#L785-L794 | train | 207,411 |
wandb/client | wandb/vendor/prompt_toolkit/buffer_mapping.py | BufferMapping.focus | 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] | python | 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] | [
"def",
"focus",
"(",
"self",
",",
"cli",
",",
"buffer_name",
")",
":",
"assert",
"isinstance",
"(",
"buffer_name",
",",
"six",
".",
"text_type",
")",
"self",
".",
"focus_stack",
"=",
"[",
"buffer_name",
"]"
] | Focus the buffer with the given name. | [
"Focus",
"the",
"buffer",
"with",
"the",
"given",
"name",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer_mapping.py#L71-L76 | train | 207,412 |
wandb/client | wandb/vendor/prompt_toolkit/buffer_mapping.py | BufferMapping.push_focus | 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) | python | 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) | [
"def",
"push_focus",
"(",
"self",
",",
"cli",
",",
"buffer_name",
")",
":",
"assert",
"isinstance",
"(",
"buffer_name",
",",
"six",
".",
"text_type",
")",
"self",
".",
"focus_stack",
".",
"append",
"(",
"buffer_name",
")"
] | Push buffer on the focus stack. | [
"Push",
"buffer",
"on",
"the",
"focus",
"stack",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer_mapping.py#L78-L83 | train | 207,413 |
wandb/client | wandb/vendor/prompt_toolkit/buffer_mapping.py | BufferMapping.pop_focus | 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.') | python | 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.') | [
"def",
"pop_focus",
"(",
"self",
",",
"cli",
")",
":",
"if",
"len",
"(",
"self",
".",
"focus_stack",
")",
">",
"1",
":",
"self",
".",
"focus_stack",
".",
"pop",
"(",
")",
"else",
":",
"raise",
"IndexError",
"(",
"'Cannot pop last item from the focus stack.... | Pop buffer from the focus stack. | [
"Pop",
"buffer",
"from",
"the",
"focus",
"stack",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer_mapping.py#L85-L92 | train | 207,414 |
wandb/client | wandb/apis/__init__.py | Progress.read | 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 | python | 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 | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"bites",
"=",
"self",
".",
"file",
".",
"read",
"(",
"size",
")",
"self",
".",
"bytes_read",
"+=",
"len",
"(",
"bites",
")",
"self",
".",
"callback",
"(",
"len",
"(",
"bites",
")... | Read bytes and call the callback | [
"Read",
"bytes",
"and",
"call",
"the",
"callback"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/apis/__init__.py#L24-L29 | train | 207,415 |
wandb/client | wandb/fastai/__init__.py | WandbCallback.on_train_begin | 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) | python | 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) | [
"def",
"on_train_begin",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set self.best, method inherited from \"TrackerCallback\" by \"SaveModelCallback\"",
"super",
"(",
")",
".",
"on_train_begin",
"(",
")",
"# Ensure we don't call \"watch\" multiple times",
"if",
"not",
... | Call watch method to log model topology, gradients & weights | [
"Call",
"watch",
"method",
"to",
"log",
"model",
"topology",
"gradients",
"&",
"weights"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/fastai/__init__.py#L80-L91 | train | 207,416 |
wandb/client | wandb/fastai/__init__.py | WandbCallback.on_epoch_end | 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') | python | 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') | [
"def",
"on_epoch_end",
"(",
"self",
",",
"epoch",
",",
"smooth_loss",
",",
"last_metrics",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"save_model",
":",
"# Adapted from fast.ai \"SaveModelCallback\"",
"current",
"=",
"self",
".",
"get_monitor_value",
... | Logs training loss, validation loss and custom metrics & log prediction samples & save model | [
"Logs",
"training",
"loss",
"validation",
"loss",
"and",
"custom",
"metrics",
"&",
"log",
"prediction",
"samples",
"&",
"save",
"model"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/fastai/__init__.py#L93-L126 | train | 207,417 |
wandb/client | wandb/history.py | History.column | 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] | python | 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] | [
"def",
"column",
"(",
"self",
",",
"key",
")",
":",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"if",
"key",
"in",
"row",
":",
"yield",
"row",
"[",
"key",
"]"
] | Iterator over a given column, skipping steps that don't have that key | [
"Iterator",
"over",
"a",
"given",
"column",
"skipping",
"steps",
"that",
"don",
"t",
"have",
"that",
"key"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/history.py#L96-L101 | train | 207,418 |
wandb/client | wandb/history.py | History.add | 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) | python | 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) | [
"def",
"add",
"(",
"self",
",",
"row",
"=",
"{",
"}",
",",
"step",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"row",
",",
"collections",
".",
"Mapping",
")",
":",
"raise",
"wandb",
".",
"Error",
"(",
"'history.add expects dict-like object'",
... | 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} | [
"Adds",
"or",
"updates",
"a",
"history",
"step",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/history.py#L103-L140 | train | 207,419 |
wandb/client | wandb/history.py | History.update | 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 | python | 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 | [
"def",
"update",
"(",
"self",
",",
"new_vals",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"new_vals",
")",
":",
"k",
"=",
"k",
".",
"strip",
"(",
")",
"if",
"k",
"in",
"self",
".",
"row",
":",
"warnings",
".",
"warn",
... | Add a dictionary of values to the current step without writing it to disk. | [
"Add",
"a",
"dictionary",
"of",
"values",
"to",
"the",
"current",
"step",
"without",
"writing",
"it",
"to",
"disk",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/history.py#L142-L150 | train | 207,420 |
wandb/client | wandb/history.py | History.step | 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 | python | 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 | [
"def",
"step",
"(",
"self",
",",
"compute",
"=",
"True",
")",
":",
"if",
"self",
".",
"batched",
":",
"# we're already in a context manager",
"raise",
"wandb",
".",
"Error",
"(",
"\"Nested History step contexts aren't supported\"",
")",
"self",
".",
"batched",
"="... | 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 | [
"Context",
"manager",
"to",
"gradually",
"build",
"a",
"history",
"row",
"then",
"commit",
"it",
"at",
"the",
"end",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/history.py#L153-L170 | train | 207,421 |
wandb/client | wandb/history.py | History._index | 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 | python | 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 | [
"def",
"_index",
"(",
"self",
",",
"row",
")",
":",
"self",
".",
"rows",
".",
"append",
"(",
"row",
")",
"self",
".",
"_keys",
".",
"update",
"(",
"row",
".",
"keys",
"(",
")",
")",
"self",
".",
"_steps",
"+=",
"1"
] | 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. | [
"Add",
"a",
"row",
"to",
"the",
"internal",
"list",
"of",
"rows",
"without",
"writing",
"it",
"to",
"disk",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/history.py#L186-L194 | train | 207,422 |
wandb/client | wandb/io_wrap.py | wandb_pty | 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 | python | 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 | [
"def",
"wandb_pty",
"(",
"resize",
"=",
"True",
")",
":",
"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",... | Get a PTY set to raw mode and registered to hear about window size changes. | [
"Get",
"a",
"PTY",
"set",
"to",
"raw",
"mode",
"and",
"registered",
"to",
"hear",
"about",
"window",
"size",
"changes",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/io_wrap.py#L154-L170 | train | 207,423 |
wandb/client | wandb/io_wrap.py | spawn_reader_writer | 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 | python | 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 | [
"def",
"spawn_reader_writer",
"(",
"get_data_fn",
",",
"put_data_fn",
")",
":",
"def",
"_reader_thread",
"(",
")",
":",
"while",
"True",
":",
"out",
"=",
"get_data_fn",
"(",
")",
"put_data_fn",
"(",
"out",
")",
"if",
"not",
"out",
":",
"# EOF.",
"# We've p... | 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 | [
"Spawn",
"a",
"thread",
"that",
"reads",
"from",
"a",
"data",
"source",
"and",
"writes",
"to",
"a",
"sink",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/io_wrap.py#L267-L291 | train | 207,424 |
wandb/client | wandb/io_wrap.py | FileRedirector.restore | 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) | python | 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) | [
"def",
"restore",
"(",
"self",
")",
":",
"# NOTE: dup2 makes `self._from_fd` inheritable unconditionally",
"self",
".",
"redir_file",
".",
"flush",
"(",
")",
"os",
".",
"dup2",
"(",
"self",
".",
"orig_file",
".",
"fileno",
"(",
")",
",",
"self",
".",
"_from_fd... | Restore `self.redir_file` to its original state. | [
"Restore",
"self",
".",
"redir_file",
"to",
"its",
"original",
"state",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/io_wrap.py#L325-L330 | train | 207,425 |
wandb/client | wandb/vendor/prompt_toolkit/contrib/telnet/protocol.py | TelnetProtocolParser.negotiate | 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)) | python | 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)) | [
"def",
"negotiate",
"(",
"self",
",",
"data",
")",
":",
"command",
",",
"payload",
"=",
"data",
"[",
"0",
":",
"1",
"]",
",",
"data",
"[",
"1",
":",
"]",
"assert",
"isinstance",
"(",
"command",
",",
"bytes",
")",
"if",
"command",
"==",
"NAWS",
":... | Got negotiate data. | [
"Got",
"negotiate",
"data",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/contrib/telnet/protocol.py#L115-L125 | train | 207,426 |
wandb/client | wandb/vendor/prompt_toolkit/contrib/telnet/protocol.py | TelnetProtocolParser._parse_coroutine | 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) | python | 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) | [
"def",
"_parse_coroutine",
"(",
"self",
")",
":",
"while",
"True",
":",
"d",
"=",
"yield",
"if",
"d",
"==",
"int2byte",
"(",
"0",
")",
":",
"pass",
"# NOP",
"# Go to state escaped.",
"elif",
"d",
"==",
"IAC",
":",
"d2",
"=",
"yield",
"if",
"d2",
"=="... | Parser state machine.
Every 'yield' expression returns the next byte. | [
"Parser",
"state",
"machine",
".",
"Every",
"yield",
"expression",
"returns",
"the",
"next",
"byte",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/contrib/telnet/protocol.py#L127-L173 | train | 207,427 |
wandb/client | wandb/vendor/prompt_toolkit/contrib/telnet/protocol.py | TelnetProtocolParser.feed | def feed(self, data):
"""
Feed data to the parser.
"""
assert isinstance(data, binary_type)
for b in iterbytes(data):
self._parser.send(int2byte(b)) | python | def feed(self, data):
"""
Feed data to the parser.
"""
assert isinstance(data, binary_type)
for b in iterbytes(data):
self._parser.send(int2byte(b)) | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"binary_type",
")",
"for",
"b",
"in",
"iterbytes",
"(",
"data",
")",
":",
"self",
".",
"_parser",
".",
"send",
"(",
"int2byte",
"(",
"b",
")",
")"
] | Feed data to the parser. | [
"Feed",
"data",
"to",
"the",
"parser",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/contrib/telnet/protocol.py#L175-L181 | train | 207,428 |
wandb/client | wandb/apis/public.py | Run.create | 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"
}) | python | 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"
}) | [
"def",
"create",
"(",
"cls",
",",
"api",
",",
"run_id",
"=",
"None",
",",
"project",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"run_id",
"=",
"run_id",
"or",
"util",
".",
"generate_id",
"(",
")",
"project",
"=",
"project",
"or",
"api",
"... | Create a run for the given project | [
"Create",
"a",
"run",
"for",
"the",
"given",
"project"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/apis/public.py#L323-L354 | train | 207,429 |
wandb/client | wandb/apis/public.py | Run._exec | 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) | python | 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) | [
"def",
"_exec",
"(",
"self",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"variables",
"=",
"{",
"'entity'",
":",
"self",
".",
"username",
",",
"'project'",
":",
"self",
".",
"project",
",",
"'name'",
":",
"self",
".",
"name",
"}",
"variables",
... | Execute a query against the cloud backend | [
"Execute",
"a",
"query",
"against",
"the",
"cloud",
"backend"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/apis/public.py#L422-L427 | train | 207,430 |
wandb/client | wandb/vendor/prompt_toolkit/terminal/vt100_output.py | _get_closest_ansi_color | def _get_closest_ansi_color(r, g, b, exclude=()):
"""
Find closest ANSI color. Return it by name.
:param r: Red (Between 0 and 255.)
:param g: Green (Between 0 and 255.)
:param b: Blue (Between 0 and 255.)
:param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.)
"""
assert isinstance(exclude, tuple)
# When we have a bit of saturation, avoid the gray-like colors, otherwise,
# too often the distance to the gray color is less.
saturation = abs(r - g) + abs(g - b) + abs(b - r) # Between 0..510
if saturation > 30:
exclude += ('ansilightgray', 'ansidarkgray', 'ansiwhite', 'ansiblack')
# Take the closest color.
# (Thanks to Pygments for this part.)
distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff)
match = 'ansidefault'
for name, (r2, g2, b2) in ANSI_COLORS_TO_RGB.items():
if name != 'ansidefault' and name not in exclude:
d = (r - r2) ** 2 + (g - g2) ** 2 + (b - b2) ** 2
if d < distance:
match = name
distance = d
return match | python | def _get_closest_ansi_color(r, g, b, exclude=()):
"""
Find closest ANSI color. Return it by name.
:param r: Red (Between 0 and 255.)
:param g: Green (Between 0 and 255.)
:param b: Blue (Between 0 and 255.)
:param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.)
"""
assert isinstance(exclude, tuple)
# When we have a bit of saturation, avoid the gray-like colors, otherwise,
# too often the distance to the gray color is less.
saturation = abs(r - g) + abs(g - b) + abs(b - r) # Between 0..510
if saturation > 30:
exclude += ('ansilightgray', 'ansidarkgray', 'ansiwhite', 'ansiblack')
# Take the closest color.
# (Thanks to Pygments for this part.)
distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff)
match = 'ansidefault'
for name, (r2, g2, b2) in ANSI_COLORS_TO_RGB.items():
if name != 'ansidefault' and name not in exclude:
d = (r - r2) ** 2 + (g - g2) ** 2 + (b - b2) ** 2
if d < distance:
match = name
distance = d
return match | [
"def",
"_get_closest_ansi_color",
"(",
"r",
",",
"g",
",",
"b",
",",
"exclude",
"=",
"(",
")",
")",
":",
"assert",
"isinstance",
"(",
"exclude",
",",
"tuple",
")",
"# When we have a bit of saturation, avoid the gray-like colors, otherwise,",
"# too often the distance to... | Find closest ANSI color. Return it by name.
:param r: Red (Between 0 and 255.)
:param g: Green (Between 0 and 255.)
:param b: Blue (Between 0 and 255.)
:param exclude: A tuple of color names to exclude. (E.g. ``('ansired', )``.) | [
"Find",
"closest",
"ANSI",
"color",
".",
"Return",
"it",
"by",
"name",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/terminal/vt100_output.py#L106-L137 | train | 207,431 |
wandb/client | wandb/vendor/prompt_toolkit/terminal/vt100_output.py | _get_size | def _get_size(fileno):
# Thanks to fabric (fabfile.org), and
# http://sqizit.bartletts.id.au/2011/02/14/pseudo-terminals-in-python/
"""
Get the size of this pseudo terminal.
:param fileno: stdout.fileno()
:returns: A (rows, cols) tuple.
"""
# Inline imports, because these modules are not available on Windows.
# (This file is used by ConEmuOutput, which is used on Windows.)
import fcntl
import termios
# Buffer for the C call
buf = array.array(b'h' if six.PY2 else u'h', [0, 0, 0, 0])
# Do TIOCGWINSZ (Get)
# Note: We should not pass 'True' as a fourth parameter to 'ioctl'. (True
# is the default.) This causes segmentation faults on some systems.
# See: https://github.com/jonathanslenders/python-prompt-toolkit/pull/364
fcntl.ioctl(fileno, termios.TIOCGWINSZ, buf)
# Return rows, cols
return buf[0], buf[1] | python | def _get_size(fileno):
# Thanks to fabric (fabfile.org), and
# http://sqizit.bartletts.id.au/2011/02/14/pseudo-terminals-in-python/
"""
Get the size of this pseudo terminal.
:param fileno: stdout.fileno()
:returns: A (rows, cols) tuple.
"""
# Inline imports, because these modules are not available on Windows.
# (This file is used by ConEmuOutput, which is used on Windows.)
import fcntl
import termios
# Buffer for the C call
buf = array.array(b'h' if six.PY2 else u'h', [0, 0, 0, 0])
# Do TIOCGWINSZ (Get)
# Note: We should not pass 'True' as a fourth parameter to 'ioctl'. (True
# is the default.) This causes segmentation faults on some systems.
# See: https://github.com/jonathanslenders/python-prompt-toolkit/pull/364
fcntl.ioctl(fileno, termios.TIOCGWINSZ, buf)
# Return rows, cols
return buf[0], buf[1] | [
"def",
"_get_size",
"(",
"fileno",
")",
":",
"# Thanks to fabric (fabfile.org), and",
"# http://sqizit.bartletts.id.au/2011/02/14/pseudo-terminals-in-python/",
"# Inline imports, because these modules are not available on Windows.",
"# (This file is used by ConEmuOutput, which is used on Windows.)... | Get the size of this pseudo terminal.
:param fileno: stdout.fileno()
:returns: A (rows, cols) tuple. | [
"Get",
"the",
"size",
"of",
"this",
"pseudo",
"terminal",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/terminal/vt100_output.py#L344-L368 | train | 207,432 |
wandb/client | wandb/vendor/prompt_toolkit/terminal/vt100_output.py | _EscapeCodeCache._colors_to_code | def _colors_to_code(self, fg_color, bg_color):
" Return a tuple with the vt100 values that represent this color. "
# When requesting ANSI colors only, and both fg/bg color were converted
# to ANSI, ensure that the foreground and background color are not the
# same. (Unless they were explicitely defined to be the same color.)
fg_ansi = [()]
def get(color, bg):
table = BG_ANSI_COLORS if bg else FG_ANSI_COLORS
if color is None:
return ()
# 16 ANSI colors. (Given by name.)
elif color in table:
return (table[color], )
# RGB colors. (Defined as 'ffffff'.)
else:
try:
rgb = self._color_name_to_rgb(color)
except ValueError:
return ()
# When only 16 colors are supported, use that.
if self.ansi_colors_only():
if bg: # Background.
if fg_color != bg_color:
exclude = (fg_ansi[0], )
else:
exclude = ()
code, name = _16_bg_colors.get_code(rgb, exclude=exclude)
return (code, )
else: # Foreground.
code, name = _16_fg_colors.get_code(rgb)
fg_ansi[0] = name
return (code, )
# True colors. (Only when this feature is enabled.)
elif self.true_color:
r, g, b = rgb
return (48 if bg else 38, 2, r, g, b)
# 256 RGB colors.
else:
return (48 if bg else 38, 5, _256_colors[rgb])
result = []
result.extend(get(fg_color, False))
result.extend(get(bg_color, True))
return map(six.text_type, result) | python | def _colors_to_code(self, fg_color, bg_color):
" Return a tuple with the vt100 values that represent this color. "
# When requesting ANSI colors only, and both fg/bg color were converted
# to ANSI, ensure that the foreground and background color are not the
# same. (Unless they were explicitely defined to be the same color.)
fg_ansi = [()]
def get(color, bg):
table = BG_ANSI_COLORS if bg else FG_ANSI_COLORS
if color is None:
return ()
# 16 ANSI colors. (Given by name.)
elif color in table:
return (table[color], )
# RGB colors. (Defined as 'ffffff'.)
else:
try:
rgb = self._color_name_to_rgb(color)
except ValueError:
return ()
# When only 16 colors are supported, use that.
if self.ansi_colors_only():
if bg: # Background.
if fg_color != bg_color:
exclude = (fg_ansi[0], )
else:
exclude = ()
code, name = _16_bg_colors.get_code(rgb, exclude=exclude)
return (code, )
else: # Foreground.
code, name = _16_fg_colors.get_code(rgb)
fg_ansi[0] = name
return (code, )
# True colors. (Only when this feature is enabled.)
elif self.true_color:
r, g, b = rgb
return (48 if bg else 38, 2, r, g, b)
# 256 RGB colors.
else:
return (48 if bg else 38, 5, _256_colors[rgb])
result = []
result.extend(get(fg_color, False))
result.extend(get(bg_color, True))
return map(six.text_type, result) | [
"def",
"_colors_to_code",
"(",
"self",
",",
"fg_color",
",",
"bg_color",
")",
":",
"# When requesting ANSI colors only, and both fg/bg color were converted",
"# to ANSI, ensure that the foreground and background color are not the",
"# same. (Unless they were explicitely defined to be the sam... | Return a tuple with the vt100 values that represent this color. | [
"Return",
"a",
"tuple",
"with",
"the",
"vt100",
"values",
"that",
"represent",
"this",
"color",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/terminal/vt100_output.py#L290-L341 | train | 207,433 |
wandb/client | wandb/vendor/prompt_toolkit/terminal/vt100_output.py | Vt100_Output.set_attributes | def set_attributes(self, attrs):
"""
Create new style and output.
:param attrs: `Attrs` instance.
"""
if self.true_color() and not self.ansi_colors_only():
self.write_raw(self._escape_code_cache_true_color[attrs])
else:
self.write_raw(self._escape_code_cache[attrs]) | python | def set_attributes(self, attrs):
"""
Create new style and output.
:param attrs: `Attrs` instance.
"""
if self.true_color() and not self.ansi_colors_only():
self.write_raw(self._escape_code_cache_true_color[attrs])
else:
self.write_raw(self._escape_code_cache[attrs]) | [
"def",
"set_attributes",
"(",
"self",
",",
"attrs",
")",
":",
"if",
"self",
".",
"true_color",
"(",
")",
"and",
"not",
"self",
".",
"ansi_colors_only",
"(",
")",
":",
"self",
".",
"write_raw",
"(",
"self",
".",
"_escape_code_cache_true_color",
"[",
"attrs"... | Create new style and output.
:param attrs: `Attrs` instance. | [
"Create",
"new",
"style",
"and",
"output",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/terminal/vt100_output.py#L511-L520 | train | 207,434 |
wandb/client | wandb/__init__.py | watch | def watch(models, criterion=None, log="gradients", log_freq=100):
"""
Hooks into the torch model to collect gradients and the topology. Should be extended
to accept arbitrary ML models.
:param (torch.Module) models: The model to hook, can be a tuple
:param (torch.F) criterion: An optional loss value being optimized
:param (str) log: One of "gradients", "parameters", "all", or None
:param (int) log_freq: log gradients and parameters every N batches
:return: (wandb.Graph) The graph object that will populate after the first backward pass
"""
global watch_called
if run is None:
raise ValueError(
"You must call `wandb.init` before calling watch")
if watch_called:
raise ValueError(
"You can only call `wandb.watch` once per process. If you want to watch multiple models, pass them in as a tuple."
)
watch_called = True
log_parameters = False
log_gradients = True
if log == "all":
log_parameters = True
elif log == "parameters":
log_parameters = True
log_gradients = False
elif log is None:
log_gradients = False
if not isinstance(models, (tuple, list)):
models = (models,)
graphs = []
prefix = ''
for idx, model in enumerate(models):
if idx > 0:
prefix = "graph_%i" % idx
run.history.torch.add_log_hooks_to_pytorch_module(
model, log_parameters=log_parameters, log_gradients=log_gradients, prefix=prefix, log_freq=log_freq)
graph = wandb_torch.TorchGraph.hook_torch(model, criterion, graph_idx=idx)
graphs.append(graph)
# NOTE: the graph is set in run.summary by hook_torch on the backward pass
return graphs | python | def watch(models, criterion=None, log="gradients", log_freq=100):
"""
Hooks into the torch model to collect gradients and the topology. Should be extended
to accept arbitrary ML models.
:param (torch.Module) models: The model to hook, can be a tuple
:param (torch.F) criterion: An optional loss value being optimized
:param (str) log: One of "gradients", "parameters", "all", or None
:param (int) log_freq: log gradients and parameters every N batches
:return: (wandb.Graph) The graph object that will populate after the first backward pass
"""
global watch_called
if run is None:
raise ValueError(
"You must call `wandb.init` before calling watch")
if watch_called:
raise ValueError(
"You can only call `wandb.watch` once per process. If you want to watch multiple models, pass them in as a tuple."
)
watch_called = True
log_parameters = False
log_gradients = True
if log == "all":
log_parameters = True
elif log == "parameters":
log_parameters = True
log_gradients = False
elif log is None:
log_gradients = False
if not isinstance(models, (tuple, list)):
models = (models,)
graphs = []
prefix = ''
for idx, model in enumerate(models):
if idx > 0:
prefix = "graph_%i" % idx
run.history.torch.add_log_hooks_to_pytorch_module(
model, log_parameters=log_parameters, log_gradients=log_gradients, prefix=prefix, log_freq=log_freq)
graph = wandb_torch.TorchGraph.hook_torch(model, criterion, graph_idx=idx)
graphs.append(graph)
# NOTE: the graph is set in run.summary by hook_torch on the backward pass
return graphs | [
"def",
"watch",
"(",
"models",
",",
"criterion",
"=",
"None",
",",
"log",
"=",
"\"gradients\"",
",",
"log_freq",
"=",
"100",
")",
":",
"global",
"watch_called",
"if",
"run",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"You must call `wandb.init` before ca... | Hooks into the torch model to collect gradients and the topology. Should be extended
to accept arbitrary ML models.
:param (torch.Module) models: The model to hook, can be a tuple
:param (torch.F) criterion: An optional loss value being optimized
:param (str) log: One of "gradients", "parameters", "all", or None
:param (int) log_freq: log gradients and parameters every N batches
:return: (wandb.Graph) The graph object that will populate after the first backward pass | [
"Hooks",
"into",
"the",
"torch",
"model",
"to",
"collect",
"gradients",
"and",
"the",
"topology",
".",
"Should",
"be",
"extended",
"to",
"accept",
"arbitrary",
"ML",
"models",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/__init__.py#L96-L140 | train | 207,435 |
wandb/client | wandb/__init__.py | restore | def restore(name, run_path=None, replace=False, root="."):
""" Downloads the specified file from cloud storage into the current run directory
if it doesn exist.
name: the name of the file
run_path: optional path to a different run to pull files from
replace: whether to download the file even if it already exists locally
root: the directory to download the file to. Defaults to the current
directory or the run directory if wandb.init was called.
returns None if it can't find the file, otherwise a file object open for reading
raises wandb.CommError if it can't find the run
"""
if run_path is None and run is None:
raise ValueError(
"You must call `wandb.init` before calling restore or specify a run_path")
api = Api()
api_run = api.run(run_path or run.path)
root = run.dir if run else root
path = os.path.exists(os.path.join(root, name))
if path and replace == False:
return open(path, "r")
files = api_run.files([name])
if len(files) == 0:
return None
return files[0].download(root=root, replace=True) | python | def restore(name, run_path=None, replace=False, root="."):
""" Downloads the specified file from cloud storage into the current run directory
if it doesn exist.
name: the name of the file
run_path: optional path to a different run to pull files from
replace: whether to download the file even if it already exists locally
root: the directory to download the file to. Defaults to the current
directory or the run directory if wandb.init was called.
returns None if it can't find the file, otherwise a file object open for reading
raises wandb.CommError if it can't find the run
"""
if run_path is None and run is None:
raise ValueError(
"You must call `wandb.init` before calling restore or specify a run_path")
api = Api()
api_run = api.run(run_path or run.path)
root = run.dir if run else root
path = os.path.exists(os.path.join(root, name))
if path and replace == False:
return open(path, "r")
files = api_run.files([name])
if len(files) == 0:
return None
return files[0].download(root=root, replace=True) | [
"def",
"restore",
"(",
"name",
",",
"run_path",
"=",
"None",
",",
"replace",
"=",
"False",
",",
"root",
"=",
"\".\"",
")",
":",
"if",
"run_path",
"is",
"None",
"and",
"run",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"You must call `wandb.init` befor... | Downloads the specified file from cloud storage into the current run directory
if it doesn exist.
name: the name of the file
run_path: optional path to a different run to pull files from
replace: whether to download the file even if it already exists locally
root: the directory to download the file to. Defaults to the current
directory or the run directory if wandb.init was called.
returns None if it can't find the file, otherwise a file object open for reading
raises wandb.CommError if it can't find the run | [
"Downloads",
"the",
"specified",
"file",
"from",
"cloud",
"storage",
"into",
"the",
"current",
"run",
"directory",
"if",
"it",
"doesn",
"exist",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/__init__.py#L408-L433 | train | 207,436 |
wandb/client | wandb/__init__.py | monitor | def monitor(options={}):
"""Starts syncing with W&B if you're in Jupyter. Displays your W&B charts live in a Jupyter notebook.
It's currently a context manager for legacy reasons.
"""
try:
from IPython.display import display
except ImportError:
def display(stuff): return None
class Monitor():
def __init__(self, options={}):
if os.getenv("WANDB_JUPYTER"):
display(jupyter.Run())
else:
self.rm = False
termerror(
"wandb.monitor is only functional in Jupyter notebooks")
def __enter__(self):
termlog(
"DEPRECATED: with wandb.monitor(): is deprecated, just call wandb.monitor() to see live results.")
pass
def __exit__(self, *args):
pass
return Monitor(options) | python | def monitor(options={}):
"""Starts syncing with W&B if you're in Jupyter. Displays your W&B charts live in a Jupyter notebook.
It's currently a context manager for legacy reasons.
"""
try:
from IPython.display import display
except ImportError:
def display(stuff): return None
class Monitor():
def __init__(self, options={}):
if os.getenv("WANDB_JUPYTER"):
display(jupyter.Run())
else:
self.rm = False
termerror(
"wandb.monitor is only functional in Jupyter notebooks")
def __enter__(self):
termlog(
"DEPRECATED: with wandb.monitor(): is deprecated, just call wandb.monitor() to see live results.")
pass
def __exit__(self, *args):
pass
return Monitor(options) | [
"def",
"monitor",
"(",
"options",
"=",
"{",
"}",
")",
":",
"try",
":",
"from",
"IPython",
".",
"display",
"import",
"display",
"except",
"ImportError",
":",
"def",
"display",
"(",
"stuff",
")",
":",
"return",
"None",
"class",
"Monitor",
"(",
")",
":",
... | Starts syncing with W&B if you're in Jupyter. Displays your W&B charts live in a Jupyter notebook.
It's currently a context manager for legacy reasons. | [
"Starts",
"syncing",
"with",
"W&B",
"if",
"you",
"re",
"in",
"Jupyter",
".",
"Displays",
"your",
"W&B",
"charts",
"live",
"in",
"a",
"Jupyter",
"notebook",
".",
"It",
"s",
"currently",
"a",
"context",
"manager",
"for",
"legacy",
"reasons",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/__init__.py#L436-L462 | train | 207,437 |
wandb/client | wandb/__init__.py | log | def log(row=None, commit=True, *args, **kargs):
"""Log a dict to the global run's history. If commit is false, enables multiple calls before commiting.
Eg.
wandb.log({'train-loss': 0.5, 'accuracy': 0.9})
"""
if run is None:
raise ValueError(
"You must call `wandb.init` in the same process before calling log")
if row is None:
row = {}
if commit:
run.history.add(row, *args, **kargs)
else:
run.history.update(row, *args, **kargs) | python | def log(row=None, commit=True, *args, **kargs):
"""Log a dict to the global run's history. If commit is false, enables multiple calls before commiting.
Eg.
wandb.log({'train-loss': 0.5, 'accuracy': 0.9})
"""
if run is None:
raise ValueError(
"You must call `wandb.init` in the same process before calling log")
if row is None:
row = {}
if commit:
run.history.add(row, *args, **kargs)
else:
run.history.update(row, *args, **kargs) | [
"def",
"log",
"(",
"row",
"=",
"None",
",",
"commit",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"run",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"You must call `wandb.init` in the same process before calling log\"",
")",
"... | Log a dict to the global run's history. If commit is false, enables multiple calls before commiting.
Eg.
wandb.log({'train-loss': 0.5, 'accuracy': 0.9}) | [
"Log",
"a",
"dict",
"to",
"the",
"global",
"run",
"s",
"history",
".",
"If",
"commit",
"is",
"false",
"enables",
"multiple",
"calls",
"before",
"commiting",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/__init__.py#L465-L481 | train | 207,438 |
wandb/client | wandb/__init__.py | reset_env | def reset_env(exclude=[]):
"""Remove environment variables, used in Jupyter notebooks"""
if os.getenv(env.INITED):
wandb_keys = [key for key in os.environ.keys() if key.startswith(
'WANDB_') and key not in exclude]
for key in wandb_keys:
del os.environ[key]
return True
else:
return False | python | def reset_env(exclude=[]):
"""Remove environment variables, used in Jupyter notebooks"""
if os.getenv(env.INITED):
wandb_keys = [key for key in os.environ.keys() if key.startswith(
'WANDB_') and key not in exclude]
for key in wandb_keys:
del os.environ[key]
return True
else:
return False | [
"def",
"reset_env",
"(",
"exclude",
"=",
"[",
"]",
")",
":",
"if",
"os",
".",
"getenv",
"(",
"env",
".",
"INITED",
")",
":",
"wandb_keys",
"=",
"[",
"key",
"for",
"key",
"in",
"os",
".",
"environ",
".",
"keys",
"(",
")",
"if",
"key",
".",
"star... | Remove environment variables, used in Jupyter notebooks | [
"Remove",
"environment",
"variables",
"used",
"in",
"Jupyter",
"notebooks"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/__init__.py#L498-L507 | train | 207,439 |
wandb/client | wandb/__init__.py | try_to_set_up_global_logging | def try_to_set_up_global_logging():
"""Try to set up global W&B debug log that gets re-written by every W&B process.
It may fail (and return False) eg. if the current directory isn't user-writable
"""
root = logging.getLogger()
root.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(filename)s:%(funcName)s():%(lineno)s] %(message)s')
if env.is_debug():
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
root.addHandler(handler)
try:
handler = logging.FileHandler(GLOBAL_LOG_FNAME, mode='w')
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
root.addHandler(handler)
except IOError as e: # eg. in case wandb directory isn't writable
termerror('Failed to set up logging: {}'.format(e))
return False
return True | python | def try_to_set_up_global_logging():
"""Try to set up global W&B debug log that gets re-written by every W&B process.
It may fail (and return False) eg. if the current directory isn't user-writable
"""
root = logging.getLogger()
root.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(filename)s:%(funcName)s():%(lineno)s] %(message)s')
if env.is_debug():
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
root.addHandler(handler)
try:
handler = logging.FileHandler(GLOBAL_LOG_FNAME, mode='w')
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
root.addHandler(handler)
except IOError as e: # eg. in case wandb directory isn't writable
termerror('Failed to set up logging: {}'.format(e))
return False
return True | [
"def",
"try_to_set_up_global_logging",
"(",
")",
":",
"root",
"=",
"logging",
".",
"getLogger",
"(",
")",
"root",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s %(levelname)-7s %(threadName)-10... | Try to set up global W&B debug log that gets re-written by every W&B process.
It may fail (and return False) eg. if the current directory isn't user-writable | [
"Try",
"to",
"set",
"up",
"global",
"W&B",
"debug",
"log",
"that",
"gets",
"re",
"-",
"written",
"by",
"every",
"W&B",
"process",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/__init__.py#L510-L537 | train | 207,440 |
wandb/client | wandb/__init__.py | sagemaker_auth | def sagemaker_auth(overrides={}, path="."):
""" Write a secrets.env file with the W&B ApiKey and any additional secrets passed.
Args:
overrides (dict, optional): Additional environment variables to write to secrets.env
path (str, optional): The path to write the secrets file.
"""
api_key = overrides.get(env.API_KEY, Api().api_key)
if api_key is None:
raise ValueError(
"Can't find W&B ApiKey, set the WANDB_API_KEY env variable or run `wandb login`")
overrides[env.API_KEY] = api_key
with open(os.path.join(path, "secrets.env"), "w") as file:
for k, v in six.iteritems(overrides):
file.write("{}={}\n".format(k, v)) | python | def sagemaker_auth(overrides={}, path="."):
""" Write a secrets.env file with the W&B ApiKey and any additional secrets passed.
Args:
overrides (dict, optional): Additional environment variables to write to secrets.env
path (str, optional): The path to write the secrets file.
"""
api_key = overrides.get(env.API_KEY, Api().api_key)
if api_key is None:
raise ValueError(
"Can't find W&B ApiKey, set the WANDB_API_KEY env variable or run `wandb login`")
overrides[env.API_KEY] = api_key
with open(os.path.join(path, "secrets.env"), "w") as file:
for k, v in six.iteritems(overrides):
file.write("{}={}\n".format(k, v)) | [
"def",
"sagemaker_auth",
"(",
"overrides",
"=",
"{",
"}",
",",
"path",
"=",
"\".\"",
")",
":",
"api_key",
"=",
"overrides",
".",
"get",
"(",
"env",
".",
"API_KEY",
",",
"Api",
"(",
")",
".",
"api_key",
")",
"if",
"api_key",
"is",
"None",
":",
"rais... | Write a secrets.env file with the W&B ApiKey and any additional secrets passed.
Args:
overrides (dict, optional): Additional environment variables to write to secrets.env
path (str, optional): The path to write the secrets file. | [
"Write",
"a",
"secrets",
".",
"env",
"file",
"with",
"the",
"W&B",
"ApiKey",
"and",
"any",
"additional",
"secrets",
"passed",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/__init__.py#L550-L565 | train | 207,441 |
wandb/client | wandb/vendor/prompt_toolkit/styles/from_dict.py | style_from_dict | def style_from_dict(style_dict, include_defaults=True):
"""
Create a ``Style`` instance from a dictionary or other mapping.
The dictionary is equivalent to the ``Style.styles`` dictionary from
pygments, with a few additions: it supports 'reverse' and 'blink'.
Usage::
style_from_dict({
Token: '#ff0000 bold underline',
Token.Title: 'blink',
Token.SomethingElse: 'reverse',
})
:param include_defaults: Include the defaults (built-in) styling for
selected text, etc...)
"""
assert isinstance(style_dict, Mapping)
if include_defaults:
s2 = {}
s2.update(DEFAULT_STYLE_EXTENSIONS)
s2.update(style_dict)
style_dict = s2
# Expand token inheritance and turn style description into Attrs.
token_to_attrs = {}
# (Loop through the tokens in order. Sorting makes sure that
# we process the parent first.)
for ttype, styledef in sorted(style_dict.items()):
# Start from parent Attrs or default Attrs.
attrs = DEFAULT_ATTRS
if 'noinherit' not in styledef:
for i in range(1, len(ttype) + 1):
try:
attrs = token_to_attrs[ttype[:-i]]
except KeyError:
pass
else:
break
# Now update with the given attributes.
for part in styledef.split():
if part == 'noinherit':
pass
elif part == 'bold':
attrs = attrs._replace(bold=True)
elif part == 'nobold':
attrs = attrs._replace(bold=False)
elif part == 'italic':
attrs = attrs._replace(italic=True)
elif part == 'noitalic':
attrs = attrs._replace(italic=False)
elif part == 'underline':
attrs = attrs._replace(underline=True)
elif part == 'nounderline':
attrs = attrs._replace(underline=False)
# prompt_toolkit extensions. Not in Pygments.
elif part == 'blink':
attrs = attrs._replace(blink=True)
elif part == 'noblink':
attrs = attrs._replace(blink=False)
elif part == 'reverse':
attrs = attrs._replace(reverse=True)
elif part == 'noreverse':
attrs = attrs._replace(reverse=False)
# Pygments properties that we ignore.
elif part in ('roman', 'sans', 'mono'):
pass
elif part.startswith('border:'):
pass
# Colors.
elif part.startswith('bg:'):
attrs = attrs._replace(bgcolor=_colorformat(part[3:]))
else:
attrs = attrs._replace(color=_colorformat(part))
token_to_attrs[ttype] = attrs
return _StyleFromDict(token_to_attrs) | python | def style_from_dict(style_dict, include_defaults=True):
"""
Create a ``Style`` instance from a dictionary or other mapping.
The dictionary is equivalent to the ``Style.styles`` dictionary from
pygments, with a few additions: it supports 'reverse' and 'blink'.
Usage::
style_from_dict({
Token: '#ff0000 bold underline',
Token.Title: 'blink',
Token.SomethingElse: 'reverse',
})
:param include_defaults: Include the defaults (built-in) styling for
selected text, etc...)
"""
assert isinstance(style_dict, Mapping)
if include_defaults:
s2 = {}
s2.update(DEFAULT_STYLE_EXTENSIONS)
s2.update(style_dict)
style_dict = s2
# Expand token inheritance and turn style description into Attrs.
token_to_attrs = {}
# (Loop through the tokens in order. Sorting makes sure that
# we process the parent first.)
for ttype, styledef in sorted(style_dict.items()):
# Start from parent Attrs or default Attrs.
attrs = DEFAULT_ATTRS
if 'noinherit' not in styledef:
for i in range(1, len(ttype) + 1):
try:
attrs = token_to_attrs[ttype[:-i]]
except KeyError:
pass
else:
break
# Now update with the given attributes.
for part in styledef.split():
if part == 'noinherit':
pass
elif part == 'bold':
attrs = attrs._replace(bold=True)
elif part == 'nobold':
attrs = attrs._replace(bold=False)
elif part == 'italic':
attrs = attrs._replace(italic=True)
elif part == 'noitalic':
attrs = attrs._replace(italic=False)
elif part == 'underline':
attrs = attrs._replace(underline=True)
elif part == 'nounderline':
attrs = attrs._replace(underline=False)
# prompt_toolkit extensions. Not in Pygments.
elif part == 'blink':
attrs = attrs._replace(blink=True)
elif part == 'noblink':
attrs = attrs._replace(blink=False)
elif part == 'reverse':
attrs = attrs._replace(reverse=True)
elif part == 'noreverse':
attrs = attrs._replace(reverse=False)
# Pygments properties that we ignore.
elif part in ('roman', 'sans', 'mono'):
pass
elif part.startswith('border:'):
pass
# Colors.
elif part.startswith('bg:'):
attrs = attrs._replace(bgcolor=_colorformat(part[3:]))
else:
attrs = attrs._replace(color=_colorformat(part))
token_to_attrs[ttype] = attrs
return _StyleFromDict(token_to_attrs) | [
"def",
"style_from_dict",
"(",
"style_dict",
",",
"include_defaults",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"style_dict",
",",
"Mapping",
")",
"if",
"include_defaults",
":",
"s2",
"=",
"{",
"}",
"s2",
".",
"update",
"(",
"DEFAULT_STYLE_EXTENSIONS... | Create a ``Style`` instance from a dictionary or other mapping.
The dictionary is equivalent to the ``Style.styles`` dictionary from
pygments, with a few additions: it supports 'reverse' and 'blink'.
Usage::
style_from_dict({
Token: '#ff0000 bold underline',
Token.Title: 'blink',
Token.SomethingElse: 'reverse',
})
:param include_defaults: Include the defaults (built-in) styling for
selected text, etc...) | [
"Create",
"a",
"Style",
"instance",
"from",
"a",
"dictionary",
"or",
"other",
"mapping",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/styles/from_dict.py#L42-L128 | train | 207,442 |
wandb/client | wandb/file_pusher.py | FilePusher.rename_file | def rename_file(self, old_save_name, new_save_name, new_path):
"""This only updates the name and path we use to track the file's size
and upload progress. Doesn't rename it on the back end or make us
upload from anywhere else.
"""
if old_save_name in self._files:
del self._files[old_save_name]
self.update_file(new_save_name, new_path) | python | def rename_file(self, old_save_name, new_save_name, new_path):
"""This only updates the name and path we use to track the file's size
and upload progress. Doesn't rename it on the back end or make us
upload from anywhere else.
"""
if old_save_name in self._files:
del self._files[old_save_name]
self.update_file(new_save_name, new_path) | [
"def",
"rename_file",
"(",
"self",
",",
"old_save_name",
",",
"new_save_name",
",",
"new_path",
")",
":",
"if",
"old_save_name",
"in",
"self",
".",
"_files",
":",
"del",
"self",
".",
"_files",
"[",
"old_save_name",
"]",
"self",
".",
"update_file",
"(",
"ne... | This only updates the name and path we use to track the file's size
and upload progress. Doesn't rename it on the back end or make us
upload from anywhere else. | [
"This",
"only",
"updates",
"the",
"name",
"and",
"path",
"we",
"use",
"to",
"track",
"the",
"file",
"s",
"size",
"and",
"upload",
"progress",
".",
"Doesn",
"t",
"rename",
"it",
"on",
"the",
"back",
"end",
"or",
"make",
"us",
"upload",
"from",
"anywhere... | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/file_pusher.py#L103-L110 | train | 207,443 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | register | def register(name):
"""
Store handler in the `_readline_commands` dictionary.
"""
assert isinstance(name, six.text_type)
def decorator(handler):
assert callable(handler)
_readline_commands[name] = handler
return handler
return decorator | python | def register(name):
"""
Store handler in the `_readline_commands` dictionary.
"""
assert isinstance(name, six.text_type)
def decorator(handler):
assert callable(handler)
_readline_commands[name] = handler
return handler
return decorator | [
"def",
"register",
"(",
"name",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"six",
".",
"text_type",
")",
"def",
"decorator",
"(",
"handler",
")",
":",
"assert",
"callable",
"(",
"handler",
")",
"_readline_commands",
"[",
"name",
"]",
"=",
"handl... | Store handler in the `_readline_commands` dictionary. | [
"Store",
"handler",
"in",
"the",
"_readline_commands",
"dictionary",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L26-L36 | train | 207,444 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | beginning_of_line | def beginning_of_line(event):
" Move to the start of the current line. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_start_of_line_position(after_whitespace=False) | python | def beginning_of_line(event):
" Move to the start of the current line. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_start_of_line_position(after_whitespace=False) | [
"def",
"beginning_of_line",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"buff",
".",
"cursor_position",
"+=",
"buff",
".",
"document",
".",
"get_start_of_line_position",
"(",
"after_whitespace",
"=",
"False",
")"
] | Move to the start of the current line. | [
"Move",
"to",
"the",
"start",
"of",
"the",
"current",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L54-L57 | train | 207,445 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | end_of_line | def end_of_line(event):
" Move to the end of the line. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_end_of_line_position() | python | def end_of_line(event):
" Move to the end of the line. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_end_of_line_position() | [
"def",
"end_of_line",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"buff",
".",
"cursor_position",
"+=",
"buff",
".",
"document",
".",
"get_end_of_line_position",
"(",
")"
] | Move to the end of the line. | [
"Move",
"to",
"the",
"end",
"of",
"the",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L61-L64 | train | 207,446 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | forward_char | def forward_char(event):
" Move forward a character. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_cursor_right_position(count=event.arg) | python | def forward_char(event):
" Move forward a character. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_cursor_right_position(count=event.arg) | [
"def",
"forward_char",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"buff",
".",
"cursor_position",
"+=",
"buff",
".",
"document",
".",
"get_cursor_right_position",
"(",
"count",
"=",
"event",
".",
"arg",
")"
] | Move forward a character. | [
"Move",
"forward",
"a",
"character",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L68-L71 | train | 207,447 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | backward_char | def backward_char(event):
" Move back a character. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_cursor_left_position(count=event.arg) | python | def backward_char(event):
" Move back a character. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_cursor_left_position(count=event.arg) | [
"def",
"backward_char",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"buff",
".",
"cursor_position",
"+=",
"buff",
".",
"document",
".",
"get_cursor_left_position",
"(",
"count",
"=",
"event",
".",
"arg",
")"
] | Move back a character. | [
"Move",
"back",
"a",
"character",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L75-L78 | train | 207,448 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | forward_word | def forward_word(event):
"""
Move forward to the end of the next word. Words are composed of letters and
digits.
"""
buff = event.current_buffer
pos = buff.document.find_next_word_ending(count=event.arg)
if pos:
buff.cursor_position += pos | python | def forward_word(event):
"""
Move forward to the end of the next word. Words are composed of letters and
digits.
"""
buff = event.current_buffer
pos = buff.document.find_next_word_ending(count=event.arg)
if pos:
buff.cursor_position += pos | [
"def",
"forward_word",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"pos",
"=",
"buff",
".",
"document",
".",
"find_next_word_ending",
"(",
"count",
"=",
"event",
".",
"arg",
")",
"if",
"pos",
":",
"buff",
".",
"cursor_position",
... | Move forward to the end of the next word. Words are composed of letters and
digits. | [
"Move",
"forward",
"to",
"the",
"end",
"of",
"the",
"next",
"word",
".",
"Words",
"are",
"composed",
"of",
"letters",
"and",
"digits",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L82-L91 | train | 207,449 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | backward_word | def backward_word(event):
"""
Move back to the start of the current or previous word. Words are composed
of letters and digits.
"""
buff = event.current_buffer
pos = buff.document.find_previous_word_beginning(count=event.arg)
if pos:
buff.cursor_position += pos | python | def backward_word(event):
"""
Move back to the start of the current or previous word. Words are composed
of letters and digits.
"""
buff = event.current_buffer
pos = buff.document.find_previous_word_beginning(count=event.arg)
if pos:
buff.cursor_position += pos | [
"def",
"backward_word",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"pos",
"=",
"buff",
".",
"document",
".",
"find_previous_word_beginning",
"(",
"count",
"=",
"event",
".",
"arg",
")",
"if",
"pos",
":",
"buff",
".",
"cursor_posit... | Move back to the start of the current or previous word. Words are composed
of letters and digits. | [
"Move",
"back",
"to",
"the",
"start",
"of",
"the",
"current",
"or",
"previous",
"word",
".",
"Words",
"are",
"composed",
"of",
"letters",
"and",
"digits",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L95-L104 | train | 207,450 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | accept_line | def accept_line(event):
" Accept the line regardless of where the cursor is. "
b = event.current_buffer
b.accept_action.validate_and_handle(event.cli, b) | python | def accept_line(event):
" Accept the line regardless of where the cursor is. "
b = event.current_buffer
b.accept_action.validate_and_handle(event.cli, b) | [
"def",
"accept_line",
"(",
"event",
")",
":",
"b",
"=",
"event",
".",
"current_buffer",
"b",
".",
"accept_action",
".",
"validate_and_handle",
"(",
"event",
".",
"cli",
",",
"b",
")"
] | Accept the line regardless of where the cursor is. | [
"Accept",
"the",
"line",
"regardless",
"of",
"where",
"the",
"cursor",
"is",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L129-L132 | train | 207,451 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | end_of_history | def end_of_history(event):
"""
Move to the end of the input history, i.e., the line currently being entered.
"""
event.current_buffer.history_forward(count=10**100)
buff = event.current_buffer
buff.go_to_history(len(buff._working_lines) - 1) | python | def end_of_history(event):
"""
Move to the end of the input history, i.e., the line currently being entered.
"""
event.current_buffer.history_forward(count=10**100)
buff = event.current_buffer
buff.go_to_history(len(buff._working_lines) - 1) | [
"def",
"end_of_history",
"(",
"event",
")",
":",
"event",
".",
"current_buffer",
".",
"history_forward",
"(",
"count",
"=",
"10",
"**",
"100",
")",
"buff",
"=",
"event",
".",
"current_buffer",
"buff",
".",
"go_to_history",
"(",
"len",
"(",
"buff",
".",
"... | Move to the end of the input history, i.e., the line currently being entered. | [
"Move",
"to",
"the",
"end",
"of",
"the",
"input",
"history",
"i",
".",
"e",
".",
"the",
"line",
"currently",
"being",
"entered",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L154-L160 | train | 207,452 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | reverse_search_history | def reverse_search_history(event):
"""
Search backward starting at the current line and moving `up` through
the history as necessary. This is an incremental search.
"""
event.cli.current_search_state.direction = IncrementalSearchDirection.BACKWARD
event.cli.push_focus(SEARCH_BUFFER) | python | def reverse_search_history(event):
"""
Search backward starting at the current line and moving `up` through
the history as necessary. This is an incremental search.
"""
event.cli.current_search_state.direction = IncrementalSearchDirection.BACKWARD
event.cli.push_focus(SEARCH_BUFFER) | [
"def",
"reverse_search_history",
"(",
"event",
")",
":",
"event",
".",
"cli",
".",
"current_search_state",
".",
"direction",
"=",
"IncrementalSearchDirection",
".",
"BACKWARD",
"event",
".",
"cli",
".",
"push_focus",
"(",
"SEARCH_BUFFER",
")"
] | Search backward starting at the current line and moving `up` through
the history as necessary. This is an incremental search. | [
"Search",
"backward",
"starting",
"at",
"the",
"current",
"line",
"and",
"moving",
"up",
"through",
"the",
"history",
"as",
"necessary",
".",
"This",
"is",
"an",
"incremental",
"search",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L164-L170 | train | 207,453 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | delete_char | def delete_char(event):
" Delete character before the cursor. "
deleted = event.current_buffer.delete(count=event.arg)
if not deleted:
event.cli.output.bell() | python | def delete_char(event):
" Delete character before the cursor. "
deleted = event.current_buffer.delete(count=event.arg)
if not deleted:
event.cli.output.bell() | [
"def",
"delete_char",
"(",
"event",
")",
":",
"deleted",
"=",
"event",
".",
"current_buffer",
".",
"delete",
"(",
"count",
"=",
"event",
".",
"arg",
")",
"if",
"not",
"deleted",
":",
"event",
".",
"cli",
".",
"output",
".",
"bell",
"(",
")"
] | Delete character before the cursor. | [
"Delete",
"character",
"before",
"the",
"cursor",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L186-L190 | train | 207,454 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | backward_delete_char | def backward_delete_char(event):
" Delete the character behind the cursor. "
if event.arg < 0:
# When a negative argument has been given, this should delete in front
# of the cursor.
deleted = event.current_buffer.delete(count=-event.arg)
else:
deleted = event.current_buffer.delete_before_cursor(count=event.arg)
if not deleted:
event.cli.output.bell() | python | def backward_delete_char(event):
" Delete the character behind the cursor. "
if event.arg < 0:
# When a negative argument has been given, this should delete in front
# of the cursor.
deleted = event.current_buffer.delete(count=-event.arg)
else:
deleted = event.current_buffer.delete_before_cursor(count=event.arg)
if not deleted:
event.cli.output.bell() | [
"def",
"backward_delete_char",
"(",
"event",
")",
":",
"if",
"event",
".",
"arg",
"<",
"0",
":",
"# When a negative argument has been given, this should delete in front",
"# of the cursor.",
"deleted",
"=",
"event",
".",
"current_buffer",
".",
"delete",
"(",
"count",
... | Delete the character behind the cursor. | [
"Delete",
"the",
"character",
"behind",
"the",
"cursor",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L194-L204 | train | 207,455 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | kill_line | def kill_line(event):
"""
Kill the text from the cursor to the end of the line.
If we are at the end of the line, this should remove the newline.
(That way, it is possible to delete multiple lines by executing this
command multiple times.)
"""
buff = event.current_buffer
if event.arg < 0:
deleted = buff.delete_before_cursor(count=-buff.document.get_start_of_line_position())
else:
if buff.document.current_char == '\n':
deleted = buff.delete(1)
else:
deleted = buff.delete(count=buff.document.get_end_of_line_position())
event.cli.clipboard.set_text(deleted) | python | def kill_line(event):
"""
Kill the text from the cursor to the end of the line.
If we are at the end of the line, this should remove the newline.
(That way, it is possible to delete multiple lines by executing this
command multiple times.)
"""
buff = event.current_buffer
if event.arg < 0:
deleted = buff.delete_before_cursor(count=-buff.document.get_start_of_line_position())
else:
if buff.document.current_char == '\n':
deleted = buff.delete(1)
else:
deleted = buff.delete(count=buff.document.get_end_of_line_position())
event.cli.clipboard.set_text(deleted) | [
"def",
"kill_line",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"if",
"event",
".",
"arg",
"<",
"0",
":",
"deleted",
"=",
"buff",
".",
"delete_before_cursor",
"(",
"count",
"=",
"-",
"buff",
".",
"document",
".",
"get_start_of_li... | Kill the text from the cursor to the end of the line.
If we are at the end of the line, this should remove the newline.
(That way, it is possible to delete multiple lines by executing this
command multiple times.) | [
"Kill",
"the",
"text",
"from",
"the",
"cursor",
"to",
"the",
"end",
"of",
"the",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L285-L301 | train | 207,456 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | kill_word | def kill_word(event):
"""
Kill from point to the end of the current word, or if between words, to the
end of the next word. Word boundaries are the same as forward-word.
"""
buff = event.current_buffer
pos = buff.document.find_next_word_ending(count=event.arg)
if pos:
deleted = buff.delete(count=pos)
event.cli.clipboard.set_text(deleted) | python | def kill_word(event):
"""
Kill from point to the end of the current word, or if between words, to the
end of the next word. Word boundaries are the same as forward-word.
"""
buff = event.current_buffer
pos = buff.document.find_next_word_ending(count=event.arg)
if pos:
deleted = buff.delete(count=pos)
event.cli.clipboard.set_text(deleted) | [
"def",
"kill_word",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"pos",
"=",
"buff",
".",
"document",
".",
"find_next_word_ending",
"(",
"count",
"=",
"event",
".",
"arg",
")",
"if",
"pos",
":",
"deleted",
"=",
"buff",
".",
"del... | Kill from point to the end of the current word, or if between words, to the
end of the next word. Word boundaries are the same as forward-word. | [
"Kill",
"from",
"point",
"to",
"the",
"end",
"of",
"the",
"current",
"word",
"or",
"if",
"between",
"words",
"to",
"the",
"end",
"of",
"the",
"next",
"word",
".",
"Word",
"boundaries",
"are",
"the",
"same",
"as",
"forward",
"-",
"word",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L305-L315 | train | 207,457 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | unix_word_rubout | def unix_word_rubout(event, WORD=True):
"""
Kill the word behind point, using whitespace as a word boundary.
Usually bound to ControlW.
"""
buff = event.current_buffer
pos = buff.document.find_start_of_previous_word(count=event.arg, WORD=WORD)
if pos is None:
# Nothing found? delete until the start of the document. (The
# input starts with whitespace and no words were found before the
# cursor.)
pos = - buff.cursor_position
if pos:
deleted = buff.delete_before_cursor(count=-pos)
# If the previous key press was also Control-W, concatenate deleted
# text.
if event.is_repeat:
deleted += event.cli.clipboard.get_data().text
event.cli.clipboard.set_text(deleted)
else:
# Nothing to delete. Bell.
event.cli.output.bell() | python | def unix_word_rubout(event, WORD=True):
"""
Kill the word behind point, using whitespace as a word boundary.
Usually bound to ControlW.
"""
buff = event.current_buffer
pos = buff.document.find_start_of_previous_word(count=event.arg, WORD=WORD)
if pos is None:
# Nothing found? delete until the start of the document. (The
# input starts with whitespace and no words were found before the
# cursor.)
pos = - buff.cursor_position
if pos:
deleted = buff.delete_before_cursor(count=-pos)
# If the previous key press was also Control-W, concatenate deleted
# text.
if event.is_repeat:
deleted += event.cli.clipboard.get_data().text
event.cli.clipboard.set_text(deleted)
else:
# Nothing to delete. Bell.
event.cli.output.bell() | [
"def",
"unix_word_rubout",
"(",
"event",
",",
"WORD",
"=",
"True",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"pos",
"=",
"buff",
".",
"document",
".",
"find_start_of_previous_word",
"(",
"count",
"=",
"event",
".",
"arg",
",",
"WORD",
"=",
"... | Kill the word behind point, using whitespace as a word boundary.
Usually bound to ControlW. | [
"Kill",
"the",
"word",
"behind",
"point",
"using",
"whitespace",
"as",
"a",
"word",
"boundary",
".",
"Usually",
"bound",
"to",
"ControlW",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L319-L344 | train | 207,458 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | delete_horizontal_space | def delete_horizontal_space(event):
" Delete all spaces and tabs around point. "
buff = event.current_buffer
text_before_cursor = buff.document.text_before_cursor
text_after_cursor = buff.document.text_after_cursor
delete_before = len(text_before_cursor) - len(text_before_cursor.rstrip('\t '))
delete_after = len(text_after_cursor) - len(text_after_cursor.lstrip('\t '))
buff.delete_before_cursor(count=delete_before)
buff.delete(count=delete_after) | python | def delete_horizontal_space(event):
" Delete all spaces and tabs around point. "
buff = event.current_buffer
text_before_cursor = buff.document.text_before_cursor
text_after_cursor = buff.document.text_after_cursor
delete_before = len(text_before_cursor) - len(text_before_cursor.rstrip('\t '))
delete_after = len(text_after_cursor) - len(text_after_cursor.lstrip('\t '))
buff.delete_before_cursor(count=delete_before)
buff.delete(count=delete_after) | [
"def",
"delete_horizontal_space",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"text_before_cursor",
"=",
"buff",
".",
"document",
".",
"text_before_cursor",
"text_after_cursor",
"=",
"buff",
".",
"document",
".",
"text_after_cursor",
"delete... | Delete all spaces and tabs around point. | [
"Delete",
"all",
"spaces",
"and",
"tabs",
"around",
"point",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L357-L367 | train | 207,459 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | unix_line_discard | def unix_line_discard(event):
"""
Kill backward from the cursor to the beginning of the current line.
"""
buff = event.current_buffer
if buff.document.cursor_position_col == 0 and buff.document.cursor_position > 0:
buff.delete_before_cursor(count=1)
else:
deleted = buff.delete_before_cursor(count=-buff.document.get_start_of_line_position())
event.cli.clipboard.set_text(deleted) | python | def unix_line_discard(event):
"""
Kill backward from the cursor to the beginning of the current line.
"""
buff = event.current_buffer
if buff.document.cursor_position_col == 0 and buff.document.cursor_position > 0:
buff.delete_before_cursor(count=1)
else:
deleted = buff.delete_before_cursor(count=-buff.document.get_start_of_line_position())
event.cli.clipboard.set_text(deleted) | [
"def",
"unix_line_discard",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"if",
"buff",
".",
"document",
".",
"cursor_position_col",
"==",
"0",
"and",
"buff",
".",
"document",
".",
"cursor_position",
">",
"0",
":",
"buff",
".",
"dele... | Kill backward from the cursor to the beginning of the current line. | [
"Kill",
"backward",
"from",
"the",
"cursor",
"to",
"the",
"beginning",
"of",
"the",
"current",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L371-L381 | train | 207,460 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | yank | def yank(event):
"""
Paste before cursor.
"""
event.current_buffer.paste_clipboard_data(
event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS) | python | def yank(event):
"""
Paste before cursor.
"""
event.current_buffer.paste_clipboard_data(
event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS) | [
"def",
"yank",
"(",
"event",
")",
":",
"event",
".",
"current_buffer",
".",
"paste_clipboard_data",
"(",
"event",
".",
"cli",
".",
"clipboard",
".",
"get_data",
"(",
")",
",",
"count",
"=",
"event",
".",
"arg",
",",
"paste_mode",
"=",
"PasteMode",
".",
... | Paste before cursor. | [
"Paste",
"before",
"cursor",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L385-L390 | train | 207,461 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | yank_last_arg | def yank_last_arg(event):
"""
Like `yank_nth_arg`, but if no argument has been given, yank the last word
of each line.
"""
n = (event.arg if event.arg_present else None)
event.current_buffer.yank_last_arg(n) | python | def yank_last_arg(event):
"""
Like `yank_nth_arg`, but if no argument has been given, yank the last word
of each line.
"""
n = (event.arg if event.arg_present else None)
event.current_buffer.yank_last_arg(n) | [
"def",
"yank_last_arg",
"(",
"event",
")",
":",
"n",
"=",
"(",
"event",
".",
"arg",
"if",
"event",
".",
"arg_present",
"else",
"None",
")",
"event",
".",
"current_buffer",
".",
"yank_last_arg",
"(",
"n",
")"
] | Like `yank_nth_arg`, but if no argument has been given, yank the last word
of each line. | [
"Like",
"yank_nth_arg",
"but",
"if",
"no",
"argument",
"has",
"been",
"given",
"yank",
"the",
"last",
"word",
"of",
"each",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L403-L409 | train | 207,462 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | yank_pop | def yank_pop(event):
"""
Rotate the kill ring, and yank the new top. Only works following yank or
yank-pop.
"""
buff = event.current_buffer
doc_before_paste = buff.document_before_paste
clipboard = event.cli.clipboard
if doc_before_paste is not None:
buff.document = doc_before_paste
clipboard.rotate()
buff.paste_clipboard_data(
clipboard.get_data(), paste_mode=PasteMode.EMACS) | python | def yank_pop(event):
"""
Rotate the kill ring, and yank the new top. Only works following yank or
yank-pop.
"""
buff = event.current_buffer
doc_before_paste = buff.document_before_paste
clipboard = event.cli.clipboard
if doc_before_paste is not None:
buff.document = doc_before_paste
clipboard.rotate()
buff.paste_clipboard_data(
clipboard.get_data(), paste_mode=PasteMode.EMACS) | [
"def",
"yank_pop",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"doc_before_paste",
"=",
"buff",
".",
"document_before_paste",
"clipboard",
"=",
"event",
".",
"cli",
".",
"clipboard",
"if",
"doc_before_paste",
"is",
"not",
"None",
":",
... | Rotate the kill ring, and yank the new top. Only works following yank or
yank-pop. | [
"Rotate",
"the",
"kill",
"ring",
"and",
"yank",
"the",
"new",
"top",
".",
"Only",
"works",
"following",
"yank",
"or",
"yank",
"-",
"pop",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L412-L425 | train | 207,463 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | print_last_kbd_macro | def print_last_kbd_macro(event):
" Print the last keboard macro. "
# TODO: Make the format suitable for the inputrc file.
def print_macro():
for k in event.cli.input_processor.macro:
print(k)
event.cli.run_in_terminal(print_macro) | python | def print_last_kbd_macro(event):
" Print the last keboard macro. "
# TODO: Make the format suitable for the inputrc file.
def print_macro():
for k in event.cli.input_processor.macro:
print(k)
event.cli.run_in_terminal(print_macro) | [
"def",
"print_last_kbd_macro",
"(",
"event",
")",
":",
"# TODO: Make the format suitable for the inputrc file.",
"def",
"print_macro",
"(",
")",
":",
"for",
"k",
"in",
"event",
".",
"cli",
".",
"input_processor",
".",
"macro",
":",
"print",
"(",
"k",
")",
"event... | Print the last keboard macro. | [
"Print",
"the",
"last",
"keboard",
"macro",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L482-L488 | train | 207,464 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | insert_comment | def insert_comment(event):
"""
Without numeric argument, comment all lines.
With numeric argument, uncomment all lines.
In any case accept the input.
"""
buff = event.current_buffer
# Transform all lines.
if event.arg != 1:
def change(line):
return line[1:] if line.startswith('#') else line
else:
def change(line):
return '#' + line
buff.document = Document(
text='\n'.join(map(change, buff.text.splitlines())),
cursor_position=0)
# Accept input.
buff.accept_action.validate_and_handle(event.cli, buff) | python | def insert_comment(event):
"""
Without numeric argument, comment all lines.
With numeric argument, uncomment all lines.
In any case accept the input.
"""
buff = event.current_buffer
# Transform all lines.
if event.arg != 1:
def change(line):
return line[1:] if line.startswith('#') else line
else:
def change(line):
return '#' + line
buff.document = Document(
text='\n'.join(map(change, buff.text.splitlines())),
cursor_position=0)
# Accept input.
buff.accept_action.validate_and_handle(event.cli, buff) | [
"def",
"insert_comment",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"# Transform all lines.",
"if",
"event",
".",
"arg",
"!=",
"1",
":",
"def",
"change",
"(",
"line",
")",
":",
"return",
"line",
"[",
"1",
":",
"]",
"if",
"line... | Without numeric argument, comment all lines.
With numeric argument, uncomment all lines.
In any case accept the input. | [
"Without",
"numeric",
"argument",
"comment",
"all",
"lines",
".",
"With",
"numeric",
"argument",
"uncomment",
"all",
"lines",
".",
"In",
"any",
"case",
"accept",
"the",
"input",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L501-L522 | train | 207,465 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | operate_and_get_next | def operate_and_get_next(event):
"""
Accept the current line for execution and fetch the next line relative to
the current line from the history for editing.
"""
buff = event.current_buffer
new_index = buff.working_index + 1
# Accept the current input. (This will also redraw the interface in the
# 'done' state.)
buff.accept_action.validate_and_handle(event.cli, buff)
# Set the new index at the start of the next run.
def set_working_index():
if new_index < len(buff._working_lines):
buff.working_index = new_index
event.cli.pre_run_callables.append(set_working_index) | python | def operate_and_get_next(event):
"""
Accept the current line for execution and fetch the next line relative to
the current line from the history for editing.
"""
buff = event.current_buffer
new_index = buff.working_index + 1
# Accept the current input. (This will also redraw the interface in the
# 'done' state.)
buff.accept_action.validate_and_handle(event.cli, buff)
# Set the new index at the start of the next run.
def set_working_index():
if new_index < len(buff._working_lines):
buff.working_index = new_index
event.cli.pre_run_callables.append(set_working_index) | [
"def",
"operate_and_get_next",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"new_index",
"=",
"buff",
".",
"working_index",
"+",
"1",
"# Accept the current input. (This will also redraw the interface in the",
"# 'done' state.)",
"buff",
".",
"accep... | Accept the current line for execution and fetch the next line relative to
the current line from the history for editing. | [
"Accept",
"the",
"current",
"line",
"for",
"execution",
"and",
"fetch",
"the",
"next",
"line",
"relative",
"to",
"the",
"current",
"line",
"from",
"the",
"history",
"for",
"editing",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L550-L567 | train | 207,466 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py | edit_and_execute | def edit_and_execute(event):
"""
Invoke an editor on the current command line, and accept the result.
"""
buff = event.current_buffer
buff.open_in_editor(event.cli)
buff.accept_action.validate_and_handle(event.cli, buff) | python | def edit_and_execute(event):
"""
Invoke an editor on the current command line, and accept the result.
"""
buff = event.current_buffer
buff.open_in_editor(event.cli)
buff.accept_action.validate_and_handle(event.cli, buff) | [
"def",
"edit_and_execute",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"buff",
".",
"open_in_editor",
"(",
"event",
".",
"cli",
")",
"buff",
".",
"accept_action",
".",
"validate_and_handle",
"(",
"event",
".",
"cli",
",",
"buff",
"... | Invoke an editor on the current command line, and accept the result. | [
"Invoke",
"an",
"editor",
"on",
"the",
"current",
"command",
"line",
"and",
"accept",
"the",
"result",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L571-L578 | train | 207,467 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/basic.py | load_auto_suggestion_bindings | def load_auto_suggestion_bindings():
"""
Key bindings for accepting auto suggestion text.
"""
registry = Registry()
handle = registry.add_binding
suggestion_available = Condition(
lambda cli:
cli.current_buffer.suggestion is not None and
cli.current_buffer.document.is_cursor_at_the_end)
@handle(Keys.ControlF, filter=suggestion_available)
@handle(Keys.ControlE, filter=suggestion_available)
@handle(Keys.Right, filter=suggestion_available)
def _(event):
" Accept suggestion. "
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
return registry | python | def load_auto_suggestion_bindings():
"""
Key bindings for accepting auto suggestion text.
"""
registry = Registry()
handle = registry.add_binding
suggestion_available = Condition(
lambda cli:
cli.current_buffer.suggestion is not None and
cli.current_buffer.document.is_cursor_at_the_end)
@handle(Keys.ControlF, filter=suggestion_available)
@handle(Keys.ControlE, filter=suggestion_available)
@handle(Keys.Right, filter=suggestion_available)
def _(event):
" Accept suggestion. "
b = event.current_buffer
suggestion = b.suggestion
if suggestion:
b.insert_text(suggestion.text)
return registry | [
"def",
"load_auto_suggestion_bindings",
"(",
")",
":",
"registry",
"=",
"Registry",
"(",
")",
"handle",
"=",
"registry",
".",
"add_binding",
"suggestion_available",
"=",
"Condition",
"(",
"lambda",
"cli",
":",
"cli",
".",
"current_buffer",
".",
"suggestion",
"is... | Key bindings for accepting auto suggestion text. | [
"Key",
"bindings",
"for",
"accepting",
"auto",
"suggestion",
"text",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/basic.py#L384-L407 | train | 207,468 |
wandb/client | wandb/typedtable.py | TypedTable.set_columns | def set_columns(self, types):
"""Set the column types
args:
types: iterable of (column_name, type) pairs.
"""
if self._types:
raise wandb.Error('TypedTable.set_columns called more than once.')
try:
for key, type_ in types:
if type_ not in TYPE_TO_TYPESTRING:
raise wandb.Error('TypedTable.set_columns received invalid type ({}) for key "{}".\n Valid types: {}'.format(
type_, key, '[%s]' % ', '.join(VALID_TYPE_NAMES)))
except TypeError:
raise wandb.Error(
'TypedTable.set_columns requires iterable of (column_name, type) pairs.')
self._types = dict(types)
self._output.add({
'typemap': {k: TYPE_TO_TYPESTRING[type_] for k, type_ in types},
'columns': [t[0] for t in types]}) | python | def set_columns(self, types):
"""Set the column types
args:
types: iterable of (column_name, type) pairs.
"""
if self._types:
raise wandb.Error('TypedTable.set_columns called more than once.')
try:
for key, type_ in types:
if type_ not in TYPE_TO_TYPESTRING:
raise wandb.Error('TypedTable.set_columns received invalid type ({}) for key "{}".\n Valid types: {}'.format(
type_, key, '[%s]' % ', '.join(VALID_TYPE_NAMES)))
except TypeError:
raise wandb.Error(
'TypedTable.set_columns requires iterable of (column_name, type) pairs.')
self._types = dict(types)
self._output.add({
'typemap': {k: TYPE_TO_TYPESTRING[type_] for k, type_ in types},
'columns': [t[0] for t in types]}) | [
"def",
"set_columns",
"(",
"self",
",",
"types",
")",
":",
"if",
"self",
".",
"_types",
":",
"raise",
"wandb",
".",
"Error",
"(",
"'TypedTable.set_columns called more than once.'",
")",
"try",
":",
"for",
"key",
",",
"type_",
"in",
"types",
":",
"if",
"typ... | Set the column types
args:
types: iterable of (column_name, type) pairs. | [
"Set",
"the",
"column",
"types"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/typedtable.py#L37-L56 | train | 207,469 |
wandb/client | wandb/vendor/prompt_toolkit/renderer.py | Renderer.rows_above_layout | def rows_above_layout(self):
"""
Return the number of rows visible in the terminal above the layout.
"""
if self._in_alternate_screen:
return 0
elif self._min_available_height > 0:
total_rows = self.output.get_size().rows
last_screen_height = self._last_screen.height if self._last_screen else 0
return total_rows - max(self._min_available_height, last_screen_height)
else:
raise HeightIsUnknownError('Rows above layout is unknown.') | python | def rows_above_layout(self):
"""
Return the number of rows visible in the terminal above the layout.
"""
if self._in_alternate_screen:
return 0
elif self._min_available_height > 0:
total_rows = self.output.get_size().rows
last_screen_height = self._last_screen.height if self._last_screen else 0
return total_rows - max(self._min_available_height, last_screen_height)
else:
raise HeightIsUnknownError('Rows above layout is unknown.') | [
"def",
"rows_above_layout",
"(",
"self",
")",
":",
"if",
"self",
".",
"_in_alternate_screen",
":",
"return",
"0",
"elif",
"self",
".",
"_min_available_height",
">",
"0",
":",
"total_rows",
"=",
"self",
".",
"output",
".",
"get_size",
"(",
")",
".",
"rows",... | Return the number of rows visible in the terminal above the layout. | [
"Return",
"the",
"number",
"of",
"rows",
"visible",
"in",
"the",
"terminal",
"above",
"the",
"layout",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/renderer.py#L324-L335 | train | 207,470 |
wandb/client | wandb/vendor/prompt_toolkit/renderer.py | Renderer.render | def render(self, cli, layout, is_done=False):
"""
Render the current interface to the output.
:param is_done: When True, put the cursor at the end of the interface. We
won't print any changes to this part.
"""
output = self.output
# Enter alternate screen.
if self.use_alternate_screen and not self._in_alternate_screen:
self._in_alternate_screen = True
output.enter_alternate_screen()
# Enable bracketed paste.
if not self._bracketed_paste_enabled:
self.output.enable_bracketed_paste()
self._bracketed_paste_enabled = True
# Enable/disable mouse support.
needs_mouse_support = self.mouse_support(cli)
if needs_mouse_support and not self._mouse_support_enabled:
output.enable_mouse_support()
self._mouse_support_enabled = True
elif not needs_mouse_support and self._mouse_support_enabled:
output.disable_mouse_support()
self._mouse_support_enabled = False
# Create screen and write layout to it.
size = output.get_size()
screen = Screen()
screen.show_cursor = False # Hide cursor by default, unless one of the
# containers decides to display it.
mouse_handlers = MouseHandlers()
if is_done:
height = 0 # When we are done, we don't necessary want to fill up until the bottom.
else:
height = self._last_screen.height if self._last_screen else 0
height = max(self._min_available_height, height)
# When te size changes, don't consider the previous screen.
if self._last_size != size:
self._last_screen = None
# When we render using another style, do a full repaint. (Forget about
# the previous rendered screen.)
# (But note that we still use _last_screen to calculate the height.)
if self.style.invalidation_hash() != self._last_style_hash:
self._last_screen = None
self._attrs_for_token = None
if self._attrs_for_token is None:
self._attrs_for_token = _TokenToAttrsCache(self.style.get_attrs_for_token)
self._last_style_hash = self.style.invalidation_hash()
layout.write_to_screen(cli, screen, mouse_handlers, WritePosition(
xpos=0,
ypos=0,
width=size.columns,
height=(size.rows if self.use_alternate_screen else height),
extended_height=size.rows,
))
# When grayed. Replace all tokens in the new screen.
if cli.is_aborting or cli.is_exiting:
screen.replace_all_tokens(Token.Aborted)
# Process diff and write to output.
self._cursor_pos, self._last_token = _output_screen_diff(
output, screen, self._cursor_pos,
self._last_screen, self._last_token, is_done,
use_alternate_screen=self.use_alternate_screen,
attrs_for_token=self._attrs_for_token,
size=size,
previous_width=(self._last_size.columns if self._last_size else 0))
self._last_screen = screen
self._last_size = size
self.mouse_handlers = mouse_handlers
# Write title if it changed.
new_title = cli.terminal_title
if new_title != self._last_title:
if new_title is None:
self.output.clear_title()
else:
self.output.set_title(new_title)
self._last_title = new_title
output.flush() | python | def render(self, cli, layout, is_done=False):
"""
Render the current interface to the output.
:param is_done: When True, put the cursor at the end of the interface. We
won't print any changes to this part.
"""
output = self.output
# Enter alternate screen.
if self.use_alternate_screen and not self._in_alternate_screen:
self._in_alternate_screen = True
output.enter_alternate_screen()
# Enable bracketed paste.
if not self._bracketed_paste_enabled:
self.output.enable_bracketed_paste()
self._bracketed_paste_enabled = True
# Enable/disable mouse support.
needs_mouse_support = self.mouse_support(cli)
if needs_mouse_support and not self._mouse_support_enabled:
output.enable_mouse_support()
self._mouse_support_enabled = True
elif not needs_mouse_support and self._mouse_support_enabled:
output.disable_mouse_support()
self._mouse_support_enabled = False
# Create screen and write layout to it.
size = output.get_size()
screen = Screen()
screen.show_cursor = False # Hide cursor by default, unless one of the
# containers decides to display it.
mouse_handlers = MouseHandlers()
if is_done:
height = 0 # When we are done, we don't necessary want to fill up until the bottom.
else:
height = self._last_screen.height if self._last_screen else 0
height = max(self._min_available_height, height)
# When te size changes, don't consider the previous screen.
if self._last_size != size:
self._last_screen = None
# When we render using another style, do a full repaint. (Forget about
# the previous rendered screen.)
# (But note that we still use _last_screen to calculate the height.)
if self.style.invalidation_hash() != self._last_style_hash:
self._last_screen = None
self._attrs_for_token = None
if self._attrs_for_token is None:
self._attrs_for_token = _TokenToAttrsCache(self.style.get_attrs_for_token)
self._last_style_hash = self.style.invalidation_hash()
layout.write_to_screen(cli, screen, mouse_handlers, WritePosition(
xpos=0,
ypos=0,
width=size.columns,
height=(size.rows if self.use_alternate_screen else height),
extended_height=size.rows,
))
# When grayed. Replace all tokens in the new screen.
if cli.is_aborting or cli.is_exiting:
screen.replace_all_tokens(Token.Aborted)
# Process diff and write to output.
self._cursor_pos, self._last_token = _output_screen_diff(
output, screen, self._cursor_pos,
self._last_screen, self._last_token, is_done,
use_alternate_screen=self.use_alternate_screen,
attrs_for_token=self._attrs_for_token,
size=size,
previous_width=(self._last_size.columns if self._last_size else 0))
self._last_screen = screen
self._last_size = size
self.mouse_handlers = mouse_handlers
# Write title if it changed.
new_title = cli.terminal_title
if new_title != self._last_title:
if new_title is None:
self.output.clear_title()
else:
self.output.set_title(new_title)
self._last_title = new_title
output.flush() | [
"def",
"render",
"(",
"self",
",",
"cli",
",",
"layout",
",",
"is_done",
"=",
"False",
")",
":",
"output",
"=",
"self",
".",
"output",
"# Enter alternate screen.",
"if",
"self",
".",
"use_alternate_screen",
"and",
"not",
"self",
".",
"_in_alternate_screen",
... | Render the current interface to the output.
:param is_done: When True, put the cursor at the end of the interface. We
won't print any changes to this part. | [
"Render",
"the",
"current",
"interface",
"to",
"the",
"output",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/renderer.py#L374-L465 | train | 207,471 |
wandb/client | wandb/vendor/prompt_toolkit/renderer.py | Renderer.clear | def clear(self):
"""
Clear screen and go to 0,0
"""
# Erase current output first.
self.erase()
# Send "Erase Screen" command and go to (0, 0).
output = self.output
output.erase_screen()
output.cursor_goto(0, 0)
output.flush()
self.request_absolute_cursor_position() | python | def clear(self):
"""
Clear screen and go to 0,0
"""
# Erase current output first.
self.erase()
# Send "Erase Screen" command and go to (0, 0).
output = self.output
output.erase_screen()
output.cursor_goto(0, 0)
output.flush()
self.request_absolute_cursor_position() | [
"def",
"clear",
"(",
"self",
")",
":",
"# Erase current output first.",
"self",
".",
"erase",
"(",
")",
"# Send \"Erase Screen\" command and go to (0, 0).",
"output",
"=",
"self",
".",
"output",
"output",
".",
"erase_screen",
"(",
")",
"output",
".",
"cursor_goto",
... | Clear screen and go to 0,0 | [
"Clear",
"screen",
"and",
"go",
"to",
"0",
"0"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/renderer.py#L492-L506 | train | 207,472 |
wandb/client | wandb/vendor/prompt_toolkit/input.py | PipeInput.close | def close(self):
" Close pipe fds. "
os.close(self._r)
os.close(self._w)
self._r = None
self._w = None | python | def close(self):
" Close pipe fds. "
os.close(self._r)
os.close(self._w)
self._r = None
self._w = None | [
"def",
"close",
"(",
"self",
")",
":",
"os",
".",
"close",
"(",
"self",
".",
"_r",
")",
"os",
".",
"close",
"(",
"self",
".",
"_w",
")",
"self",
".",
"_r",
"=",
"None",
"self",
".",
"_w",
"=",
"None"
] | Close pipe fds. | [
"Close",
"pipe",
"fds",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/input.py#L130-L135 | train | 207,473 |
wandb/client | wandb/vendor/prompt_toolkit/layout/screen.py | Screen.replace_all_tokens | def replace_all_tokens(self, token):
"""
For all the characters in the screen. Set the token to the given `token`.
"""
b = self.data_buffer
for y, row in b.items():
for x, char in row.items():
b[y][x] = _CHAR_CACHE[char.char, token] | python | def replace_all_tokens(self, token):
"""
For all the characters in the screen. Set the token to the given `token`.
"""
b = self.data_buffer
for y, row in b.items():
for x, char in row.items():
b[y][x] = _CHAR_CACHE[char.char, token] | [
"def",
"replace_all_tokens",
"(",
"self",
",",
"token",
")",
":",
"b",
"=",
"self",
".",
"data_buffer",
"for",
"y",
",",
"row",
"in",
"b",
".",
"items",
"(",
")",
":",
"for",
"x",
",",
"char",
"in",
"row",
".",
"items",
"(",
")",
":",
"b",
"[",... | For all the characters in the screen. Set the token to the given `token`. | [
"For",
"all",
"the",
"characters",
"in",
"the",
"screen",
".",
"Set",
"the",
"token",
"to",
"the",
"given",
"token",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/screen.py#L124-L132 | train | 207,474 |
wandb/client | wandb/apis/file_stream.py | FileStreamApi._handle_response | def _handle_response(self, response):
"""Logs dropped chunks and updates dynamic settings"""
if isinstance(response, Exception):
logging.error("dropped chunk %s" % response)
elif response.json().get("limits"):
parsed = response.json()
self._api.dynamic_settings.update(parsed["limits"]) | python | def _handle_response(self, response):
"""Logs dropped chunks and updates dynamic settings"""
if isinstance(response, Exception):
logging.error("dropped chunk %s" % response)
elif response.json().get("limits"):
parsed = response.json()
self._api.dynamic_settings.update(parsed["limits"]) | [
"def",
"_handle_response",
"(",
"self",
",",
"response",
")",
":",
"if",
"isinstance",
"(",
"response",
",",
"Exception",
")",
":",
"logging",
".",
"error",
"(",
"\"dropped chunk %s\"",
"%",
"response",
")",
"elif",
"response",
".",
"json",
"(",
")",
".",
... | Logs dropped chunks and updates dynamic settings | [
"Logs",
"dropped",
"chunks",
"and",
"updates",
"dynamic",
"settings"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/apis/file_stream.py#L179-L185 | train | 207,475 |
wandb/client | wandb/apis/file_stream.py | FileStreamApi.push | def push(self, filename, data):
"""Push a chunk of a file to the streaming endpoint.
Args:
filename: Name of file that this is a chunk of.
chunk_id: TODO: change to 'offset'
chunk: File data.
"""
self._queue.put(Chunk(filename, data)) | python | def push(self, filename, data):
"""Push a chunk of a file to the streaming endpoint.
Args:
filename: Name of file that this is a chunk of.
chunk_id: TODO: change to 'offset'
chunk: File data.
"""
self._queue.put(Chunk(filename, data)) | [
"def",
"push",
"(",
"self",
",",
"filename",
",",
"data",
")",
":",
"self",
".",
"_queue",
".",
"put",
"(",
"Chunk",
"(",
"filename",
",",
"data",
")",
")"
] | Push a chunk of a file to the streaming endpoint.
Args:
filename: Name of file that this is a chunk of.
chunk_id: TODO: change to 'offset'
chunk: File data. | [
"Push",
"a",
"chunk",
"of",
"a",
"file",
"to",
"the",
"streaming",
"endpoint",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/apis/file_stream.py#L208-L216 | train | 207,476 |
wandb/client | wandb/apis/file_stream.py | FileStreamApi.finish | def finish(self, exitcode):
"""Cleans up.
Anything pushed after finish will be dropped.
Args:
exitcode: The exitcode of the watched process.
"""
self._queue.put(self.Finish(exitcode))
self._thread.join() | python | def finish(self, exitcode):
"""Cleans up.
Anything pushed after finish will be dropped.
Args:
exitcode: The exitcode of the watched process.
"""
self._queue.put(self.Finish(exitcode))
self._thread.join() | [
"def",
"finish",
"(",
"self",
",",
"exitcode",
")",
":",
"self",
".",
"_queue",
".",
"put",
"(",
"self",
".",
"Finish",
"(",
"exitcode",
")",
")",
"self",
".",
"_thread",
".",
"join",
"(",
")"
] | Cleans up.
Anything pushed after finish will be dropped.
Args:
exitcode: The exitcode of the watched process. | [
"Cleans",
"up",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/apis/file_stream.py#L218-L227 | train | 207,477 |
wandb/client | wandb/docker/__init__.py | shell | def shell(cmd):
"Simple wrapper for calling docker, returning None on error and the output on success"
try:
return subprocess.check_output(['docker'] + cmd, stderr=subprocess.STDOUT).decode('utf8').strip()
except subprocess.CalledProcessError:
return None | python | def shell(cmd):
"Simple wrapper for calling docker, returning None on error and the output on success"
try:
return subprocess.check_output(['docker'] + cmd, stderr=subprocess.STDOUT).decode('utf8').strip()
except subprocess.CalledProcessError:
return None | [
"def",
"shell",
"(",
"cmd",
")",
":",
"try",
":",
"return",
"subprocess",
".",
"check_output",
"(",
"[",
"'docker'",
"]",
"+",
"cmd",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
".",
"decode",
"(",
"'utf8'",
")",
".",
"strip",
"(",
")",
"... | Simple wrapper for calling docker, returning None on error and the output on success | [
"Simple",
"wrapper",
"for",
"calling",
"docker",
"returning",
"None",
"on",
"error",
"and",
"the",
"output",
"on",
"success"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/docker/__init__.py#L14-L19 | train | 207,478 |
wandb/client | wandb/docker/__init__.py | auth_token | def auth_token(registry, repo):
"""Makes a request to the root of a v2 docker registry to get the auth url.
Always returns a dictionary, if there's no token key we couldn't authenticate
"""
# TODO: Cache tokens?
auth_info = auth_config.resolve_authconfig(registry)
if auth_info:
normalized = {k.lower(): v for k, v in six.iteritems(auth_info)}
auth_info = (normalized.get("username"), normalized.get("password"))
response = requests.get("https://{}/v2/".format(registry), timeout=3)
if response.headers.get("www-authenticate"):
try:
info = www_authenticate.parse(response.headers['www-authenticate'])
except ValueError:
info = {}
else:
log.error("Received {} when attempting to authenticate with {}".format(
response, registry))
info = {}
if info.get("bearer"):
res = requests.get(info["bearer"]["realm"] +
"?service={}&scope=repository:{}:pull".format(
info["bearer"]["service"], repo), auth=auth_info, timeout=3)
res.raise_for_status()
return res.json()
return {} | python | def auth_token(registry, repo):
"""Makes a request to the root of a v2 docker registry to get the auth url.
Always returns a dictionary, if there's no token key we couldn't authenticate
"""
# TODO: Cache tokens?
auth_info = auth_config.resolve_authconfig(registry)
if auth_info:
normalized = {k.lower(): v for k, v in six.iteritems(auth_info)}
auth_info = (normalized.get("username"), normalized.get("password"))
response = requests.get("https://{}/v2/".format(registry), timeout=3)
if response.headers.get("www-authenticate"):
try:
info = www_authenticate.parse(response.headers['www-authenticate'])
except ValueError:
info = {}
else:
log.error("Received {} when attempting to authenticate with {}".format(
response, registry))
info = {}
if info.get("bearer"):
res = requests.get(info["bearer"]["realm"] +
"?service={}&scope=repository:{}:pull".format(
info["bearer"]["service"], repo), auth=auth_info, timeout=3)
res.raise_for_status()
return res.json()
return {} | [
"def",
"auth_token",
"(",
"registry",
",",
"repo",
")",
":",
"# TODO: Cache tokens?",
"auth_info",
"=",
"auth_config",
".",
"resolve_authconfig",
"(",
"registry",
")",
"if",
"auth_info",
":",
"normalized",
"=",
"{",
"k",
".",
"lower",
"(",
")",
":",
"v",
"... | Makes a request to the root of a v2 docker registry to get the auth url.
Always returns a dictionary, if there's no token key we couldn't authenticate | [
"Makes",
"a",
"request",
"to",
"the",
"root",
"of",
"a",
"v2",
"docker",
"registry",
"to",
"get",
"the",
"auth",
"url",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/docker/__init__.py#L47-L73 | train | 207,479 |
wandb/client | wandb/docker/__init__.py | image_id_from_registry | def image_id_from_registry(image_name):
"""Get the docker id from a public or private registry"""
registry, repository, tag = parse(image_name)
try:
token = auth_token(registry, repository).get("token")
# dockerhub is crazy
if registry == "index.docker.io":
registry = "registry-1.docker.io"
res = requests.head("https://{}/v2/{}/manifests/{}".format(registry, repository, tag), headers={
"Authorization": "Bearer {}".format(token),
"Accept": "application/vnd.docker.distribution.manifest.v2+json"
}, timeout=5)
res.raise_for_status()
except requests.RequestException:
log.error("Received {} when attempting to get digest for {}".format(
res, image_name))
return None
return "@".join([registry+"/"+repository, res.headers["Docker-Content-Digest"]]) | python | def image_id_from_registry(image_name):
"""Get the docker id from a public or private registry"""
registry, repository, tag = parse(image_name)
try:
token = auth_token(registry, repository).get("token")
# dockerhub is crazy
if registry == "index.docker.io":
registry = "registry-1.docker.io"
res = requests.head("https://{}/v2/{}/manifests/{}".format(registry, repository, tag), headers={
"Authorization": "Bearer {}".format(token),
"Accept": "application/vnd.docker.distribution.manifest.v2+json"
}, timeout=5)
res.raise_for_status()
except requests.RequestException:
log.error("Received {} when attempting to get digest for {}".format(
res, image_name))
return None
return "@".join([registry+"/"+repository, res.headers["Docker-Content-Digest"]]) | [
"def",
"image_id_from_registry",
"(",
"image_name",
")",
":",
"registry",
",",
"repository",
",",
"tag",
"=",
"parse",
"(",
"image_name",
")",
"try",
":",
"token",
"=",
"auth_token",
"(",
"registry",
",",
"repository",
")",
".",
"get",
"(",
"\"token\"",
")... | Get the docker id from a public or private registry | [
"Get",
"the",
"docker",
"id",
"from",
"a",
"public",
"or",
"private",
"registry"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/docker/__init__.py#L76-L93 | train | 207,480 |
wandb/client | wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py | _CompiledGrammar.escape | def escape(self, varname, value):
"""
Escape `value` to fit in the place of this variable into the grammar.
"""
f = self.escape_funcs.get(varname)
return f(value) if f else value | python | def escape(self, varname, value):
"""
Escape `value` to fit in the place of this variable into the grammar.
"""
f = self.escape_funcs.get(varname)
return f(value) if f else value | [
"def",
"escape",
"(",
"self",
",",
"varname",
",",
"value",
")",
":",
"f",
"=",
"self",
".",
"escape_funcs",
".",
"get",
"(",
"varname",
")",
"return",
"f",
"(",
"value",
")",
"if",
"f",
"else",
"value"
] | Escape `value` to fit in the place of this variable into the grammar. | [
"Escape",
"value",
"to",
"fit",
"in",
"the",
"place",
"of",
"this",
"variable",
"into",
"the",
"grammar",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py#L100-L105 | train | 207,481 |
wandb/client | wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py | _CompiledGrammar.unescape | def unescape(self, varname, value):
"""
Unescape `value`.
"""
f = self.unescape_funcs.get(varname)
return f(value) if f else value | python | def unescape(self, varname, value):
"""
Unescape `value`.
"""
f = self.unescape_funcs.get(varname)
return f(value) if f else value | [
"def",
"unescape",
"(",
"self",
",",
"varname",
",",
"value",
")",
":",
"f",
"=",
"self",
".",
"unescape_funcs",
".",
"get",
"(",
"varname",
")",
"return",
"f",
"(",
"value",
")",
"if",
"f",
"else",
"value"
] | Unescape `value`. | [
"Unescape",
"value",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py#L107-L112 | train | 207,482 |
wandb/client | wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py | _CompiledGrammar._transform_prefix | def _transform_prefix(cls, root_node, create_group_func):
"""
Yield all the regular expressions matching a prefix of the grammar
defined by the `Node` instance.
This can yield multiple expressions, because in the case of on OR
operation in the grammar, we can have another outcome depending on
which clause would appear first. E.g. "(A|B)C" is not the same as
"(B|A)C" because the regex engine is lazy and takes the first match.
However, because we the current input is actually a prefix of the
grammar which meight not yet contain the data for "C", we need to know
both intermediate states, in order to call the appropriate
autocompletion for both cases.
:param root_node: The :class:`Node` instance for which we generate the grammar.
:param create_group_func: A callable which takes a `Node` and returns the next
free name for this node.
"""
def transform(node):
# Generate regexes for all permutations of this OR. Each node
# should be in front once.
if isinstance(node, Any):
for c in node.children:
for r in transform(c):
yield '(?:%s)?' % r
# For a sequence. We can either have a match for the sequence
# of all the children, or for an exact match of the first X
# children, followed by a partial match of the next children.
elif isinstance(node, Sequence):
for i in range(len(node.children)):
a = [cls._transform(c, create_group_func) for c in node.children[:i]]
for c in transform(node.children[i]):
yield '(?:%s)' % (''.join(a) + c)
elif isinstance(node, Regex):
yield '(?:%s)?' % node.regex
elif isinstance(node, Lookahead):
if node.negative:
yield '(?!%s)' % cls._transform(node.childnode, create_group_func)
else:
# Not sure what the correct semantics are in this case.
# (Probably it's not worth implementing this.)
raise Exception('Positive lookahead not yet supported.')
elif isinstance(node, Variable):
# (Note that we should not append a '?' here. the 'transform'
# method will already recursively do that.)
for c in transform(node.childnode):
yield '(?P<%s>%s)' % (create_group_func(node), c)
elif isinstance(node, Repeat):
# If we have a repetition of 8 times. That would mean that the
# current input could have for instance 7 times a complete
# match, followed by a partial match.
prefix = cls._transform(node.childnode, create_group_func)
for c in transform(node.childnode):
if node.max_repeat:
repeat_sign = '{,%i}' % (node.max_repeat - 1)
else:
repeat_sign = '*'
yield '(?:%s)%s%s(?:%s)?' % (
prefix,
repeat_sign,
('' if node.greedy else '?'),
c)
else:
raise TypeError('Got %r' % node)
for r in transform(root_node):
yield '^%s$' % r | python | def _transform_prefix(cls, root_node, create_group_func):
"""
Yield all the regular expressions matching a prefix of the grammar
defined by the `Node` instance.
This can yield multiple expressions, because in the case of on OR
operation in the grammar, we can have another outcome depending on
which clause would appear first. E.g. "(A|B)C" is not the same as
"(B|A)C" because the regex engine is lazy and takes the first match.
However, because we the current input is actually a prefix of the
grammar which meight not yet contain the data for "C", we need to know
both intermediate states, in order to call the appropriate
autocompletion for both cases.
:param root_node: The :class:`Node` instance for which we generate the grammar.
:param create_group_func: A callable which takes a `Node` and returns the next
free name for this node.
"""
def transform(node):
# Generate regexes for all permutations of this OR. Each node
# should be in front once.
if isinstance(node, Any):
for c in node.children:
for r in transform(c):
yield '(?:%s)?' % r
# For a sequence. We can either have a match for the sequence
# of all the children, or for an exact match of the first X
# children, followed by a partial match of the next children.
elif isinstance(node, Sequence):
for i in range(len(node.children)):
a = [cls._transform(c, create_group_func) for c in node.children[:i]]
for c in transform(node.children[i]):
yield '(?:%s)' % (''.join(a) + c)
elif isinstance(node, Regex):
yield '(?:%s)?' % node.regex
elif isinstance(node, Lookahead):
if node.negative:
yield '(?!%s)' % cls._transform(node.childnode, create_group_func)
else:
# Not sure what the correct semantics are in this case.
# (Probably it's not worth implementing this.)
raise Exception('Positive lookahead not yet supported.')
elif isinstance(node, Variable):
# (Note that we should not append a '?' here. the 'transform'
# method will already recursively do that.)
for c in transform(node.childnode):
yield '(?P<%s>%s)' % (create_group_func(node), c)
elif isinstance(node, Repeat):
# If we have a repetition of 8 times. That would mean that the
# current input could have for instance 7 times a complete
# match, followed by a partial match.
prefix = cls._transform(node.childnode, create_group_func)
for c in transform(node.childnode):
if node.max_repeat:
repeat_sign = '{,%i}' % (node.max_repeat - 1)
else:
repeat_sign = '*'
yield '(?:%s)%s%s(?:%s)?' % (
prefix,
repeat_sign,
('' if node.greedy else '?'),
c)
else:
raise TypeError('Got %r' % node)
for r in transform(root_node):
yield '^%s$' % r | [
"def",
"_transform_prefix",
"(",
"cls",
",",
"root_node",
",",
"create_group_func",
")",
":",
"def",
"transform",
"(",
"node",
")",
":",
"# Generate regexes for all permutations of this OR. Each node",
"# should be in front once.",
"if",
"isinstance",
"(",
"node",
",",
... | Yield all the regular expressions matching a prefix of the grammar
defined by the `Node` instance.
This can yield multiple expressions, because in the case of on OR
operation in the grammar, we can have another outcome depending on
which clause would appear first. E.g. "(A|B)C" is not the same as
"(B|A)C" because the regex engine is lazy and takes the first match.
However, because we the current input is actually a prefix of the
grammar which meight not yet contain the data for "C", we need to know
both intermediate states, in order to call the appropriate
autocompletion for both cases.
:param root_node: The :class:`Node` instance for which we generate the grammar.
:param create_group_func: A callable which takes a `Node` and returns the next
free name for this node. | [
"Yield",
"all",
"the",
"regular",
"expressions",
"matching",
"a",
"prefix",
"of",
"the",
"grammar",
"defined",
"by",
"the",
"Node",
"instance",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py#L157-L230 | train | 207,483 |
wandb/client | wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py | Match.trailing_input | def trailing_input(self):
"""
Get the `MatchVariable` instance, representing trailing input, if there is any.
"Trailing input" is input at the end that does not match the grammar anymore, but
when this is removed from the end of the input, the input would be a valid string.
"""
slices = []
# Find all regex group for the name _INVALID_TRAILING_INPUT.
for r, re_match in self._re_matches:
for group_name, group_index in r.groupindex.items():
if group_name == _INVALID_TRAILING_INPUT:
slices.append(re_match.regs[group_index])
# Take the smallest part. (Smaller trailing text means that a larger input has
# been matched, so that is better.)
if slices:
slice = [max(i[0] for i in slices), max(i[1] for i in slices)]
value = self.string[slice[0]:slice[1]]
return MatchVariable('<trailing_input>', value, slice) | python | def trailing_input(self):
"""
Get the `MatchVariable` instance, representing trailing input, if there is any.
"Trailing input" is input at the end that does not match the grammar anymore, but
when this is removed from the end of the input, the input would be a valid string.
"""
slices = []
# Find all regex group for the name _INVALID_TRAILING_INPUT.
for r, re_match in self._re_matches:
for group_name, group_index in r.groupindex.items():
if group_name == _INVALID_TRAILING_INPUT:
slices.append(re_match.regs[group_index])
# Take the smallest part. (Smaller trailing text means that a larger input has
# been matched, so that is better.)
if slices:
slice = [max(i[0] for i in slices), max(i[1] for i in slices)]
value = self.string[slice[0]:slice[1]]
return MatchVariable('<trailing_input>', value, slice) | [
"def",
"trailing_input",
"(",
"self",
")",
":",
"slices",
"=",
"[",
"]",
"# Find all regex group for the name _INVALID_TRAILING_INPUT.",
"for",
"r",
",",
"re_match",
"in",
"self",
".",
"_re_matches",
":",
"for",
"group_name",
",",
"group_index",
"in",
"r",
".",
... | Get the `MatchVariable` instance, representing trailing input, if there is any.
"Trailing input" is input at the end that does not match the grammar anymore, but
when this is removed from the end of the input, the input would be a valid string. | [
"Get",
"the",
"MatchVariable",
"instance",
"representing",
"trailing",
"input",
"if",
"there",
"is",
"any",
".",
"Trailing",
"input",
"is",
"input",
"at",
"the",
"end",
"that",
"does",
"not",
"match",
"the",
"grammar",
"anymore",
"but",
"when",
"this",
"is",... | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py#L311-L330 | train | 207,484 |
wandb/client | wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py | Match.end_nodes | def end_nodes(self):
"""
Yields `MatchVariable` instances for all the nodes having their end
position at the end of the input string.
"""
for varname, reg in self._nodes_to_regs():
# If this part goes until the end of the input string.
if reg[1] == len(self.string):
value = self._unescape(varname, self.string[reg[0]: reg[1]])
yield MatchVariable(varname, value, (reg[0], reg[1])) | python | def end_nodes(self):
"""
Yields `MatchVariable` instances for all the nodes having their end
position at the end of the input string.
"""
for varname, reg in self._nodes_to_regs():
# If this part goes until the end of the input string.
if reg[1] == len(self.string):
value = self._unescape(varname, self.string[reg[0]: reg[1]])
yield MatchVariable(varname, value, (reg[0], reg[1])) | [
"def",
"end_nodes",
"(",
"self",
")",
":",
"for",
"varname",
",",
"reg",
"in",
"self",
".",
"_nodes_to_regs",
"(",
")",
":",
"# If this part goes until the end of the input string.",
"if",
"reg",
"[",
"1",
"]",
"==",
"len",
"(",
"self",
".",
"string",
")",
... | Yields `MatchVariable` instances for all the nodes having their end
position at the end of the input string. | [
"Yields",
"MatchVariable",
"instances",
"for",
"all",
"the",
"nodes",
"having",
"their",
"end",
"position",
"at",
"the",
"end",
"of",
"the",
"input",
"string",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/contrib/regular_languages/compiler.py#L332-L341 | train | 207,485 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/vi_state.py | ViState.reset | def reset(self, mode=InputMode.INSERT):
"""
Reset state, go back to the given mode. INSERT by default.
"""
# Go back to insert mode.
self.input_mode = mode
self.waiting_for_digraph = False
self.operator_func = None
self.operator_arg = None | python | def reset(self, mode=InputMode.INSERT):
"""
Reset state, go back to the given mode. INSERT by default.
"""
# Go back to insert mode.
self.input_mode = mode
self.waiting_for_digraph = False
self.operator_func = None
self.operator_arg = None | [
"def",
"reset",
"(",
"self",
",",
"mode",
"=",
"InputMode",
".",
"INSERT",
")",
":",
"# Go back to insert mode.",
"self",
".",
"input_mode",
"=",
"mode",
"self",
".",
"waiting_for_digraph",
"=",
"False",
"self",
".",
"operator_func",
"=",
"None",
"self",
"."... | Reset state, go back to the given mode. INSERT by default. | [
"Reset",
"state",
"go",
"back",
"to",
"the",
"given",
"mode",
".",
"INSERT",
"by",
"default",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/vi_state.py#L52-L61 | train | 207,486 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | CommandLineInterface.add_buffer | def add_buffer(self, name, buffer, focus=False):
"""
Insert a new buffer.
"""
assert isinstance(buffer, Buffer)
self.buffers[name] = buffer
if focus:
self.buffers.focus(name)
# Create asynchronous completer / auto suggestion.
auto_suggest_function = self._create_auto_suggest_function(buffer)
completer_function = self._create_async_completer(buffer)
self._async_completers[name] = completer_function
# Complete/suggest on text insert.
def create_on_insert_handler():
"""
Wrapper around the asynchronous completer and auto suggestion, that
ensures that it's only called while typing if the
`complete_while_typing` filter is enabled.
"""
def on_text_insert(_):
# Only complete when "complete_while_typing" is enabled.
if buffer.completer and buffer.complete_while_typing():
completer_function()
# Call auto_suggest.
if buffer.auto_suggest:
auto_suggest_function()
return on_text_insert
buffer.on_text_insert += create_on_insert_handler()
def buffer_changed(_):
"""
When the text in a buffer changes.
(A paste event is also a change, but not an insert. So we don't
want to do autocompletions in this case, but we want to propagate
the on_buffer_changed event.)
"""
# Trigger on_buffer_changed.
self.on_buffer_changed.fire()
buffer.on_text_changed += buffer_changed | python | def add_buffer(self, name, buffer, focus=False):
"""
Insert a new buffer.
"""
assert isinstance(buffer, Buffer)
self.buffers[name] = buffer
if focus:
self.buffers.focus(name)
# Create asynchronous completer / auto suggestion.
auto_suggest_function = self._create_auto_suggest_function(buffer)
completer_function = self._create_async_completer(buffer)
self._async_completers[name] = completer_function
# Complete/suggest on text insert.
def create_on_insert_handler():
"""
Wrapper around the asynchronous completer and auto suggestion, that
ensures that it's only called while typing if the
`complete_while_typing` filter is enabled.
"""
def on_text_insert(_):
# Only complete when "complete_while_typing" is enabled.
if buffer.completer and buffer.complete_while_typing():
completer_function()
# Call auto_suggest.
if buffer.auto_suggest:
auto_suggest_function()
return on_text_insert
buffer.on_text_insert += create_on_insert_handler()
def buffer_changed(_):
"""
When the text in a buffer changes.
(A paste event is also a change, but not an insert. So we don't
want to do autocompletions in this case, but we want to propagate
the on_buffer_changed event.)
"""
# Trigger on_buffer_changed.
self.on_buffer_changed.fire()
buffer.on_text_changed += buffer_changed | [
"def",
"add_buffer",
"(",
"self",
",",
"name",
",",
"buffer",
",",
"focus",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"buffer",
",",
"Buffer",
")",
"self",
".",
"buffers",
"[",
"name",
"]",
"=",
"buffer",
"if",
"focus",
":",
"self",
".",
... | Insert a new buffer. | [
"Insert",
"a",
"new",
"buffer",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L155-L200 | train | 207,487 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | CommandLineInterface.terminal_title | def terminal_title(self):
"""
Return the current title to be displayed in the terminal.
When this in `None`, the terminal title remains the original.
"""
result = self.application.get_title()
# Make sure that this function returns a unicode object,
# and not a byte string.
assert result is None or isinstance(result, six.text_type)
return result | python | def terminal_title(self):
"""
Return the current title to be displayed in the terminal.
When this in `None`, the terminal title remains the original.
"""
result = self.application.get_title()
# Make sure that this function returns a unicode object,
# and not a byte string.
assert result is None or isinstance(result, six.text_type)
return result | [
"def",
"terminal_title",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"application",
".",
"get_title",
"(",
")",
"# Make sure that this function returns a unicode object,",
"# and not a byte string.",
"assert",
"result",
"is",
"None",
"or",
"isinstance",
"(",
"r... | Return the current title to be displayed in the terminal.
When this in `None`, the terminal title remains the original. | [
"Return",
"the",
"current",
"title",
"to",
"be",
"displayed",
"in",
"the",
"terminal",
".",
"When",
"this",
"in",
"None",
"the",
"terminal",
"title",
"remains",
"the",
"original",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L255-L265 | train | 207,488 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | CommandLineInterface.reset | def reset(self, reset_current_buffer=False):
"""
Reset everything, for reading the next input.
:param reset_current_buffer: XXX: not used anymore. The reason for
having this option in the past was when this CommandLineInterface
is run multiple times, that we could reset the buffer content from
the previous run. This is now handled in the AcceptAction.
"""
# Notice that we don't reset the buffers. (This happens just before
# returning, and when we have multiple buffers, we clearly want the
# content in the other buffers to remain unchanged between several
# calls of `run`. (And the same is true for the focus stack.)
self._exit_flag = False
self._abort_flag = False
self._return_value = None
self.renderer.reset()
self.input_processor.reset()
self.layout.reset()
self.vi_state.reset()
# Search new search state. (Does also remember what has to be
# highlighted.)
self.search_state = SearchState(ignore_case=Condition(lambda: self.is_ignoring_case))
# Trigger reset event.
self.on_reset.fire() | python | def reset(self, reset_current_buffer=False):
"""
Reset everything, for reading the next input.
:param reset_current_buffer: XXX: not used anymore. The reason for
having this option in the past was when this CommandLineInterface
is run multiple times, that we could reset the buffer content from
the previous run. This is now handled in the AcceptAction.
"""
# Notice that we don't reset the buffers. (This happens just before
# returning, and when we have multiple buffers, we clearly want the
# content in the other buffers to remain unchanged between several
# calls of `run`. (And the same is true for the focus stack.)
self._exit_flag = False
self._abort_flag = False
self._return_value = None
self.renderer.reset()
self.input_processor.reset()
self.layout.reset()
self.vi_state.reset()
# Search new search state. (Does also remember what has to be
# highlighted.)
self.search_state = SearchState(ignore_case=Condition(lambda: self.is_ignoring_case))
# Trigger reset event.
self.on_reset.fire() | [
"def",
"reset",
"(",
"self",
",",
"reset_current_buffer",
"=",
"False",
")",
":",
"# Notice that we don't reset the buffers. (This happens just before",
"# returning, and when we have multiple buffers, we clearly want the",
"# content in the other buffers to remain unchanged between several"... | Reset everything, for reading the next input.
:param reset_current_buffer: XXX: not used anymore. The reason for
having this option in the past was when this CommandLineInterface
is run multiple times, that we could reset the buffer content from
the previous run. This is now handled in the AcceptAction. | [
"Reset",
"everything",
"for",
"reading",
"the",
"next",
"input",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L274-L303 | train | 207,489 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | CommandLineInterface.invalidate | def invalidate(self):
"""
Thread safe way of sending a repaint trigger to the input event loop.
"""
# Never schedule a second redraw, when a previous one has not yet been
# executed. (This should protect against other threads calling
# 'invalidate' many times, resulting in 100% CPU.)
if self._invalidated:
return
else:
self._invalidated = True
# Trigger event.
self.on_invalidate.fire()
if self.eventloop is not None:
def redraw():
self._invalidated = False
self._redraw()
# Call redraw in the eventloop (thread safe).
# Usually with the high priority, in order to make the application
# feel responsive, but this can be tuned by changing the value of
# `max_render_postpone_time`.
if self.max_render_postpone_time:
_max_postpone_until = time.time() + self.max_render_postpone_time
else:
_max_postpone_until = None
self.eventloop.call_from_executor(
redraw, _max_postpone_until=_max_postpone_until) | python | def invalidate(self):
"""
Thread safe way of sending a repaint trigger to the input event loop.
"""
# Never schedule a second redraw, when a previous one has not yet been
# executed. (This should protect against other threads calling
# 'invalidate' many times, resulting in 100% CPU.)
if self._invalidated:
return
else:
self._invalidated = True
# Trigger event.
self.on_invalidate.fire()
if self.eventloop is not None:
def redraw():
self._invalidated = False
self._redraw()
# Call redraw in the eventloop (thread safe).
# Usually with the high priority, in order to make the application
# feel responsive, but this can be tuned by changing the value of
# `max_render_postpone_time`.
if self.max_render_postpone_time:
_max_postpone_until = time.time() + self.max_render_postpone_time
else:
_max_postpone_until = None
self.eventloop.call_from_executor(
redraw, _max_postpone_until=_max_postpone_until) | [
"def",
"invalidate",
"(",
"self",
")",
":",
"# Never schedule a second redraw, when a previous one has not yet been",
"# executed. (This should protect against other threads calling",
"# 'invalidate' many times, resulting in 100% CPU.)",
"if",
"self",
".",
"_invalidated",
":",
"return",
... | Thread safe way of sending a repaint trigger to the input event loop. | [
"Thread",
"safe",
"way",
"of",
"sending",
"a",
"repaint",
"trigger",
"to",
"the",
"input",
"event",
"loop",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L315-L345 | train | 207,490 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | CommandLineInterface._on_resize | def _on_resize(self):
"""
When the window size changes, we erase the current output and request
again the cursor position. When the CPR answer arrives, the output is
drawn again.
"""
# Erase, request position (when cursor is at the start position)
# and redraw again. -- The order is important.
self.renderer.erase(leave_alternate_screen=False, erase_title=False)
self.renderer.request_absolute_cursor_position()
self._redraw() | python | def _on_resize(self):
"""
When the window size changes, we erase the current output and request
again the cursor position. When the CPR answer arrives, the output is
drawn again.
"""
# Erase, request position (when cursor is at the start position)
# and redraw again. -- The order is important.
self.renderer.erase(leave_alternate_screen=False, erase_title=False)
self.renderer.request_absolute_cursor_position()
self._redraw() | [
"def",
"_on_resize",
"(",
"self",
")",
":",
"# Erase, request position (when cursor is at the start position)",
"# and redraw again. -- The order is important.",
"self",
".",
"renderer",
".",
"erase",
"(",
"leave_alternate_screen",
"=",
"False",
",",
"erase_title",
"=",
"Fals... | When the window size changes, we erase the current output and request
again the cursor position. When the CPR answer arrives, the output is
drawn again. | [
"When",
"the",
"window",
"size",
"changes",
"we",
"erase",
"the",
"current",
"output",
"and",
"request",
"again",
"the",
"cursor",
"position",
".",
"When",
"the",
"CPR",
"answer",
"arrives",
"the",
"output",
"is",
"drawn",
"again",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L363-L373 | train | 207,491 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | CommandLineInterface._pre_run | def _pre_run(self, pre_run=None):
" Called during `run`. "
if pre_run:
pre_run()
# Process registered "pre_run_callables" and clear list.
for c in self.pre_run_callables:
c()
del self.pre_run_callables[:] | python | def _pre_run(self, pre_run=None):
" Called during `run`. "
if pre_run:
pre_run()
# Process registered "pre_run_callables" and clear list.
for c in self.pre_run_callables:
c()
del self.pre_run_callables[:] | [
"def",
"_pre_run",
"(",
"self",
",",
"pre_run",
"=",
"None",
")",
":",
"if",
"pre_run",
":",
"pre_run",
"(",
")",
"# Process registered \"pre_run_callables\" and clear list.",
"for",
"c",
"in",
"self",
".",
"pre_run_callables",
":",
"c",
"(",
")",
"del",
"self... | Called during `run`. | [
"Called",
"during",
"run",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L380-L388 | train | 207,492 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | CommandLineInterface.run | def run(self, reset_current_buffer=False, pre_run=None):
"""
Read input from the command line.
This runs the eventloop until a return value has been set.
:param reset_current_buffer: XXX: Not used anymore.
:param pre_run: Callable that is called right after the reset has taken
place. This allows custom initialisation.
"""
assert pre_run is None or callable(pre_run)
try:
self._is_running = True
self.on_start.fire()
self.reset()
# Call pre_run.
self._pre_run(pre_run)
# Run eventloop in raw mode.
with self.input.raw_mode():
self.renderer.request_absolute_cursor_position()
self._redraw()
self.eventloop.run(self.input, self.create_eventloop_callbacks())
finally:
# Clean up renderer. (This will leave the alternate screen, if we use
# that.)
# If exit/abort haven't been called set, but another exception was
# thrown instead for some reason, make sure that we redraw in exit
# mode.
if not self.is_done:
self._exit_flag = True
self._redraw()
self.renderer.reset()
self.on_stop.fire()
self._is_running = False
# Return result.
return self.return_value() | python | def run(self, reset_current_buffer=False, pre_run=None):
"""
Read input from the command line.
This runs the eventloop until a return value has been set.
:param reset_current_buffer: XXX: Not used anymore.
:param pre_run: Callable that is called right after the reset has taken
place. This allows custom initialisation.
"""
assert pre_run is None or callable(pre_run)
try:
self._is_running = True
self.on_start.fire()
self.reset()
# Call pre_run.
self._pre_run(pre_run)
# Run eventloop in raw mode.
with self.input.raw_mode():
self.renderer.request_absolute_cursor_position()
self._redraw()
self.eventloop.run(self.input, self.create_eventloop_callbacks())
finally:
# Clean up renderer. (This will leave the alternate screen, if we use
# that.)
# If exit/abort haven't been called set, but another exception was
# thrown instead for some reason, make sure that we redraw in exit
# mode.
if not self.is_done:
self._exit_flag = True
self._redraw()
self.renderer.reset()
self.on_stop.fire()
self._is_running = False
# Return result.
return self.return_value() | [
"def",
"run",
"(",
"self",
",",
"reset_current_buffer",
"=",
"False",
",",
"pre_run",
"=",
"None",
")",
":",
"assert",
"pre_run",
"is",
"None",
"or",
"callable",
"(",
"pre_run",
")",
"try",
":",
"self",
".",
"_is_running",
"=",
"True",
"self",
".",
"on... | Read input from the command line.
This runs the eventloop until a return value has been set.
:param reset_current_buffer: XXX: Not used anymore.
:param pre_run: Callable that is called right after the reset has taken
place. This allows custom initialisation. | [
"Read",
"input",
"from",
"the",
"command",
"line",
".",
"This",
"runs",
"the",
"eventloop",
"until",
"a",
"return",
"value",
"has",
"been",
"set",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L390-L432 | train | 207,493 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | CommandLineInterface.exit | def exit(self):
"""
Set exit. When Control-D has been pressed.
"""
on_exit = self.application.on_exit
self._exit_flag = True
self._redraw()
if on_exit == AbortAction.RAISE_EXCEPTION:
def eof_error():
raise EOFError()
self._set_return_callable(eof_error)
elif on_exit == AbortAction.RETRY:
self.reset()
self.renderer.request_absolute_cursor_position()
self.current_buffer.reset()
elif on_exit == AbortAction.RETURN_NONE:
self.set_return_value(None) | python | def exit(self):
"""
Set exit. When Control-D has been pressed.
"""
on_exit = self.application.on_exit
self._exit_flag = True
self._redraw()
if on_exit == AbortAction.RAISE_EXCEPTION:
def eof_error():
raise EOFError()
self._set_return_callable(eof_error)
elif on_exit == AbortAction.RETRY:
self.reset()
self.renderer.request_absolute_cursor_position()
self.current_buffer.reset()
elif on_exit == AbortAction.RETURN_NONE:
self.set_return_value(None) | [
"def",
"exit",
"(",
"self",
")",
":",
"on_exit",
"=",
"self",
".",
"application",
".",
"on_exit",
"self",
".",
"_exit_flag",
"=",
"True",
"self",
".",
"_redraw",
"(",
")",
"if",
"on_exit",
"==",
"AbortAction",
".",
"RAISE_EXCEPTION",
":",
"def",
"eof_err... | Set exit. When Control-D has been pressed. | [
"Set",
"exit",
".",
"When",
"Control",
"-",
"D",
"has",
"been",
"pressed",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L553-L572 | train | 207,494 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | CommandLineInterface.abort | def abort(self):
"""
Set abort. When Control-C has been pressed.
"""
on_abort = self.application.on_abort
self._abort_flag = True
self._redraw()
if on_abort == AbortAction.RAISE_EXCEPTION:
def keyboard_interrupt():
raise KeyboardInterrupt()
self._set_return_callable(keyboard_interrupt)
elif on_abort == AbortAction.RETRY:
self.reset()
self.renderer.request_absolute_cursor_position()
self.current_buffer.reset()
elif on_abort == AbortAction.RETURN_NONE:
self.set_return_value(None) | python | def abort(self):
"""
Set abort. When Control-C has been pressed.
"""
on_abort = self.application.on_abort
self._abort_flag = True
self._redraw()
if on_abort == AbortAction.RAISE_EXCEPTION:
def keyboard_interrupt():
raise KeyboardInterrupt()
self._set_return_callable(keyboard_interrupt)
elif on_abort == AbortAction.RETRY:
self.reset()
self.renderer.request_absolute_cursor_position()
self.current_buffer.reset()
elif on_abort == AbortAction.RETURN_NONE:
self.set_return_value(None) | [
"def",
"abort",
"(",
"self",
")",
":",
"on_abort",
"=",
"self",
".",
"application",
".",
"on_abort",
"self",
".",
"_abort_flag",
"=",
"True",
"self",
".",
"_redraw",
"(",
")",
"if",
"on_abort",
"==",
"AbortAction",
".",
"RAISE_EXCEPTION",
":",
"def",
"ke... | Set abort. When Control-C has been pressed. | [
"Set",
"abort",
".",
"When",
"Control",
"-",
"C",
"has",
"been",
"pressed",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L574-L593 | train | 207,495 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | CommandLineInterface.run_in_terminal | def run_in_terminal(self, func, render_cli_done=False, cooked_mode=True):
"""
Run function on the terminal above the prompt.
What this does is first hiding the prompt, then running this callable
(which can safely output to the terminal), and then again rendering the
prompt which causes the output of this function to scroll above the
prompt.
:param func: The callable to execute.
:param render_cli_done: When True, render the interface in the
'Done' state first, then execute the function. If False,
erase the interface first.
:param cooked_mode: When True (the default), switch the input to
cooked mode while executing the function.
:returns: the result of `func`.
"""
# Draw interface in 'done' state, or erase.
if render_cli_done:
self._return_value = True
self._redraw()
self.renderer.reset() # Make sure to disable mouse mode, etc...
else:
self.renderer.erase()
self._return_value = None
# Run system command.
if cooked_mode:
with self.input.cooked_mode():
result = func()
else:
result = func()
# Redraw interface again.
self.renderer.reset()
self.renderer.request_absolute_cursor_position()
self._redraw()
return result | python | def run_in_terminal(self, func, render_cli_done=False, cooked_mode=True):
"""
Run function on the terminal above the prompt.
What this does is first hiding the prompt, then running this callable
(which can safely output to the terminal), and then again rendering the
prompt which causes the output of this function to scroll above the
prompt.
:param func: The callable to execute.
:param render_cli_done: When True, render the interface in the
'Done' state first, then execute the function. If False,
erase the interface first.
:param cooked_mode: When True (the default), switch the input to
cooked mode while executing the function.
:returns: the result of `func`.
"""
# Draw interface in 'done' state, or erase.
if render_cli_done:
self._return_value = True
self._redraw()
self.renderer.reset() # Make sure to disable mouse mode, etc...
else:
self.renderer.erase()
self._return_value = None
# Run system command.
if cooked_mode:
with self.input.cooked_mode():
result = func()
else:
result = func()
# Redraw interface again.
self.renderer.reset()
self.renderer.request_absolute_cursor_position()
self._redraw()
return result | [
"def",
"run_in_terminal",
"(",
"self",
",",
"func",
",",
"render_cli_done",
"=",
"False",
",",
"cooked_mode",
"=",
"True",
")",
":",
"# Draw interface in 'done' state, or erase.",
"if",
"render_cli_done",
":",
"self",
".",
"_return_value",
"=",
"True",
"self",
"."... | Run function on the terminal above the prompt.
What this does is first hiding the prompt, then running this callable
(which can safely output to the terminal), and then again rendering the
prompt which causes the output of this function to scroll above the
prompt.
:param func: The callable to execute.
:param render_cli_done: When True, render the interface in the
'Done' state first, then execute the function. If False,
erase the interface first.
:param cooked_mode: When True (the default), switch the input to
cooked mode while executing the function.
:returns: the result of `func`. | [
"Run",
"function",
"on",
"the",
"terminal",
"above",
"the",
"prompt",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L614-L653 | train | 207,496 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | CommandLineInterface.run_application_generator | def run_application_generator(self, coroutine, render_cli_done=False):
"""
EXPERIMENTAL
Like `run_in_terminal`, but takes a generator that can yield Application instances.
Example:
def f():
yield Application1(...)
print('...')
yield Application2(...)
cli.run_in_terminal_async(f)
The values which are yielded by the given coroutine are supposed to be
`Application` instances that run in the current CLI, all other code is
supposed to be CPU bound, so except for yielding the applications,
there should not be any user interaction or I/O in the given function.
"""
# Draw interface in 'done' state, or erase.
if render_cli_done:
self._return_value = True
self._redraw()
self.renderer.reset() # Make sure to disable mouse mode, etc...
else:
self.renderer.erase()
self._return_value = None
# Loop through the generator.
g = coroutine()
assert isinstance(g, types.GeneratorType)
def step_next(send_value=None):
" Execute next step of the coroutine."
try:
# Run until next yield, in cooked mode.
with self.input.cooked_mode():
result = g.send(send_value)
except StopIteration:
done()
except:
done()
raise
else:
# Process yielded value from coroutine.
assert isinstance(result, Application)
self.run_sub_application(result, done_callback=step_next,
_from_application_generator=True)
def done():
# Redraw interface again.
self.renderer.reset()
self.renderer.request_absolute_cursor_position()
self._redraw()
# Start processing coroutine.
step_next() | python | def run_application_generator(self, coroutine, render_cli_done=False):
"""
EXPERIMENTAL
Like `run_in_terminal`, but takes a generator that can yield Application instances.
Example:
def f():
yield Application1(...)
print('...')
yield Application2(...)
cli.run_in_terminal_async(f)
The values which are yielded by the given coroutine are supposed to be
`Application` instances that run in the current CLI, all other code is
supposed to be CPU bound, so except for yielding the applications,
there should not be any user interaction or I/O in the given function.
"""
# Draw interface in 'done' state, or erase.
if render_cli_done:
self._return_value = True
self._redraw()
self.renderer.reset() # Make sure to disable mouse mode, etc...
else:
self.renderer.erase()
self._return_value = None
# Loop through the generator.
g = coroutine()
assert isinstance(g, types.GeneratorType)
def step_next(send_value=None):
" Execute next step of the coroutine."
try:
# Run until next yield, in cooked mode.
with self.input.cooked_mode():
result = g.send(send_value)
except StopIteration:
done()
except:
done()
raise
else:
# Process yielded value from coroutine.
assert isinstance(result, Application)
self.run_sub_application(result, done_callback=step_next,
_from_application_generator=True)
def done():
# Redraw interface again.
self.renderer.reset()
self.renderer.request_absolute_cursor_position()
self._redraw()
# Start processing coroutine.
step_next() | [
"def",
"run_application_generator",
"(",
"self",
",",
"coroutine",
",",
"render_cli_done",
"=",
"False",
")",
":",
"# Draw interface in 'done' state, or erase.",
"if",
"render_cli_done",
":",
"self",
".",
"_return_value",
"=",
"True",
"self",
".",
"_redraw",
"(",
")... | EXPERIMENTAL
Like `run_in_terminal`, but takes a generator that can yield Application instances.
Example:
def f():
yield Application1(...)
print('...')
yield Application2(...)
cli.run_in_terminal_async(f)
The values which are yielded by the given coroutine are supposed to be
`Application` instances that run in the current CLI, all other code is
supposed to be CPU bound, so except for yielding the applications,
there should not be any user interaction or I/O in the given function. | [
"EXPERIMENTAL",
"Like",
"run_in_terminal",
"but",
"takes",
"a",
"generator",
"that",
"can",
"yield",
"Application",
"instances",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L655-L710 | train | 207,497 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | CommandLineInterface.patch_stdout_context | def patch_stdout_context(self, raw=False, patch_stdout=True, patch_stderr=True):
"""
Return a context manager that will replace ``sys.stdout`` with a proxy
that makes sure that all printed text will appear above the prompt, and
that it doesn't destroy the output from the renderer.
:param patch_stdout: Replace `sys.stdout`.
:param patch_stderr: Replace `sys.stderr`.
"""
return _PatchStdoutContext(
self.stdout_proxy(raw=raw),
patch_stdout=patch_stdout, patch_stderr=patch_stderr) | python | def patch_stdout_context(self, raw=False, patch_stdout=True, patch_stderr=True):
"""
Return a context manager that will replace ``sys.stdout`` with a proxy
that makes sure that all printed text will appear above the prompt, and
that it doesn't destroy the output from the renderer.
:param patch_stdout: Replace `sys.stdout`.
:param patch_stderr: Replace `sys.stderr`.
"""
return _PatchStdoutContext(
self.stdout_proxy(raw=raw),
patch_stdout=patch_stdout, patch_stderr=patch_stderr) | [
"def",
"patch_stdout_context",
"(",
"self",
",",
"raw",
"=",
"False",
",",
"patch_stdout",
"=",
"True",
",",
"patch_stderr",
"=",
"True",
")",
":",
"return",
"_PatchStdoutContext",
"(",
"self",
".",
"stdout_proxy",
"(",
"raw",
"=",
"raw",
")",
",",
"patch_... | Return a context manager that will replace ``sys.stdout`` with a proxy
that makes sure that all printed text will appear above the prompt, and
that it doesn't destroy the output from the renderer.
:param patch_stdout: Replace `sys.stdout`.
:param patch_stderr: Replace `sys.stderr`. | [
"Return",
"a",
"context",
"manager",
"that",
"will",
"replace",
"sys",
".",
"stdout",
"with",
"a",
"proxy",
"that",
"makes",
"sure",
"that",
"all",
"printed",
"text",
"will",
"appear",
"above",
"the",
"prompt",
"and",
"that",
"it",
"doesn",
"t",
"destroy",... | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L987-L998 | train | 207,498 |
wandb/client | wandb/vendor/prompt_toolkit/interface.py | _InterfaceEventLoopCallbacks._active_cli | def _active_cli(self):
"""
Return the active `CommandLineInterface`.
"""
cli = self.cli
# If there is a sub CLI. That one is always active.
while cli._sub_cli:
cli = cli._sub_cli
return cli | python | def _active_cli(self):
"""
Return the active `CommandLineInterface`.
"""
cli = self.cli
# If there is a sub CLI. That one is always active.
while cli._sub_cli:
cli = cli._sub_cli
return cli | [
"def",
"_active_cli",
"(",
"self",
")",
":",
"cli",
"=",
"self",
".",
"cli",
"# If there is a sub CLI. That one is always active.",
"while",
"cli",
".",
"_sub_cli",
":",
"cli",
"=",
"cli",
".",
"_sub_cli",
"return",
"cli"
] | Return the active `CommandLineInterface`. | [
"Return",
"the",
"active",
"CommandLineInterface",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L1014-L1024 | train | 207,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.