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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
nickstenning/honcho | honcho/environ.py | expand_processes | def expand_processes(processes, concurrency=None, env=None, quiet=None, port=None):
"""
Get a list of the processes that need to be started given the specified
list of process types, concurrency, environment, quietness, and base port
number.
Returns a list of ProcessParams objects, which have `name`, `cmd`, `env`,
and `quiet` attributes, corresponding to the parameters to the constructor
of `honcho.process.Process`.
"""
if env is not None and env.get("PORT") is not None:
port = int(env.get("PORT"))
if quiet is None:
quiet = []
con = defaultdict(lambda: 1)
if concurrency is not None:
con.update(concurrency)
out = []
for name, cmd in compat.iteritems(processes):
for i in range(con[name]):
n = "{0}.{1}".format(name, i + 1)
c = cmd
q = name in quiet
e = {'HONCHO_PROCESS_NAME': n}
if env is not None:
e.update(env)
if port is not None:
e['PORT'] = str(port + i)
params = ProcessParams(n, c, q, e)
out.append(params)
if port is not None:
port += 100
return out | python | def expand_processes(processes, concurrency=None, env=None, quiet=None, port=None):
"""
Get a list of the processes that need to be started given the specified
list of process types, concurrency, environment, quietness, and base port
number.
Returns a list of ProcessParams objects, which have `name`, `cmd`, `env`,
and `quiet` attributes, corresponding to the parameters to the constructor
of `honcho.process.Process`.
"""
if env is not None and env.get("PORT") is not None:
port = int(env.get("PORT"))
if quiet is None:
quiet = []
con = defaultdict(lambda: 1)
if concurrency is not None:
con.update(concurrency)
out = []
for name, cmd in compat.iteritems(processes):
for i in range(con[name]):
n = "{0}.{1}".format(name, i + 1)
c = cmd
q = name in quiet
e = {'HONCHO_PROCESS_NAME': n}
if env is not None:
e.update(env)
if port is not None:
e['PORT'] = str(port + i)
params = ProcessParams(n, c, q, e)
out.append(params)
if port is not None:
port += 100
return out | [
"def",
"expand_processes",
"(",
"processes",
",",
"concurrency",
"=",
"None",
",",
"env",
"=",
"None",
",",
"quiet",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"env",
"is",
"not",
"None",
"and",
"env",
".",
"get",
"(",
"\"PORT\"",
")",
... | Get a list of the processes that need to be started given the specified
list of process types, concurrency, environment, quietness, and base port
number.
Returns a list of ProcessParams objects, which have `name`, `cmd`, `env`,
and `quiet` attributes, corresponding to the parameters to the constructor
of `honcho.process.Process`. | [
"Get",
"a",
"list",
"of",
"the",
"processes",
"that",
"need",
"to",
"be",
"started",
"given",
"the",
"specified",
"list",
"of",
"process",
"types",
"concurrency",
"environment",
"quietness",
"and",
"base",
"port",
"number",
"."
] | f3b2e1e11868283f4c3463102b7ed3bd00f26b32 | https://github.com/nickstenning/honcho/blob/f3b2e1e11868283f4c3463102b7ed3bd00f26b32/honcho/environ.py#L105-L143 | train | 207,200 |
nickstenning/honcho | honcho/export/base.py | dashrepl | def dashrepl(value):
"""
Replace any non-word characters with a dash.
"""
patt = re.compile(r'\W', re.UNICODE)
return re.sub(patt, '-', value) | python | def dashrepl(value):
"""
Replace any non-word characters with a dash.
"""
patt = re.compile(r'\W', re.UNICODE)
return re.sub(patt, '-', value) | [
"def",
"dashrepl",
"(",
"value",
")",
":",
"patt",
"=",
"re",
".",
"compile",
"(",
"r'\\W'",
",",
"re",
".",
"UNICODE",
")",
"return",
"re",
".",
"sub",
"(",
"patt",
",",
"'-'",
",",
"value",
")"
] | Replace any non-word characters with a dash. | [
"Replace",
"any",
"non",
"-",
"word",
"characters",
"with",
"a",
"dash",
"."
] | f3b2e1e11868283f4c3463102b7ed3bd00f26b32 | https://github.com/nickstenning/honcho/blob/f3b2e1e11868283f4c3463102b7ed3bd00f26b32/honcho/export/base.py#L57-L62 | train | 207,201 |
jrief/django-sass-processor | sass_processor/management/commands/compilescss.py | Command.find_sources | def find_sources(self):
"""
Look for Python sources available for the current configuration.
"""
app_configs = apps.get_app_configs()
for app_config in app_configs:
ignore_dirs = []
for root, dirs, files in os.walk(app_config.path):
if [True for idir in ignore_dirs if root.startswith(idir)]:
continue
if '__init__.py' not in files:
ignore_dirs.append(root)
continue
for filename in files:
basename, ext = os.path.splitext(filename)
if ext != '.py':
continue
yield os.path.abspath(os.path.join(root, filename)) | python | def find_sources(self):
"""
Look for Python sources available for the current configuration.
"""
app_configs = apps.get_app_configs()
for app_config in app_configs:
ignore_dirs = []
for root, dirs, files in os.walk(app_config.path):
if [True for idir in ignore_dirs if root.startswith(idir)]:
continue
if '__init__.py' not in files:
ignore_dirs.append(root)
continue
for filename in files:
basename, ext = os.path.splitext(filename)
if ext != '.py':
continue
yield os.path.abspath(os.path.join(root, filename)) | [
"def",
"find_sources",
"(",
"self",
")",
":",
"app_configs",
"=",
"apps",
".",
"get_app_configs",
"(",
")",
"for",
"app_config",
"in",
"app_configs",
":",
"ignore_dirs",
"=",
"[",
"]",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
... | Look for Python sources available for the current configuration. | [
"Look",
"for",
"Python",
"sources",
"available",
"for",
"the",
"current",
"configuration",
"."
] | 3ca746258432b1428daee9a2b2f7e05a1e327492 | https://github.com/jrief/django-sass-processor/blob/3ca746258432b1428daee9a2b2f7e05a1e327492/sass_processor/management/commands/compilescss.py#L180-L197 | train | 207,202 |
jrief/django-sass-processor | sass_processor/management/commands/compilescss.py | Command.find_templates | def find_templates(self):
"""
Look for templates and extract the nodes containing the SASS file.
"""
paths = set()
for loader in self.get_loaders():
try:
module = import_module(loader.__module__)
get_template_sources = getattr(
module, 'get_template_sources', loader.get_template_sources)
template_sources = get_template_sources('')
paths.update([t.name if isinstance(t, Origin) else t for t in template_sources])
except (ImportError, AttributeError):
pass
if not paths:
raise CommandError(
"No template paths found. None of the configured template loaders provided template paths")
templates = set()
for path in paths:
for root, _, files in os.walk(str(path)):
templates.update(os.path.join(root, name)
for name in files if not name.startswith('.') and
any(name.endswith(ext) for ext in self.template_exts))
if not templates:
raise CommandError(
"No templates found. Make sure your TEMPLATE_LOADERS and TEMPLATE_DIRS settings are correct.")
return templates | python | def find_templates(self):
"""
Look for templates and extract the nodes containing the SASS file.
"""
paths = set()
for loader in self.get_loaders():
try:
module = import_module(loader.__module__)
get_template_sources = getattr(
module, 'get_template_sources', loader.get_template_sources)
template_sources = get_template_sources('')
paths.update([t.name if isinstance(t, Origin) else t for t in template_sources])
except (ImportError, AttributeError):
pass
if not paths:
raise CommandError(
"No template paths found. None of the configured template loaders provided template paths")
templates = set()
for path in paths:
for root, _, files in os.walk(str(path)):
templates.update(os.path.join(root, name)
for name in files if not name.startswith('.') and
any(name.endswith(ext) for ext in self.template_exts))
if not templates:
raise CommandError(
"No templates found. Make sure your TEMPLATE_LOADERS and TEMPLATE_DIRS settings are correct.")
return templates | [
"def",
"find_templates",
"(",
"self",
")",
":",
"paths",
"=",
"set",
"(",
")",
"for",
"loader",
"in",
"self",
".",
"get_loaders",
"(",
")",
":",
"try",
":",
"module",
"=",
"import_module",
"(",
"loader",
".",
"__module__",
")",
"get_template_sources",
"=... | Look for templates and extract the nodes containing the SASS file. | [
"Look",
"for",
"templates",
"and",
"extract",
"the",
"nodes",
"containing",
"the",
"SASS",
"file",
"."
] | 3ca746258432b1428daee9a2b2f7e05a1e327492 | https://github.com/jrief/django-sass-processor/blob/3ca746258432b1428daee9a2b2f7e05a1e327492/sass_processor/management/commands/compilescss.py#L216-L242 | train | 207,203 |
jrief/django-sass-processor | sass_processor/management/commands/compilescss.py | Command.compile_sass | def compile_sass(self, sass_filename, sass_fileurl):
"""
Compile the given SASS file into CSS
"""
compile_kwargs = {
'filename': sass_filename,
'include_paths': SassProcessor.include_paths + APPS_INCLUDE_DIRS,
'custom_functions': get_custom_functions(),
}
if self.sass_precision:
compile_kwargs['precision'] = self.sass_precision
if self.sass_output_style:
compile_kwargs['output_style'] = self.sass_output_style
content = sass.compile(**compile_kwargs)
self.save_to_destination(content, sass_filename, sass_fileurl)
self.processed_files.append(sass_filename)
if self.verbosity > 1:
self.stdout.write("Compiled SASS/SCSS file: '{0}'\n".format(sass_filename)) | python | def compile_sass(self, sass_filename, sass_fileurl):
"""
Compile the given SASS file into CSS
"""
compile_kwargs = {
'filename': sass_filename,
'include_paths': SassProcessor.include_paths + APPS_INCLUDE_DIRS,
'custom_functions': get_custom_functions(),
}
if self.sass_precision:
compile_kwargs['precision'] = self.sass_precision
if self.sass_output_style:
compile_kwargs['output_style'] = self.sass_output_style
content = sass.compile(**compile_kwargs)
self.save_to_destination(content, sass_filename, sass_fileurl)
self.processed_files.append(sass_filename)
if self.verbosity > 1:
self.stdout.write("Compiled SASS/SCSS file: '{0}'\n".format(sass_filename)) | [
"def",
"compile_sass",
"(",
"self",
",",
"sass_filename",
",",
"sass_fileurl",
")",
":",
"compile_kwargs",
"=",
"{",
"'filename'",
":",
"sass_filename",
",",
"'include_paths'",
":",
"SassProcessor",
".",
"include_paths",
"+",
"APPS_INCLUDE_DIRS",
",",
"'custom_funct... | Compile the given SASS file into CSS | [
"Compile",
"the",
"given",
"SASS",
"file",
"into",
"CSS"
] | 3ca746258432b1428daee9a2b2f7e05a1e327492 | https://github.com/jrief/django-sass-processor/blob/3ca746258432b1428daee9a2b2f7e05a1e327492/sass_processor/management/commands/compilescss.py#L279-L296 | train | 207,204 |
jrief/django-sass-processor | sass_processor/management/commands/compilescss.py | Command.walk_nodes | def walk_nodes(self, node, original):
"""
Iterate over the nodes recursively yielding the templatetag 'sass_src'
"""
try:
# try with django-compressor<2.1
nodelist = self.parser.get_nodelist(node, original=original)
except TypeError:
nodelist = self.parser.get_nodelist(node, original=original, context=None)
for node in nodelist:
if isinstance(node, SassSrcNode):
if node.is_sass:
yield node
else:
for node in self.walk_nodes(node, original=original):
yield node | python | def walk_nodes(self, node, original):
"""
Iterate over the nodes recursively yielding the templatetag 'sass_src'
"""
try:
# try with django-compressor<2.1
nodelist = self.parser.get_nodelist(node, original=original)
except TypeError:
nodelist = self.parser.get_nodelist(node, original=original, context=None)
for node in nodelist:
if isinstance(node, SassSrcNode):
if node.is_sass:
yield node
else:
for node in self.walk_nodes(node, original=original):
yield node | [
"def",
"walk_nodes",
"(",
"self",
",",
"node",
",",
"original",
")",
":",
"try",
":",
"# try with django-compressor<2.1",
"nodelist",
"=",
"self",
".",
"parser",
".",
"get_nodelist",
"(",
"node",
",",
"original",
"=",
"original",
")",
"except",
"TypeError",
... | Iterate over the nodes recursively yielding the templatetag 'sass_src' | [
"Iterate",
"over",
"the",
"nodes",
"recursively",
"yielding",
"the",
"templatetag",
"sass_src"
] | 3ca746258432b1428daee9a2b2f7e05a1e327492 | https://github.com/jrief/django-sass-processor/blob/3ca746258432b1428daee9a2b2f7e05a1e327492/sass_processor/management/commands/compilescss.py#L323-L338 | train | 207,205 |
jrief/django-sass-processor | sass_processor/utils.py | get_custom_functions | def get_custom_functions():
"""
Return a dict of function names, to be used from inside SASS
"""
def get_setting(*args):
try:
return getattr(settings, args[0])
except AttributeError as e:
raise TemplateSyntaxError(str(e))
if hasattr(get_custom_functions, '_custom_functions'):
return get_custom_functions._custom_functions
get_custom_functions._custom_functions = {sass.SassFunction('get-setting', ('key',), get_setting)}
for name, func in getattr(settings, 'SASS_PROCESSOR_CUSTOM_FUNCTIONS', {}).items():
try:
if isinstance(func, six.string_types):
func = import_string(func)
except Exception as e:
raise TemplateSyntaxError(str(e))
else:
if not inspect.isfunction(func):
raise TemplateSyntaxError("{} is not a Python function".format(func))
if six.PY2:
func_args = inspect.getargspec(func).args
else:
func_args = inspect.getfullargspec(func).args
sass_func = sass.SassFunction(name, func_args, func)
get_custom_functions._custom_functions.add(sass_func)
return get_custom_functions._custom_functions | python | def get_custom_functions():
"""
Return a dict of function names, to be used from inside SASS
"""
def get_setting(*args):
try:
return getattr(settings, args[0])
except AttributeError as e:
raise TemplateSyntaxError(str(e))
if hasattr(get_custom_functions, '_custom_functions'):
return get_custom_functions._custom_functions
get_custom_functions._custom_functions = {sass.SassFunction('get-setting', ('key',), get_setting)}
for name, func in getattr(settings, 'SASS_PROCESSOR_CUSTOM_FUNCTIONS', {}).items():
try:
if isinstance(func, six.string_types):
func = import_string(func)
except Exception as e:
raise TemplateSyntaxError(str(e))
else:
if not inspect.isfunction(func):
raise TemplateSyntaxError("{} is not a Python function".format(func))
if six.PY2:
func_args = inspect.getargspec(func).args
else:
func_args = inspect.getfullargspec(func).args
sass_func = sass.SassFunction(name, func_args, func)
get_custom_functions._custom_functions.add(sass_func)
return get_custom_functions._custom_functions | [
"def",
"get_custom_functions",
"(",
")",
":",
"def",
"get_setting",
"(",
"*",
"args",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"settings",
",",
"args",
"[",
"0",
"]",
")",
"except",
"AttributeError",
"as",
"e",
":",
"raise",
"TemplateSyntaxError",
... | Return a dict of function names, to be used from inside SASS | [
"Return",
"a",
"dict",
"of",
"function",
"names",
"to",
"be",
"used",
"from",
"inside",
"SASS"
] | 3ca746258432b1428daee9a2b2f7e05a1e327492 | https://github.com/jrief/django-sass-processor/blob/3ca746258432b1428daee9a2b2f7e05a1e327492/sass_processor/utils.py#L14-L42 | train | 207,206 |
adafruit/Adafruit_CircuitPython_ADS1x15 | adafruit_ads1x15/ads1x15.py | ADS1x15.read | def read(self, pin, is_differential=False):
"""I2C Interface for ADS1x15-based ADCs reads.
params:
:param pin: individual or differential pin.
:param bool is_differential: single-ended or differential read.
"""
pin = pin if is_differential else pin + 0x04
return self._read(pin) | python | def read(self, pin, is_differential=False):
"""I2C Interface for ADS1x15-based ADCs reads.
params:
:param pin: individual or differential pin.
:param bool is_differential: single-ended or differential read.
"""
pin = pin if is_differential else pin + 0x04
return self._read(pin) | [
"def",
"read",
"(",
"self",
",",
"pin",
",",
"is_differential",
"=",
"False",
")",
":",
"pin",
"=",
"pin",
"if",
"is_differential",
"else",
"pin",
"+",
"0x04",
"return",
"self",
".",
"_read",
"(",
"pin",
")"
] | I2C Interface for ADS1x15-based ADCs reads.
params:
:param pin: individual or differential pin.
:param bool is_differential: single-ended or differential read. | [
"I2C",
"Interface",
"for",
"ADS1x15",
"-",
"based",
"ADCs",
"reads",
"."
] | 5ba760c6de40824386f1df343603eab77d3e336c | https://github.com/adafruit/Adafruit_CircuitPython_ADS1x15/blob/5ba760c6de40824386f1df343603eab77d3e336c/adafruit_ads1x15/ads1x15.py#L129-L137 | train | 207,207 |
adafruit/Adafruit_CircuitPython_ADS1x15 | adafruit_ads1x15/ads1x15.py | ADS1x15._read | def _read(self, pin):
"""Perform an ADC read. Returns the signed integer result of the read."""
config = _ADS1X15_CONFIG_OS_SINGLE
config |= (pin & 0x07) << _ADS1X15_CONFIG_MUX_OFFSET
config |= _ADS1X15_CONFIG_GAIN[self.gain]
config |= self.mode
config |= self.rate_config[self.data_rate]
config |= _ADS1X15_CONFIG_COMP_QUE_DISABLE
self._write_register(_ADS1X15_POINTER_CONFIG, config)
while not self._conversion_complete():
time.sleep(0.01)
return self.get_last_result() | python | def _read(self, pin):
"""Perform an ADC read. Returns the signed integer result of the read."""
config = _ADS1X15_CONFIG_OS_SINGLE
config |= (pin & 0x07) << _ADS1X15_CONFIG_MUX_OFFSET
config |= _ADS1X15_CONFIG_GAIN[self.gain]
config |= self.mode
config |= self.rate_config[self.data_rate]
config |= _ADS1X15_CONFIG_COMP_QUE_DISABLE
self._write_register(_ADS1X15_POINTER_CONFIG, config)
while not self._conversion_complete():
time.sleep(0.01)
return self.get_last_result() | [
"def",
"_read",
"(",
"self",
",",
"pin",
")",
":",
"config",
"=",
"_ADS1X15_CONFIG_OS_SINGLE",
"config",
"|=",
"(",
"pin",
"&",
"0x07",
")",
"<<",
"_ADS1X15_CONFIG_MUX_OFFSET",
"config",
"|=",
"_ADS1X15_CONFIG_GAIN",
"[",
"self",
".",
"gain",
"]",
"config",
... | Perform an ADC read. Returns the signed integer result of the read. | [
"Perform",
"an",
"ADC",
"read",
".",
"Returns",
"the",
"signed",
"integer",
"result",
"of",
"the",
"read",
"."
] | 5ba760c6de40824386f1df343603eab77d3e336c | https://github.com/adafruit/Adafruit_CircuitPython_ADS1x15/blob/5ba760c6de40824386f1df343603eab77d3e336c/adafruit_ads1x15/ads1x15.py#L151-L164 | train | 207,208 |
adafruit/Adafruit_CircuitPython_ADS1x15 | adafruit_ads1x15/ads1x15.py | ADS1x15._write_register | def _write_register(self, reg, value):
"""Write 16 bit value to register."""
self.buf[0] = reg
self.buf[1] = (value >> 8) & 0xFF
self.buf[2] = value & 0xFF
with self.i2c_device as i2c:
i2c.write(self.buf) | python | def _write_register(self, reg, value):
"""Write 16 bit value to register."""
self.buf[0] = reg
self.buf[1] = (value >> 8) & 0xFF
self.buf[2] = value & 0xFF
with self.i2c_device as i2c:
i2c.write(self.buf) | [
"def",
"_write_register",
"(",
"self",
",",
"reg",
",",
"value",
")",
":",
"self",
".",
"buf",
"[",
"0",
"]",
"=",
"reg",
"self",
".",
"buf",
"[",
"1",
"]",
"=",
"(",
"value",
">>",
"8",
")",
"&",
"0xFF",
"self",
".",
"buf",
"[",
"2",
"]",
... | Write 16 bit value to register. | [
"Write",
"16",
"bit",
"value",
"to",
"register",
"."
] | 5ba760c6de40824386f1df343603eab77d3e336c | https://github.com/adafruit/Adafruit_CircuitPython_ADS1x15/blob/5ba760c6de40824386f1df343603eab77d3e336c/adafruit_ads1x15/ads1x15.py#L179-L185 | train | 207,209 |
adafruit/Adafruit_CircuitPython_ADS1x15 | adafruit_ads1x15/ads1x15.py | ADS1x15._read_register | def _read_register(self, reg):
"""Read 16 bit register value."""
self.buf[0] = reg
with self.i2c_device as i2c:
i2c.write(self.buf, end=1, stop=False)
i2c.readinto(self.buf, end=2)
return self.buf[0] << 8 | self.buf[1] | python | def _read_register(self, reg):
"""Read 16 bit register value."""
self.buf[0] = reg
with self.i2c_device as i2c:
i2c.write(self.buf, end=1, stop=False)
i2c.readinto(self.buf, end=2)
return self.buf[0] << 8 | self.buf[1] | [
"def",
"_read_register",
"(",
"self",
",",
"reg",
")",
":",
"self",
".",
"buf",
"[",
"0",
"]",
"=",
"reg",
"with",
"self",
".",
"i2c_device",
"as",
"i2c",
":",
"i2c",
".",
"write",
"(",
"self",
".",
"buf",
",",
"end",
"=",
"1",
",",
"stop",
"="... | Read 16 bit register value. | [
"Read",
"16",
"bit",
"register",
"value",
"."
] | 5ba760c6de40824386f1df343603eab77d3e336c | https://github.com/adafruit/Adafruit_CircuitPython_ADS1x15/blob/5ba760c6de40824386f1df343603eab77d3e336c/adafruit_ads1x15/ads1x15.py#L187-L193 | train | 207,210 |
adafruit/Adafruit_CircuitPython_ADS1x15 | adafruit_ads1x15/analog_in.py | AnalogIn.value | def value(self):
"""Returns the value of an ADC pin as an integer."""
return self._ads.read(self._pin_setting, is_differential=self.is_differential) | python | def value(self):
"""Returns the value of an ADC pin as an integer."""
return self._ads.read(self._pin_setting, is_differential=self.is_differential) | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"self",
".",
"_ads",
".",
"read",
"(",
"self",
".",
"_pin_setting",
",",
"is_differential",
"=",
"self",
".",
"is_differential",
")"
] | Returns the value of an ADC pin as an integer. | [
"Returns",
"the",
"value",
"of",
"an",
"ADC",
"pin",
"as",
"an",
"integer",
"."
] | 5ba760c6de40824386f1df343603eab77d3e336c | https://github.com/adafruit/Adafruit_CircuitPython_ADS1x15/blob/5ba760c6de40824386f1df343603eab77d3e336c/adafruit_ads1x15/analog_in.py#L71-L73 | train | 207,211 |
adafruit/Adafruit_CircuitPython_ADS1x15 | adafruit_ads1x15/analog_in.py | AnalogIn.voltage | def voltage(self):
"""Returns the voltage from the ADC pin as a floating point value."""
raw = self.value
volts = raw * (_ADS1X15_PGA_RANGE[self._ads.gain] / (2**(self._ads.bits-1) - 1))
return volts | python | def voltage(self):
"""Returns the voltage from the ADC pin as a floating point value."""
raw = self.value
volts = raw * (_ADS1X15_PGA_RANGE[self._ads.gain] / (2**(self._ads.bits-1) - 1))
return volts | [
"def",
"voltage",
"(",
"self",
")",
":",
"raw",
"=",
"self",
".",
"value",
"volts",
"=",
"raw",
"*",
"(",
"_ADS1X15_PGA_RANGE",
"[",
"self",
".",
"_ads",
".",
"gain",
"]",
"/",
"(",
"2",
"**",
"(",
"self",
".",
"_ads",
".",
"bits",
"-",
"1",
")... | Returns the voltage from the ADC pin as a floating point value. | [
"Returns",
"the",
"voltage",
"from",
"the",
"ADC",
"pin",
"as",
"a",
"floating",
"point",
"value",
"."
] | 5ba760c6de40824386f1df343603eab77d3e336c | https://github.com/adafruit/Adafruit_CircuitPython_ADS1x15/blob/5ba760c6de40824386f1df343603eab77d3e336c/adafruit_ads1x15/analog_in.py#L76-L80 | train | 207,212 |
sixpack/sixpack | sixpack/models.py | Experiment.sequential_id | def sequential_id(self, client):
"""Return the sequential id for this test for the passed in client"""
if client.client_id not in self._sequential_ids:
id_ = sequential_id("e:{0}:users".format(self.name), client.client_id)
self._sequential_ids[client.client_id] = id_
return self._sequential_ids[client.client_id] | python | def sequential_id(self, client):
"""Return the sequential id for this test for the passed in client"""
if client.client_id not in self._sequential_ids:
id_ = sequential_id("e:{0}:users".format(self.name), client.client_id)
self._sequential_ids[client.client_id] = id_
return self._sequential_ids[client.client_id] | [
"def",
"sequential_id",
"(",
"self",
",",
"client",
")",
":",
"if",
"client",
".",
"client_id",
"not",
"in",
"self",
".",
"_sequential_ids",
":",
"id_",
"=",
"sequential_id",
"(",
"\"e:{0}:users\"",
".",
"format",
"(",
"self",
".",
"name",
")",
",",
"cli... | Return the sequential id for this test for the passed in client | [
"Return",
"the",
"sequential",
"id",
"for",
"this",
"test",
"for",
"the",
"passed",
"in",
"client"
] | fec044a35eea79dd7b9af73fafe1b7d15f1d9ef8 | https://github.com/sixpack/sixpack/blob/fec044a35eea79dd7b9af73fafe1b7d15f1d9ef8/sixpack/models.py#L315-L320 | train | 207,213 |
sixpack/sixpack | sixpack/models.py | Alternative.record_participation | def record_participation(self, client, dt=None):
"""Record a user's participation in a test along with a given variation"""
if dt is None:
date = datetime.now()
else:
date = dt
experiment_key = self.experiment.name
pipe = self.redis.pipeline()
pipe.sadd(_key("p:{0}:years".format(experiment_key)), date.strftime('%Y'))
pipe.sadd(_key("p:{0}:months".format(experiment_key)), date.strftime('%Y-%m'))
pipe.sadd(_key("p:{0}:days".format(experiment_key)), date.strftime('%Y-%m-%d'))
pipe.execute()
keys = [
_key("p:{0}:_all:all".format(experiment_key)),
_key("p:{0}:_all:{1}".format(experiment_key, date.strftime('%Y'))),
_key("p:{0}:_all:{1}".format(experiment_key, date.strftime('%Y-%m'))),
_key("p:{0}:_all:{1}".format(experiment_key, date.strftime('%Y-%m-%d'))),
_key("p:{0}:{1}:all".format(experiment_key, self.name)),
_key("p:{0}:{1}:{2}".format(experiment_key, self.name, date.strftime('%Y'))),
_key("p:{0}:{1}:{2}".format(experiment_key, self.name, date.strftime('%Y-%m'))),
_key("p:{0}:{1}:{2}".format(experiment_key, self.name, date.strftime('%Y-%m-%d'))),
]
msetbit(keys=keys, args=([self.experiment.sequential_id(client), 1] * len(keys))) | python | def record_participation(self, client, dt=None):
"""Record a user's participation in a test along with a given variation"""
if dt is None:
date = datetime.now()
else:
date = dt
experiment_key = self.experiment.name
pipe = self.redis.pipeline()
pipe.sadd(_key("p:{0}:years".format(experiment_key)), date.strftime('%Y'))
pipe.sadd(_key("p:{0}:months".format(experiment_key)), date.strftime('%Y-%m'))
pipe.sadd(_key("p:{0}:days".format(experiment_key)), date.strftime('%Y-%m-%d'))
pipe.execute()
keys = [
_key("p:{0}:_all:all".format(experiment_key)),
_key("p:{0}:_all:{1}".format(experiment_key, date.strftime('%Y'))),
_key("p:{0}:_all:{1}".format(experiment_key, date.strftime('%Y-%m'))),
_key("p:{0}:_all:{1}".format(experiment_key, date.strftime('%Y-%m-%d'))),
_key("p:{0}:{1}:all".format(experiment_key, self.name)),
_key("p:{0}:{1}:{2}".format(experiment_key, self.name, date.strftime('%Y'))),
_key("p:{0}:{1}:{2}".format(experiment_key, self.name, date.strftime('%Y-%m'))),
_key("p:{0}:{1}:{2}".format(experiment_key, self.name, date.strftime('%Y-%m-%d'))),
]
msetbit(keys=keys, args=([self.experiment.sequential_id(client), 1] * len(keys))) | [
"def",
"record_participation",
"(",
"self",
",",
"client",
",",
"dt",
"=",
"None",
")",
":",
"if",
"dt",
"is",
"None",
":",
"date",
"=",
"datetime",
".",
"now",
"(",
")",
"else",
":",
"date",
"=",
"dt",
"experiment_key",
"=",
"self",
".",
"experiment... | Record a user's participation in a test along with a given variation | [
"Record",
"a",
"user",
"s",
"participation",
"in",
"a",
"test",
"along",
"with",
"a",
"given",
"variation"
] | fec044a35eea79dd7b9af73fafe1b7d15f1d9ef8 | https://github.com/sixpack/sixpack/blob/fec044a35eea79dd7b9af73fafe1b7d15f1d9ef8/sixpack/models.py#L629-L656 | train | 207,214 |
sixpack/sixpack | sixpack/db.py | sequential_id | def sequential_id(k, identifier):
"""Map an arbitrary string identifier to a set of sequential ids"""
key = _key(k)
return int(monotonic_zadd(keys=[key], args=[identifier])) | python | def sequential_id(k, identifier):
"""Map an arbitrary string identifier to a set of sequential ids"""
key = _key(k)
return int(monotonic_zadd(keys=[key], args=[identifier])) | [
"def",
"sequential_id",
"(",
"k",
",",
"identifier",
")",
":",
"key",
"=",
"_key",
"(",
"k",
")",
"return",
"int",
"(",
"monotonic_zadd",
"(",
"keys",
"=",
"[",
"key",
"]",
",",
"args",
"=",
"[",
"identifier",
"]",
")",
")"
] | Map an arbitrary string identifier to a set of sequential ids | [
"Map",
"an",
"arbitrary",
"string",
"identifier",
"to",
"a",
"set",
"of",
"sequential",
"ids"
] | fec044a35eea79dd7b9af73fafe1b7d15f1d9ef8 | https://github.com/sixpack/sixpack/blob/fec044a35eea79dd7b9af73fafe1b7d15f1d9ef8/sixpack/db.py#L46-L49 | train | 207,215 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/emacs.py | load_emacs_open_in_editor_bindings | def load_emacs_open_in_editor_bindings():
"""
Pressing C-X C-E will open the buffer in an external editor.
"""
registry = Registry()
registry.add_binding(Keys.ControlX, Keys.ControlE,
filter=EmacsMode() & ~HasSelection())(
get_by_name('edit-and-execute-command'))
return registry | python | def load_emacs_open_in_editor_bindings():
"""
Pressing C-X C-E will open the buffer in an external editor.
"""
registry = Registry()
registry.add_binding(Keys.ControlX, Keys.ControlE,
filter=EmacsMode() & ~HasSelection())(
get_by_name('edit-and-execute-command'))
return registry | [
"def",
"load_emacs_open_in_editor_bindings",
"(",
")",
":",
"registry",
"=",
"Registry",
"(",
")",
"registry",
".",
"add_binding",
"(",
"Keys",
".",
"ControlX",
",",
"Keys",
".",
"ControlE",
",",
"filter",
"=",
"EmacsMode",
"(",
")",
"&",
"~",
"HasSelection"... | Pressing C-X C-E will open the buffer in an external editor. | [
"Pressing",
"C",
"-",
"X",
"C",
"-",
"E",
"will",
"open",
"the",
"buffer",
"in",
"an",
"external",
"editor",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/emacs.py#L302-L312 | train | 207,216 |
wandb/client | wandb/vendor/prompt_toolkit/eventloop/win32.py | _create_event | def _create_event():
"""
Creates a Win32 unnamed Event .
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx
"""
return windll.kernel32.CreateEventA(pointer(SECURITY_ATTRIBUTES()), BOOL(True), BOOL(False), None) | python | def _create_event():
"""
Creates a Win32 unnamed Event .
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx
"""
return windll.kernel32.CreateEventA(pointer(SECURITY_ATTRIBUTES()), BOOL(True), BOOL(False), None) | [
"def",
"_create_event",
"(",
")",
":",
"return",
"windll",
".",
"kernel32",
".",
"CreateEventA",
"(",
"pointer",
"(",
"SECURITY_ATTRIBUTES",
"(",
")",
")",
",",
"BOOL",
"(",
"True",
")",
",",
"BOOL",
"(",
"False",
")",
",",
"None",
")"
] | Creates a Win32 unnamed Event .
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx | [
"Creates",
"a",
"Win32",
"unnamed",
"Event",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/eventloop/win32.py#L181-L187 | train | 207,217 |
wandb/client | wandb/vendor/prompt_toolkit/eventloop/win32.py | Win32EventLoop._ready_for_reading | def _ready_for_reading(self, timeout=None):
"""
Return the handle that is ready for reading or `None` on timeout.
"""
handles = [self._event, self._console_input_reader.handle]
handles.extend(self._read_fds.keys())
return _wait_for_handles(handles, timeout) | python | def _ready_for_reading(self, timeout=None):
"""
Return the handle that is ready for reading or `None` on timeout.
"""
handles = [self._event, self._console_input_reader.handle]
handles.extend(self._read_fds.keys())
return _wait_for_handles(handles, timeout) | [
"def",
"_ready_for_reading",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"handles",
"=",
"[",
"self",
".",
"_event",
",",
"self",
".",
"_console_input_reader",
".",
"handle",
"]",
"handles",
".",
"extend",
"(",
"self",
".",
"_read_fds",
".",
"key... | Return the handle that is ready for reading or `None` on timeout. | [
"Return",
"the",
"handle",
"that",
"is",
"ready",
"for",
"reading",
"or",
"None",
"on",
"timeout",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/eventloop/win32.py#L97-L103 | train | 207,218 |
wandb/client | wandb/vendor/prompt_toolkit/eventloop/win32.py | Win32EventLoop.add_reader | def add_reader(self, fd, callback):
" Start watching the file descriptor for read availability. "
h = msvcrt.get_osfhandle(fd)
self._read_fds[h] = callback | python | def add_reader(self, fd, callback):
" Start watching the file descriptor for read availability. "
h = msvcrt.get_osfhandle(fd)
self._read_fds[h] = callback | [
"def",
"add_reader",
"(",
"self",
",",
"fd",
",",
"callback",
")",
":",
"h",
"=",
"msvcrt",
".",
"get_osfhandle",
"(",
"fd",
")",
"self",
".",
"_read_fds",
"[",
"h",
"]",
"=",
"callback"
] | Start watching the file descriptor for read availability. | [
"Start",
"watching",
"the",
"file",
"descriptor",
"for",
"read",
"availability",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/eventloop/win32.py#L149-L152 | train | 207,219 |
wandb/client | wandb/vendor/prompt_toolkit/eventloop/win32.py | Win32EventLoop.remove_reader | def remove_reader(self, fd):
" Stop watching the file descriptor for read availability. "
h = msvcrt.get_osfhandle(fd)
if h in self._read_fds:
del self._read_fds[h] | python | def remove_reader(self, fd):
" Stop watching the file descriptor for read availability. "
h = msvcrt.get_osfhandle(fd)
if h in self._read_fds:
del self._read_fds[h] | [
"def",
"remove_reader",
"(",
"self",
",",
"fd",
")",
":",
"h",
"=",
"msvcrt",
".",
"get_osfhandle",
"(",
"fd",
")",
"if",
"h",
"in",
"self",
".",
"_read_fds",
":",
"del",
"self",
".",
"_read_fds",
"[",
"h",
"]"
] | Stop watching the file descriptor for read availability. | [
"Stop",
"watching",
"the",
"file",
"descriptor",
"for",
"read",
"availability",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/eventloop/win32.py#L154-L158 | train | 207,220 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | AcceptAction.validate_and_handle | def validate_and_handle(self, cli, buffer):
"""
Validate buffer and handle the accept action.
"""
if buffer.validate():
if self.handler:
self.handler(cli, buffer)
buffer.append_to_history() | python | def validate_and_handle(self, cli, buffer):
"""
Validate buffer and handle the accept action.
"""
if buffer.validate():
if self.handler:
self.handler(cli, buffer)
buffer.append_to_history() | [
"def",
"validate_and_handle",
"(",
"self",
",",
"cli",
",",
"buffer",
")",
":",
"if",
"buffer",
".",
"validate",
"(",
")",
":",
"if",
"self",
".",
"handler",
":",
"self",
".",
"handler",
"(",
"cli",
",",
"buffer",
")",
"buffer",
".",
"append_to_history... | Validate buffer and handle the accept action. | [
"Validate",
"buffer",
"and",
"handle",
"the",
"accept",
"action",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L78-L86 | train | 207,221 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer._set_text | def _set_text(self, value):
""" set text at current working_index. Return whether it changed. """
working_index = self.working_index
working_lines = self._working_lines
original_value = working_lines[working_index]
working_lines[working_index] = value
# Return True when this text has been changed.
if len(value) != len(original_value):
# For Python 2, it seems that when two strings have a different
# length and one is a prefix of the other, Python still scans
# character by character to see whether the strings are different.
# (Some benchmarking showed significant differences for big
# documents. >100,000 of lines.)
return True
elif value != original_value:
return True
return False | python | def _set_text(self, value):
""" set text at current working_index. Return whether it changed. """
working_index = self.working_index
working_lines = self._working_lines
original_value = working_lines[working_index]
working_lines[working_index] = value
# Return True when this text has been changed.
if len(value) != len(original_value):
# For Python 2, it seems that when two strings have a different
# length and one is a prefix of the other, Python still scans
# character by character to see whether the strings are different.
# (Some benchmarking showed significant differences for big
# documents. >100,000 of lines.)
return True
elif value != original_value:
return True
return False | [
"def",
"_set_text",
"(",
"self",
",",
"value",
")",
":",
"working_index",
"=",
"self",
".",
"working_index",
"working_lines",
"=",
"self",
".",
"_working_lines",
"original_value",
"=",
"working_lines",
"[",
"working_index",
"]",
"working_lines",
"[",
"working_inde... | set text at current working_index. Return whether it changed. | [
"set",
"text",
"at",
"current",
"working_index",
".",
"Return",
"whether",
"it",
"changed",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L333-L351 | train | 207,222 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer._set_cursor_position | def _set_cursor_position(self, value):
""" Set cursor position. Return whether it changed. """
original_position = self.__cursor_position
self.__cursor_position = max(0, value)
return value != original_position | python | def _set_cursor_position(self, value):
""" Set cursor position. Return whether it changed. """
original_position = self.__cursor_position
self.__cursor_position = max(0, value)
return value != original_position | [
"def",
"_set_cursor_position",
"(",
"self",
",",
"value",
")",
":",
"original_position",
"=",
"self",
".",
"__cursor_position",
"self",
".",
"__cursor_position",
"=",
"max",
"(",
"0",
",",
"value",
")",
"return",
"value",
"!=",
"original_position"
] | Set cursor position. Return whether it changed. | [
"Set",
"cursor",
"position",
".",
"Return",
"whether",
"it",
"changed",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L353-L358 | train | 207,223 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.cursor_position | def cursor_position(self, value):
"""
Setting cursor position.
"""
assert isinstance(value, int)
assert value <= len(self.text)
changed = self._set_cursor_position(value)
if changed:
self._cursor_position_changed() | python | def cursor_position(self, value):
"""
Setting cursor position.
"""
assert isinstance(value, int)
assert value <= len(self.text)
changed = self._set_cursor_position(value)
if changed:
self._cursor_position_changed() | [
"def",
"cursor_position",
"(",
"self",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"int",
")",
"assert",
"value",
"<=",
"len",
"(",
"self",
".",
"text",
")",
"changed",
"=",
"self",
".",
"_set_cursor_position",
"(",
"value",
")",
... | Setting cursor position. | [
"Setting",
"cursor",
"position",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L391-L401 | train | 207,224 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.transform_lines | def transform_lines(self, line_index_iterator, transform_callback):
"""
Transforms the text on a range of lines.
When the iterator yield an index not in the range of lines that the
document contains, it skips them silently.
To uppercase some lines::
new_text = transform_lines(range(5,10), lambda text: text.upper())
:param line_index_iterator: Iterator of line numbers (int)
:param transform_callback: callable that takes the original text of a
line, and return the new text for this line.
:returns: The new text.
"""
# Split lines
lines = self.text.split('\n')
# Apply transformation
for index in line_index_iterator:
try:
lines[index] = transform_callback(lines[index])
except IndexError:
pass
return '\n'.join(lines) | python | def transform_lines(self, line_index_iterator, transform_callback):
"""
Transforms the text on a range of lines.
When the iterator yield an index not in the range of lines that the
document contains, it skips them silently.
To uppercase some lines::
new_text = transform_lines(range(5,10), lambda text: text.upper())
:param line_index_iterator: Iterator of line numbers (int)
:param transform_callback: callable that takes the original text of a
line, and return the new text for this line.
:returns: The new text.
"""
# Split lines
lines = self.text.split('\n')
# Apply transformation
for index in line_index_iterator:
try:
lines[index] = transform_callback(lines[index])
except IndexError:
pass
return '\n'.join(lines) | [
"def",
"transform_lines",
"(",
"self",
",",
"line_index_iterator",
",",
"transform_callback",
")",
":",
"# Split lines",
"lines",
"=",
"self",
".",
"text",
".",
"split",
"(",
"'\\n'",
")",
"# Apply transformation",
"for",
"index",
"in",
"line_index_iterator",
":",... | Transforms the text on a range of lines.
When the iterator yield an index not in the range of lines that the
document contains, it skips them silently.
To uppercase some lines::
new_text = transform_lines(range(5,10), lambda text: text.upper())
:param line_index_iterator: Iterator of line numbers (int)
:param transform_callback: callable that takes the original text of a
line, and return the new text for this line.
:returns: The new text. | [
"Transforms",
"the",
"text",
"on",
"a",
"range",
"of",
"lines",
".",
"When",
"the",
"iterator",
"yield",
"an",
"index",
"not",
"in",
"the",
"range",
"of",
"lines",
"that",
"the",
"document",
"contains",
"it",
"skips",
"them",
"silently",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L509-L535 | train | 207,225 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.transform_current_line | def transform_current_line(self, transform_callback):
"""
Apply the given transformation function to the current line.
:param transform_callback: callable that takes a string and return a new string.
"""
document = self.document
a = document.cursor_position + document.get_start_of_line_position()
b = document.cursor_position + document.get_end_of_line_position()
self.text = (
document.text[:a] +
transform_callback(document.text[a:b]) +
document.text[b:]) | python | def transform_current_line(self, transform_callback):
"""
Apply the given transformation function to the current line.
:param transform_callback: callable that takes a string and return a new string.
"""
document = self.document
a = document.cursor_position + document.get_start_of_line_position()
b = document.cursor_position + document.get_end_of_line_position()
self.text = (
document.text[:a] +
transform_callback(document.text[a:b]) +
document.text[b:]) | [
"def",
"transform_current_line",
"(",
"self",
",",
"transform_callback",
")",
":",
"document",
"=",
"self",
".",
"document",
"a",
"=",
"document",
".",
"cursor_position",
"+",
"document",
".",
"get_start_of_line_position",
"(",
")",
"b",
"=",
"document",
".",
... | Apply the given transformation function to the current line.
:param transform_callback: callable that takes a string and return a new string. | [
"Apply",
"the",
"given",
"transformation",
"function",
"to",
"the",
"current",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L537-L549 | train | 207,226 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.transform_region | def transform_region(self, from_, to, transform_callback):
"""
Transform a part of the input string.
:param from_: (int) start position.
:param to: (int) end position.
:param transform_callback: Callable which accepts a string and returns
the transformed string.
"""
assert from_ < to
self.text = ''.join([
self.text[:from_] +
transform_callback(self.text[from_:to]) +
self.text[to:]
]) | python | def transform_region(self, from_, to, transform_callback):
"""
Transform a part of the input string.
:param from_: (int) start position.
:param to: (int) end position.
:param transform_callback: Callable which accepts a string and returns
the transformed string.
"""
assert from_ < to
self.text = ''.join([
self.text[:from_] +
transform_callback(self.text[from_:to]) +
self.text[to:]
]) | [
"def",
"transform_region",
"(",
"self",
",",
"from_",
",",
"to",
",",
"transform_callback",
")",
":",
"assert",
"from_",
"<",
"to",
"self",
".",
"text",
"=",
"''",
".",
"join",
"(",
"[",
"self",
".",
"text",
"[",
":",
"from_",
"]",
"+",
"transform_ca... | Transform a part of the input string.
:param from_: (int) start position.
:param to: (int) end position.
:param transform_callback: Callable which accepts a string and returns
the transformed string. | [
"Transform",
"a",
"part",
"of",
"the",
"input",
"string",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L551-L566 | train | 207,227 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.delete_before_cursor | def delete_before_cursor(self, count=1):
"""
Delete specified number of characters before cursor and return the
deleted text.
"""
assert count >= 0
deleted = ''
if self.cursor_position > 0:
deleted = self.text[self.cursor_position - count:self.cursor_position]
new_text = self.text[:self.cursor_position - count] + self.text[self.cursor_position:]
new_cursor_position = self.cursor_position - len(deleted)
# Set new Document atomically.
self.document = Document(new_text, new_cursor_position)
return deleted | python | def delete_before_cursor(self, count=1):
"""
Delete specified number of characters before cursor and return the
deleted text.
"""
assert count >= 0
deleted = ''
if self.cursor_position > 0:
deleted = self.text[self.cursor_position - count:self.cursor_position]
new_text = self.text[:self.cursor_position - count] + self.text[self.cursor_position:]
new_cursor_position = self.cursor_position - len(deleted)
# Set new Document atomically.
self.document = Document(new_text, new_cursor_position)
return deleted | [
"def",
"delete_before_cursor",
"(",
"self",
",",
"count",
"=",
"1",
")",
":",
"assert",
"count",
">=",
"0",
"deleted",
"=",
"''",
"if",
"self",
".",
"cursor_position",
">",
"0",
":",
"deleted",
"=",
"self",
".",
"text",
"[",
"self",
".",
"cursor_positi... | Delete specified number of characters before cursor and return the
deleted text. | [
"Delete",
"specified",
"number",
"of",
"characters",
"before",
"cursor",
"and",
"return",
"the",
"deleted",
"text",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L624-L641 | train | 207,228 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.delete | def delete(self, count=1):
"""
Delete specified number of characters and Return the deleted text.
"""
if self.cursor_position < len(self.text):
deleted = self.document.text_after_cursor[:count]
self.text = self.text[:self.cursor_position] + \
self.text[self.cursor_position + len(deleted):]
return deleted
else:
return '' | python | def delete(self, count=1):
"""
Delete specified number of characters and Return the deleted text.
"""
if self.cursor_position < len(self.text):
deleted = self.document.text_after_cursor[:count]
self.text = self.text[:self.cursor_position] + \
self.text[self.cursor_position + len(deleted):]
return deleted
else:
return '' | [
"def",
"delete",
"(",
"self",
",",
"count",
"=",
"1",
")",
":",
"if",
"self",
".",
"cursor_position",
"<",
"len",
"(",
"self",
".",
"text",
")",
":",
"deleted",
"=",
"self",
".",
"document",
".",
"text_after_cursor",
"[",
":",
"count",
"]",
"self",
... | Delete specified number of characters and Return the deleted text. | [
"Delete",
"specified",
"number",
"of",
"characters",
"and",
"Return",
"the",
"deleted",
"text",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L643-L653 | train | 207,229 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.join_next_line | def join_next_line(self, separator=' '):
"""
Join the next line to the current one by deleting the line ending after
the current line.
"""
if not self.document.on_last_line:
self.cursor_position += self.document.get_end_of_line_position()
self.delete()
# Remove spaces.
self.text = (self.document.text_before_cursor + separator +
self.document.text_after_cursor.lstrip(' ')) | python | def join_next_line(self, separator=' '):
"""
Join the next line to the current one by deleting the line ending after
the current line.
"""
if not self.document.on_last_line:
self.cursor_position += self.document.get_end_of_line_position()
self.delete()
# Remove spaces.
self.text = (self.document.text_before_cursor + separator +
self.document.text_after_cursor.lstrip(' ')) | [
"def",
"join_next_line",
"(",
"self",
",",
"separator",
"=",
"' '",
")",
":",
"if",
"not",
"self",
".",
"document",
".",
"on_last_line",
":",
"self",
".",
"cursor_position",
"+=",
"self",
".",
"document",
".",
"get_end_of_line_position",
"(",
")",
"self",
... | Join the next line to the current one by deleting the line ending after
the current line. | [
"Join",
"the",
"next",
"line",
"to",
"the",
"current",
"one",
"by",
"deleting",
"the",
"line",
"ending",
"after",
"the",
"current",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L655-L666 | train | 207,230 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.join_selected_lines | def join_selected_lines(self, separator=' '):
"""
Join the selected lines.
"""
assert self.selection_state
# Get lines.
from_, to = sorted([self.cursor_position, self.selection_state.original_cursor_position])
before = self.text[:from_]
lines = self.text[from_:to].splitlines()
after = self.text[to:]
# Replace leading spaces with just one space.
lines = [l.lstrip(' ') + separator for l in lines]
# Set new document.
self.document = Document(text=before + ''.join(lines) + after,
cursor_position=len(before + ''.join(lines[:-1])) - 1) | python | def join_selected_lines(self, separator=' '):
"""
Join the selected lines.
"""
assert self.selection_state
# Get lines.
from_, to = sorted([self.cursor_position, self.selection_state.original_cursor_position])
before = self.text[:from_]
lines = self.text[from_:to].splitlines()
after = self.text[to:]
# Replace leading spaces with just one space.
lines = [l.lstrip(' ') + separator for l in lines]
# Set new document.
self.document = Document(text=before + ''.join(lines) + after,
cursor_position=len(before + ''.join(lines[:-1])) - 1) | [
"def",
"join_selected_lines",
"(",
"self",
",",
"separator",
"=",
"' '",
")",
":",
"assert",
"self",
".",
"selection_state",
"# Get lines.",
"from_",
",",
"to",
"=",
"sorted",
"(",
"[",
"self",
".",
"cursor_position",
",",
"self",
".",
"selection_state",
"."... | Join the selected lines. | [
"Join",
"the",
"selected",
"lines",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L668-L686 | train | 207,231 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.swap_characters_before_cursor | def swap_characters_before_cursor(self):
"""
Swap the last two characters before the cursor.
"""
pos = self.cursor_position
if pos >= 2:
a = self.text[pos - 2]
b = self.text[pos - 1]
self.text = self.text[:pos-2] + b + a + self.text[pos:] | python | def swap_characters_before_cursor(self):
"""
Swap the last two characters before the cursor.
"""
pos = self.cursor_position
if pos >= 2:
a = self.text[pos - 2]
b = self.text[pos - 1]
self.text = self.text[:pos-2] + b + a + self.text[pos:] | [
"def",
"swap_characters_before_cursor",
"(",
"self",
")",
":",
"pos",
"=",
"self",
".",
"cursor_position",
"if",
"pos",
">=",
"2",
":",
"a",
"=",
"self",
".",
"text",
"[",
"pos",
"-",
"2",
"]",
"b",
"=",
"self",
".",
"text",
"[",
"pos",
"-",
"1",
... | Swap the last two characters before the cursor. | [
"Swap",
"the",
"last",
"two",
"characters",
"before",
"the",
"cursor",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L688-L698 | train | 207,232 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.go_to_history | def go_to_history(self, index):
"""
Go to this item in the history.
"""
if index < len(self._working_lines):
self.working_index = index
self.cursor_position = len(self.text) | python | def go_to_history(self, index):
"""
Go to this item in the history.
"""
if index < len(self._working_lines):
self.working_index = index
self.cursor_position = len(self.text) | [
"def",
"go_to_history",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"<",
"len",
"(",
"self",
".",
"_working_lines",
")",
":",
"self",
".",
"working_index",
"=",
"index",
"self",
".",
"cursor_position",
"=",
"len",
"(",
"self",
".",
"text",
")"
... | Go to this item in the history. | [
"Go",
"to",
"this",
"item",
"in",
"the",
"history",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L700-L706 | train | 207,233 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.start_history_lines_completion | def start_history_lines_completion(self):
"""
Start a completion based on all the other lines in the document and the
history.
"""
found_completions = set()
completions = []
# For every line of the whole history, find matches with the current line.
current_line = self.document.current_line_before_cursor.lstrip()
for i, string in enumerate(self._working_lines):
for j, l in enumerate(string.split('\n')):
l = l.strip()
if l and l.startswith(current_line):
# When a new line has been found.
if l not in found_completions:
found_completions.add(l)
# Create completion.
if i == self.working_index:
display_meta = "Current, line %s" % (j+1)
else:
display_meta = "History %s, line %s" % (i+1, j+1)
completions.append(Completion(
l,
start_position=-len(current_line),
display_meta=display_meta))
self.set_completions(completions=completions[::-1]) | python | def start_history_lines_completion(self):
"""
Start a completion based on all the other lines in the document and the
history.
"""
found_completions = set()
completions = []
# For every line of the whole history, find matches with the current line.
current_line = self.document.current_line_before_cursor.lstrip()
for i, string in enumerate(self._working_lines):
for j, l in enumerate(string.split('\n')):
l = l.strip()
if l and l.startswith(current_line):
# When a new line has been found.
if l not in found_completions:
found_completions.add(l)
# Create completion.
if i == self.working_index:
display_meta = "Current, line %s" % (j+1)
else:
display_meta = "History %s, line %s" % (i+1, j+1)
completions.append(Completion(
l,
start_position=-len(current_line),
display_meta=display_meta))
self.set_completions(completions=completions[::-1]) | [
"def",
"start_history_lines_completion",
"(",
"self",
")",
":",
"found_completions",
"=",
"set",
"(",
")",
"completions",
"=",
"[",
"]",
"# For every line of the whole history, find matches with the current line.",
"current_line",
"=",
"self",
".",
"document",
".",
"curre... | Start a completion based on all the other lines in the document and the
history. | [
"Start",
"a",
"completion",
"based",
"on",
"all",
"the",
"other",
"lines",
"in",
"the",
"document",
"and",
"the",
"history",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L784-L814 | train | 207,234 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.go_to_completion | def go_to_completion(self, index):
"""
Select a completion from the list of current completions.
"""
assert index is None or isinstance(index, int)
assert self.complete_state
# Set new completion
state = self.complete_state.go_to_index(index)
# Set text/cursor position
new_text, new_cursor_position = state.new_text_and_position()
self.document = Document(new_text, new_cursor_position)
# (changing text/cursor position will unset complete_state.)
self.complete_state = state | python | def go_to_completion(self, index):
"""
Select a completion from the list of current completions.
"""
assert index is None or isinstance(index, int)
assert self.complete_state
# Set new completion
state = self.complete_state.go_to_index(index)
# Set text/cursor position
new_text, new_cursor_position = state.new_text_and_position()
self.document = Document(new_text, new_cursor_position)
# (changing text/cursor position will unset complete_state.)
self.complete_state = state | [
"def",
"go_to_completion",
"(",
"self",
",",
"index",
")",
":",
"assert",
"index",
"is",
"None",
"or",
"isinstance",
"(",
"index",
",",
"int",
")",
"assert",
"self",
".",
"complete_state",
"# Set new completion",
"state",
"=",
"self",
".",
"complete_state",
... | Select a completion from the list of current completions. | [
"Select",
"a",
"completion",
"from",
"the",
"list",
"of",
"current",
"completions",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L816-L831 | train | 207,235 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.apply_completion | def apply_completion(self, completion):
"""
Insert a given completion.
"""
assert isinstance(completion, Completion)
# If there was already a completion active, cancel that one.
if self.complete_state:
self.go_to_completion(None)
self.complete_state = None
# Insert text from the given completion.
self.delete_before_cursor(-completion.start_position)
self.insert_text(completion.text) | python | def apply_completion(self, completion):
"""
Insert a given completion.
"""
assert isinstance(completion, Completion)
# If there was already a completion active, cancel that one.
if self.complete_state:
self.go_to_completion(None)
self.complete_state = None
# Insert text from the given completion.
self.delete_before_cursor(-completion.start_position)
self.insert_text(completion.text) | [
"def",
"apply_completion",
"(",
"self",
",",
"completion",
")",
":",
"assert",
"isinstance",
"(",
"completion",
",",
"Completion",
")",
"# If there was already a completion active, cancel that one.",
"if",
"self",
".",
"complete_state",
":",
"self",
".",
"go_to_completi... | Insert a given completion. | [
"Insert",
"a",
"given",
"completion",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L833-L846 | train | 207,236 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer._set_history_search | def _set_history_search(self):
""" Set `history_search_text`. """
if self.enable_history_search():
if self.history_search_text is None:
self.history_search_text = self.document.text_before_cursor
else:
self.history_search_text = None | python | def _set_history_search(self):
""" Set `history_search_text`. """
if self.enable_history_search():
if self.history_search_text is None:
self.history_search_text = self.document.text_before_cursor
else:
self.history_search_text = None | [
"def",
"_set_history_search",
"(",
"self",
")",
":",
"if",
"self",
".",
"enable_history_search",
"(",
")",
":",
"if",
"self",
".",
"history_search_text",
"is",
"None",
":",
"self",
".",
"history_search_text",
"=",
"self",
".",
"document",
".",
"text_before_cur... | Set `history_search_text`. | [
"Set",
"history_search_text",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L848-L854 | train | 207,237 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.history_forward | def history_forward(self, count=1):
"""
Move forwards through the history.
:param count: Amount of items to move forward.
"""
self._set_history_search()
# Go forward in history.
found_something = False
for i in range(self.working_index + 1, len(self._working_lines)):
if self._history_matches(i):
self.working_index = i
count -= 1
found_something = True
if count == 0:
break
# If we found an entry, move cursor to the end of the first line.
if found_something:
self.cursor_position = 0
self.cursor_position += self.document.get_end_of_line_position() | python | def history_forward(self, count=1):
"""
Move forwards through the history.
:param count: Amount of items to move forward.
"""
self._set_history_search()
# Go forward in history.
found_something = False
for i in range(self.working_index + 1, len(self._working_lines)):
if self._history_matches(i):
self.working_index = i
count -= 1
found_something = True
if count == 0:
break
# If we found an entry, move cursor to the end of the first line.
if found_something:
self.cursor_position = 0
self.cursor_position += self.document.get_end_of_line_position() | [
"def",
"history_forward",
"(",
"self",
",",
"count",
"=",
"1",
")",
":",
"self",
".",
"_set_history_search",
"(",
")",
"# Go forward in history.",
"found_something",
"=",
"False",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"working_index",
"+",
"1",
",",
... | Move forwards through the history.
:param count: Amount of items to move forward. | [
"Move",
"forwards",
"through",
"the",
"history",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L864-L886 | train | 207,238 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.history_backward | def history_backward(self, count=1):
"""
Move backwards through history.
"""
self._set_history_search()
# Go back in history.
found_something = False
for i in range(self.working_index - 1, -1, -1):
if self._history_matches(i):
self.working_index = i
count -= 1
found_something = True
if count == 0:
break
# If we move to another entry, move cursor to the end of the line.
if found_something:
self.cursor_position = len(self.text) | python | def history_backward(self, count=1):
"""
Move backwards through history.
"""
self._set_history_search()
# Go back in history.
found_something = False
for i in range(self.working_index - 1, -1, -1):
if self._history_matches(i):
self.working_index = i
count -= 1
found_something = True
if count == 0:
break
# If we move to another entry, move cursor to the end of the line.
if found_something:
self.cursor_position = len(self.text) | [
"def",
"history_backward",
"(",
"self",
",",
"count",
"=",
"1",
")",
":",
"self",
".",
"_set_history_search",
"(",
")",
"# Go back in history.",
"found_something",
"=",
"False",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"working_index",
"-",
"1",
",",
"... | Move backwards through history. | [
"Move",
"backwards",
"through",
"history",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L888-L907 | train | 207,239 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.start_selection | def start_selection(self, selection_type=SelectionType.CHARACTERS):
"""
Take the current cursor position as the start of this selection.
"""
self.selection_state = SelectionState(self.cursor_position, selection_type) | python | def start_selection(self, selection_type=SelectionType.CHARACTERS):
"""
Take the current cursor position as the start of this selection.
"""
self.selection_state = SelectionState(self.cursor_position, selection_type) | [
"def",
"start_selection",
"(",
"self",
",",
"selection_type",
"=",
"SelectionType",
".",
"CHARACTERS",
")",
":",
"self",
".",
"selection_state",
"=",
"SelectionState",
"(",
"self",
".",
"cursor_position",
",",
"selection_type",
")"
] | Take the current cursor position as the start of this selection. | [
"Take",
"the",
"current",
"cursor",
"position",
"as",
"the",
"start",
"of",
"this",
"selection",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L966-L970 | train | 207,240 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.paste_clipboard_data | def paste_clipboard_data(self, data, paste_mode=PasteMode.EMACS, count=1):
"""
Insert the data from the clipboard.
"""
assert isinstance(data, ClipboardData)
assert paste_mode in (PasteMode.VI_BEFORE, PasteMode.VI_AFTER, PasteMode.EMACS)
original_document = self.document
self.document = self.document.paste_clipboard_data(data, paste_mode=paste_mode, count=count)
# Remember original document. This assignment should come at the end,
# because assigning to 'document' will erase it.
self.document_before_paste = original_document | python | def paste_clipboard_data(self, data, paste_mode=PasteMode.EMACS, count=1):
"""
Insert the data from the clipboard.
"""
assert isinstance(data, ClipboardData)
assert paste_mode in (PasteMode.VI_BEFORE, PasteMode.VI_AFTER, PasteMode.EMACS)
original_document = self.document
self.document = self.document.paste_clipboard_data(data, paste_mode=paste_mode, count=count)
# Remember original document. This assignment should come at the end,
# because assigning to 'document' will erase it.
self.document_before_paste = original_document | [
"def",
"paste_clipboard_data",
"(",
"self",
",",
"data",
",",
"paste_mode",
"=",
"PasteMode",
".",
"EMACS",
",",
"count",
"=",
"1",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"ClipboardData",
")",
"assert",
"paste_mode",
"in",
"(",
"PasteMode",
".... | Insert the data from the clipboard. | [
"Insert",
"the",
"data",
"from",
"the",
"clipboard",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L989-L1001 | train | 207,241 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.newline | def newline(self, copy_margin=True):
"""
Insert a line ending at the current position.
"""
if copy_margin:
self.insert_text('\n' + self.document.leading_whitespace_in_current_line)
else:
self.insert_text('\n') | python | def newline(self, copy_margin=True):
"""
Insert a line ending at the current position.
"""
if copy_margin:
self.insert_text('\n' + self.document.leading_whitespace_in_current_line)
else:
self.insert_text('\n') | [
"def",
"newline",
"(",
"self",
",",
"copy_margin",
"=",
"True",
")",
":",
"if",
"copy_margin",
":",
"self",
".",
"insert_text",
"(",
"'\\n'",
"+",
"self",
".",
"document",
".",
"leading_whitespace_in_current_line",
")",
"else",
":",
"self",
".",
"insert_text... | Insert a line ending at the current position. | [
"Insert",
"a",
"line",
"ending",
"at",
"the",
"current",
"position",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L1003-L1010 | train | 207,242 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.insert_line_above | def insert_line_above(self, copy_margin=True):
"""
Insert a new line above the current one.
"""
if copy_margin:
insert = self.document.leading_whitespace_in_current_line + '\n'
else:
insert = '\n'
self.cursor_position += self.document.get_start_of_line_position()
self.insert_text(insert)
self.cursor_position -= 1 | python | def insert_line_above(self, copy_margin=True):
"""
Insert a new line above the current one.
"""
if copy_margin:
insert = self.document.leading_whitespace_in_current_line + '\n'
else:
insert = '\n'
self.cursor_position += self.document.get_start_of_line_position()
self.insert_text(insert)
self.cursor_position -= 1 | [
"def",
"insert_line_above",
"(",
"self",
",",
"copy_margin",
"=",
"True",
")",
":",
"if",
"copy_margin",
":",
"insert",
"=",
"self",
".",
"document",
".",
"leading_whitespace_in_current_line",
"+",
"'\\n'",
"else",
":",
"insert",
"=",
"'\\n'",
"self",
".",
"... | Insert a new line above the current one. | [
"Insert",
"a",
"new",
"line",
"above",
"the",
"current",
"one",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L1012-L1023 | train | 207,243 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.insert_line_below | def insert_line_below(self, copy_margin=True):
"""
Insert a new line below the current one.
"""
if copy_margin:
insert = '\n' + self.document.leading_whitespace_in_current_line
else:
insert = '\n'
self.cursor_position += self.document.get_end_of_line_position()
self.insert_text(insert) | python | def insert_line_below(self, copy_margin=True):
"""
Insert a new line below the current one.
"""
if copy_margin:
insert = '\n' + self.document.leading_whitespace_in_current_line
else:
insert = '\n'
self.cursor_position += self.document.get_end_of_line_position()
self.insert_text(insert) | [
"def",
"insert_line_below",
"(",
"self",
",",
"copy_margin",
"=",
"True",
")",
":",
"if",
"copy_margin",
":",
"insert",
"=",
"'\\n'",
"+",
"self",
".",
"document",
".",
"leading_whitespace_in_current_line",
"else",
":",
"insert",
"=",
"'\\n'",
"self",
".",
"... | Insert a new line below the current one. | [
"Insert",
"a",
"new",
"line",
"below",
"the",
"current",
"one",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L1025-L1035 | train | 207,244 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.insert_text | def insert_text(self, data, overwrite=False, move_cursor=True, fire_event=True):
"""
Insert characters at cursor position.
:param fire_event: Fire `on_text_insert` event. This is mainly used to
trigger autocompletion while typing.
"""
# Original text & cursor position.
otext = self.text
ocpos = self.cursor_position
# In insert/text mode.
if overwrite:
# Don't overwrite the newline itself. Just before the line ending,
# it should act like insert mode.
overwritten_text = otext[ocpos:ocpos + len(data)]
if '\n' in overwritten_text:
overwritten_text = overwritten_text[:overwritten_text.find('\n')]
self.text = otext[:ocpos] + data + otext[ocpos + len(overwritten_text):]
else:
self.text = otext[:ocpos] + data + otext[ocpos:]
if move_cursor:
self.cursor_position += len(data)
# Fire 'on_text_insert' event.
if fire_event:
self.on_text_insert.fire() | python | def insert_text(self, data, overwrite=False, move_cursor=True, fire_event=True):
"""
Insert characters at cursor position.
:param fire_event: Fire `on_text_insert` event. This is mainly used to
trigger autocompletion while typing.
"""
# Original text & cursor position.
otext = self.text
ocpos = self.cursor_position
# In insert/text mode.
if overwrite:
# Don't overwrite the newline itself. Just before the line ending,
# it should act like insert mode.
overwritten_text = otext[ocpos:ocpos + len(data)]
if '\n' in overwritten_text:
overwritten_text = overwritten_text[:overwritten_text.find('\n')]
self.text = otext[:ocpos] + data + otext[ocpos + len(overwritten_text):]
else:
self.text = otext[:ocpos] + data + otext[ocpos:]
if move_cursor:
self.cursor_position += len(data)
# Fire 'on_text_insert' event.
if fire_event:
self.on_text_insert.fire() | [
"def",
"insert_text",
"(",
"self",
",",
"data",
",",
"overwrite",
"=",
"False",
",",
"move_cursor",
"=",
"True",
",",
"fire_event",
"=",
"True",
")",
":",
"# Original text & cursor position.",
"otext",
"=",
"self",
".",
"text",
"ocpos",
"=",
"self",
".",
"... | Insert characters at cursor position.
:param fire_event: Fire `on_text_insert` event. This is mainly used to
trigger autocompletion while typing. | [
"Insert",
"characters",
"at",
"cursor",
"position",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L1037-L1065 | train | 207,245 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.validate | def validate(self):
"""
Returns `True` if valid.
"""
# Don't call the validator again, if it was already called for the
# current input.
if self.validation_state != ValidationState.UNKNOWN:
return self.validation_state == ValidationState.VALID
# Validate first. If not valid, set validation exception.
if self.validator:
try:
self.validator.validate(self.document)
except ValidationError as e:
# Set cursor position (don't allow invalid values.)
cursor_position = e.cursor_position
self.cursor_position = min(max(0, cursor_position), len(self.text))
self.validation_state = ValidationState.INVALID
self.validation_error = e
return False
self.validation_state = ValidationState.VALID
self.validation_error = None
return True | python | def validate(self):
"""
Returns `True` if valid.
"""
# Don't call the validator again, if it was already called for the
# current input.
if self.validation_state != ValidationState.UNKNOWN:
return self.validation_state == ValidationState.VALID
# Validate first. If not valid, set validation exception.
if self.validator:
try:
self.validator.validate(self.document)
except ValidationError as e:
# Set cursor position (don't allow invalid values.)
cursor_position = e.cursor_position
self.cursor_position = min(max(0, cursor_position), len(self.text))
self.validation_state = ValidationState.INVALID
self.validation_error = e
return False
self.validation_state = ValidationState.VALID
self.validation_error = None
return True | [
"def",
"validate",
"(",
"self",
")",
":",
"# Don't call the validator again, if it was already called for the",
"# current input.",
"if",
"self",
".",
"validation_state",
"!=",
"ValidationState",
".",
"UNKNOWN",
":",
"return",
"self",
".",
"validation_state",
"==",
"Valid... | Returns `True` if valid. | [
"Returns",
"True",
"if",
"valid",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L1092-L1116 | train | 207,246 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer.open_in_editor | def open_in_editor(self, cli):
"""
Open code in editor.
:param cli: :class:`~prompt_toolkit.interface.CommandLineInterface`
instance.
"""
if self.read_only():
raise EditReadOnlyBuffer()
# Write to temporary file
descriptor, filename = tempfile.mkstemp(self.tempfile_suffix)
os.write(descriptor, self.text.encode('utf-8'))
os.close(descriptor)
# Open in editor
# (We need to use `cli.run_in_terminal`, because not all editors go to
# the alternate screen buffer, and some could influence the cursor
# position.)
succes = cli.run_in_terminal(lambda: self._open_file_in_editor(filename))
# Read content again.
if succes:
with open(filename, 'rb') as f:
text = f.read().decode('utf-8')
# Drop trailing newline. (Editors are supposed to add it at the
# end, but we don't need it.)
if text.endswith('\n'):
text = text[:-1]
self.document = Document(
text=text,
cursor_position=len(text))
# Clean up temp file.
os.remove(filename) | python | def open_in_editor(self, cli):
"""
Open code in editor.
:param cli: :class:`~prompt_toolkit.interface.CommandLineInterface`
instance.
"""
if self.read_only():
raise EditReadOnlyBuffer()
# Write to temporary file
descriptor, filename = tempfile.mkstemp(self.tempfile_suffix)
os.write(descriptor, self.text.encode('utf-8'))
os.close(descriptor)
# Open in editor
# (We need to use `cli.run_in_terminal`, because not all editors go to
# the alternate screen buffer, and some could influence the cursor
# position.)
succes = cli.run_in_terminal(lambda: self._open_file_in_editor(filename))
# Read content again.
if succes:
with open(filename, 'rb') as f:
text = f.read().decode('utf-8')
# Drop trailing newline. (Editors are supposed to add it at the
# end, but we don't need it.)
if text.endswith('\n'):
text = text[:-1]
self.document = Document(
text=text,
cursor_position=len(text))
# Clean up temp file.
os.remove(filename) | [
"def",
"open_in_editor",
"(",
"self",
",",
"cli",
")",
":",
"if",
"self",
".",
"read_only",
"(",
")",
":",
"raise",
"EditReadOnlyBuffer",
"(",
")",
"# Write to temporary file",
"descriptor",
",",
"filename",
"=",
"tempfile",
".",
"mkstemp",
"(",
"self",
".",... | Open code in editor.
:param cli: :class:`~prompt_toolkit.interface.CommandLineInterface`
instance. | [
"Open",
"code",
"in",
"editor",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L1256-L1292 | train | 207,247 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | Buffer._open_file_in_editor | def _open_file_in_editor(self, filename):
"""
Call editor executable.
Return True when we received a zero return code.
"""
# If the 'VISUAL' or 'EDITOR' environment variable has been set, use that.
# Otherwise, fall back to the first available editor that we can find.
visual = os.environ.get('VISUAL')
editor = os.environ.get('EDITOR')
editors = [
visual,
editor,
# Order of preference.
'/usr/bin/editor',
'/usr/bin/nano',
'/usr/bin/pico',
'/usr/bin/vi',
'/usr/bin/emacs',
]
for e in editors:
if e:
try:
# Use 'shlex.split()', because $VISUAL can contain spaces
# and quotes.
returncode = subprocess.call(shlex.split(e) + [filename])
return returncode == 0
except OSError:
# Executable does not exist, try the next one.
pass
return False | python | def _open_file_in_editor(self, filename):
"""
Call editor executable.
Return True when we received a zero return code.
"""
# If the 'VISUAL' or 'EDITOR' environment variable has been set, use that.
# Otherwise, fall back to the first available editor that we can find.
visual = os.environ.get('VISUAL')
editor = os.environ.get('EDITOR')
editors = [
visual,
editor,
# Order of preference.
'/usr/bin/editor',
'/usr/bin/nano',
'/usr/bin/pico',
'/usr/bin/vi',
'/usr/bin/emacs',
]
for e in editors:
if e:
try:
# Use 'shlex.split()', because $VISUAL can contain spaces
# and quotes.
returncode = subprocess.call(shlex.split(e) + [filename])
return returncode == 0
except OSError:
# Executable does not exist, try the next one.
pass
return False | [
"def",
"_open_file_in_editor",
"(",
"self",
",",
"filename",
")",
":",
"# If the 'VISUAL' or 'EDITOR' environment variable has been set, use that.",
"# Otherwise, fall back to the first available editor that we can find.",
"visual",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'V... | Call editor executable.
Return True when we received a zero return code. | [
"Call",
"editor",
"executable",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L1294-L1329 | train | 207,248 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.lines | def lines(self):
"""
Array of all the lines.
"""
# Cache, because this one is reused very often.
if self._cache.lines is None:
self._cache.lines = _ImmutableLineList(self.text.split('\n'))
return self._cache.lines | python | def lines(self):
"""
Array of all the lines.
"""
# Cache, because this one is reused very often.
if self._cache.lines is None:
self._cache.lines = _ImmutableLineList(self.text.split('\n'))
return self._cache.lines | [
"def",
"lines",
"(",
"self",
")",
":",
"# Cache, because this one is reused very often.",
"if",
"self",
".",
"_cache",
".",
"lines",
"is",
"None",
":",
"self",
".",
"_cache",
".",
"lines",
"=",
"_ImmutableLineList",
"(",
"self",
".",
"text",
".",
"split",
"(... | Array of all the lines. | [
"Array",
"of",
"all",
"the",
"lines",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L167-L175 | train | 207,249 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document._line_start_indexes | def _line_start_indexes(self):
"""
Array pointing to the start indexes of all the lines.
"""
# Cache, because this is often reused. (If it is used, it's often used
# many times. And this has to be fast for editing big documents!)
if self._cache.line_indexes is None:
# Create list of line lengths.
line_lengths = map(len, self.lines)
# Calculate cumulative sums.
indexes = [0]
append = indexes.append
pos = 0
for line_length in line_lengths:
pos += line_length + 1
append(pos)
# Remove the last item. (This is not a new line.)
if len(indexes) > 1:
indexes.pop()
self._cache.line_indexes = indexes
return self._cache.line_indexes | python | def _line_start_indexes(self):
"""
Array pointing to the start indexes of all the lines.
"""
# Cache, because this is often reused. (If it is used, it's often used
# many times. And this has to be fast for editing big documents!)
if self._cache.line_indexes is None:
# Create list of line lengths.
line_lengths = map(len, self.lines)
# Calculate cumulative sums.
indexes = [0]
append = indexes.append
pos = 0
for line_length in line_lengths:
pos += line_length + 1
append(pos)
# Remove the last item. (This is not a new line.)
if len(indexes) > 1:
indexes.pop()
self._cache.line_indexes = indexes
return self._cache.line_indexes | [
"def",
"_line_start_indexes",
"(",
"self",
")",
":",
"# Cache, because this is often reused. (If it is used, it's often used",
"# many times. And this has to be fast for editing big documents!)",
"if",
"self",
".",
"_cache",
".",
"line_indexes",
"is",
"None",
":",
"# Create list of... | Array pointing to the start indexes of all the lines. | [
"Array",
"pointing",
"to",
"the",
"start",
"indexes",
"of",
"all",
"the",
"lines",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L178-L203 | train | 207,250 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.leading_whitespace_in_current_line | def leading_whitespace_in_current_line(self):
""" The leading whitespace in the left margin of the current line. """
current_line = self.current_line
length = len(current_line) - len(current_line.lstrip())
return current_line[:length] | python | def leading_whitespace_in_current_line(self):
""" The leading whitespace in the left margin of the current line. """
current_line = self.current_line
length = len(current_line) - len(current_line.lstrip())
return current_line[:length] | [
"def",
"leading_whitespace_in_current_line",
"(",
"self",
")",
":",
"current_line",
"=",
"self",
".",
"current_line",
"length",
"=",
"len",
"(",
"current_line",
")",
"-",
"len",
"(",
"current_line",
".",
"lstrip",
"(",
")",
")",
"return",
"current_line",
"[",
... | The leading whitespace in the left margin of the current line. | [
"The",
"leading",
"whitespace",
"in",
"the",
"left",
"margin",
"of",
"the",
"current",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L225-L229 | train | 207,251 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document._find_line_start_index | def _find_line_start_index(self, index):
"""
For the index of a character at a certain line, calculate the index of
the first character on that line.
Return (row, index) tuple.
"""
indexes = self._line_start_indexes
pos = bisect.bisect_right(indexes, index) - 1
return pos, indexes[pos] | python | def _find_line_start_index(self, index):
"""
For the index of a character at a certain line, calculate the index of
the first character on that line.
Return (row, index) tuple.
"""
indexes = self._line_start_indexes
pos = bisect.bisect_right(indexes, index) - 1
return pos, indexes[pos] | [
"def",
"_find_line_start_index",
"(",
"self",
",",
"index",
")",
":",
"indexes",
"=",
"self",
".",
"_line_start_indexes",
"pos",
"=",
"bisect",
".",
"bisect_right",
"(",
"indexes",
",",
"index",
")",
"-",
"1",
"return",
"pos",
",",
"indexes",
"[",
"pos",
... | For the index of a character at a certain line, calculate the index of
the first character on that line.
Return (row, index) tuple. | [
"For",
"the",
"index",
"of",
"a",
"character",
"at",
"a",
"certain",
"line",
"calculate",
"the",
"index",
"of",
"the",
"first",
"character",
"on",
"that",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L273-L283 | train | 207,252 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.has_match_at_current_position | def has_match_at_current_position(self, sub):
"""
`True` when this substring is found at the cursor position.
"""
return self.text.find(sub, self.cursor_position) == self.cursor_position | python | def has_match_at_current_position(self, sub):
"""
`True` when this substring is found at the cursor position.
"""
return self.text.find(sub, self.cursor_position) == self.cursor_position | [
"def",
"has_match_at_current_position",
"(",
"self",
",",
"sub",
")",
":",
"return",
"self",
".",
"text",
".",
"find",
"(",
"sub",
",",
"self",
".",
"cursor_position",
")",
"==",
"self",
".",
"cursor_position"
] | `True` when this substring is found at the cursor position. | [
"True",
"when",
"this",
"substring",
"is",
"found",
"at",
"the",
"cursor",
"position",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L332-L336 | train | 207,253 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.find | def find(self, sub, in_current_line=False, include_current_position=False,
ignore_case=False, count=1):
"""
Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance.
"""
assert isinstance(ignore_case, bool)
if in_current_line:
text = self.current_line_after_cursor
else:
text = self.text_after_cursor
if not include_current_position:
if len(text) == 0:
return # (Otherwise, we always get a match for the empty string.)
else:
text = text[1:]
flags = re.IGNORECASE if ignore_case else 0
iterator = re.finditer(re.escape(sub), text, flags)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
if include_current_position:
return match.start(0)
else:
return match.start(0) + 1
except StopIteration:
pass | python | def find(self, sub, in_current_line=False, include_current_position=False,
ignore_case=False, count=1):
"""
Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance.
"""
assert isinstance(ignore_case, bool)
if in_current_line:
text = self.current_line_after_cursor
else:
text = self.text_after_cursor
if not include_current_position:
if len(text) == 0:
return # (Otherwise, we always get a match for the empty string.)
else:
text = text[1:]
flags = re.IGNORECASE if ignore_case else 0
iterator = re.finditer(re.escape(sub), text, flags)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
if include_current_position:
return match.start(0)
else:
return match.start(0) + 1
except StopIteration:
pass | [
"def",
"find",
"(",
"self",
",",
"sub",
",",
"in_current_line",
"=",
"False",
",",
"include_current_position",
"=",
"False",
",",
"ignore_case",
"=",
"False",
",",
"count",
"=",
"1",
")",
":",
"assert",
"isinstance",
"(",
"ignore_case",
",",
"bool",
")",
... | Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance. | [
"Find",
"text",
"after",
"the",
"cursor",
"return",
"position",
"relative",
"to",
"the",
"cursor",
"position",
".",
"Return",
"None",
"if",
"nothing",
"was",
"found",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L338-L370 | train | 207,254 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.find_all | def find_all(self, sub, ignore_case=False):
"""
Find all occurances of the substring. Return a list of absolute
positions in the document.
"""
flags = re.IGNORECASE if ignore_case else 0
return [a.start() for a in re.finditer(re.escape(sub), self.text, flags)] | python | def find_all(self, sub, ignore_case=False):
"""
Find all occurances of the substring. Return a list of absolute
positions in the document.
"""
flags = re.IGNORECASE if ignore_case else 0
return [a.start() for a in re.finditer(re.escape(sub), self.text, flags)] | [
"def",
"find_all",
"(",
"self",
",",
"sub",
",",
"ignore_case",
"=",
"False",
")",
":",
"flags",
"=",
"re",
".",
"IGNORECASE",
"if",
"ignore_case",
"else",
"0",
"return",
"[",
"a",
".",
"start",
"(",
")",
"for",
"a",
"in",
"re",
".",
"finditer",
"(... | Find all occurances of the substring. Return a list of absolute
positions in the document. | [
"Find",
"all",
"occurances",
"of",
"the",
"substring",
".",
"Return",
"a",
"list",
"of",
"absolute",
"positions",
"in",
"the",
"document",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L372-L378 | train | 207,255 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.find_backwards | def find_backwards(self, sub, in_current_line=False, ignore_case=False, count=1):
"""
Find `text` before the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance.
"""
if in_current_line:
before_cursor = self.current_line_before_cursor[::-1]
else:
before_cursor = self.text_before_cursor[::-1]
flags = re.IGNORECASE if ignore_case else 0
iterator = re.finditer(re.escape(sub[::-1]), before_cursor, flags)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return - match.start(0) - len(sub)
except StopIteration:
pass | python | def find_backwards(self, sub, in_current_line=False, ignore_case=False, count=1):
"""
Find `text` before the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance.
"""
if in_current_line:
before_cursor = self.current_line_before_cursor[::-1]
else:
before_cursor = self.text_before_cursor[::-1]
flags = re.IGNORECASE if ignore_case else 0
iterator = re.finditer(re.escape(sub[::-1]), before_cursor, flags)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return - match.start(0) - len(sub)
except StopIteration:
pass | [
"def",
"find_backwards",
"(",
"self",
",",
"sub",
",",
"in_current_line",
"=",
"False",
",",
"ignore_case",
"=",
"False",
",",
"count",
"=",
"1",
")",
":",
"if",
"in_current_line",
":",
"before_cursor",
"=",
"self",
".",
"current_line_before_cursor",
"[",
":... | Find `text` before the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance. | [
"Find",
"text",
"before",
"the",
"cursor",
"return",
"position",
"relative",
"to",
"the",
"cursor",
"position",
".",
"Return",
"None",
"if",
"nothing",
"was",
"found",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L380-L400 | train | 207,256 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.get_word_before_cursor | def get_word_before_cursor(self, WORD=False):
"""
Give the word before the cursor.
If we have whitespace before the cursor this returns an empty string.
"""
if self.text_before_cursor[-1:].isspace():
return ''
else:
return self.text_before_cursor[self.find_start_of_previous_word(WORD=WORD):] | python | def get_word_before_cursor(self, WORD=False):
"""
Give the word before the cursor.
If we have whitespace before the cursor this returns an empty string.
"""
if self.text_before_cursor[-1:].isspace():
return ''
else:
return self.text_before_cursor[self.find_start_of_previous_word(WORD=WORD):] | [
"def",
"get_word_before_cursor",
"(",
"self",
",",
"WORD",
"=",
"False",
")",
":",
"if",
"self",
".",
"text_before_cursor",
"[",
"-",
"1",
":",
"]",
".",
"isspace",
"(",
")",
":",
"return",
"''",
"else",
":",
"return",
"self",
".",
"text_before_cursor",
... | Give the word before the cursor.
If we have whitespace before the cursor this returns an empty string. | [
"Give",
"the",
"word",
"before",
"the",
"cursor",
".",
"If",
"we",
"have",
"whitespace",
"before",
"the",
"cursor",
"this",
"returns",
"an",
"empty",
"string",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L402-L410 | train | 207,257 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.get_word_under_cursor | def get_word_under_cursor(self, WORD=False):
"""
Return the word, currently below the cursor.
This returns an empty string when the cursor is on a whitespace region.
"""
start, end = self.find_boundaries_of_current_word(WORD=WORD)
return self.text[self.cursor_position + start: self.cursor_position + end] | python | def get_word_under_cursor(self, WORD=False):
"""
Return the word, currently below the cursor.
This returns an empty string when the cursor is on a whitespace region.
"""
start, end = self.find_boundaries_of_current_word(WORD=WORD)
return self.text[self.cursor_position + start: self.cursor_position + end] | [
"def",
"get_word_under_cursor",
"(",
"self",
",",
"WORD",
"=",
"False",
")",
":",
"start",
",",
"end",
"=",
"self",
".",
"find_boundaries_of_current_word",
"(",
"WORD",
"=",
"WORD",
")",
"return",
"self",
".",
"text",
"[",
"self",
".",
"cursor_position",
"... | Return the word, currently below the cursor.
This returns an empty string when the cursor is on a whitespace region. | [
"Return",
"the",
"word",
"currently",
"below",
"the",
"cursor",
".",
"This",
"returns",
"an",
"empty",
"string",
"when",
"the",
"cursor",
"is",
"on",
"a",
"whitespace",
"region",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L470-L476 | train | 207,258 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.find_next_word_beginning | def find_next_word_beginning(self, count=1, WORD=False):
"""
Return an index relative to the cursor position pointing to the start
of the next word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_previous_word_beginning(count=-count, WORD=WORD)
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(self.text_after_cursor)
try:
for i, match in enumerate(iterator):
# Take first match, unless it's the word on which we're right now.
if i == 0 and match.start(1) == 0:
count += 1
if i + 1 == count:
return match.start(1)
except StopIteration:
pass | python | def find_next_word_beginning(self, count=1, WORD=False):
"""
Return an index relative to the cursor position pointing to the start
of the next word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_previous_word_beginning(count=-count, WORD=WORD)
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(self.text_after_cursor)
try:
for i, match in enumerate(iterator):
# Take first match, unless it's the word on which we're right now.
if i == 0 and match.start(1) == 0:
count += 1
if i + 1 == count:
return match.start(1)
except StopIteration:
pass | [
"def",
"find_next_word_beginning",
"(",
"self",
",",
"count",
"=",
"1",
",",
"WORD",
"=",
"False",
")",
":",
"if",
"count",
"<",
"0",
":",
"return",
"self",
".",
"find_previous_word_beginning",
"(",
"count",
"=",
"-",
"count",
",",
"WORD",
"=",
"WORD",
... | Return an index relative to the cursor position pointing to the start
of the next word. Return `None` if nothing was found. | [
"Return",
"an",
"index",
"relative",
"to",
"the",
"cursor",
"position",
"pointing",
"to",
"the",
"start",
"of",
"the",
"next",
"word",
".",
"Return",
"None",
"if",
"nothing",
"was",
"found",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L478-L498 | train | 207,259 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.find_next_word_ending | def find_next_word_ending(self, include_current_position=False, count=1, WORD=False):
"""
Return an index relative to the cursor position pointing to the end
of the next word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_previous_word_ending(count=-count, WORD=WORD)
if include_current_position:
text = self.text_after_cursor
else:
text = self.text_after_cursor[1:]
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterable = regex.finditer(text)
try:
for i, match in enumerate(iterable):
if i + 1 == count:
value = match.end(1)
if include_current_position:
return value
else:
return value + 1
except StopIteration:
pass | python | def find_next_word_ending(self, include_current_position=False, count=1, WORD=False):
"""
Return an index relative to the cursor position pointing to the end
of the next word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_previous_word_ending(count=-count, WORD=WORD)
if include_current_position:
text = self.text_after_cursor
else:
text = self.text_after_cursor[1:]
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterable = regex.finditer(text)
try:
for i, match in enumerate(iterable):
if i + 1 == count:
value = match.end(1)
if include_current_position:
return value
else:
return value + 1
except StopIteration:
pass | [
"def",
"find_next_word_ending",
"(",
"self",
",",
"include_current_position",
"=",
"False",
",",
"count",
"=",
"1",
",",
"WORD",
"=",
"False",
")",
":",
"if",
"count",
"<",
"0",
":",
"return",
"self",
".",
"find_previous_word_ending",
"(",
"count",
"=",
"-... | Return an index relative to the cursor position pointing to the end
of the next word. Return `None` if nothing was found. | [
"Return",
"an",
"index",
"relative",
"to",
"the",
"cursor",
"position",
"pointing",
"to",
"the",
"end",
"of",
"the",
"next",
"word",
".",
"Return",
"None",
"if",
"nothing",
"was",
"found",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L500-L527 | train | 207,260 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.find_previous_word_ending | def find_previous_word_ending(self, count=1, WORD=False):
"""
Return an index relative to the cursor position pointing to the end
of the previous word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_next_word_ending(count=-count, WORD=WORD)
text_before_cursor = self.text_after_cursor[:1] + self.text_before_cursor[::-1]
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(text_before_cursor)
try:
for i, match in enumerate(iterator):
# Take first match, unless it's the word on which we're right now.
if i == 0 and match.start(1) == 0:
count += 1
if i + 1 == count:
return -match.start(1) + 1
except StopIteration:
pass | python | def find_previous_word_ending(self, count=1, WORD=False):
"""
Return an index relative to the cursor position pointing to the end
of the previous word. Return `None` if nothing was found.
"""
if count < 0:
return self.find_next_word_ending(count=-count, WORD=WORD)
text_before_cursor = self.text_after_cursor[:1] + self.text_before_cursor[::-1]
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(text_before_cursor)
try:
for i, match in enumerate(iterator):
# Take first match, unless it's the word on which we're right now.
if i == 0 and match.start(1) == 0:
count += 1
if i + 1 == count:
return -match.start(1) + 1
except StopIteration:
pass | [
"def",
"find_previous_word_ending",
"(",
"self",
",",
"count",
"=",
"1",
",",
"WORD",
"=",
"False",
")",
":",
"if",
"count",
"<",
"0",
":",
"return",
"self",
".",
"find_next_word_ending",
"(",
"count",
"=",
"-",
"count",
",",
"WORD",
"=",
"WORD",
")",
... | Return an index relative to the cursor position pointing to the end
of the previous word. Return `None` if nothing was found. | [
"Return",
"an",
"index",
"relative",
"to",
"the",
"cursor",
"position",
"pointing",
"to",
"the",
"end",
"of",
"the",
"previous",
"word",
".",
"Return",
"None",
"if",
"nothing",
"was",
"found",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L547-L569 | train | 207,261 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.find_next_matching_line | def find_next_matching_line(self, match_func, count=1):
"""
Look downwards for empty lines.
Return the line index, relative to the current line.
"""
result = None
for index, line in enumerate(self.lines[self.cursor_position_row + 1:]):
if match_func(line):
result = 1 + index
count -= 1
if count == 0:
break
return result | python | def find_next_matching_line(self, match_func, count=1):
"""
Look downwards for empty lines.
Return the line index, relative to the current line.
"""
result = None
for index, line in enumerate(self.lines[self.cursor_position_row + 1:]):
if match_func(line):
result = 1 + index
count -= 1
if count == 0:
break
return result | [
"def",
"find_next_matching_line",
"(",
"self",
",",
"match_func",
",",
"count",
"=",
"1",
")",
":",
"result",
"=",
"None",
"for",
"index",
",",
"line",
"in",
"enumerate",
"(",
"self",
".",
"lines",
"[",
"self",
".",
"cursor_position_row",
"+",
"1",
":",
... | Look downwards for empty lines.
Return the line index, relative to the current line. | [
"Look",
"downwards",
"for",
"empty",
"lines",
".",
"Return",
"the",
"line",
"index",
"relative",
"to",
"the",
"current",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L571-L586 | train | 207,262 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.get_cursor_left_position | def get_cursor_left_position(self, count=1):
"""
Relative position for cursor left.
"""
if count < 0:
return self.get_cursor_right_position(-count)
return - min(self.cursor_position_col, count) | python | def get_cursor_left_position(self, count=1):
"""
Relative position for cursor left.
"""
if count < 0:
return self.get_cursor_right_position(-count)
return - min(self.cursor_position_col, count) | [
"def",
"get_cursor_left_position",
"(",
"self",
",",
"count",
"=",
"1",
")",
":",
"if",
"count",
"<",
"0",
":",
"return",
"self",
".",
"get_cursor_right_position",
"(",
"-",
"count",
")",
"return",
"-",
"min",
"(",
"self",
".",
"cursor_position_col",
",",
... | Relative position for cursor left. | [
"Relative",
"position",
"for",
"cursor",
"left",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L605-L612 | train | 207,263 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.get_cursor_right_position | def get_cursor_right_position(self, count=1):
"""
Relative position for cursor_right.
"""
if count < 0:
return self.get_cursor_left_position(-count)
return min(count, len(self.current_line_after_cursor)) | python | def get_cursor_right_position(self, count=1):
"""
Relative position for cursor_right.
"""
if count < 0:
return self.get_cursor_left_position(-count)
return min(count, len(self.current_line_after_cursor)) | [
"def",
"get_cursor_right_position",
"(",
"self",
",",
"count",
"=",
"1",
")",
":",
"if",
"count",
"<",
"0",
":",
"return",
"self",
".",
"get_cursor_left_position",
"(",
"-",
"count",
")",
"return",
"min",
"(",
"count",
",",
"len",
"(",
"self",
".",
"cu... | Relative position for cursor_right. | [
"Relative",
"position",
"for",
"cursor_right",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L614-L621 | train | 207,264 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.find_enclosing_bracket_right | def find_enclosing_bracket_right(self, left_ch, right_ch, end_pos=None):
"""
Find the right bracket enclosing current position. Return the relative
position to the cursor position.
When `end_pos` is given, don't look past the position.
"""
if self.current_char == right_ch:
return 0
if end_pos is None:
end_pos = len(self.text)
else:
end_pos = min(len(self.text), end_pos)
stack = 1
# Look forward.
for i in range(self.cursor_position + 1, end_pos):
c = self.text[i]
if c == left_ch:
stack += 1
elif c == right_ch:
stack -= 1
if stack == 0:
return i - self.cursor_position | python | def find_enclosing_bracket_right(self, left_ch, right_ch, end_pos=None):
"""
Find the right bracket enclosing current position. Return the relative
position to the cursor position.
When `end_pos` is given, don't look past the position.
"""
if self.current_char == right_ch:
return 0
if end_pos is None:
end_pos = len(self.text)
else:
end_pos = min(len(self.text), end_pos)
stack = 1
# Look forward.
for i in range(self.cursor_position + 1, end_pos):
c = self.text[i]
if c == left_ch:
stack += 1
elif c == right_ch:
stack -= 1
if stack == 0:
return i - self.cursor_position | [
"def",
"find_enclosing_bracket_right",
"(",
"self",
",",
"left_ch",
",",
"right_ch",
",",
"end_pos",
"=",
"None",
")",
":",
"if",
"self",
".",
"current_char",
"==",
"right_ch",
":",
"return",
"0",
"if",
"end_pos",
"is",
"None",
":",
"end_pos",
"=",
"len",
... | Find the right bracket enclosing current position. Return the relative
position to the cursor position.
When `end_pos` is given, don't look past the position. | [
"Find",
"the",
"right",
"bracket",
"enclosing",
"current",
"position",
".",
"Return",
"the",
"relative",
"position",
"to",
"the",
"cursor",
"position",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L651-L678 | train | 207,265 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.find_enclosing_bracket_left | def find_enclosing_bracket_left(self, left_ch, right_ch, start_pos=None):
"""
Find the left bracket enclosing current position. Return the relative
position to the cursor position.
When `start_pos` is given, don't look past the position.
"""
if self.current_char == left_ch:
return 0
if start_pos is None:
start_pos = 0
else:
start_pos = max(0, start_pos)
stack = 1
# Look backward.
for i in range(self.cursor_position - 1, start_pos - 1, -1):
c = self.text[i]
if c == right_ch:
stack += 1
elif c == left_ch:
stack -= 1
if stack == 0:
return i - self.cursor_position | python | def find_enclosing_bracket_left(self, left_ch, right_ch, start_pos=None):
"""
Find the left bracket enclosing current position. Return the relative
position to the cursor position.
When `start_pos` is given, don't look past the position.
"""
if self.current_char == left_ch:
return 0
if start_pos is None:
start_pos = 0
else:
start_pos = max(0, start_pos)
stack = 1
# Look backward.
for i in range(self.cursor_position - 1, start_pos - 1, -1):
c = self.text[i]
if c == right_ch:
stack += 1
elif c == left_ch:
stack -= 1
if stack == 0:
return i - self.cursor_position | [
"def",
"find_enclosing_bracket_left",
"(",
"self",
",",
"left_ch",
",",
"right_ch",
",",
"start_pos",
"=",
"None",
")",
":",
"if",
"self",
".",
"current_char",
"==",
"left_ch",
":",
"return",
"0",
"if",
"start_pos",
"is",
"None",
":",
"start_pos",
"=",
"0"... | Find the left bracket enclosing current position. Return the relative
position to the cursor position.
When `start_pos` is given, don't look past the position. | [
"Find",
"the",
"left",
"bracket",
"enclosing",
"current",
"position",
".",
"Return",
"the",
"relative",
"position",
"to",
"the",
"cursor",
"position",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L680-L707 | train | 207,266 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.find_matching_bracket_position | def find_matching_bracket_position(self, start_pos=None, end_pos=None):
"""
Return relative cursor position of matching [, (, { or < bracket.
When `start_pos` or `end_pos` are given. Don't look past the positions.
"""
# Look for a match.
for A, B in '()', '[]', '{}', '<>':
if self.current_char == A:
return self.find_enclosing_bracket_right(A, B, end_pos=end_pos) or 0
elif self.current_char == B:
return self.find_enclosing_bracket_left(A, B, start_pos=start_pos) or 0
return 0 | python | def find_matching_bracket_position(self, start_pos=None, end_pos=None):
"""
Return relative cursor position of matching [, (, { or < bracket.
When `start_pos` or `end_pos` are given. Don't look past the positions.
"""
# Look for a match.
for A, B in '()', '[]', '{}', '<>':
if self.current_char == A:
return self.find_enclosing_bracket_right(A, B, end_pos=end_pos) or 0
elif self.current_char == B:
return self.find_enclosing_bracket_left(A, B, start_pos=start_pos) or 0
return 0 | [
"def",
"find_matching_bracket_position",
"(",
"self",
",",
"start_pos",
"=",
"None",
",",
"end_pos",
"=",
"None",
")",
":",
"# Look for a match.",
"for",
"A",
",",
"B",
"in",
"'()'",
",",
"'[]'",
",",
"'{}'",
",",
"'<>'",
":",
"if",
"self",
".",
"current... | Return relative cursor position of matching [, (, { or < bracket.
When `start_pos` or `end_pos` are given. Don't look past the positions. | [
"Return",
"relative",
"cursor",
"position",
"of",
"matching",
"[",
"(",
"{",
"or",
"<",
"bracket",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L709-L723 | train | 207,267 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.get_start_of_line_position | def get_start_of_line_position(self, after_whitespace=False):
""" Relative position for the start of this line. """
if after_whitespace:
current_line = self.current_line
return len(current_line) - len(current_line.lstrip()) - self.cursor_position_col
else:
return - len(self.current_line_before_cursor) | python | def get_start_of_line_position(self, after_whitespace=False):
""" Relative position for the start of this line. """
if after_whitespace:
current_line = self.current_line
return len(current_line) - len(current_line.lstrip()) - self.cursor_position_col
else:
return - len(self.current_line_before_cursor) | [
"def",
"get_start_of_line_position",
"(",
"self",
",",
"after_whitespace",
"=",
"False",
")",
":",
"if",
"after_whitespace",
":",
"current_line",
"=",
"self",
".",
"current_line",
"return",
"len",
"(",
"current_line",
")",
"-",
"len",
"(",
"current_line",
".",
... | Relative position for the start of this line. | [
"Relative",
"position",
"for",
"the",
"start",
"of",
"this",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L733-L739 | train | 207,268 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.empty_line_count_at_the_end | def empty_line_count_at_the_end(self):
"""
Return number of empty lines at the end of the document.
"""
count = 0
for line in self.lines[::-1]:
if not line or line.isspace():
count += 1
else:
break
return count | python | def empty_line_count_at_the_end(self):
"""
Return number of empty lines at the end of the document.
"""
count = 0
for line in self.lines[::-1]:
if not line or line.isspace():
count += 1
else:
break
return count | [
"def",
"empty_line_count_at_the_end",
"(",
"self",
")",
":",
"count",
"=",
"0",
"for",
"line",
"in",
"self",
".",
"lines",
"[",
":",
":",
"-",
"1",
"]",
":",
"if",
"not",
"line",
"or",
"line",
".",
"isspace",
"(",
")",
":",
"count",
"+=",
"1",
"e... | Return number of empty lines at the end of the document. | [
"Return",
"number",
"of",
"empty",
"lines",
"at",
"the",
"end",
"of",
"the",
"document",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L931-L942 | train | 207,269 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.insert_after | def insert_after(self, text):
"""
Create a new document, with this text inserted after the buffer.
It keeps selection ranges and cursor position in sync.
"""
return Document(
text=self.text + text,
cursor_position=self.cursor_position,
selection=self.selection) | python | def insert_after(self, text):
"""
Create a new document, with this text inserted after the buffer.
It keeps selection ranges and cursor position in sync.
"""
return Document(
text=self.text + text,
cursor_position=self.cursor_position,
selection=self.selection) | [
"def",
"insert_after",
"(",
"self",
",",
"text",
")",
":",
"return",
"Document",
"(",
"text",
"=",
"self",
".",
"text",
"+",
"text",
",",
"cursor_position",
"=",
"self",
".",
"cursor_position",
",",
"selection",
"=",
"self",
".",
"selection",
")"
] | Create a new document, with this text inserted after the buffer.
It keeps selection ranges and cursor position in sync. | [
"Create",
"a",
"new",
"document",
"with",
"this",
"text",
"inserted",
"after",
"the",
"buffer",
".",
"It",
"keeps",
"selection",
"ranges",
"and",
"cursor",
"position",
"in",
"sync",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L976-L984 | train | 207,270 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | Document.insert_before | def insert_before(self, text):
"""
Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync.
"""
selection_state = self.selection
if selection_state:
selection_state = SelectionState(
original_cursor_position=selection_state.original_cursor_position + len(text),
type=selection_state.type)
return Document(
text=text + self.text,
cursor_position=self.cursor_position + len(text),
selection=selection_state) | python | def insert_before(self, text):
"""
Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync.
"""
selection_state = self.selection
if selection_state:
selection_state = SelectionState(
original_cursor_position=selection_state.original_cursor_position + len(text),
type=selection_state.type)
return Document(
text=text + self.text,
cursor_position=self.cursor_position + len(text),
selection=selection_state) | [
"def",
"insert_before",
"(",
"self",
",",
"text",
")",
":",
"selection_state",
"=",
"self",
".",
"selection",
"if",
"selection_state",
":",
"selection_state",
"=",
"SelectionState",
"(",
"original_cursor_position",
"=",
"selection_state",
".",
"original_cursor_positio... | Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync. | [
"Create",
"a",
"new",
"document",
"with",
"this",
"text",
"inserted",
"before",
"the",
"buffer",
".",
"It",
"keeps",
"selection",
"ranges",
"and",
"cursor",
"position",
"in",
"sync",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L986-L1001 | train | 207,271 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/defaults.py | load_key_bindings | def load_key_bindings(
get_search_state=None,
enable_abort_and_exit_bindings=False,
enable_system_bindings=False,
enable_search=False,
enable_open_in_editor=False,
enable_extra_page_navigation=False,
enable_auto_suggest_bindings=False):
"""
Create a Registry object that contains the default key bindings.
:param enable_abort_and_exit_bindings: Filter to enable Ctrl-C and Ctrl-D.
:param enable_system_bindings: Filter to enable the system bindings (meta-!
prompt and Control-Z suspension.)
:param enable_search: Filter to enable the search bindings.
:param enable_open_in_editor: Filter to enable open-in-editor.
:param enable_open_in_editor: Filter to enable open-in-editor.
:param enable_extra_page_navigation: Filter for enabling extra page
navigation. (Bindings for up/down scrolling through long pages, like in
Emacs or Vi.)
:param enable_auto_suggest_bindings: Filter to enable fish-style suggestions.
"""
assert get_search_state is None or callable(get_search_state)
# Accept both Filters and booleans as input.
enable_abort_and_exit_bindings = to_cli_filter(enable_abort_and_exit_bindings)
enable_system_bindings = to_cli_filter(enable_system_bindings)
enable_search = to_cli_filter(enable_search)
enable_open_in_editor = to_cli_filter(enable_open_in_editor)
enable_extra_page_navigation = to_cli_filter(enable_extra_page_navigation)
enable_auto_suggest_bindings = to_cli_filter(enable_auto_suggest_bindings)
registry = MergedRegistry([
# Load basic bindings.
load_basic_bindings(),
load_mouse_bindings(),
ConditionalRegistry(load_abort_and_exit_bindings(),
enable_abort_and_exit_bindings),
ConditionalRegistry(load_basic_system_bindings(),
enable_system_bindings),
# Load emacs bindings.
load_emacs_bindings(),
ConditionalRegistry(load_emacs_open_in_editor_bindings(),
enable_open_in_editor),
ConditionalRegistry(load_emacs_search_bindings(get_search_state=get_search_state),
enable_search),
ConditionalRegistry(load_emacs_system_bindings(),
enable_system_bindings),
ConditionalRegistry(load_extra_emacs_page_navigation_bindings(),
enable_extra_page_navigation),
# Load Vi bindings.
load_vi_bindings(get_search_state=get_search_state),
ConditionalRegistry(load_vi_open_in_editor_bindings(),
enable_open_in_editor),
ConditionalRegistry(load_vi_search_bindings(get_search_state=get_search_state),
enable_search),
ConditionalRegistry(load_vi_system_bindings(),
enable_system_bindings),
ConditionalRegistry(load_extra_vi_page_navigation_bindings(),
enable_extra_page_navigation),
# Suggestion bindings.
# (This has to come at the end, because the Vi bindings also have an
# implementation for the "right arrow", but we really want the
# suggestion binding when a suggestion is available.)
ConditionalRegistry(load_auto_suggestion_bindings(),
enable_auto_suggest_bindings),
])
return registry | python | def load_key_bindings(
get_search_state=None,
enable_abort_and_exit_bindings=False,
enable_system_bindings=False,
enable_search=False,
enable_open_in_editor=False,
enable_extra_page_navigation=False,
enable_auto_suggest_bindings=False):
"""
Create a Registry object that contains the default key bindings.
:param enable_abort_and_exit_bindings: Filter to enable Ctrl-C and Ctrl-D.
:param enable_system_bindings: Filter to enable the system bindings (meta-!
prompt and Control-Z suspension.)
:param enable_search: Filter to enable the search bindings.
:param enable_open_in_editor: Filter to enable open-in-editor.
:param enable_open_in_editor: Filter to enable open-in-editor.
:param enable_extra_page_navigation: Filter for enabling extra page
navigation. (Bindings for up/down scrolling through long pages, like in
Emacs or Vi.)
:param enable_auto_suggest_bindings: Filter to enable fish-style suggestions.
"""
assert get_search_state is None or callable(get_search_state)
# Accept both Filters and booleans as input.
enable_abort_and_exit_bindings = to_cli_filter(enable_abort_and_exit_bindings)
enable_system_bindings = to_cli_filter(enable_system_bindings)
enable_search = to_cli_filter(enable_search)
enable_open_in_editor = to_cli_filter(enable_open_in_editor)
enable_extra_page_navigation = to_cli_filter(enable_extra_page_navigation)
enable_auto_suggest_bindings = to_cli_filter(enable_auto_suggest_bindings)
registry = MergedRegistry([
# Load basic bindings.
load_basic_bindings(),
load_mouse_bindings(),
ConditionalRegistry(load_abort_and_exit_bindings(),
enable_abort_and_exit_bindings),
ConditionalRegistry(load_basic_system_bindings(),
enable_system_bindings),
# Load emacs bindings.
load_emacs_bindings(),
ConditionalRegistry(load_emacs_open_in_editor_bindings(),
enable_open_in_editor),
ConditionalRegistry(load_emacs_search_bindings(get_search_state=get_search_state),
enable_search),
ConditionalRegistry(load_emacs_system_bindings(),
enable_system_bindings),
ConditionalRegistry(load_extra_emacs_page_navigation_bindings(),
enable_extra_page_navigation),
# Load Vi bindings.
load_vi_bindings(get_search_state=get_search_state),
ConditionalRegistry(load_vi_open_in_editor_bindings(),
enable_open_in_editor),
ConditionalRegistry(load_vi_search_bindings(get_search_state=get_search_state),
enable_search),
ConditionalRegistry(load_vi_system_bindings(),
enable_system_bindings),
ConditionalRegistry(load_extra_vi_page_navigation_bindings(),
enable_extra_page_navigation),
# Suggestion bindings.
# (This has to come at the end, because the Vi bindings also have an
# implementation for the "right arrow", but we really want the
# suggestion binding when a suggestion is available.)
ConditionalRegistry(load_auto_suggestion_bindings(),
enable_auto_suggest_bindings),
])
return registry | [
"def",
"load_key_bindings",
"(",
"get_search_state",
"=",
"None",
",",
"enable_abort_and_exit_bindings",
"=",
"False",
",",
"enable_system_bindings",
"=",
"False",
",",
"enable_search",
"=",
"False",
",",
"enable_open_in_editor",
"=",
"False",
",",
"enable_extra_page_na... | Create a Registry object that contains the default key bindings.
:param enable_abort_and_exit_bindings: Filter to enable Ctrl-C and Ctrl-D.
:param enable_system_bindings: Filter to enable the system bindings (meta-!
prompt and Control-Z suspension.)
:param enable_search: Filter to enable the search bindings.
:param enable_open_in_editor: Filter to enable open-in-editor.
:param enable_open_in_editor: Filter to enable open-in-editor.
:param enable_extra_page_navigation: Filter for enabling extra page
navigation. (Bindings for up/down scrolling through long pages, like in
Emacs or Vi.)
:param enable_auto_suggest_bindings: Filter to enable fish-style suggestions. | [
"Create",
"a",
"Registry",
"object",
"that",
"contains",
"the",
"default",
"key",
"bindings",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/defaults.py#L20-L102 | train | 207,272 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/defaults.py | load_key_bindings_for_prompt | def load_key_bindings_for_prompt(**kw):
"""
Create a ``Registry`` object with the defaults key bindings for an input
prompt.
This activates the key bindings for abort/exit (Ctrl-C/Ctrl-D),
incremental search and auto suggestions.
(Not for full screen applications.)
"""
kw.setdefault('enable_abort_and_exit_bindings', True)
kw.setdefault('enable_search', True)
kw.setdefault('enable_auto_suggest_bindings', True)
return load_key_bindings(**kw) | python | def load_key_bindings_for_prompt(**kw):
"""
Create a ``Registry`` object with the defaults key bindings for an input
prompt.
This activates the key bindings for abort/exit (Ctrl-C/Ctrl-D),
incremental search and auto suggestions.
(Not for full screen applications.)
"""
kw.setdefault('enable_abort_and_exit_bindings', True)
kw.setdefault('enable_search', True)
kw.setdefault('enable_auto_suggest_bindings', True)
return load_key_bindings(**kw) | [
"def",
"load_key_bindings_for_prompt",
"(",
"*",
"*",
"kw",
")",
":",
"kw",
".",
"setdefault",
"(",
"'enable_abort_and_exit_bindings'",
",",
"True",
")",
"kw",
".",
"setdefault",
"(",
"'enable_search'",
",",
"True",
")",
"kw",
".",
"setdefault",
"(",
"'enable_... | Create a ``Registry`` object with the defaults key bindings for an input
prompt.
This activates the key bindings for abort/exit (Ctrl-C/Ctrl-D),
incremental search and auto suggestions.
(Not for full screen applications.) | [
"Create",
"a",
"Registry",
"object",
"with",
"the",
"defaults",
"key",
"bindings",
"for",
"an",
"input",
"prompt",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/defaults.py#L105-L119 | train | 207,273 |
wandb/client | wandb/vendor/prompt_toolkit/shortcuts.py | _split_multiline_prompt | def _split_multiline_prompt(get_prompt_tokens):
"""
Take a `get_prompt_tokens` function and return three new functions instead.
One that tells whether this prompt consists of multiple lines; one that
returns the tokens to be shown on the lines above the input; and another
one with the tokens to be shown at the first line of the input.
"""
def has_before_tokens(cli):
for token, char in get_prompt_tokens(cli):
if '\n' in char:
return True
return False
def before(cli):
result = []
found_nl = False
for token, char in reversed(explode_tokens(get_prompt_tokens(cli))):
if found_nl:
result.insert(0, (token, char))
elif char == '\n':
found_nl = True
return result
def first_input_line(cli):
result = []
for token, char in reversed(explode_tokens(get_prompt_tokens(cli))):
if char == '\n':
break
else:
result.insert(0, (token, char))
return result
return has_before_tokens, before, first_input_line | python | def _split_multiline_prompt(get_prompt_tokens):
"""
Take a `get_prompt_tokens` function and return three new functions instead.
One that tells whether this prompt consists of multiple lines; one that
returns the tokens to be shown on the lines above the input; and another
one with the tokens to be shown at the first line of the input.
"""
def has_before_tokens(cli):
for token, char in get_prompt_tokens(cli):
if '\n' in char:
return True
return False
def before(cli):
result = []
found_nl = False
for token, char in reversed(explode_tokens(get_prompt_tokens(cli))):
if found_nl:
result.insert(0, (token, char))
elif char == '\n':
found_nl = True
return result
def first_input_line(cli):
result = []
for token, char in reversed(explode_tokens(get_prompt_tokens(cli))):
if char == '\n':
break
else:
result.insert(0, (token, char))
return result
return has_before_tokens, before, first_input_line | [
"def",
"_split_multiline_prompt",
"(",
"get_prompt_tokens",
")",
":",
"def",
"has_before_tokens",
"(",
"cli",
")",
":",
"for",
"token",
",",
"char",
"in",
"get_prompt_tokens",
"(",
"cli",
")",
":",
"if",
"'\\n'",
"in",
"char",
":",
"return",
"True",
"return"... | Take a `get_prompt_tokens` function and return three new functions instead.
One that tells whether this prompt consists of multiple lines; one that
returns the tokens to be shown on the lines above the input; and another
one with the tokens to be shown at the first line of the input. | [
"Take",
"a",
"get_prompt_tokens",
"function",
"and",
"return",
"three",
"new",
"functions",
"instead",
".",
"One",
"that",
"tells",
"whether",
"this",
"prompt",
"consists",
"of",
"multiple",
"lines",
";",
"one",
"that",
"returns",
"the",
"tokens",
"to",
"be",
... | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/shortcuts.py#L148-L180 | train | 207,274 |
wandb/client | wandb/vendor/prompt_toolkit/shortcuts.py | prompt | def prompt(message='', **kwargs):
"""
Get input from the user and return it.
This is a wrapper around a lot of ``prompt_toolkit`` functionality and can
be a replacement for `raw_input`. (or GNU readline.)
If you want to keep your history across several calls, create one
:class:`~prompt_toolkit.history.History` instance and pass it every time.
This function accepts many keyword arguments. Except for the following,
they are a proxy to the arguments of :func:`.create_prompt_application`.
:param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that
print statements from other threads won't destroy the prompt. (They
will be printed above the prompt instead.)
:param return_asyncio_coroutine: When True, return a asyncio coroutine. (Python >3.3)
:param true_color: When True, use 24bit colors instead of 256 colors.
:param refresh_interval: (number; in seconds) When given, refresh the UI
every so many seconds.
"""
patch_stdout = kwargs.pop('patch_stdout', False)
return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine', False)
true_color = kwargs.pop('true_color', False)
refresh_interval = kwargs.pop('refresh_interval', 0)
eventloop = kwargs.pop('eventloop', None)
application = create_prompt_application(message, **kwargs)
return run_application(application,
patch_stdout=patch_stdout,
return_asyncio_coroutine=return_asyncio_coroutine,
true_color=true_color,
refresh_interval=refresh_interval,
eventloop=eventloop) | python | def prompt(message='', **kwargs):
"""
Get input from the user and return it.
This is a wrapper around a lot of ``prompt_toolkit`` functionality and can
be a replacement for `raw_input`. (or GNU readline.)
If you want to keep your history across several calls, create one
:class:`~prompt_toolkit.history.History` instance and pass it every time.
This function accepts many keyword arguments. Except for the following,
they are a proxy to the arguments of :func:`.create_prompt_application`.
:param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that
print statements from other threads won't destroy the prompt. (They
will be printed above the prompt instead.)
:param return_asyncio_coroutine: When True, return a asyncio coroutine. (Python >3.3)
:param true_color: When True, use 24bit colors instead of 256 colors.
:param refresh_interval: (number; in seconds) When given, refresh the UI
every so many seconds.
"""
patch_stdout = kwargs.pop('patch_stdout', False)
return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine', False)
true_color = kwargs.pop('true_color', False)
refresh_interval = kwargs.pop('refresh_interval', 0)
eventloop = kwargs.pop('eventloop', None)
application = create_prompt_application(message, **kwargs)
return run_application(application,
patch_stdout=patch_stdout,
return_asyncio_coroutine=return_asyncio_coroutine,
true_color=true_color,
refresh_interval=refresh_interval,
eventloop=eventloop) | [
"def",
"prompt",
"(",
"message",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"patch_stdout",
"=",
"kwargs",
".",
"pop",
"(",
"'patch_stdout'",
",",
"False",
")",
"return_asyncio_coroutine",
"=",
"kwargs",
".",
"pop",
"(",
"'return_asyncio_coroutine'",
",",... | Get input from the user and return it.
This is a wrapper around a lot of ``prompt_toolkit`` functionality and can
be a replacement for `raw_input`. (or GNU readline.)
If you want to keep your history across several calls, create one
:class:`~prompt_toolkit.history.History` instance and pass it every time.
This function accepts many keyword arguments. Except for the following,
they are a proxy to the arguments of :func:`.create_prompt_application`.
:param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that
print statements from other threads won't destroy the prompt. (They
will be printed above the prompt instead.)
:param return_asyncio_coroutine: When True, return a asyncio coroutine. (Python >3.3)
:param true_color: When True, use 24bit colors instead of 256 colors.
:param refresh_interval: (number; in seconds) When given, refresh the UI
every so many seconds. | [
"Get",
"input",
"from",
"the",
"user",
"and",
"return",
"it",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/shortcuts.py#L514-L548 | train | 207,275 |
wandb/client | wandb/vendor/prompt_toolkit/shortcuts.py | run_application | def run_application(
application, patch_stdout=False, return_asyncio_coroutine=False,
true_color=False, refresh_interval=0, eventloop=None):
"""
Run a prompt toolkit application.
:param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that
print statements from other threads won't destroy the prompt. (They
will be printed above the prompt instead.)
:param return_asyncio_coroutine: When True, return a asyncio coroutine. (Python >3.3)
:param true_color: When True, use 24bit colors instead of 256 colors.
:param refresh_interval: (number; in seconds) When given, refresh the UI
every so many seconds.
"""
assert isinstance(application, Application)
if return_asyncio_coroutine:
eventloop = create_asyncio_eventloop()
else:
eventloop = eventloop or create_eventloop()
# Create CommandLineInterface.
cli = CommandLineInterface(
application=application,
eventloop=eventloop,
output=create_output(true_color=true_color))
# Set up refresh interval.
if refresh_interval:
done = [False]
def start_refresh_loop(cli):
def run():
while not done[0]:
time.sleep(refresh_interval)
cli.request_redraw()
t = threading.Thread(target=run)
t.daemon = True
t.start()
def stop_refresh_loop(cli):
done[0] = True
cli.on_start += start_refresh_loop
cli.on_stop += stop_refresh_loop
# Replace stdout.
patch_context = cli.patch_stdout_context(raw=True) if patch_stdout else DummyContext()
# Read input and return it.
if return_asyncio_coroutine:
# Create an asyncio coroutine and call it.
exec_context = {'patch_context': patch_context, 'cli': cli,
'Document': Document}
exec_(textwrap.dedent('''
def prompt_coro():
# Inline import, because it slows down startup when asyncio is not
# needed.
import asyncio
@asyncio.coroutine
def run():
with patch_context:
result = yield from cli.run_async()
if isinstance(result, Document): # Backwards-compatibility.
return result.text
return result
return run()
'''), exec_context)
return exec_context['prompt_coro']()
else:
try:
with patch_context:
result = cli.run()
if isinstance(result, Document): # Backwards-compatibility.
return result.text
return result
finally:
eventloop.close() | python | def run_application(
application, patch_stdout=False, return_asyncio_coroutine=False,
true_color=False, refresh_interval=0, eventloop=None):
"""
Run a prompt toolkit application.
:param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that
print statements from other threads won't destroy the prompt. (They
will be printed above the prompt instead.)
:param return_asyncio_coroutine: When True, return a asyncio coroutine. (Python >3.3)
:param true_color: When True, use 24bit colors instead of 256 colors.
:param refresh_interval: (number; in seconds) When given, refresh the UI
every so many seconds.
"""
assert isinstance(application, Application)
if return_asyncio_coroutine:
eventloop = create_asyncio_eventloop()
else:
eventloop = eventloop or create_eventloop()
# Create CommandLineInterface.
cli = CommandLineInterface(
application=application,
eventloop=eventloop,
output=create_output(true_color=true_color))
# Set up refresh interval.
if refresh_interval:
done = [False]
def start_refresh_loop(cli):
def run():
while not done[0]:
time.sleep(refresh_interval)
cli.request_redraw()
t = threading.Thread(target=run)
t.daemon = True
t.start()
def stop_refresh_loop(cli):
done[0] = True
cli.on_start += start_refresh_loop
cli.on_stop += stop_refresh_loop
# Replace stdout.
patch_context = cli.patch_stdout_context(raw=True) if patch_stdout else DummyContext()
# Read input and return it.
if return_asyncio_coroutine:
# Create an asyncio coroutine and call it.
exec_context = {'patch_context': patch_context, 'cli': cli,
'Document': Document}
exec_(textwrap.dedent('''
def prompt_coro():
# Inline import, because it slows down startup when asyncio is not
# needed.
import asyncio
@asyncio.coroutine
def run():
with patch_context:
result = yield from cli.run_async()
if isinstance(result, Document): # Backwards-compatibility.
return result.text
return result
return run()
'''), exec_context)
return exec_context['prompt_coro']()
else:
try:
with patch_context:
result = cli.run()
if isinstance(result, Document): # Backwards-compatibility.
return result.text
return result
finally:
eventloop.close() | [
"def",
"run_application",
"(",
"application",
",",
"patch_stdout",
"=",
"False",
",",
"return_asyncio_coroutine",
"=",
"False",
",",
"true_color",
"=",
"False",
",",
"refresh_interval",
"=",
"0",
",",
"eventloop",
"=",
"None",
")",
":",
"assert",
"isinstance",
... | Run a prompt toolkit application.
:param patch_stdout: Replace ``sys.stdout`` by a proxy that ensures that
print statements from other threads won't destroy the prompt. (They
will be printed above the prompt instead.)
:param return_asyncio_coroutine: When True, return a asyncio coroutine. (Python >3.3)
:param true_color: When True, use 24bit colors instead of 256 colors.
:param refresh_interval: (number; in seconds) When given, refresh the UI
every so many seconds. | [
"Run",
"a",
"prompt",
"toolkit",
"application",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/shortcuts.py#L551-L631 | train | 207,276 |
wandb/client | wandb/vendor/prompt_toolkit/terminal/win32_output.py | _create_ansi_color_dict | def _create_ansi_color_dict(color_cls):
" Create a table that maps the 16 named ansi colors to their Windows code. "
return {
'ansidefault': color_cls.BLACK,
'ansiblack': color_cls.BLACK,
'ansidarkgray': color_cls.BLACK | color_cls.INTENSITY,
'ansilightgray': color_cls.GRAY,
'ansiwhite': color_cls.GRAY | color_cls.INTENSITY,
# Low intensity.
'ansidarkred': color_cls.RED,
'ansidarkgreen': color_cls.GREEN,
'ansibrown': color_cls.YELLOW,
'ansidarkblue': color_cls.BLUE,
'ansipurple': color_cls.MAGENTA,
'ansiteal': color_cls.CYAN,
# High intensity.
'ansired': color_cls.RED | color_cls.INTENSITY,
'ansigreen': color_cls.GREEN | color_cls.INTENSITY,
'ansiyellow': color_cls.YELLOW | color_cls.INTENSITY,
'ansiblue': color_cls.BLUE | color_cls.INTENSITY,
'ansifuchsia': color_cls.MAGENTA | color_cls.INTENSITY,
'ansiturquoise': color_cls.CYAN | color_cls.INTENSITY,
} | python | def _create_ansi_color_dict(color_cls):
" Create a table that maps the 16 named ansi colors to their Windows code. "
return {
'ansidefault': color_cls.BLACK,
'ansiblack': color_cls.BLACK,
'ansidarkgray': color_cls.BLACK | color_cls.INTENSITY,
'ansilightgray': color_cls.GRAY,
'ansiwhite': color_cls.GRAY | color_cls.INTENSITY,
# Low intensity.
'ansidarkred': color_cls.RED,
'ansidarkgreen': color_cls.GREEN,
'ansibrown': color_cls.YELLOW,
'ansidarkblue': color_cls.BLUE,
'ansipurple': color_cls.MAGENTA,
'ansiteal': color_cls.CYAN,
# High intensity.
'ansired': color_cls.RED | color_cls.INTENSITY,
'ansigreen': color_cls.GREEN | color_cls.INTENSITY,
'ansiyellow': color_cls.YELLOW | color_cls.INTENSITY,
'ansiblue': color_cls.BLUE | color_cls.INTENSITY,
'ansifuchsia': color_cls.MAGENTA | color_cls.INTENSITY,
'ansiturquoise': color_cls.CYAN | color_cls.INTENSITY,
} | [
"def",
"_create_ansi_color_dict",
"(",
"color_cls",
")",
":",
"return",
"{",
"'ansidefault'",
":",
"color_cls",
".",
"BLACK",
",",
"'ansiblack'",
":",
"color_cls",
".",
"BLACK",
",",
"'ansidarkgray'",
":",
"color_cls",
".",
"BLACK",
"|",
"color_cls",
".",
"INT... | Create a table that maps the 16 named ansi colors to their Windows code. | [
"Create",
"a",
"table",
"that",
"maps",
"the",
"16",
"named",
"ansi",
"colors",
"to",
"their",
"Windows",
"code",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/terminal/win32_output.py#L429-L453 | train | 207,277 |
wandb/client | wandb/vendor/prompt_toolkit/terminal/win32_output.py | Win32Output._winapi | def _winapi(self, func, *a, **kw):
"""
Flush and call win API function.
"""
self.flush()
if _DEBUG_RENDER_OUTPUT:
self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n')
self.LOG.write(b' ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b'\n')
self.LOG.write(b' ' + ', '.join(['%r' % type(i) for i in a]).encode('utf-8') + b'\n')
self.LOG.flush()
try:
return func(*a, **kw)
except ArgumentError as e:
if _DEBUG_RENDER_OUTPUT:
self.LOG.write((' Error in %r %r %s\n' % (func.__name__, e, e)).encode('utf-8')) | python | def _winapi(self, func, *a, **kw):
"""
Flush and call win API function.
"""
self.flush()
if _DEBUG_RENDER_OUTPUT:
self.LOG.write(('%r' % func.__name__).encode('utf-8') + b'\n')
self.LOG.write(b' ' + ', '.join(['%r' % i for i in a]).encode('utf-8') + b'\n')
self.LOG.write(b' ' + ', '.join(['%r' % type(i) for i in a]).encode('utf-8') + b'\n')
self.LOG.flush()
try:
return func(*a, **kw)
except ArgumentError as e:
if _DEBUG_RENDER_OUTPUT:
self.LOG.write((' Error in %r %r %s\n' % (func.__name__, e, e)).encode('utf-8')) | [
"def",
"_winapi",
"(",
"self",
",",
"func",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"flush",
"(",
")",
"if",
"_DEBUG_RENDER_OUTPUT",
":",
"self",
".",
"LOG",
".",
"write",
"(",
"(",
"'%r'",
"%",
"func",
".",
"__name__",
")",
... | Flush and call win API function. | [
"Flush",
"and",
"call",
"win",
"API",
"function",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/terminal/win32_output.py#L122-L138 | train | 207,278 |
wandb/client | wandb/vendor/prompt_toolkit/terminal/win32_output.py | Win32Output.get_win32_screen_buffer_info | def get_win32_screen_buffer_info(self):
"""
Return Screen buffer info.
"""
# NOTE: We don't call the `GetConsoleScreenBufferInfo` API through
# `self._winapi`. Doing so causes Python to crash on certain 64bit
# Python versions. (Reproduced with 64bit Python 2.7.6, on Windows
# 10). It is not clear why. Possibly, it has to do with passing
# these objects as an argument, or through *args.
# The Python documentation contains the following - possibly related - warning:
# ctypes does not support passing unions or structures with
# bit-fields to functions by value. While this may work on 32-bit
# x86, it's not guaranteed by the library to work in the general
# case. Unions and structures with bit-fields should always be
# passed to functions by pointer.
# Also see:
# - https://github.com/ipython/ipython/issues/10070
# - https://github.com/jonathanslenders/python-prompt-toolkit/issues/406
# - https://github.com/jonathanslenders/python-prompt-toolkit/issues/86
self.flush()
sbinfo = CONSOLE_SCREEN_BUFFER_INFO()
success = windll.kernel32.GetConsoleScreenBufferInfo(self.hconsole, byref(sbinfo))
# success = self._winapi(windll.kernel32.GetConsoleScreenBufferInfo,
# self.hconsole, byref(sbinfo))
if success:
return sbinfo
else:
raise NoConsoleScreenBufferError | python | def get_win32_screen_buffer_info(self):
"""
Return Screen buffer info.
"""
# NOTE: We don't call the `GetConsoleScreenBufferInfo` API through
# `self._winapi`. Doing so causes Python to crash on certain 64bit
# Python versions. (Reproduced with 64bit Python 2.7.6, on Windows
# 10). It is not clear why. Possibly, it has to do with passing
# these objects as an argument, or through *args.
# The Python documentation contains the following - possibly related - warning:
# ctypes does not support passing unions or structures with
# bit-fields to functions by value. While this may work on 32-bit
# x86, it's not guaranteed by the library to work in the general
# case. Unions and structures with bit-fields should always be
# passed to functions by pointer.
# Also see:
# - https://github.com/ipython/ipython/issues/10070
# - https://github.com/jonathanslenders/python-prompt-toolkit/issues/406
# - https://github.com/jonathanslenders/python-prompt-toolkit/issues/86
self.flush()
sbinfo = CONSOLE_SCREEN_BUFFER_INFO()
success = windll.kernel32.GetConsoleScreenBufferInfo(self.hconsole, byref(sbinfo))
# success = self._winapi(windll.kernel32.GetConsoleScreenBufferInfo,
# self.hconsole, byref(sbinfo))
if success:
return sbinfo
else:
raise NoConsoleScreenBufferError | [
"def",
"get_win32_screen_buffer_info",
"(",
"self",
")",
":",
"# NOTE: We don't call the `GetConsoleScreenBufferInfo` API through",
"# `self._winapi`. Doing so causes Python to crash on certain 64bit",
"# Python versions. (Reproduced with 64bit Python 2.7.6, on Windows",
"# 10). It is ... | Return Screen buffer info. | [
"Return",
"Screen",
"buffer",
"info",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/terminal/win32_output.py#L140-L172 | train | 207,279 |
wandb/client | wandb/vendor/prompt_toolkit/terminal/win32_output.py | Win32Output.enter_alternate_screen | def enter_alternate_screen(self):
"""
Go to alternate screen buffer.
"""
if not self._in_alternate_screen:
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
# Create a new console buffer and activate that one.
handle = self._winapi(windll.kernel32.CreateConsoleScreenBuffer, GENERIC_READ|GENERIC_WRITE,
DWORD(0), None, DWORD(1), None)
self._winapi(windll.kernel32.SetConsoleActiveScreenBuffer, handle)
self.hconsole = handle
self._in_alternate_screen = True | python | def enter_alternate_screen(self):
"""
Go to alternate screen buffer.
"""
if not self._in_alternate_screen:
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
# Create a new console buffer and activate that one.
handle = self._winapi(windll.kernel32.CreateConsoleScreenBuffer, GENERIC_READ|GENERIC_WRITE,
DWORD(0), None, DWORD(1), None)
self._winapi(windll.kernel32.SetConsoleActiveScreenBuffer, handle)
self.hconsole = handle
self._in_alternate_screen = True | [
"def",
"enter_alternate_screen",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_in_alternate_screen",
":",
"GENERIC_READ",
"=",
"0x80000000",
"GENERIC_WRITE",
"=",
"0x40000000",
"# Create a new console buffer and activate that one.",
"handle",
"=",
"self",
".",
"_wi... | Go to alternate screen buffer. | [
"Go",
"to",
"alternate",
"screen",
"buffer",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/terminal/win32_output.py#L340-L354 | train | 207,280 |
wandb/client | wandb/vendor/prompt_toolkit/terminal/win32_output.py | Win32Output.quit_alternate_screen | def quit_alternate_screen(self):
"""
Make stdout again the active buffer.
"""
if self._in_alternate_screen:
stdout = self._winapi(windll.kernel32.GetStdHandle, STD_OUTPUT_HANDLE)
self._winapi(windll.kernel32.SetConsoleActiveScreenBuffer, stdout)
self._winapi(windll.kernel32.CloseHandle, self.hconsole)
self.hconsole = stdout
self._in_alternate_screen = False | python | def quit_alternate_screen(self):
"""
Make stdout again the active buffer.
"""
if self._in_alternate_screen:
stdout = self._winapi(windll.kernel32.GetStdHandle, STD_OUTPUT_HANDLE)
self._winapi(windll.kernel32.SetConsoleActiveScreenBuffer, stdout)
self._winapi(windll.kernel32.CloseHandle, self.hconsole)
self.hconsole = stdout
self._in_alternate_screen = False | [
"def",
"quit_alternate_screen",
"(",
"self",
")",
":",
"if",
"self",
".",
"_in_alternate_screen",
":",
"stdout",
"=",
"self",
".",
"_winapi",
"(",
"windll",
".",
"kernel32",
".",
"GetStdHandle",
",",
"STD_OUTPUT_HANDLE",
")",
"self",
".",
"_winapi",
"(",
"wi... | Make stdout again the active buffer. | [
"Make",
"stdout",
"again",
"the",
"active",
"buffer",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/terminal/win32_output.py#L356-L365 | train | 207,281 |
wandb/client | wandb/vendor/prompt_toolkit/terminal/win32_output.py | Win32Output.win32_refresh_window | def win32_refresh_window(cls):
"""
Call win32 API to refresh the whole Window.
This is sometimes necessary when the application paints background
for completion menus. When the menu disappears, it leaves traces due
to a bug in the Windows Console. Sending a repaint request solves it.
"""
# Get console handle
handle = windll.kernel32.GetConsoleWindow()
RDW_INVALIDATE = 0x0001
windll.user32.RedrawWindow(handle, None, None, c_uint(RDW_INVALIDATE)) | python | def win32_refresh_window(cls):
"""
Call win32 API to refresh the whole Window.
This is sometimes necessary when the application paints background
for completion menus. When the menu disappears, it leaves traces due
to a bug in the Windows Console. Sending a repaint request solves it.
"""
# Get console handle
handle = windll.kernel32.GetConsoleWindow()
RDW_INVALIDATE = 0x0001
windll.user32.RedrawWindow(handle, None, None, c_uint(RDW_INVALIDATE)) | [
"def",
"win32_refresh_window",
"(",
"cls",
")",
":",
"# Get console handle",
"handle",
"=",
"windll",
".",
"kernel32",
".",
"GetConsoleWindow",
"(",
")",
"RDW_INVALIDATE",
"=",
"0x0001",
"windll",
".",
"user32",
".",
"RedrawWindow",
"(",
"handle",
",",
"None",
... | Call win32 API to refresh the whole Window.
This is sometimes necessary when the application paints background
for completion menus. When the menu disappears, it leaves traces due
to a bug in the Windows Console. Sending a repaint request solves it. | [
"Call",
"win32",
"API",
"to",
"refresh",
"the",
"whole",
"Window",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/terminal/win32_output.py#L390-L402 | train | 207,282 |
wandb/client | wandb/vendor/prompt_toolkit/terminal/win32_output.py | ColorLookupTable._build_color_table | def _build_color_table():
"""
Build an RGB-to-256 color conversion table
"""
FG = FOREGROUND_COLOR
BG = BACKROUND_COLOR
return [
(0x00, 0x00, 0x00, FG.BLACK, BG.BLACK),
(0x00, 0x00, 0xaa, FG.BLUE, BG.BLUE),
(0x00, 0xaa, 0x00, FG.GREEN, BG.GREEN),
(0x00, 0xaa, 0xaa, FG.CYAN, BG.CYAN),
(0xaa, 0x00, 0x00, FG.RED, BG.RED),
(0xaa, 0x00, 0xaa, FG.MAGENTA, BG.MAGENTA),
(0xaa, 0xaa, 0x00, FG.YELLOW, BG.YELLOW),
(0x88, 0x88, 0x88, FG.GRAY, BG.GRAY),
(0x44, 0x44, 0xff, FG.BLUE | FG.INTENSITY, BG.BLUE | BG.INTENSITY),
(0x44, 0xff, 0x44, FG.GREEN | FG.INTENSITY, BG.GREEN | BG.INTENSITY),
(0x44, 0xff, 0xff, FG.CYAN | FG.INTENSITY, BG.CYAN | BG.INTENSITY),
(0xff, 0x44, 0x44, FG.RED | FG.INTENSITY, BG.RED | BG.INTENSITY),
(0xff, 0x44, 0xff, FG.MAGENTA | FG.INTENSITY, BG.MAGENTA | BG.INTENSITY),
(0xff, 0xff, 0x44, FG.YELLOW | FG.INTENSITY, BG.YELLOW | BG.INTENSITY),
(0x44, 0x44, 0x44, FG.BLACK | FG.INTENSITY, BG.BLACK | BG.INTENSITY),
(0xff, 0xff, 0xff, FG.GRAY | FG.INTENSITY, BG.GRAY | BG.INTENSITY),
] | python | def _build_color_table():
"""
Build an RGB-to-256 color conversion table
"""
FG = FOREGROUND_COLOR
BG = BACKROUND_COLOR
return [
(0x00, 0x00, 0x00, FG.BLACK, BG.BLACK),
(0x00, 0x00, 0xaa, FG.BLUE, BG.BLUE),
(0x00, 0xaa, 0x00, FG.GREEN, BG.GREEN),
(0x00, 0xaa, 0xaa, FG.CYAN, BG.CYAN),
(0xaa, 0x00, 0x00, FG.RED, BG.RED),
(0xaa, 0x00, 0xaa, FG.MAGENTA, BG.MAGENTA),
(0xaa, 0xaa, 0x00, FG.YELLOW, BG.YELLOW),
(0x88, 0x88, 0x88, FG.GRAY, BG.GRAY),
(0x44, 0x44, 0xff, FG.BLUE | FG.INTENSITY, BG.BLUE | BG.INTENSITY),
(0x44, 0xff, 0x44, FG.GREEN | FG.INTENSITY, BG.GREEN | BG.INTENSITY),
(0x44, 0xff, 0xff, FG.CYAN | FG.INTENSITY, BG.CYAN | BG.INTENSITY),
(0xff, 0x44, 0x44, FG.RED | FG.INTENSITY, BG.RED | BG.INTENSITY),
(0xff, 0x44, 0xff, FG.MAGENTA | FG.INTENSITY, BG.MAGENTA | BG.INTENSITY),
(0xff, 0xff, 0x44, FG.YELLOW | FG.INTENSITY, BG.YELLOW | BG.INTENSITY),
(0x44, 0x44, 0x44, FG.BLACK | FG.INTENSITY, BG.BLACK | BG.INTENSITY),
(0xff, 0xff, 0xff, FG.GRAY | FG.INTENSITY, BG.GRAY | BG.INTENSITY),
] | [
"def",
"_build_color_table",
"(",
")",
":",
"FG",
"=",
"FOREGROUND_COLOR",
"BG",
"=",
"BACKROUND_COLOR",
"return",
"[",
"(",
"0x00",
",",
"0x00",
",",
"0x00",
",",
"FG",
".",
"BLACK",
",",
"BG",
".",
"BLACK",
")",
",",
"(",
"0x00",
",",
"0x00",
",",
... | Build an RGB-to-256 color conversion table | [
"Build",
"an",
"RGB",
"-",
"to",
"-",
"256",
"color",
"conversion",
"table"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/terminal/win32_output.py#L471-L497 | train | 207,283 |
wandb/client | wandb/wandb_torch.py | TorchHistory.log_tensor_stats | def log_tensor_stats(self, tensor, name):
"""Add distribution statistics on a tensor's elements to the current History entry
"""
# TODO Handle the case of duplicate names.
if (isinstance(tensor, tuple) or isinstance(tensor, list)):
while (isinstance(tensor, tuple) or isinstance(tensor, list)) and (isinstance(tensor[0], tuple) or isinstance(tensor[0], list)):
tensor = [item for sublist in tensor for item in sublist]
tensor = torch.cat([t.view(-1) for t in tensor])
# checking for inheritance from _TensorBase didn't work for some reason
if not hasattr(tensor, 'shape'):
cls = type(tensor)
raise TypeError('Expected Tensor, not {}.{}'.format(
cls.__module__, cls.__name__))
history = self._history()
if history is None or not history.compute:
return
# HalfTensors on cpu do not support view(), upconvert to 32bit
if isinstance(tensor, torch.HalfTensor):
tensor = tensor.clone().type(torch.FloatTensor).detach()
flat = tensor.view(-1)
# For pytorch 0.3 we use unoptimized numpy histograms (detach is new in 0.4)
if not hasattr(flat, "detach"):
tensor = flat.cpu().clone().numpy()
history.row.update({
name: wandb.Histogram(tensor)
})
return
if flat.is_cuda:
# TODO(jhr): see if pytorch will accept something upstream to check cuda support for ops
# until then, we are going to have to catch a specific exception to check for histc support.
if self._is_cuda_histc_supported is None:
self._is_cuda_histc_supported = True
check = torch.cuda.FloatTensor(1).fill_(0)
try:
check = flat.histc(bins=self._num_bins)
except RuntimeError as e:
# Only work around missing support with specific exception
if str(e).startswith("_th_histc is not implemented"):
self._is_cuda_histc_supported = False
if not self._is_cuda_histc_supported:
flat = flat.cpu().clone().detach()
# As of torch 1.0.1.post2+nightly, float16 cuda summary ops are not supported (convert to float32)
if isinstance(flat, torch.cuda.HalfTensor):
flat = flat.clone().type(torch.cuda.FloatTensor).detach()
if isinstance(flat, torch.HalfTensor):
flat = flat.clone().type(torch.FloatTensor).detach()
tmin = flat.min().item()
tmax = flat.max().item()
tensor = flat.histc(bins=self._num_bins, min=tmin, max=tmax)
tensor = tensor.cpu().clone().detach()
bins = torch.linspace(tmin, tmax, steps=self._num_bins + 1)
history.row.update({
name: wandb.Histogram(np_histogram=(
tensor.tolist(), bins.tolist()))
}) | python | def log_tensor_stats(self, tensor, name):
"""Add distribution statistics on a tensor's elements to the current History entry
"""
# TODO Handle the case of duplicate names.
if (isinstance(tensor, tuple) or isinstance(tensor, list)):
while (isinstance(tensor, tuple) or isinstance(tensor, list)) and (isinstance(tensor[0], tuple) or isinstance(tensor[0], list)):
tensor = [item for sublist in tensor for item in sublist]
tensor = torch.cat([t.view(-1) for t in tensor])
# checking for inheritance from _TensorBase didn't work for some reason
if not hasattr(tensor, 'shape'):
cls = type(tensor)
raise TypeError('Expected Tensor, not {}.{}'.format(
cls.__module__, cls.__name__))
history = self._history()
if history is None or not history.compute:
return
# HalfTensors on cpu do not support view(), upconvert to 32bit
if isinstance(tensor, torch.HalfTensor):
tensor = tensor.clone().type(torch.FloatTensor).detach()
flat = tensor.view(-1)
# For pytorch 0.3 we use unoptimized numpy histograms (detach is new in 0.4)
if not hasattr(flat, "detach"):
tensor = flat.cpu().clone().numpy()
history.row.update({
name: wandb.Histogram(tensor)
})
return
if flat.is_cuda:
# TODO(jhr): see if pytorch will accept something upstream to check cuda support for ops
# until then, we are going to have to catch a specific exception to check for histc support.
if self._is_cuda_histc_supported is None:
self._is_cuda_histc_supported = True
check = torch.cuda.FloatTensor(1).fill_(0)
try:
check = flat.histc(bins=self._num_bins)
except RuntimeError as e:
# Only work around missing support with specific exception
if str(e).startswith("_th_histc is not implemented"):
self._is_cuda_histc_supported = False
if not self._is_cuda_histc_supported:
flat = flat.cpu().clone().detach()
# As of torch 1.0.1.post2+nightly, float16 cuda summary ops are not supported (convert to float32)
if isinstance(flat, torch.cuda.HalfTensor):
flat = flat.clone().type(torch.cuda.FloatTensor).detach()
if isinstance(flat, torch.HalfTensor):
flat = flat.clone().type(torch.FloatTensor).detach()
tmin = flat.min().item()
tmax = flat.max().item()
tensor = flat.histc(bins=self._num_bins, min=tmin, max=tmax)
tensor = tensor.cpu().clone().detach()
bins = torch.linspace(tmin, tmax, steps=self._num_bins + 1)
history.row.update({
name: wandb.Histogram(np_histogram=(
tensor.tolist(), bins.tolist()))
}) | [
"def",
"log_tensor_stats",
"(",
"self",
",",
"tensor",
",",
"name",
")",
":",
"# TODO Handle the case of duplicate names.",
"if",
"(",
"isinstance",
"(",
"tensor",
",",
"tuple",
")",
"or",
"isinstance",
"(",
"tensor",
",",
"list",
")",
")",
":",
"while",
"("... | Add distribution statistics on a tensor's elements to the current History entry | [
"Add",
"distribution",
"statistics",
"on",
"a",
"tensor",
"s",
"elements",
"to",
"the",
"current",
"History",
"entry"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/wandb_torch.py#L110-L175 | train | 207,284 |
wandb/client | wandb/vendor/prompt_toolkit/layout/controls.py | UIContent.get_height_for_line | def get_height_for_line(self, lineno, width):
"""
Return the height that a given line would need if it is rendered in a
space with the given width.
"""
try:
return self._line_heights[lineno, width]
except KeyError:
text = token_list_to_text(self.get_line(lineno))
result = self.get_height_for_text(text, width)
# Cache and return
self._line_heights[lineno, width] = result
return result | python | def get_height_for_line(self, lineno, width):
"""
Return the height that a given line would need if it is rendered in a
space with the given width.
"""
try:
return self._line_heights[lineno, width]
except KeyError:
text = token_list_to_text(self.get_line(lineno))
result = self.get_height_for_text(text, width)
# Cache and return
self._line_heights[lineno, width] = result
return result | [
"def",
"get_height_for_line",
"(",
"self",
",",
"lineno",
",",
"width",
")",
":",
"try",
":",
"return",
"self",
".",
"_line_heights",
"[",
"lineno",
",",
"width",
"]",
"except",
"KeyError",
":",
"text",
"=",
"token_list_to_text",
"(",
"self",
".",
"get_lin... | Return the height that a given line would need if it is rendered in a
space with the given width. | [
"Return",
"the",
"height",
"that",
"a",
"given",
"line",
"would",
"need",
"if",
"it",
"is",
"rendered",
"in",
"a",
"space",
"with",
"the",
"given",
"width",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/controls.py#L136-L149 | train | 207,285 |
wandb/client | wandb/vendor/prompt_toolkit/layout/controls.py | TokenListControl.preferred_width | def preferred_width(self, cli, max_available_width):
"""
Return the preferred width for this control.
That is the width of the longest line.
"""
text = token_list_to_text(self._get_tokens_cached(cli))
line_lengths = [get_cwidth(l) for l in text.split('\n')]
return max(line_lengths) | python | def preferred_width(self, cli, max_available_width):
"""
Return the preferred width for this control.
That is the width of the longest line.
"""
text = token_list_to_text(self._get_tokens_cached(cli))
line_lengths = [get_cwidth(l) for l in text.split('\n')]
return max(line_lengths) | [
"def",
"preferred_width",
"(",
"self",
",",
"cli",
",",
"max_available_width",
")",
":",
"text",
"=",
"token_list_to_text",
"(",
"self",
".",
"_get_tokens_cached",
"(",
"cli",
")",
")",
"line_lengths",
"=",
"[",
"get_cwidth",
"(",
"l",
")",
"for",
"l",
"in... | Return the preferred width for this control.
That is the width of the longest line. | [
"Return",
"the",
"preferred",
"width",
"for",
"this",
"control",
".",
"That",
"is",
"the",
"width",
"of",
"the",
"longest",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/controls.py#L244-L251 | train | 207,286 |
wandb/client | wandb/vendor/prompt_toolkit/layout/controls.py | TokenListControl.mouse_handler | def mouse_handler(self, cli, mouse_event):
"""
Handle mouse events.
(When the token list contained mouse handlers and the user clicked on
on any of these, the matching handler is called. This handler can still
return `NotImplemented` in case we want the `Window` to handle this
particular event.)
"""
if self._tokens:
# Read the generator.
tokens_for_line = list(split_lines(self._tokens))
try:
tokens = tokens_for_line[mouse_event.position.y]
except IndexError:
return NotImplemented
else:
# Find position in the token list.
xpos = mouse_event.position.x
# Find mouse handler for this character.
count = 0
for item in tokens:
count += len(item[1])
if count >= xpos:
if len(item) >= 3:
# Handler found. Call it.
# (Handler can return NotImplemented, so return
# that result.)
handler = item[2]
return handler(cli, mouse_event)
else:
break
# Otherwise, don't handle here.
return NotImplemented | python | def mouse_handler(self, cli, mouse_event):
"""
Handle mouse events.
(When the token list contained mouse handlers and the user clicked on
on any of these, the matching handler is called. This handler can still
return `NotImplemented` in case we want the `Window` to handle this
particular event.)
"""
if self._tokens:
# Read the generator.
tokens_for_line = list(split_lines(self._tokens))
try:
tokens = tokens_for_line[mouse_event.position.y]
except IndexError:
return NotImplemented
else:
# Find position in the token list.
xpos = mouse_event.position.x
# Find mouse handler for this character.
count = 0
for item in tokens:
count += len(item[1])
if count >= xpos:
if len(item) >= 3:
# Handler found. Call it.
# (Handler can return NotImplemented, so return
# that result.)
handler = item[2]
return handler(cli, mouse_event)
else:
break
# Otherwise, don't handle here.
return NotImplemented | [
"def",
"mouse_handler",
"(",
"self",
",",
"cli",
",",
"mouse_event",
")",
":",
"if",
"self",
".",
"_tokens",
":",
"# Read the generator.",
"tokens_for_line",
"=",
"list",
"(",
"split_lines",
"(",
"self",
".",
"_tokens",
")",
")",
"try",
":",
"tokens",
"=",... | Handle mouse events.
(When the token list contained mouse handlers and the user clicked on
on any of these, the matching handler is called. This handler can still
return `NotImplemented` in case we want the `Window` to handle this
particular event.) | [
"Handle",
"mouse",
"events",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/controls.py#L324-L360 | train | 207,287 |
wandb/client | wandb/vendor/prompt_toolkit/layout/controls.py | BufferControl._get_tokens_for_line_func | def _get_tokens_for_line_func(self, cli, document):
"""
Create a function that returns the tokens for a given line.
"""
# Cache using `document.text`.
def get_tokens_for_line():
return self.lexer.lex_document(cli, document)
return self._token_cache.get(document.text, get_tokens_for_line) | python | def _get_tokens_for_line_func(self, cli, document):
"""
Create a function that returns the tokens for a given line.
"""
# Cache using `document.text`.
def get_tokens_for_line():
return self.lexer.lex_document(cli, document)
return self._token_cache.get(document.text, get_tokens_for_line) | [
"def",
"_get_tokens_for_line_func",
"(",
"self",
",",
"cli",
",",
"document",
")",
":",
"# Cache using `document.text`.",
"def",
"get_tokens_for_line",
"(",
")",
":",
"return",
"self",
".",
"lexer",
".",
"lex_document",
"(",
"cli",
",",
"document",
")",
"return"... | Create a function that returns the tokens for a given line. | [
"Create",
"a",
"function",
"that",
"returns",
"the",
"tokens",
"for",
"a",
"given",
"line",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/controls.py#L522-L530 | train | 207,288 |
wandb/client | wandb/vendor/prompt_toolkit/layout/controls.py | BufferControl.create_content | def create_content(self, cli, width, height):
"""
Create a UIContent.
"""
buffer = self._buffer(cli)
# Get the document to be shown. If we are currently searching (the
# search buffer has focus, and the preview_search filter is enabled),
# then use the search document, which has possibly a different
# text/cursor position.)
def preview_now():
""" True when we should preview a search. """
return bool(self.preview_search(cli) and
cli.buffers[self.search_buffer_name].text)
if preview_now():
if self.get_search_state:
ss = self.get_search_state(cli)
else:
ss = cli.search_state
document = buffer.document_for_search(SearchState(
text=cli.current_buffer.text,
direction=ss.direction,
ignore_case=ss.ignore_case))
else:
document = buffer.document
get_processed_line = self._create_get_processed_line_func(cli, document)
self._last_get_processed_line = get_processed_line
def translate_rowcol(row, col):
" Return the content column for this coordinate. "
return Point(y=row, x=get_processed_line(row).source_to_display(col))
def get_line(i):
" Return the tokens for a given line number. "
tokens = get_processed_line(i).tokens
# Add a space at the end, because that is a possible cursor
# position. (When inserting after the input.) We should do this on
# all the lines, not just the line containing the cursor. (Because
# otherwise, line wrapping/scrolling could change when moving the
# cursor around.)
tokens = tokens + [(self.default_char.token, ' ')]
return tokens
content = UIContent(
get_line=get_line,
line_count=document.line_count,
cursor_position=translate_rowcol(document.cursor_position_row,
document.cursor_position_col),
default_char=self.default_char)
# If there is an auto completion going on, use that start point for a
# pop-up menu position. (But only when this buffer has the focus --
# there is only one place for a menu, determined by the focussed buffer.)
if cli.current_buffer_name == self.buffer_name:
menu_position = self.menu_position(cli) if self.menu_position else None
if menu_position is not None:
assert isinstance(menu_position, int)
menu_row, menu_col = buffer.document.translate_index_to_position(menu_position)
content.menu_position = translate_rowcol(menu_row, menu_col)
elif buffer.complete_state:
# Position for completion menu.
# Note: We use 'min', because the original cursor position could be
# behind the input string when the actual completion is for
# some reason shorter than the text we had before. (A completion
# can change and shorten the input.)
menu_row, menu_col = buffer.document.translate_index_to_position(
min(buffer.cursor_position,
buffer.complete_state.original_document.cursor_position))
content.menu_position = translate_rowcol(menu_row, menu_col)
else:
content.menu_position = None
return content | python | def create_content(self, cli, width, height):
"""
Create a UIContent.
"""
buffer = self._buffer(cli)
# Get the document to be shown. If we are currently searching (the
# search buffer has focus, and the preview_search filter is enabled),
# then use the search document, which has possibly a different
# text/cursor position.)
def preview_now():
""" True when we should preview a search. """
return bool(self.preview_search(cli) and
cli.buffers[self.search_buffer_name].text)
if preview_now():
if self.get_search_state:
ss = self.get_search_state(cli)
else:
ss = cli.search_state
document = buffer.document_for_search(SearchState(
text=cli.current_buffer.text,
direction=ss.direction,
ignore_case=ss.ignore_case))
else:
document = buffer.document
get_processed_line = self._create_get_processed_line_func(cli, document)
self._last_get_processed_line = get_processed_line
def translate_rowcol(row, col):
" Return the content column for this coordinate. "
return Point(y=row, x=get_processed_line(row).source_to_display(col))
def get_line(i):
" Return the tokens for a given line number. "
tokens = get_processed_line(i).tokens
# Add a space at the end, because that is a possible cursor
# position. (When inserting after the input.) We should do this on
# all the lines, not just the line containing the cursor. (Because
# otherwise, line wrapping/scrolling could change when moving the
# cursor around.)
tokens = tokens + [(self.default_char.token, ' ')]
return tokens
content = UIContent(
get_line=get_line,
line_count=document.line_count,
cursor_position=translate_rowcol(document.cursor_position_row,
document.cursor_position_col),
default_char=self.default_char)
# If there is an auto completion going on, use that start point for a
# pop-up menu position. (But only when this buffer has the focus --
# there is only one place for a menu, determined by the focussed buffer.)
if cli.current_buffer_name == self.buffer_name:
menu_position = self.menu_position(cli) if self.menu_position else None
if menu_position is not None:
assert isinstance(menu_position, int)
menu_row, menu_col = buffer.document.translate_index_to_position(menu_position)
content.menu_position = translate_rowcol(menu_row, menu_col)
elif buffer.complete_state:
# Position for completion menu.
# Note: We use 'min', because the original cursor position could be
# behind the input string when the actual completion is for
# some reason shorter than the text we had before. (A completion
# can change and shorten the input.)
menu_row, menu_col = buffer.document.translate_index_to_position(
min(buffer.cursor_position,
buffer.complete_state.original_document.cursor_position))
content.menu_position = translate_rowcol(menu_row, menu_col)
else:
content.menu_position = None
return content | [
"def",
"create_content",
"(",
"self",
",",
"cli",
",",
"width",
",",
"height",
")",
":",
"buffer",
"=",
"self",
".",
"_buffer",
"(",
"cli",
")",
"# Get the document to be shown. If we are currently searching (the",
"# search buffer has focus, and the preview_search filter i... | Create a UIContent. | [
"Create",
"a",
"UIContent",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/controls.py#L590-L666 | train | 207,289 |
wandb/client | wandb/vendor/prompt_toolkit/layout/controls.py | BufferControl.mouse_handler | def mouse_handler(self, cli, mouse_event):
"""
Mouse handler for this control.
"""
buffer = self._buffer(cli)
position = mouse_event.position
# Focus buffer when clicked.
if self.has_focus(cli):
if self._last_get_processed_line:
processed_line = self._last_get_processed_line(position.y)
# Translate coordinates back to the cursor position of the
# original input.
xpos = processed_line.display_to_source(position.x)
index = buffer.document.translate_row_col_to_index(position.y, xpos)
# Set the cursor position.
if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
buffer.exit_selection()
buffer.cursor_position = index
elif mouse_event.event_type == MouseEventType.MOUSE_UP:
# When the cursor was moved to another place, select the text.
# (The >1 is actually a small but acceptable workaround for
# selecting text in Vi navigation mode. In navigation mode,
# the cursor can never be after the text, so the cursor
# will be repositioned automatically.)
if abs(buffer.cursor_position - index) > 1:
buffer.start_selection(selection_type=SelectionType.CHARACTERS)
buffer.cursor_position = index
# Select word around cursor on double click.
# Two MOUSE_UP events in a short timespan are considered a double click.
double_click = self._last_click_timestamp and time.time() - self._last_click_timestamp < .3
self._last_click_timestamp = time.time()
if double_click:
start, end = buffer.document.find_boundaries_of_current_word()
buffer.cursor_position += start
buffer.start_selection(selection_type=SelectionType.CHARACTERS)
buffer.cursor_position += end - start
else:
# Don't handle scroll events here.
return NotImplemented
# Not focussed, but focussing on click events.
else:
if self.focus_on_click(cli) and mouse_event.event_type == MouseEventType.MOUSE_UP:
# Focus happens on mouseup. (If we did this on mousedown, the
# up event will be received at the point where this widget is
# focussed and be handled anyway.)
cli.focus(self.buffer_name)
else:
return NotImplemented | python | def mouse_handler(self, cli, mouse_event):
"""
Mouse handler for this control.
"""
buffer = self._buffer(cli)
position = mouse_event.position
# Focus buffer when clicked.
if self.has_focus(cli):
if self._last_get_processed_line:
processed_line = self._last_get_processed_line(position.y)
# Translate coordinates back to the cursor position of the
# original input.
xpos = processed_line.display_to_source(position.x)
index = buffer.document.translate_row_col_to_index(position.y, xpos)
# Set the cursor position.
if mouse_event.event_type == MouseEventType.MOUSE_DOWN:
buffer.exit_selection()
buffer.cursor_position = index
elif mouse_event.event_type == MouseEventType.MOUSE_UP:
# When the cursor was moved to another place, select the text.
# (The >1 is actually a small but acceptable workaround for
# selecting text in Vi navigation mode. In navigation mode,
# the cursor can never be after the text, so the cursor
# will be repositioned automatically.)
if abs(buffer.cursor_position - index) > 1:
buffer.start_selection(selection_type=SelectionType.CHARACTERS)
buffer.cursor_position = index
# Select word around cursor on double click.
# Two MOUSE_UP events in a short timespan are considered a double click.
double_click = self._last_click_timestamp and time.time() - self._last_click_timestamp < .3
self._last_click_timestamp = time.time()
if double_click:
start, end = buffer.document.find_boundaries_of_current_word()
buffer.cursor_position += start
buffer.start_selection(selection_type=SelectionType.CHARACTERS)
buffer.cursor_position += end - start
else:
# Don't handle scroll events here.
return NotImplemented
# Not focussed, but focussing on click events.
else:
if self.focus_on_click(cli) and mouse_event.event_type == MouseEventType.MOUSE_UP:
# Focus happens on mouseup. (If we did this on mousedown, the
# up event will be received at the point where this widget is
# focussed and be handled anyway.)
cli.focus(self.buffer_name)
else:
return NotImplemented | [
"def",
"mouse_handler",
"(",
"self",
",",
"cli",
",",
"mouse_event",
")",
":",
"buffer",
"=",
"self",
".",
"_buffer",
"(",
"cli",
")",
"position",
"=",
"mouse_event",
".",
"position",
"# Focus buffer when clicked.",
"if",
"self",
".",
"has_focus",
"(",
"cli"... | Mouse handler for this control. | [
"Mouse",
"handler",
"for",
"this",
"control",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/controls.py#L668-L722 | train | 207,290 |
wandb/client | wandb/vendor/prompt_toolkit/layout/prompt.py | _get_arg_tokens | def _get_arg_tokens(cli):
"""
Tokens for the arg-prompt.
"""
arg = cli.input_processor.arg
return [
(Token.Prompt.Arg, '(arg: '),
(Token.Prompt.Arg.Text, str(arg)),
(Token.Prompt.Arg, ') '),
] | python | def _get_arg_tokens(cli):
"""
Tokens for the arg-prompt.
"""
arg = cli.input_processor.arg
return [
(Token.Prompt.Arg, '(arg: '),
(Token.Prompt.Arg.Text, str(arg)),
(Token.Prompt.Arg, ') '),
] | [
"def",
"_get_arg_tokens",
"(",
"cli",
")",
":",
"arg",
"=",
"cli",
".",
"input_processor",
".",
"arg",
"return",
"[",
"(",
"Token",
".",
"Prompt",
".",
"Arg",
",",
"'(arg: '",
")",
",",
"(",
"Token",
".",
"Prompt",
".",
"Arg",
".",
"Text",
",",
"st... | Tokens for the arg-prompt. | [
"Tokens",
"for",
"the",
"arg",
"-",
"prompt",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/prompt.py#L101-L111 | train | 207,291 |
wandb/client | wandb/vendor/prompt_toolkit/layout/prompt.py | DefaultPrompt.from_message | def from_message(cls, message='> '):
"""
Create a default prompt with a static message text.
"""
assert isinstance(message, text_type)
def get_message_tokens(cli):
return [(Token.Prompt, message)]
return cls(get_message_tokens) | python | def from_message(cls, message='> '):
"""
Create a default prompt with a static message text.
"""
assert isinstance(message, text_type)
def get_message_tokens(cli):
return [(Token.Prompt, message)]
return cls(get_message_tokens) | [
"def",
"from_message",
"(",
"cls",
",",
"message",
"=",
"'> '",
")",
":",
"assert",
"isinstance",
"(",
"message",
",",
"text_type",
")",
"def",
"get_message_tokens",
"(",
"cli",
")",
":",
"return",
"[",
"(",
"Token",
".",
"Prompt",
",",
"message",
")",
... | Create a default prompt with a static message text. | [
"Create",
"a",
"default",
"prompt",
"with",
"a",
"static",
"message",
"text",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/prompt.py#L38-L46 | train | 207,292 |
wandb/client | wandb/jsonlfile.py | write_jsonl_file | def write_jsonl_file(fname, data):
"""Writes a jsonl file.
Args:
data: list of json encoded data
"""
if not isinstance(data, list):
print('warning: malformed json data for file', fname)
return
with open(fname, 'w') as of:
for row in data:
# TODO: other malformed cases?
if row.strip():
of.write('%s\n' % row.strip()) | python | def write_jsonl_file(fname, data):
"""Writes a jsonl file.
Args:
data: list of json encoded data
"""
if not isinstance(data, list):
print('warning: malformed json data for file', fname)
return
with open(fname, 'w') as of:
for row in data:
# TODO: other malformed cases?
if row.strip():
of.write('%s\n' % row.strip()) | [
"def",
"write_jsonl_file",
"(",
"fname",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"print",
"(",
"'warning: malformed json data for file'",
",",
"fname",
")",
"return",
"with",
"open",
"(",
"fname",
",",
"'w'",
"... | Writes a jsonl file.
Args:
data: list of json encoded data | [
"Writes",
"a",
"jsonl",
"file",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/jsonlfile.py#L78-L91 | train | 207,293 |
wandb/client | wandb/vendor/prompt_toolkit/eventloop/posix.py | PosixEventLoop.received_winch | def received_winch(self):
"""
Notify the event loop that SIGWINCH has been received
"""
# Process signal asynchronously, because this handler can write to the
# output, and doing this inside the signal handler causes easily
# reentrant calls, giving runtime errors..
# Furthur, this has to be thread safe. When the CommandLineInterface
# runs not in the main thread, this function still has to be called
# from the main thread. (The only place where we can install signal
# handlers.)
def process_winch():
if self._callbacks:
self._callbacks.terminal_size_changed()
self.call_from_executor(process_winch) | python | def received_winch(self):
"""
Notify the event loop that SIGWINCH has been received
"""
# Process signal asynchronously, because this handler can write to the
# output, and doing this inside the signal handler causes easily
# reentrant calls, giving runtime errors..
# Furthur, this has to be thread safe. When the CommandLineInterface
# runs not in the main thread, this function still has to be called
# from the main thread. (The only place where we can install signal
# handlers.)
def process_winch():
if self._callbacks:
self._callbacks.terminal_size_changed()
self.call_from_executor(process_winch) | [
"def",
"received_winch",
"(",
"self",
")",
":",
"# Process signal asynchronously, because this handler can write to the",
"# output, and doing this inside the signal handler causes easily",
"# reentrant calls, giving runtime errors..",
"# Furthur, this has to be thread safe. When the CommandLineIn... | Notify the event loop that SIGWINCH has been received | [
"Notify",
"the",
"event",
"loop",
"that",
"SIGWINCH",
"has",
"been",
"received"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/eventloop/posix.py#L191-L207 | train | 207,294 |
wandb/client | wandb/vendor/prompt_toolkit/eventloop/posix.py | PosixEventLoop.add_reader | def add_reader(self, fd, callback):
" Add read file descriptor to the event loop. "
fd = fd_to_int(fd)
self._read_fds[fd] = callback
self.selector.register(fd) | python | def add_reader(self, fd, callback):
" Add read file descriptor to the event loop. "
fd = fd_to_int(fd)
self._read_fds[fd] = callback
self.selector.register(fd) | [
"def",
"add_reader",
"(",
"self",
",",
"fd",
",",
"callback",
")",
":",
"fd",
"=",
"fd_to_int",
"(",
"fd",
")",
"self",
".",
"_read_fds",
"[",
"fd",
"]",
"=",
"callback",
"self",
".",
"selector",
".",
"register",
"(",
"fd",
")"
] | Add read file descriptor to the event loop. | [
"Add",
"read",
"file",
"descriptor",
"to",
"the",
"event",
"loop",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/eventloop/posix.py#L271-L275 | train | 207,295 |
wandb/client | wandb/vendor/prompt_toolkit/eventloop/posix.py | PosixEventLoop.remove_reader | def remove_reader(self, fd):
" Remove read file descriptor from the event loop. "
fd = fd_to_int(fd)
if fd in self._read_fds:
del self._read_fds[fd]
self.selector.unregister(fd) | python | def remove_reader(self, fd):
" Remove read file descriptor from the event loop. "
fd = fd_to_int(fd)
if fd in self._read_fds:
del self._read_fds[fd]
self.selector.unregister(fd) | [
"def",
"remove_reader",
"(",
"self",
",",
"fd",
")",
":",
"fd",
"=",
"fd_to_int",
"(",
"fd",
")",
"if",
"fd",
"in",
"self",
".",
"_read_fds",
":",
"del",
"self",
".",
"_read_fds",
"[",
"fd",
"]",
"self",
".",
"selector",
".",
"unregister",
"(",
"fd... | Remove read file descriptor from the event loop. | [
"Remove",
"read",
"file",
"descriptor",
"from",
"the",
"event",
"loop",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/eventloop/posix.py#L277-L284 | train | 207,296 |
wandb/client | wandb/vendor/prompt_toolkit/cache.py | memoized | def memoized(maxsize=1024):
"""
Momoization decorator for immutable classes and pure functions.
"""
cache = SimpleCache(maxsize=maxsize)
def decorator(obj):
@wraps(obj)
def new_callable(*a, **kw):
def create_new():
return obj(*a, **kw)
key = (a, tuple(kw.items()))
return cache.get(key, create_new)
return new_callable
return decorator | python | def memoized(maxsize=1024):
"""
Momoization decorator for immutable classes and pure functions.
"""
cache = SimpleCache(maxsize=maxsize)
def decorator(obj):
@wraps(obj)
def new_callable(*a, **kw):
def create_new():
return obj(*a, **kw)
key = (a, tuple(kw.items()))
return cache.get(key, create_new)
return new_callable
return decorator | [
"def",
"memoized",
"(",
"maxsize",
"=",
"1024",
")",
":",
"cache",
"=",
"SimpleCache",
"(",
"maxsize",
"=",
"maxsize",
")",
"def",
"decorator",
"(",
"obj",
")",
":",
"@",
"wraps",
"(",
"obj",
")",
"def",
"new_callable",
"(",
"*",
"a",
",",
"*",
"*"... | Momoization decorator for immutable classes and pure functions. | [
"Momoization",
"decorator",
"for",
"immutable",
"classes",
"and",
"pure",
"functions",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/cache.py#L96-L111 | train | 207,297 |
wandb/client | wandb/vendor/prompt_toolkit/cache.py | SimpleCache.get | def get(self, key, getter_func):
"""
Get object from the cache.
If not found, call `getter_func` to resolve it, and put that on the top
of the cache instead.
"""
# Look in cache first.
try:
return self._data[key]
except KeyError:
# Not found? Get it.
value = getter_func()
self._data[key] = value
self._keys.append(key)
# Remove the oldest key when the size is exceeded.
if len(self._data) > self.maxsize:
key_to_remove = self._keys.popleft()
if key_to_remove in self._data:
del self._data[key_to_remove]
return value | python | def get(self, key, getter_func):
"""
Get object from the cache.
If not found, call `getter_func` to resolve it, and put that on the top
of the cache instead.
"""
# Look in cache first.
try:
return self._data[key]
except KeyError:
# Not found? Get it.
value = getter_func()
self._data[key] = value
self._keys.append(key)
# Remove the oldest key when the size is exceeded.
if len(self._data) > self.maxsize:
key_to_remove = self._keys.popleft()
if key_to_remove in self._data:
del self._data[key_to_remove]
return value | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"getter_func",
")",
":",
"# Look in cache first.",
"try",
":",
"return",
"self",
".",
"_data",
"[",
"key",
"]",
"except",
"KeyError",
":",
"# Not found? Get it.",
"value",
"=",
"getter_func",
"(",
")",
"self",
".... | Get object from the cache.
If not found, call `getter_func` to resolve it, and put that on the top
of the cache instead. | [
"Get",
"object",
"from",
"the",
"cache",
".",
"If",
"not",
"found",
"call",
"getter_func",
"to",
"resolve",
"it",
"and",
"put",
"that",
"on",
"the",
"top",
"of",
"the",
"cache",
"instead",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/cache.py#L26-L47 | train | 207,298 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/registry.py | Registry.add_binding | def add_binding(self, *keys, **kwargs):
"""
Decorator for annotating key bindings.
:param filter: :class:`~prompt_toolkit.filters.CLIFilter` to determine
when this key binding is active.
:param eager: :class:`~prompt_toolkit.filters.CLIFilter` or `bool`.
When True, ignore potential longer matches when this key binding is
hit. E.g. when there is an active eager key binding for Ctrl-X,
execute the handler immediately and ignore the key binding for
Ctrl-X Ctrl-E of which it is a prefix.
:param save_before: Callable that takes an `Event` and returns True if
we should save the current buffer, before handling the event.
(That's the default.)
"""
filter = to_cli_filter(kwargs.pop('filter', True))
eager = to_cli_filter(kwargs.pop('eager', False))
save_before = kwargs.pop('save_before', lambda e: True)
to_cli_filter(kwargs.pop('invalidate_ui', True)) # Deprecated! (ignored.)
assert not kwargs
assert keys
assert all(isinstance(k, (Key, text_type)) for k in keys), \
'Key bindings should consist of Key and string (unicode) instances.'
assert callable(save_before)
if isinstance(filter, Never):
# When a filter is Never, it will always stay disabled, so in that case
# don't bother putting it in the registry. It will slow down every key
# press otherwise.
def decorator(func):
return func
else:
def decorator(func):
self.key_bindings.append(
_Binding(keys, func, filter=filter, eager=eager,
save_before=save_before))
self._clear_cache()
return func
return decorator | python | def add_binding(self, *keys, **kwargs):
"""
Decorator for annotating key bindings.
:param filter: :class:`~prompt_toolkit.filters.CLIFilter` to determine
when this key binding is active.
:param eager: :class:`~prompt_toolkit.filters.CLIFilter` or `bool`.
When True, ignore potential longer matches when this key binding is
hit. E.g. when there is an active eager key binding for Ctrl-X,
execute the handler immediately and ignore the key binding for
Ctrl-X Ctrl-E of which it is a prefix.
:param save_before: Callable that takes an `Event` and returns True if
we should save the current buffer, before handling the event.
(That's the default.)
"""
filter = to_cli_filter(kwargs.pop('filter', True))
eager = to_cli_filter(kwargs.pop('eager', False))
save_before = kwargs.pop('save_before', lambda e: True)
to_cli_filter(kwargs.pop('invalidate_ui', True)) # Deprecated! (ignored.)
assert not kwargs
assert keys
assert all(isinstance(k, (Key, text_type)) for k in keys), \
'Key bindings should consist of Key and string (unicode) instances.'
assert callable(save_before)
if isinstance(filter, Never):
# When a filter is Never, it will always stay disabled, so in that case
# don't bother putting it in the registry. It will slow down every key
# press otherwise.
def decorator(func):
return func
else:
def decorator(func):
self.key_bindings.append(
_Binding(keys, func, filter=filter, eager=eager,
save_before=save_before))
self._clear_cache()
return func
return decorator | [
"def",
"add_binding",
"(",
"self",
",",
"*",
"keys",
",",
"*",
"*",
"kwargs",
")",
":",
"filter",
"=",
"to_cli_filter",
"(",
"kwargs",
".",
"pop",
"(",
"'filter'",
",",
"True",
")",
")",
"eager",
"=",
"to_cli_filter",
"(",
"kwargs",
".",
"pop",
"(",
... | Decorator for annotating key bindings.
:param filter: :class:`~prompt_toolkit.filters.CLIFilter` to determine
when this key binding is active.
:param eager: :class:`~prompt_toolkit.filters.CLIFilter` or `bool`.
When True, ignore potential longer matches when this key binding is
hit. E.g. when there is an active eager key binding for Ctrl-X,
execute the handler immediately and ignore the key binding for
Ctrl-X Ctrl-E of which it is a prefix.
:param save_before: Callable that takes an `Event` and returns True if
we should save the current buffer, before handling the event.
(That's the default.) | [
"Decorator",
"for",
"annotating",
"key",
"bindings",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/registry.py#L101-L141 | train | 207,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.