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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
dylanaraps/pywal
pywal/__main__.py
parse_args
def parse_args(parser): """Process args.""" args = parser.parse_args() if args.q: logging.getLogger().disabled = True sys.stdout = sys.stderr = open(os.devnull, "w") if args.a: util.Color.alpha_num = args.a if args.i: image_file = image.get(args.i, iterative=args.i...
python
def parse_args(parser): """Process args.""" args = parser.parse_args() if args.q: logging.getLogger().disabled = True sys.stdout = sys.stderr = open(os.devnull, "w") if args.a: util.Color.alpha_num = args.a if args.i: image_file = image.get(args.i, iterative=args.i...
[ "def", "parse_args", "(", "parser", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "q", ":", "logging", ".", "getLogger", "(", ")", ".", "disabled", "=", "True", "sys", ".", "stdout", "=", "sys", ".", "stderr", "="...
Process args.
[ "Process", "args", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/__main__.py#L150-L195
train
dylanaraps/pywal
pywal/sequences.py
set_special
def set_special(index, color, iterm_name="h", alpha=100): """Convert a hex color to a special sequence.""" if OS == "Darwin" and iterm_name: return "\033]P%s%s\033\\" % (iterm_name, color.strip("#")) if index in [11, 708] and alpha != "100": return "\033]%s;[%s]%s\033\\" % (index, alpha, co...
python
def set_special(index, color, iterm_name="h", alpha=100): """Convert a hex color to a special sequence.""" if OS == "Darwin" and iterm_name: return "\033]P%s%s\033\\" % (iterm_name, color.strip("#")) if index in [11, 708] and alpha != "100": return "\033]%s;[%s]%s\033\\" % (index, alpha, co...
[ "def", "set_special", "(", "index", ",", "color", ",", "iterm_name", "=", "\"h\"", ",", "alpha", "=", "100", ")", ":", "if", "OS", "==", "\"Darwin\"", "and", "iterm_name", ":", "return", "\"\\033]P%s%s\\033\\\\\"", "%", "(", "iterm_name", ",", "color", "."...
Convert a hex color to a special sequence.
[ "Convert", "a", "hex", "color", "to", "a", "special", "sequence", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L12-L20
train
dylanaraps/pywal
pywal/sequences.py
set_color
def set_color(index, color): """Convert a hex color to a text color sequence.""" if OS == "Darwin" and index < 20: return "\033]P%1x%s\033\\" % (index, color.strip("#")) return "\033]4;%s;%s\033\\" % (index, color)
python
def set_color(index, color): """Convert a hex color to a text color sequence.""" if OS == "Darwin" and index < 20: return "\033]P%1x%s\033\\" % (index, color.strip("#")) return "\033]4;%s;%s\033\\" % (index, color)
[ "def", "set_color", "(", "index", ",", "color", ")", ":", "if", "OS", "==", "\"Darwin\"", "and", "index", "<", "20", ":", "return", "\"\\033]P%1x%s\\033\\\\\"", "%", "(", "index", ",", "color", ".", "strip", "(", "\"#\"", ")", ")", "return", "\"\\033]4;%...
Convert a hex color to a text color sequence.
[ "Convert", "a", "hex", "color", "to", "a", "text", "color", "sequence", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L23-L28
train
dylanaraps/pywal
pywal/sequences.py
create_sequences
def create_sequences(colors, vte_fix=False): """Create the escape sequences.""" alpha = colors["alpha"] # Colors 0-15. sequences = [set_color(index, colors["colors"]["color%s" % index]) for index in range(16)] # Special colors. # Source: https://goo.gl/KcoQgP # 10 = foregr...
python
def create_sequences(colors, vte_fix=False): """Create the escape sequences.""" alpha = colors["alpha"] # Colors 0-15. sequences = [set_color(index, colors["colors"]["color%s" % index]) for index in range(16)] # Special colors. # Source: https://goo.gl/KcoQgP # 10 = foregr...
[ "def", "create_sequences", "(", "colors", ",", "vte_fix", "=", "False", ")", ":", "alpha", "=", "colors", "[", "\"alpha\"", "]", "# Colors 0-15.", "sequences", "=", "[", "set_color", "(", "index", ",", "colors", "[", "\"colors\"", "]", "[", "\"color%s\"", ...
Create the escape sequences.
[ "Create", "the", "escape", "sequences", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L38-L69
train
dylanaraps/pywal
pywal/sequences.py
send
def send(colors, cache_dir=CACHE_DIR, to_send=True, vte_fix=False): """Send colors to all open terminals.""" if OS == "Darwin": tty_pattern = "/dev/ttys00[0-9]*" else: tty_pattern = "/dev/pts/[0-9]*" sequences = create_sequences(colors, vte_fix) # Writing to "/dev/pts/[0-9] lets y...
python
def send(colors, cache_dir=CACHE_DIR, to_send=True, vte_fix=False): """Send colors to all open terminals.""" if OS == "Darwin": tty_pattern = "/dev/ttys00[0-9]*" else: tty_pattern = "/dev/pts/[0-9]*" sequences = create_sequences(colors, vte_fix) # Writing to "/dev/pts/[0-9] lets y...
[ "def", "send", "(", "colors", ",", "cache_dir", "=", "CACHE_DIR", ",", "to_send", "=", "True", ",", "vte_fix", "=", "False", ")", ":", "if", "OS", "==", "\"Darwin\"", ":", "tty_pattern", "=", "\"/dev/ttys00[0-9]*\"", "else", ":", "tty_pattern", "=", "\"/de...
Send colors to all open terminals.
[ "Send", "colors", "to", "all", "open", "terminals", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L72-L88
train
dylanaraps/pywal
pywal/export.py
template
def template(colors, input_file, output_file=None): """Read template file, substitute markers and save the file elsewhere.""" template_data = util.read_file_raw(input_file) try: template_data = "".join(template_data).format(**colors) except ValueError: logging.error("Syntax error...
python
def template(colors, input_file, output_file=None): """Read template file, substitute markers and save the file elsewhere.""" template_data = util.read_file_raw(input_file) try: template_data = "".join(template_data).format(**colors) except ValueError: logging.error("Syntax error...
[ "def", "template", "(", "colors", ",", "input_file", ",", "output_file", "=", "None", ")", ":", "template_data", "=", "util", ".", "read_file_raw", "(", "input_file", ")", "try", ":", "template_data", "=", "\"\"", ".", "join", "(", "template_data", ")", "....
Read template file, substitute markers and save the file elsewhere.
[ "Read", "template", "file", "substitute", "markers", "and", "save", "the", "file", "elsewhere", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/export.py#L11-L22
train
dylanaraps/pywal
pywal/export.py
every
def every(colors, output_dir=CACHE_DIR): """Export all template files.""" colors = flatten_colors(colors) template_dir = os.path.join(MODULE_DIR, "templates") template_dir_user = os.path.join(CONF_DIR, "templates") util.create_dir(template_dir_user) join = os.path.join # Minor optimization. ...
python
def every(colors, output_dir=CACHE_DIR): """Export all template files.""" colors = flatten_colors(colors) template_dir = os.path.join(MODULE_DIR, "templates") template_dir_user = os.path.join(CONF_DIR, "templates") util.create_dir(template_dir_user) join = os.path.join # Minor optimization. ...
[ "def", "every", "(", "colors", ",", "output_dir", "=", "CACHE_DIR", ")", ":", "colors", "=", "flatten_colors", "(", "colors", ")", "template_dir", "=", "os", ".", "path", ".", "join", "(", "MODULE_DIR", ",", "\"templates\"", ")", "template_dir_user", "=", ...
Export all template files.
[ "Export", "all", "template", "files", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/export.py#L62-L76
train
dylanaraps/pywal
pywal/export.py
color
def color(colors, export_type, output_file=None): """Export a single template file.""" all_colors = flatten_colors(colors) template_name = get_export_type(export_type) template_file = os.path.join(MODULE_DIR, "templates", template_name) output_file = output_file or os.path.join(CACHE_DIR, template_...
python
def color(colors, export_type, output_file=None): """Export a single template file.""" all_colors = flatten_colors(colors) template_name = get_export_type(export_type) template_file = os.path.join(MODULE_DIR, "templates", template_name) output_file = output_file or os.path.join(CACHE_DIR, template_...
[ "def", "color", "(", "colors", ",", "export_type", ",", "output_file", "=", "None", ")", ":", "all_colors", "=", "flatten_colors", "(", "colors", ")", "template_name", "=", "get_export_type", "(", "export_type", ")", "template_file", "=", "os", ".", "path", ...
Export a single template file.
[ "Export", "a", "single", "template", "file", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/export.py#L79-L91
train
dylanaraps/pywal
pywal/reload.py
tty
def tty(tty_reload): """Load colors in tty.""" tty_script = os.path.join(CACHE_DIR, "colors-tty.sh") term = os.environ.get("TERM") if tty_reload and term == "linux": subprocess.Popen(["sh", tty_script])
python
def tty(tty_reload): """Load colors in tty.""" tty_script = os.path.join(CACHE_DIR, "colors-tty.sh") term = os.environ.get("TERM") if tty_reload and term == "linux": subprocess.Popen(["sh", tty_script])
[ "def", "tty", "(", "tty_reload", ")", ":", "tty_script", "=", "os", ".", "path", ".", "join", "(", "CACHE_DIR", ",", "\"colors-tty.sh\"", ")", "term", "=", "os", ".", "environ", ".", "get", "(", "\"TERM\"", ")", "if", "tty_reload", "and", "term", "==",...
Load colors in tty.
[ "Load", "colors", "in", "tty", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L13-L19
train
dylanaraps/pywal
pywal/reload.py
xrdb
def xrdb(xrdb_files=None): """Merge the colors into the X db so new terminals use them.""" xrdb_files = xrdb_files or \ [os.path.join(CACHE_DIR, "colors.Xresources")] if shutil.which("xrdb") and OS != "Darwin": for file in xrdb_files: subprocess.run(["xrdb", "-merge", "-quiet", ...
python
def xrdb(xrdb_files=None): """Merge the colors into the X db so new terminals use them.""" xrdb_files = xrdb_files or \ [os.path.join(CACHE_DIR, "colors.Xresources")] if shutil.which("xrdb") and OS != "Darwin": for file in xrdb_files: subprocess.run(["xrdb", "-merge", "-quiet", ...
[ "def", "xrdb", "(", "xrdb_files", "=", "None", ")", ":", "xrdb_files", "=", "xrdb_files", "or", "[", "os", ".", "path", ".", "join", "(", "CACHE_DIR", ",", "\"colors.Xresources\"", ")", "]", "if", "shutil", ".", "which", "(", "\"xrdb\"", ")", "and", "O...
Merge the colors into the X db so new terminals use them.
[ "Merge", "the", "colors", "into", "the", "X", "db", "so", "new", "terminals", "use", "them", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L22-L29
train
dylanaraps/pywal
pywal/reload.py
gtk
def gtk(): """Reload GTK theme on the fly.""" # Here we call a Python 2 script to reload the GTK themes. # This is done because the Python 3 GTK/Gdk libraries don't # provide a way of doing this. if shutil.which("python2"): gtk_reload = os.path.join(MODULE_DIR, "scripts", "gtk_reload.py") ...
python
def gtk(): """Reload GTK theme on the fly.""" # Here we call a Python 2 script to reload the GTK themes. # This is done because the Python 3 GTK/Gdk libraries don't # provide a way of doing this. if shutil.which("python2"): gtk_reload = os.path.join(MODULE_DIR, "scripts", "gtk_reload.py") ...
[ "def", "gtk", "(", ")", ":", "# Here we call a Python 2 script to reload the GTK themes.", "# This is done because the Python 3 GTK/Gdk libraries don't", "# provide a way of doing this.", "if", "shutil", ".", "which", "(", "\"python2\"", ")", ":", "gtk_reload", "=", "os", ".", ...
Reload GTK theme on the fly.
[ "Reload", "GTK", "theme", "on", "the", "fly", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L32-L42
train
dylanaraps/pywal
pywal/reload.py
env
def env(xrdb_file=None, tty_reload=True): """Reload environment.""" xrdb(xrdb_file) i3() bspwm() kitty() sway() polybar() logging.info("Reloaded environment.") tty(tty_reload)
python
def env(xrdb_file=None, tty_reload=True): """Reload environment.""" xrdb(xrdb_file) i3() bspwm() kitty() sway() polybar() logging.info("Reloaded environment.") tty(tty_reload)
[ "def", "env", "(", "xrdb_file", "=", "None", ",", "tty_reload", "=", "True", ")", ":", "xrdb", "(", "xrdb_file", ")", "i3", "(", ")", "bspwm", "(", ")", "kitty", "(", ")", "sway", "(", ")", "polybar", "(", ")", "logging", ".", "info", "(", "\"Rel...
Reload environment.
[ "Reload", "environment", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L86-L95
train
IDSIA/sacred
sacred/run.py
Run.add_resource
def add_resource(self, filename): """Add a file as a resource. In Sacred terminology a resource is a file that the experiment needed to access during a run. In case of a MongoObserver that means making sure the file is stored in the database (but avoiding duplicates) along its p...
python
def add_resource(self, filename): """Add a file as a resource. In Sacred terminology a resource is a file that the experiment needed to access during a run. In case of a MongoObserver that means making sure the file is stored in the database (but avoiding duplicates) along its p...
[ "def", "add_resource", "(", "self", ",", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "self", ".", "_emit_resource_added", "(", "filename", ")" ]
Add a file as a resource. In Sacred terminology a resource is a file that the experiment needed to access during a run. In case of a MongoObserver that means making sure the file is stored in the database (but avoiding duplicates) along its path and md5 sum. See also :py:meth:`...
[ "Add", "a", "file", "as", "a", "resource", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/run.py#L142-L158
train
IDSIA/sacred
sacred/initialize.py
find_best_match
def find_best_match(path, prefixes): """Find the Ingredient that shares the longest prefix with path.""" path_parts = path.split('.') for p in prefixes: if len(p) <= len(path_parts) and p == path_parts[:len(p)]: return '.'.join(p), '.'.join(path_parts[len(p):]) return '', path
python
def find_best_match(path, prefixes): """Find the Ingredient that shares the longest prefix with path.""" path_parts = path.split('.') for p in prefixes: if len(p) <= len(path_parts) and p == path_parts[:len(p)]: return '.'.join(p), '.'.join(path_parts[len(p):]) return '', path
[ "def", "find_best_match", "(", "path", ",", "prefixes", ")", ":", "path_parts", "=", "path", ".", "split", "(", "'.'", ")", "for", "p", "in", "prefixes", ":", "if", "len", "(", "p", ")", "<=", "len", "(", "path_parts", ")", "and", "p", "==", "path_...
Find the Ingredient that shares the longest prefix with path.
[ "Find", "the", "Ingredient", "that", "shares", "the", "longest", "prefix", "with", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/initialize.py#L316-L322
train
IDSIA/sacred
sacred/commands.py
_non_unicode_repr
def _non_unicode_repr(objekt, context, maxlevels, level): """ Used to override the pprint format method to get rid of unicode prefixes. E.g.: 'John' instead of u'John'. """ repr_string, isreadable, isrecursive = pprint._safe_repr(objekt, context, ...
python
def _non_unicode_repr(objekt, context, maxlevels, level): """ Used to override the pprint format method to get rid of unicode prefixes. E.g.: 'John' instead of u'John'. """ repr_string, isreadable, isrecursive = pprint._safe_repr(objekt, context, ...
[ "def", "_non_unicode_repr", "(", "objekt", ",", "context", ",", "maxlevels", ",", "level", ")", ":", "repr_string", ",", "isreadable", ",", "isrecursive", "=", "pprint", ".", "_safe_repr", "(", "objekt", ",", "context", ",", "maxlevels", ",", "level", ")", ...
Used to override the pprint format method to get rid of unicode prefixes. E.g.: 'John' instead of u'John'.
[ "Used", "to", "override", "the", "pprint", "format", "method", "to", "get", "rid", "of", "unicode", "prefixes", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L40-L50
train
IDSIA/sacred
sacred/commands.py
print_config
def print_config(_run): """ Print the updated configuration and exit. Text is highlighted: green: value modified blue: value added red: value modified but type changed """ final_config = _run.config config_mods = _run.config_modifications print(_format_config(final_c...
python
def print_config(_run): """ Print the updated configuration and exit. Text is highlighted: green: value modified blue: value added red: value modified but type changed """ final_config = _run.config config_mods = _run.config_modifications print(_format_config(final_c...
[ "def", "print_config", "(", "_run", ")", ":", "final_config", "=", "_run", ".", "config", "config_mods", "=", "_run", ".", "config_modifications", "print", "(", "_format_config", "(", "final_config", ",", "config_mods", ")", ")" ]
Print the updated configuration and exit. Text is highlighted: green: value modified blue: value added red: value modified but type changed
[ "Print", "the", "updated", "configuration", "and", "exit", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L57-L68
train
IDSIA/sacred
sacred/commands.py
print_named_configs
def print_named_configs(ingredient): """ Returns a command function that prints the available named configs for the ingredient and all sub-ingredients and exits. The output is highlighted: white: config names grey: doc """ def print_named_configs(): """Print the avail...
python
def print_named_configs(ingredient): """ Returns a command function that prints the available named configs for the ingredient and all sub-ingredients and exits. The output is highlighted: white: config names grey: doc """ def print_named_configs(): """Print the avail...
[ "def", "print_named_configs", "(", "ingredient", ")", ":", "def", "print_named_configs", "(", ")", ":", "\"\"\"Print the available named configs and exit.\"\"\"", "named_configs", "=", "OrderedDict", "(", "ingredient", ".", "gather_named_configs", "(", ")", ")", "print", ...
Returns a command function that prints the available named configs for the ingredient and all sub-ingredients and exits. The output is highlighted: white: config names grey: doc
[ "Returns", "a", "command", "function", "that", "prints", "the", "available", "named", "configs", "for", "the", "ingredient", "and", "all", "sub", "-", "ingredients", "and", "exits", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L94-L109
train
IDSIA/sacred
sacred/commands.py
print_dependencies
def print_dependencies(_run): """Print the detected source-files and dependencies.""" print('Dependencies:') for dep in _run.experiment_info['dependencies']: pack, _, version = dep.partition('==') print(' {:<20} == {}'.format(pack, version)) print('\nSources:') for source, digest i...
python
def print_dependencies(_run): """Print the detected source-files and dependencies.""" print('Dependencies:') for dep in _run.experiment_info['dependencies']: pack, _, version = dep.partition('==') print(' {:<20} == {}'.format(pack, version)) print('\nSources:') for source, digest i...
[ "def", "print_dependencies", "(", "_run", ")", ":", "print", "(", "'Dependencies:'", ")", "for", "dep", "in", "_run", ".", "experiment_info", "[", "'dependencies'", "]", ":", "pack", ",", "_", ",", "version", "=", "dep", ".", "partition", "(", "'=='", ")...
Print the detected source-files and dependencies.
[ "Print", "the", "detected", "source", "-", "files", "and", "dependencies", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L119-L137
train
IDSIA/sacred
sacred/commands.py
save_config
def save_config(_config, _log, config_filename='config.json'): """ Store the updated configuration in a file. By default uses the filename "config.json", but that can be changed by setting the config_filename config entry. """ if 'config_filename' in _config: del _config['config_filenam...
python
def save_config(_config, _log, config_filename='config.json'): """ Store the updated configuration in a file. By default uses the filename "config.json", but that can be changed by setting the config_filename config entry. """ if 'config_filename' in _config: del _config['config_filenam...
[ "def", "save_config", "(", "_config", ",", "_log", ",", "config_filename", "=", "'config.json'", ")", ":", "if", "'config_filename'", "in", "_config", ":", "del", "_config", "[", "'config_filename'", "]", "_log", ".", "info", "(", "'Saving config to \"{}\"'", "....
Store the updated configuration in a file. By default uses the filename "config.json", but that can be changed by setting the config_filename config entry.
[ "Store", "the", "updated", "configuration", "in", "a", "file", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L140-L150
train
IDSIA/sacred
sacred/observers/file_storage.py
FileStorageObserver.log_metrics
def log_metrics(self, metrics_by_name, info): """Store new measurements into metrics.json. """ try: metrics_path = os.path.join(self.dir, "metrics.json") with open(metrics_path, 'r') as f: saved_metrics = json.load(f) except IOError: # ...
python
def log_metrics(self, metrics_by_name, info): """Store new measurements into metrics.json. """ try: metrics_path = os.path.join(self.dir, "metrics.json") with open(metrics_path, 'r') as f: saved_metrics = json.load(f) except IOError: # ...
[ "def", "log_metrics", "(", "self", ",", "metrics_by_name", ",", "info", ")", ":", "try", ":", "metrics_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dir", ",", "\"metrics.json\"", ")", "with", "open", "(", "metrics_path", ",", "'r'", "...
Store new measurements into metrics.json.
[ "Store", "new", "measurements", "into", "metrics", ".", "json", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/file_storage.py#L217-L244
train
IDSIA/sacred
sacred/config/custom_containers.py
is_different
def is_different(old_value, new_value): """Numpy aware comparison between two values.""" if opt.has_numpy: return not opt.np.array_equal(old_value, new_value) else: return old_value != new_value
python
def is_different(old_value, new_value): """Numpy aware comparison between two values.""" if opt.has_numpy: return not opt.np.array_equal(old_value, new_value) else: return old_value != new_value
[ "def", "is_different", "(", "old_value", ",", "new_value", ")", ":", "if", "opt", ".", "has_numpy", ":", "return", "not", "opt", ".", "np", ".", "array_equal", "(", "old_value", ",", "new_value", ")", "else", ":", "return", "old_value", "!=", "new_value" ]
Numpy aware comparison between two values.
[ "Numpy", "aware", "comparison", "between", "two", "values", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/config/custom_containers.py#L273-L278
train
IDSIA/sacred
sacred/experiment.py
Experiment.main
def main(self, function): """ Decorator to define the main function of the experiment. The main function of an experiment is the default command that is being run when no command is specified, or when calling the run() method. Usually it is more convenient to use ``automain`` i...
python
def main(self, function): """ Decorator to define the main function of the experiment. The main function of an experiment is the default command that is being run when no command is specified, or when calling the run() method. Usually it is more convenient to use ``automain`` i...
[ "def", "main", "(", "self", ",", "function", ")", ":", "captured", "=", "self", ".", "command", "(", "function", ")", "self", ".", "default_command", "=", "captured", ".", "__name__", "return", "captured" ]
Decorator to define the main function of the experiment. The main function of an experiment is the default command that is being run when no command is specified, or when calling the run() method. Usually it is more convenient to use ``automain`` instead.
[ "Decorator", "to", "define", "the", "main", "function", "of", "the", "experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L96-L107
train
IDSIA/sacred
sacred/experiment.py
Experiment.option_hook
def option_hook(self, function): """ Decorator for adding an option hook function. An option hook is a function that is called right before a run is created. It receives (and potentially modifies) the options dictionary. That is, the dictionary of commandline options used for ...
python
def option_hook(self, function): """ Decorator for adding an option hook function. An option hook is a function that is called right before a run is created. It receives (and potentially modifies) the options dictionary. That is, the dictionary of commandline options used for ...
[ "def", "option_hook", "(", "self", ",", "function", ")", ":", "sig", "=", "Signature", "(", "function", ")", "if", "\"options\"", "not", "in", "sig", ".", "arguments", ":", "raise", "KeyError", "(", "\"option_hook functions must have an argument called\"", "\" 'op...
Decorator for adding an option hook function. An option hook is a function that is called right before a run is created. It receives (and potentially modifies) the options dictionary. That is, the dictionary of commandline options used for this run. .. note:: The de...
[ "Decorator", "for", "adding", "an", "option", "hook", "function", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L143-L164
train
IDSIA/sacred
sacred/experiment.py
Experiment.get_usage
def get_usage(self, program_name=None): """Get the commandline usage string for this experiment.""" program_name = os.path.relpath(program_name or sys.argv[0] or 'Dummy', self.base_dir) commands = OrderedDict(self.gather_commands()) options = gather...
python
def get_usage(self, program_name=None): """Get the commandline usage string for this experiment.""" program_name = os.path.relpath(program_name or sys.argv[0] or 'Dummy', self.base_dir) commands = OrderedDict(self.gather_commands()) options = gather...
[ "def", "get_usage", "(", "self", ",", "program_name", "=", "None", ")", ":", "program_name", "=", "os", ".", "path", ".", "relpath", "(", "program_name", "or", "sys", ".", "argv", "[", "0", "]", "or", "'Dummy'", ",", "self", ".", "base_dir", ")", "co...
Get the commandline usage string for this experiment.
[ "Get", "the", "commandline", "usage", "string", "for", "this", "experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L168-L180
train
IDSIA/sacred
sacred/experiment.py
Experiment.run
def run(self, command_name=None, config_updates=None, named_configs=(), meta_info=None, options=None): """ Run the main function of the experiment or a given command. Parameters ---------- command_name : str, optional Name of the command to be run. Defaul...
python
def run(self, command_name=None, config_updates=None, named_configs=(), meta_info=None, options=None): """ Run the main function of the experiment or a given command. Parameters ---------- command_name : str, optional Name of the command to be run. Defaul...
[ "def", "run", "(", "self", ",", "command_name", "=", "None", ",", "config_updates", "=", "None", ",", "named_configs", "=", "(", ")", ",", "meta_info", "=", "None", ",", "options", "=", "None", ")", ":", "run", "=", "self", ".", "_create_run", "(", "...
Run the main function of the experiment or a given command. Parameters ---------- command_name : str, optional Name of the command to be run. Defaults to main function. config_updates : dict, optional Changes to the configuration as a nested dictionary ...
[ "Run", "the", "main", "function", "of", "the", "experiment", "or", "a", "given", "command", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L182-L213
train
IDSIA/sacred
sacred/experiment.py
Experiment.run_command
def run_command(self, command_name, config_updates=None, named_configs=(), args=(), meta_info=None): """Run the command with the given name. .. note:: Deprecated in Sacred 0.7 run_command() will be removed in Sacred 1.0. It is replaced by run() which can now ...
python
def run_command(self, command_name, config_updates=None, named_configs=(), args=(), meta_info=None): """Run the command with the given name. .. note:: Deprecated in Sacred 0.7 run_command() will be removed in Sacred 1.0. It is replaced by run() which can now ...
[ "def", "run_command", "(", "self", ",", "command_name", ",", "config_updates", "=", "None", ",", "named_configs", "=", "(", ")", ",", "args", "=", "(", ")", ",", "meta_info", "=", "None", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "\...
Run the command with the given name. .. note:: Deprecated in Sacred 0.7 run_command() will be removed in Sacred 1.0. It is replaced by run() which can now also handle command_names.
[ "Run", "the", "command", "with", "the", "given", "name", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L215-L227
train
IDSIA/sacred
sacred/experiment.py
Experiment.run_commandline
def run_commandline(self, argv=None): """ Run the command-line interface of this experiment. If ``argv`` is omitted it defaults to ``sys.argv``. Parameters ---------- argv : list[str] or str, optional Command-line as string or list of strings like ``sys.argv...
python
def run_commandline(self, argv=None): """ Run the command-line interface of this experiment. If ``argv`` is omitted it defaults to ``sys.argv``. Parameters ---------- argv : list[str] or str, optional Command-line as string or list of strings like ``sys.argv...
[ "def", "run_commandline", "(", "self", ",", "argv", "=", "None", ")", ":", "argv", "=", "ensure_wellformed_argv", "(", "argv", ")", "short_usage", ",", "usage", ",", "internal_usage", "=", "self", ".", "get_usage", "(", ")", "args", "=", "docopt", "(", "...
Run the command-line interface of this experiment. If ``argv`` is omitted it defaults to ``sys.argv``. Parameters ---------- argv : list[str] or str, optional Command-line as string or list of strings like ``sys.argv``. Returns ------- sacred.run.Ru...
[ "Run", "the", "command", "-", "line", "interface", "of", "this", "experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L229-L291
train
IDSIA/sacred
sacred/experiment.py
Experiment.get_default_options
def get_default_options(self): """Get a dictionary of default options as used with run. Returns ------- dict A dictionary containing option keys of the form '--beat_interval'. Their values are boolean if the option is a flag, otherwise None or its def...
python
def get_default_options(self): """Get a dictionary of default options as used with run. Returns ------- dict A dictionary containing option keys of the form '--beat_interval'. Their values are boolean if the option is a flag, otherwise None or its def...
[ "def", "get_default_options", "(", "self", ")", ":", "_", ",", "_", ",", "internal_usage", "=", "self", ".", "get_usage", "(", ")", "args", "=", "docopt", "(", "internal_usage", ",", "[", "]", ")", "return", "{", "k", ":", "v", "for", "k", ",", "v"...
Get a dictionary of default options as used with run. Returns ------- dict A dictionary containing option keys of the form '--beat_interval'. Their values are boolean if the option is a flag, otherwise None or its default value.
[ "Get", "a", "dictionary", "of", "default", "options", "as", "used", "with", "run", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L420-L433
train
IDSIA/sacred
sacred/config/signature.py
Signature.construct_arguments
def construct_arguments(self, args, kwargs, options, bound=False): """ Construct args list and kwargs dictionary for this signature. They are created such that: - the original explicit call arguments (args, kwargs) are preserved - missing arguments are filled in by name usin...
python
def construct_arguments(self, args, kwargs, options, bound=False): """ Construct args list and kwargs dictionary for this signature. They are created such that: - the original explicit call arguments (args, kwargs) are preserved - missing arguments are filled in by name usin...
[ "def", "construct_arguments", "(", "self", ",", "args", ",", "kwargs", ",", "options", ",", "bound", "=", "False", ")", ":", "expected_args", "=", "self", ".", "_get_expected_args", "(", "bound", ")", "self", ".", "_assert_no_unexpected_args", "(", "expected_a...
Construct args list and kwargs dictionary for this signature. They are created such that: - the original explicit call arguments (args, kwargs) are preserved - missing arguments are filled in by name using options (if possible) - default arguments are overridden by options ...
[ "Construct", "args", "list", "and", "kwargs", "dictionary", "for", "this", "signature", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/config/signature.py#L83-L104
train
IDSIA/sacred
sacred/stdout_capturing.py
flush
def flush(): """Try to flush all stdio buffers, both from python and from C.""" try: sys.stdout.flush() sys.stderr.flush() except (AttributeError, ValueError, IOError): pass # unsupported try: libc.fflush(None) except (AttributeError, ValueError, IOError): pa...
python
def flush(): """Try to flush all stdio buffers, both from python and from C.""" try: sys.stdout.flush() sys.stderr.flush() except (AttributeError, ValueError, IOError): pass # unsupported try: libc.fflush(None) except (AttributeError, ValueError, IOError): pa...
[ "def", "flush", "(", ")", ":", "try", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "except", "(", "AttributeError", ",", "ValueError", ",", "IOError", ")", ":", "pass", "# unsupported", "try", ":", ...
Try to flush all stdio buffers, both from python and from C.
[ "Try", "to", "flush", "all", "stdio", "buffers", "both", "from", "python", "and", "from", "C", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/stdout_capturing.py#L16-L26
train
IDSIA/sacred
sacred/stdout_capturing.py
tee_output_python
def tee_output_python(): """Duplicate sys.stdout and sys.stderr to new StringIO.""" buffer = StringIO() out = CapturedStdout(buffer) orig_stdout, orig_stderr = sys.stdout, sys.stderr flush() sys.stdout = TeeingStreamProxy(sys.stdout, buffer) sys.stderr = TeeingStreamProxy(sys.stderr, buffer)...
python
def tee_output_python(): """Duplicate sys.stdout and sys.stderr to new StringIO.""" buffer = StringIO() out = CapturedStdout(buffer) orig_stdout, orig_stderr = sys.stdout, sys.stderr flush() sys.stdout = TeeingStreamProxy(sys.stdout, buffer) sys.stderr = TeeingStreamProxy(sys.stderr, buffer)...
[ "def", "tee_output_python", "(", ")", ":", "buffer", "=", "StringIO", "(", ")", "out", "=", "CapturedStdout", "(", "buffer", ")", "orig_stdout", ",", "orig_stderr", "=", "sys", ".", "stdout", ",", "sys", ".", "stderr", "flush", "(", ")", "sys", ".", "s...
Duplicate sys.stdout and sys.stderr to new StringIO.
[ "Duplicate", "sys", ".", "stdout", "and", "sys", ".", "stderr", "to", "new", "StringIO", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/stdout_capturing.py#L97-L110
train
IDSIA/sacred
sacred/stdout_capturing.py
tee_output_fd
def tee_output_fd(): """Duplicate stdout and stderr to a file on the file descriptor level.""" with NamedTemporaryFile(mode='w+') as target: original_stdout_fd = 1 original_stderr_fd = 2 target_fd = target.fileno() # Save a copy of the original stdout and stderr file descriptors...
python
def tee_output_fd(): """Duplicate stdout and stderr to a file on the file descriptor level.""" with NamedTemporaryFile(mode='w+') as target: original_stdout_fd = 1 original_stderr_fd = 2 target_fd = target.fileno() # Save a copy of the original stdout and stderr file descriptors...
[ "def", "tee_output_fd", "(", ")", ":", "with", "NamedTemporaryFile", "(", "mode", "=", "'w+'", ")", "as", "target", ":", "original_stdout_fd", "=", "1", "original_stderr_fd", "=", "2", "target_fd", "=", "target", ".", "fileno", "(", ")", "# Save a copy of the ...
Duplicate stdout and stderr to a file on the file descriptor level.
[ "Duplicate", "stdout", "and", "stderr", "to", "a", "file", "on", "the", "file", "descriptor", "level", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/stdout_capturing.py#L118-L183
train
IDSIA/sacred
sacred/arg_parser.py
get_config_updates
def get_config_updates(updates): """ Parse the UPDATES given on the commandline. Parameters ---------- updates (list[str]): list of update-strings of the form NAME=LITERAL or just NAME. Returns ------- (dict, list): Config updates and named configs to us...
python
def get_config_updates(updates): """ Parse the UPDATES given on the commandline. Parameters ---------- updates (list[str]): list of update-strings of the form NAME=LITERAL or just NAME. Returns ------- (dict, list): Config updates and named configs to us...
[ "def", "get_config_updates", "(", "updates", ")", ":", "config_updates", "=", "{", "}", "named_configs", "=", "[", "]", "if", "not", "updates", ":", "return", "config_updates", ",", "named_configs", "for", "upd", "in", "updates", ":", "if", "upd", "==", "'...
Parse the UPDATES given on the commandline. Parameters ---------- updates (list[str]): list of update-strings of the form NAME=LITERAL or just NAME. Returns ------- (dict, list): Config updates and named configs to use
[ "Parse", "the", "UPDATES", "given", "on", "the", "commandline", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L46-L75
train
IDSIA/sacred
sacred/arg_parser.py
_format_options_usage
def _format_options_usage(options): """ Format the Options-part of the usage text. Parameters ---------- options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str Text formatted as a des...
python
def _format_options_usage(options): """ Format the Options-part of the usage text. Parameters ---------- options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str Text formatted as a des...
[ "def", "_format_options_usage", "(", "options", ")", ":", "options_usage", "=", "\"\"", "for", "op", "in", "options", ":", "short", ",", "long", "=", "op", ".", "get_flags", "(", ")", "if", "op", ".", "arg", ":", "flag", "=", "\"{short} {arg} {long}={arg}\...
Format the Options-part of the usage text. Parameters ---------- options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str Text formatted as a description for the commandline options
[ "Format", "the", "Options", "-", "part", "of", "the", "usage", "text", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L78-L109
train
IDSIA/sacred
sacred/arg_parser.py
_format_arguments_usage
def _format_arguments_usage(options): """ Construct the Arguments-part of the usage text. Parameters ---------- options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str Text formatted a...
python
def _format_arguments_usage(options): """ Construct the Arguments-part of the usage text. Parameters ---------- options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str Text formatted a...
[ "def", "_format_arguments_usage", "(", "options", ")", ":", "argument_usage", "=", "\"\"", "for", "op", "in", "options", ":", "if", "op", ".", "arg", "and", "op", ".", "arg_description", ":", "wrapped_description", "=", "textwrap", ".", "wrap", "(", "op", ...
Construct the Arguments-part of the usage text. Parameters ---------- options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str Text formatted as a description of the arguments supported by the ...
[ "Construct", "the", "Arguments", "-", "part", "of", "the", "usage", "text", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L112-L138
train
IDSIA/sacred
sacred/arg_parser.py
_format_command_usage
def _format_command_usage(commands): """ Construct the Commands-part of the usage text. Parameters ---------- commands : dict[str, func] dictionary of supported commands. Each entry should be a tuple of (name, function). Returns ------- str T...
python
def _format_command_usage(commands): """ Construct the Commands-part of the usage text. Parameters ---------- commands : dict[str, func] dictionary of supported commands. Each entry should be a tuple of (name, function). Returns ------- str T...
[ "def", "_format_command_usage", "(", "commands", ")", ":", "if", "not", "commands", ":", "return", "\"\"", "command_usage", "=", "\"\\nCommands:\\n\"", "cmd_len", "=", "max", "(", "[", "len", "(", "c", ")", "for", "c", "in", "commands", "]", "+", "[", "8...
Construct the Commands-part of the usage text. Parameters ---------- commands : dict[str, func] dictionary of supported commands. Each entry should be a tuple of (name, function). Returns ------- str Text formatted as a description of the commands.
[ "Construct", "the", "Commands", "-", "part", "of", "the", "usage", "text", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L141-L166
train
IDSIA/sacred
sacred/arg_parser.py
format_usage
def format_usage(program_name, description, commands=None, options=()): """ Construct the usage text. Parameters ---------- program_name : str Usually the name of the python file that contains the experiment. description : str description of this experiment (usua...
python
def format_usage(program_name, description, commands=None, options=()): """ Construct the usage text. Parameters ---------- program_name : str Usually the name of the python file that contains the experiment. description : str description of this experiment (usua...
[ "def", "format_usage", "(", "program_name", ",", "description", ",", "commands", "=", "None", ",", "options", "=", "(", ")", ")", ":", "usage", "=", "USAGE_TEMPLATE", ".", "format", "(", "program_name", "=", "cmd_quote", "(", "program_name", ")", ",", "des...
Construct the usage text. Parameters ---------- program_name : str Usually the name of the python file that contains the experiment. description : str description of this experiment (usually the docstring). commands : dict[str, func] Dictionary of sup...
[ "Construct", "the", "usage", "text", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L169-L199
train
IDSIA/sacred
sacred/arg_parser.py
_convert_value
def _convert_value(value): """Parse string as python literal if possible and fallback to string.""" try: return restore(ast.literal_eval(value)) except (ValueError, SyntaxError): if SETTINGS.COMMAND_LINE.STRICT_PARSING: raise # use as string if nothing else worked ...
python
def _convert_value(value): """Parse string as python literal if possible and fallback to string.""" try: return restore(ast.literal_eval(value)) except (ValueError, SyntaxError): if SETTINGS.COMMAND_LINE.STRICT_PARSING: raise # use as string if nothing else worked ...
[ "def", "_convert_value", "(", "value", ")", ":", "try", ":", "return", "restore", "(", "ast", ".", "literal_eval", "(", "value", ")", ")", "except", "(", "ValueError", ",", "SyntaxError", ")", ":", "if", "SETTINGS", ".", "COMMAND_LINE", ".", "STRICT_PARSIN...
Parse string as python literal if possible and fallback to string.
[ "Parse", "string", "as", "python", "literal", "if", "possible", "and", "fallback", "to", "string", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L206-L214
train
IDSIA/sacred
sacred/utils.py
iterate_flattened_separately
def iterate_flattened_separately(dictionary, manually_sorted_keys=None): """ Recursively iterate over the items of a dictionary in a special order. First iterate over manually sorted keys and then over all items that are non-dictionary values (sorted by keys), then over the rest (sorted by keys), p...
python
def iterate_flattened_separately(dictionary, manually_sorted_keys=None): """ Recursively iterate over the items of a dictionary in a special order. First iterate over manually sorted keys and then over all items that are non-dictionary values (sorted by keys), then over the rest (sorted by keys), p...
[ "def", "iterate_flattened_separately", "(", "dictionary", ",", "manually_sorted_keys", "=", "None", ")", ":", "if", "manually_sorted_keys", "is", "None", ":", "manually_sorted_keys", "=", "[", "]", "for", "key", "in", "manually_sorted_keys", ":", "if", "key", "in"...
Recursively iterate over the items of a dictionary in a special order. First iterate over manually sorted keys and then over all items that are non-dictionary values (sorted by keys), then over the rest (sorted by keys), providing full dotted paths for every leaf.
[ "Recursively", "iterate", "over", "the", "items", "of", "a", "dictionary", "in", "a", "special", "order", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L325-L354
train
IDSIA/sacred
sacred/utils.py
iterate_flattened
def iterate_flattened(d): """ Recursively iterate over the items of a dictionary. Provides a full dotted paths for every leaf. """ for key in sorted(d.keys()): value = d[key] if isinstance(value, dict) and value: for k, v in iterate_flattened(d[key]): yie...
python
def iterate_flattened(d): """ Recursively iterate over the items of a dictionary. Provides a full dotted paths for every leaf. """ for key in sorted(d.keys()): value = d[key] if isinstance(value, dict) and value: for k, v in iterate_flattened(d[key]): yie...
[ "def", "iterate_flattened", "(", "d", ")", ":", "for", "key", "in", "sorted", "(", "d", ".", "keys", "(", ")", ")", ":", "value", "=", "d", "[", "key", "]", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "value", ":", "for", "k", ",...
Recursively iterate over the items of a dictionary. Provides a full dotted paths for every leaf.
[ "Recursively", "iterate", "over", "the", "items", "of", "a", "dictionary", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L357-L369
train
IDSIA/sacred
sacred/utils.py
set_by_dotted_path
def set_by_dotted_path(d, path, value): """ Set an entry in a nested dict using a dotted path. Will create dictionaries as needed. Examples -------- >>> d = {'foo': {'bar': 7}} >>> set_by_dotted_path(d, 'foo.bar', 10) >>> d {'foo': {'bar': 10}} >>> set_by_dotted_path(d, 'foo.d....
python
def set_by_dotted_path(d, path, value): """ Set an entry in a nested dict using a dotted path. Will create dictionaries as needed. Examples -------- >>> d = {'foo': {'bar': 7}} >>> set_by_dotted_path(d, 'foo.bar', 10) >>> d {'foo': {'bar': 10}} >>> set_by_dotted_path(d, 'foo.d....
[ "def", "set_by_dotted_path", "(", "d", ",", "path", ",", "value", ")", ":", "split_path", "=", "path", ".", "split", "(", "'.'", ")", "current_option", "=", "d", "for", "p", "in", "split_path", "[", ":", "-", "1", "]", ":", "if", "p", "not", "in", ...
Set an entry in a nested dict using a dotted path. Will create dictionaries as needed. Examples -------- >>> d = {'foo': {'bar': 7}} >>> set_by_dotted_path(d, 'foo.bar', 10) >>> d {'foo': {'bar': 10}} >>> set_by_dotted_path(d, 'foo.d.baz', 3) >>> d {'foo': {'bar': 10, 'd': {'ba...
[ "Set", "an", "entry", "in", "a", "nested", "dict", "using", "a", "dotted", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L372-L395
train
IDSIA/sacred
sacred/utils.py
get_by_dotted_path
def get_by_dotted_path(d, path, default=None): """ Get an entry from nested dictionaries using a dotted path. Example: >>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a') 12 """ if not path: return d split_path = path.split('.') current_option = d for p in split_path: ...
python
def get_by_dotted_path(d, path, default=None): """ Get an entry from nested dictionaries using a dotted path. Example: >>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a') 12 """ if not path: return d split_path = path.split('.') current_option = d for p in split_path: ...
[ "def", "get_by_dotted_path", "(", "d", ",", "path", ",", "default", "=", "None", ")", ":", "if", "not", "path", ":", "return", "d", "split_path", "=", "path", ".", "split", "(", "'.'", ")", "current_option", "=", "d", "for", "p", "in", "split_path", ...
Get an entry from nested dictionaries using a dotted path. Example: >>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a') 12
[ "Get", "an", "entry", "from", "nested", "dictionaries", "using", "a", "dotted", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L398-L414
train
IDSIA/sacred
sacred/utils.py
iter_path_splits
def iter_path_splits(path): """ Iterate over possible splits of a dotted path. The first part can be empty the second should not be. Example: >>> list(iter_path_splits('foo.bar.baz')) [('', 'foo.bar.baz'), ('foo', 'bar.baz'), ('foo.bar', 'baz')] """ split_path = pa...
python
def iter_path_splits(path): """ Iterate over possible splits of a dotted path. The first part can be empty the second should not be. Example: >>> list(iter_path_splits('foo.bar.baz')) [('', 'foo.bar.baz'), ('foo', 'bar.baz'), ('foo.bar', 'baz')] """ split_path = pa...
[ "def", "iter_path_splits", "(", "path", ")", ":", "split_path", "=", "path", ".", "split", "(", "'.'", ")", "for", "i", "in", "range", "(", "len", "(", "split_path", ")", ")", ":", "p1", "=", "join_paths", "(", "*", "split_path", "[", ":", "i", "]"...
Iterate over possible splits of a dotted path. The first part can be empty the second should not be. Example: >>> list(iter_path_splits('foo.bar.baz')) [('', 'foo.bar.baz'), ('foo', 'bar.baz'), ('foo.bar', 'baz')]
[ "Iterate", "over", "possible", "splits", "of", "a", "dotted", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L417-L433
train
IDSIA/sacred
sacred/utils.py
is_prefix
def is_prefix(pre_path, path): """Return True if pre_path is a path-prefix of path.""" pre_path = pre_path.strip('.') path = path.strip('.') return not pre_path or path.startswith(pre_path + '.')
python
def is_prefix(pre_path, path): """Return True if pre_path is a path-prefix of path.""" pre_path = pre_path.strip('.') path = path.strip('.') return not pre_path or path.startswith(pre_path + '.')
[ "def", "is_prefix", "(", "pre_path", ",", "path", ")", ":", "pre_path", "=", "pre_path", ".", "strip", "(", "'.'", ")", "path", "=", "path", ".", "strip", "(", "'.'", ")", "return", "not", "pre_path", "or", "path", ".", "startswith", "(", "pre_path", ...
Return True if pre_path is a path-prefix of path.
[ "Return", "True", "if", "pre_path", "is", "a", "path", "-", "prefix", "of", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L454-L458
train
IDSIA/sacred
sacred/utils.py
rel_path
def rel_path(base, path): """Return path relative to base.""" if base == path: return '' assert is_prefix(base, path), "{} not a prefix of {}".format(base, path) return path[len(base):].strip('.')
python
def rel_path(base, path): """Return path relative to base.""" if base == path: return '' assert is_prefix(base, path), "{} not a prefix of {}".format(base, path) return path[len(base):].strip('.')
[ "def", "rel_path", "(", "base", ",", "path", ")", ":", "if", "base", "==", "path", ":", "return", "''", "assert", "is_prefix", "(", "base", ",", "path", ")", ",", "\"{} not a prefix of {}\"", ".", "format", "(", "base", ",", "path", ")", "return", "pat...
Return path relative to base.
[ "Return", "path", "relative", "to", "base", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L461-L466
train
IDSIA/sacred
sacred/utils.py
convert_to_nested_dict
def convert_to_nested_dict(dotted_dict): """Convert a dict with dotted path keys to corresponding nested dict.""" nested_dict = {} for k, v in iterate_flattened(dotted_dict): set_by_dotted_path(nested_dict, k, v) return nested_dict
python
def convert_to_nested_dict(dotted_dict): """Convert a dict with dotted path keys to corresponding nested dict.""" nested_dict = {} for k, v in iterate_flattened(dotted_dict): set_by_dotted_path(nested_dict, k, v) return nested_dict
[ "def", "convert_to_nested_dict", "(", "dotted_dict", ")", ":", "nested_dict", "=", "{", "}", "for", "k", ",", "v", "in", "iterate_flattened", "(", "dotted_dict", ")", ":", "set_by_dotted_path", "(", "nested_dict", ",", "k", ",", "v", ")", "return", "nested_d...
Convert a dict with dotted path keys to corresponding nested dict.
[ "Convert", "a", "dict", "with", "dotted", "path", "keys", "to", "corresponding", "nested", "dict", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L469-L474
train
IDSIA/sacred
sacred/utils.py
format_filtered_stacktrace
def format_filtered_stacktrace(filter_traceback='default'): """ Returns the traceback as `string`. `filter_traceback` can be one of: - 'always': always filter out sacred internals - 'default': Default behaviour: filter out sacred internals if the exception did not originate ...
python
def format_filtered_stacktrace(filter_traceback='default'): """ Returns the traceback as `string`. `filter_traceback` can be one of: - 'always': always filter out sacred internals - 'default': Default behaviour: filter out sacred internals if the exception did not originate ...
[ "def", "format_filtered_stacktrace", "(", "filter_traceback", "=", "'default'", ")", ":", "exc_type", ",", "exc_value", ",", "exc_traceback", "=", "sys", ".", "exc_info", "(", ")", "# determine if last exception is from sacred", "current_tb", "=", "exc_traceback", "whil...
Returns the traceback as `string`. `filter_traceback` can be one of: - 'always': always filter out sacred internals - 'default': Default behaviour: filter out sacred internals if the exception did not originate from within sacred, and print just the internal stack tr...
[ "Returns", "the", "traceback", "as", "string", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L485-L533
train
IDSIA/sacred
sacred/utils.py
get_inheritors
def get_inheritors(cls): """Get a set of all classes that inherit from the given class.""" subclasses = set() work = [cls] while work: parent = work.pop() for child in parent.__subclasses__(): if child not in subclasses: subclasses.add(child) w...
python
def get_inheritors(cls): """Get a set of all classes that inherit from the given class.""" subclasses = set() work = [cls] while work: parent = work.pop() for child in parent.__subclasses__(): if child not in subclasses: subclasses.add(child) w...
[ "def", "get_inheritors", "(", "cls", ")", ":", "subclasses", "=", "set", "(", ")", "work", "=", "[", "cls", "]", "while", "work", ":", "parent", "=", "work", ".", "pop", "(", ")", "for", "child", "in", "parent", ".", "__subclasses__", "(", ")", ":"...
Get a set of all classes that inherit from the given class.
[ "Get", "a", "set", "of", "all", "classes", "that", "inherit", "from", "the", "given", "class", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L593-L603
train
IDSIA/sacred
sacred/utils.py
apply_backspaces_and_linefeeds
def apply_backspaces_and_linefeeds(text): """ Interpret backspaces and linefeeds in text like a terminal would. Interpret text like a terminal by removing backspace and linefeed characters and applying them line by line. If final line ends with a carriage it keeps it to be concatenable with next ...
python
def apply_backspaces_and_linefeeds(text): """ Interpret backspaces and linefeeds in text like a terminal would. Interpret text like a terminal by removing backspace and linefeed characters and applying them line by line. If final line ends with a carriage it keeps it to be concatenable with next ...
[ "def", "apply_backspaces_and_linefeeds", "(", "text", ")", ":", "orig_lines", "=", "text", ".", "split", "(", "'\\n'", ")", "orig_lines_len", "=", "len", "(", "orig_lines", ")", "new_lines", "=", "[", "]", "for", "orig_line_idx", ",", "orig_line", "in", "enu...
Interpret backspaces and linefeeds in text like a terminal would. Interpret text like a terminal by removing backspace and linefeed characters and applying them line by line. If final line ends with a carriage it keeps it to be concatenable with next output chunk.
[ "Interpret", "backspaces", "and", "linefeeds", "in", "text", "like", "a", "terminal", "would", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L614-L647
train
IDSIA/sacred
sacred/utils.py
module_is_imported
def module_is_imported(modname, scope=None): """Checks if a module is imported within the current namespace.""" # return early if modname is not even cached if not module_is_in_cache(modname): return False if scope is None: # use globals() of the caller by default scope = inspect.stack...
python
def module_is_imported(modname, scope=None): """Checks if a module is imported within the current namespace.""" # return early if modname is not even cached if not module_is_in_cache(modname): return False if scope is None: # use globals() of the caller by default scope = inspect.stack...
[ "def", "module_is_imported", "(", "modname", ",", "scope", "=", "None", ")", ":", "# return early if modname is not even cached", "if", "not", "module_is_in_cache", "(", "modname", ")", ":", "return", "False", "if", "scope", "is", "None", ":", "# use globals() of th...
Checks if a module is imported within the current namespace.
[ "Checks", "if", "a", "module", "is", "imported", "within", "the", "current", "namespace", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L664-L677
train
IDSIA/sacred
sacred/observers/telegram_obs.py
TelegramObserver.from_config
def from_config(cls, filename): """ Create a TelegramObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``token`` and a ``chat_id`` and can optionally set ``silent_completion``,``comp...
python
def from_config(cls, filename): """ Create a TelegramObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``token`` and a ``chat_id`` and can optionally set ``silent_completion``,``comp...
[ "def", "from_config", "(", "cls", ",", "filename", ")", ":", "import", "telegram", "d", "=", "load_config_file", "(", "filename", ")", "request", "=", "cls", ".", "get_proxy_request", "(", "d", ")", "if", "'proxy_url'", "in", "d", "else", "None", "if", "...
Create a TelegramObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``token`` and a ``chat_id`` and can optionally set ``silent_completion``,``completed_text``, ``interrupted_text``, and ``fa...
[ "Create", "a", "TelegramObserver", "from", "a", "given", "configuration", "file", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/telegram_obs.py#L73-L96
train
IDSIA/sacred
sacred/observers/mongo.py
MongoObserver.log_metrics
def log_metrics(self, metrics_by_name, info): """Store new measurements to the database. Take measurements and store them into the metrics collection in the database. Additionally, reference the metrics in the info["metrics"] dictionary. """ if self.metrics is No...
python
def log_metrics(self, metrics_by_name, info): """Store new measurements to the database. Take measurements and store them into the metrics collection in the database. Additionally, reference the metrics in the info["metrics"] dictionary. """ if self.metrics is No...
[ "def", "log_metrics", "(", "self", ",", "metrics_by_name", ",", "info", ")", ":", "if", "self", ".", "metrics", "is", "None", ":", "# If, for whatever reason, the metrics collection has not been set", "# do not try to save anything there.", "return", "for", "key", "in", ...
Store new measurements to the database. Take measurements and store them into the metrics collection in the database. Additionally, reference the metrics in the info["metrics"] dictionary.
[ "Store", "new", "measurements", "to", "the", "database", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/mongo.py#L220-L244
train
IDSIA/sacred
sacred/dependencies.py
get_digest
def get_digest(filename): """Compute the MD5 hash for a given file.""" h = hashlib.md5() with open(filename, 'rb') as f: data = f.read(1 * MB) while data: h.update(data) data = f.read(1 * MB) return h.hexdigest()
python
def get_digest(filename): """Compute the MD5 hash for a given file.""" h = hashlib.md5() with open(filename, 'rb') as f: data = f.read(1 * MB) while data: h.update(data) data = f.read(1 * MB) return h.hexdigest()
[ "def", "get_digest", "(", "filename", ")", ":", "h", "=", "hashlib", ".", "md5", "(", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", "1", "*", "MB", ")", "while", "data", ":", "h", ...
Compute the MD5 hash for a given file.
[ "Compute", "the", "MD5", "hash", "for", "a", "given", "file", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L102-L110
train
IDSIA/sacred
sacred/dependencies.py
get_commit_if_possible
def get_commit_if_possible(filename): """Try to retrieve VCS information for a given file. Currently only supports git using the gitpython package. Parameters ---------- filename : str Returns ------- path: str The base path of the repository commit: str ...
python
def get_commit_if_possible(filename): """Try to retrieve VCS information for a given file. Currently only supports git using the gitpython package. Parameters ---------- filename : str Returns ------- path: str The base path of the repository commit: str ...
[ "def", "get_commit_if_possible", "(", "filename", ")", ":", "# git", "if", "opt", ".", "has_gitpython", ":", "from", "git", "import", "Repo", ",", "InvalidGitRepositoryError", "try", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "filename", ...
Try to retrieve VCS information for a given file. Currently only supports git using the gitpython package. Parameters ---------- filename : str Returns ------- path: str The base path of the repository commit: str The commit hash is_dirty: bool ...
[ "Try", "to", "retrieve", "VCS", "information", "for", "a", "given", "file", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L113-L146
train
IDSIA/sacred
sacred/dependencies.py
convert_path_to_module_parts
def convert_path_to_module_parts(path): """Convert path to a python file into list of module names.""" module_parts = splitall(path) if module_parts[-1] in ['__init__.py', '__init__.pyc']: # remove trailing __init__.py module_parts = module_parts[:-1] else: # remove file extensio...
python
def convert_path_to_module_parts(path): """Convert path to a python file into list of module names.""" module_parts = splitall(path) if module_parts[-1] in ['__init__.py', '__init__.pyc']: # remove trailing __init__.py module_parts = module_parts[:-1] else: # remove file extensio...
[ "def", "convert_path_to_module_parts", "(", "path", ")", ":", "module_parts", "=", "splitall", "(", "path", ")", "if", "module_parts", "[", "-", "1", "]", "in", "[", "'__init__.py'", ",", "'__init__.pyc'", "]", ":", "# remove trailing __init__.py", "module_parts",...
Convert path to a python file into list of module names.
[ "Convert", "path", "to", "a", "python", "file", "into", "list", "of", "module", "names", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L299-L308
train
IDSIA/sacred
sacred/dependencies.py
is_local_source
def is_local_source(filename, modname, experiment_path): """Check if a module comes from the given experiment path. Check if a module, given by name and filename, is from (a subdirectory of ) the given experiment path. This is used to determine if the module is a local source file, or rather a pack...
python
def is_local_source(filename, modname, experiment_path): """Check if a module comes from the given experiment path. Check if a module, given by name and filename, is from (a subdirectory of ) the given experiment path. This is used to determine if the module is a local source file, or rather a pack...
[ "def", "is_local_source", "(", "filename", ",", "modname", ",", "experiment_path", ")", ":", "if", "not", "is_subdir", "(", "filename", ",", "experiment_path", ")", ":", "return", "False", "rel_path", "=", "os", ".", "path", ".", "relpath", "(", "filename", ...
Check if a module comes from the given experiment path. Check if a module, given by name and filename, is from (a subdirectory of ) the given experiment path. This is used to determine if the module is a local source file, or rather a package dependency. Parameters ---------- filename: str...
[ "Check", "if", "a", "module", "comes", "from", "the", "given", "experiment", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L311-L347
train
IDSIA/sacred
sacred/dependencies.py
gather_sources_and_dependencies
def gather_sources_and_dependencies(globs, base_dir=None): """Scan the given globals for modules and return them as dependencies.""" experiment_path, main = get_main_file(globs) base_dir = base_dir or experiment_path gather_sources = source_discovery_strategies[SETTINGS['DISCOVER_SOURCES']] sourc...
python
def gather_sources_and_dependencies(globs, base_dir=None): """Scan the given globals for modules and return them as dependencies.""" experiment_path, main = get_main_file(globs) base_dir = base_dir or experiment_path gather_sources = source_discovery_strategies[SETTINGS['DISCOVER_SOURCES']] sourc...
[ "def", "gather_sources_and_dependencies", "(", "globs", ",", "base_dir", "=", "None", ")", ":", "experiment_path", ",", "main", "=", "get_main_file", "(", "globs", ")", "base_dir", "=", "base_dir", "or", "experiment_path", "gather_sources", "=", "source_discovery_st...
Scan the given globals for modules and return them as dependencies.
[ "Scan", "the", "given", "globals", "for", "modules", "and", "return", "them", "as", "dependencies", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L481-L501
train
IDSIA/sacred
sacred/config/utils.py
assert_is_valid_key
def assert_is_valid_key(key): """ Raise KeyError if a given config key violates any requirements. The requirements are the following and can be individually deactivated in ``sacred.SETTINGS.CONFIG_KEYS``: * ENFORCE_MONGO_COMPATIBLE (default: True): make sure the keys don't contain a '.' o...
python
def assert_is_valid_key(key): """ Raise KeyError if a given config key violates any requirements. The requirements are the following and can be individually deactivated in ``sacred.SETTINGS.CONFIG_KEYS``: * ENFORCE_MONGO_COMPATIBLE (default: True): make sure the keys don't contain a '.' o...
[ "def", "assert_is_valid_key", "(", "key", ")", ":", "if", "SETTINGS", ".", "CONFIG", ".", "ENFORCE_KEYS_MONGO_COMPATIBLE", "and", "(", "isinstance", "(", "key", ",", "basestring", ")", "and", "(", "'.'", "in", "key", "or", "key", "[", "0", "]", "==", "'$...
Raise KeyError if a given config key violates any requirements. The requirements are the following and can be individually deactivated in ``sacred.SETTINGS.CONFIG_KEYS``: * ENFORCE_MONGO_COMPATIBLE (default: True): make sure the keys don't contain a '.' or start with a '$' * ENFORCE_JSONPIC...
[ "Raise", "KeyError", "if", "a", "given", "config", "key", "violates", "any", "requirements", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/config/utils.py#L13-L65
train
IDSIA/sacred
sacred/observers/slack.py
SlackObserver.from_config
def from_config(cls, filename): """ Create a SlackObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``webhook_url`` and can optionally set ``bot_name``, ``icon``, ``completed_text``,...
python
def from_config(cls, filename): """ Create a SlackObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``webhook_url`` and can optionally set ``bot_name``, ``icon``, ``completed_text``,...
[ "def", "from_config", "(", "cls", ",", "filename", ")", ":", "d", "=", "load_config_file", "(", "filename", ")", "obs", "=", "None", "if", "'webhook_url'", "in", "d", ":", "obs", "=", "cls", "(", "d", "[", "'webhook_url'", "]", ")", "else", ":", "rai...
Create a SlackObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``webhook_url`` and can optionally set ``bot_name``, ``icon``, ``completed_text``, ``interrupted_text``, and ``failed_text``.
[ "Create", "a", "SlackObserver", "from", "a", "given", "configuration", "file", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/slack.py#L44-L65
train
IDSIA/sacred
sacred/host_info.py
get_host_info
def get_host_info(): """Collect some information about the machine this experiment runs on. Returns ------- dict A dictionary with information about the CPU, the OS and the Python version of this machine. """ host_info = {} for k, v in host_info_gatherers.items(): t...
python
def get_host_info(): """Collect some information about the machine this experiment runs on. Returns ------- dict A dictionary with information about the CPU, the OS and the Python version of this machine. """ host_info = {} for k, v in host_info_gatherers.items(): t...
[ "def", "get_host_info", "(", ")", ":", "host_info", "=", "{", "}", "for", "k", ",", "v", "in", "host_info_gatherers", ".", "items", "(", ")", ":", "try", ":", "host_info", "[", "k", "]", "=", "v", "(", ")", "except", "IgnoreHostInfo", ":", "pass", ...
Collect some information about the machine this experiment runs on. Returns ------- dict A dictionary with information about the CPU, the OS and the Python version of this machine.
[ "Collect", "some", "information", "about", "the", "machine", "this", "experiment", "runs", "on", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/host_info.py#L27-L43
train
IDSIA/sacred
sacred/host_info.py
host_info_getter
def host_info_getter(func, name=None): """ The decorated function is added to the process of collecting the host_info. This just adds the decorated function to the global ``sacred.host_info.host_info_gatherers`` dictionary. The functions from that dictionary are used when collecting the host info ...
python
def host_info_getter(func, name=None): """ The decorated function is added to the process of collecting the host_info. This just adds the decorated function to the global ``sacred.host_info.host_info_gatherers`` dictionary. The functions from that dictionary are used when collecting the host info ...
[ "def", "host_info_getter", "(", "func", ",", "name", "=", "None", ")", ":", "name", "=", "name", "or", "func", ".", "__name__", "host_info_gatherers", "[", "name", "]", "=", "func", "return", "func" ]
The decorated function is added to the process of collecting the host_info. This just adds the decorated function to the global ``sacred.host_info.host_info_gatherers`` dictionary. The functions from that dictionary are used when collecting the host info using :py:func:`~sacred.host_info.get_host_info`...
[ "The", "decorated", "function", "is", "added", "to", "the", "process", "of", "collecting", "the", "host_info", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/host_info.py#L47-L72
train
IDSIA/sacred
sacred/metrics_logger.py
linearize_metrics
def linearize_metrics(logged_metrics): """ Group metrics by name. Takes a list of individual measurements, possibly belonging to different metrics and groups them by name. :param logged_metrics: A list of ScalarMetricLogEntries :return: Measured values grouped by the metric name: {"metric_...
python
def linearize_metrics(logged_metrics): """ Group metrics by name. Takes a list of individual measurements, possibly belonging to different metrics and groups them by name. :param logged_metrics: A list of ScalarMetricLogEntries :return: Measured values grouped by the metric name: {"metric_...
[ "def", "linearize_metrics", "(", "logged_metrics", ")", ":", "metrics_by_name", "=", "{", "}", "for", "metric_entry", "in", "logged_metrics", ":", "if", "metric_entry", ".", "name", "not", "in", "metrics_by_name", ":", "metrics_by_name", "[", "metric_entry", ".", ...
Group metrics by name. Takes a list of individual measurements, possibly belonging to different metrics and groups them by name. :param logged_metrics: A list of ScalarMetricLogEntries :return: Measured values grouped by the metric name: {"metric_name1": {"steps": [0,1,2], "values": [4, 5, 6], ...
[ "Group", "metrics", "by", "name", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/metrics_logger.py#L85-L113
train
IDSIA/sacred
sacred/metrics_logger.py
MetricsLogger.get_last_metrics
def get_last_metrics(self): """Read all measurement events since last call of the method. :return List[ScalarMetricLogEntry] """ read_up_to = self._logged_metrics.qsize() messages = [] for i in range(read_up_to): try: messages.append(self._log...
python
def get_last_metrics(self): """Read all measurement events since last call of the method. :return List[ScalarMetricLogEntry] """ read_up_to = self._logged_metrics.qsize() messages = [] for i in range(read_up_to): try: messages.append(self._log...
[ "def", "get_last_metrics", "(", "self", ")", ":", "read_up_to", "=", "self", ".", "_logged_metrics", ".", "qsize", "(", ")", "messages", "=", "[", "]", "for", "i", "in", "range", "(", "read_up_to", ")", ":", "try", ":", "messages", ".", "append", "(", ...
Read all measurement events since last call of the method. :return List[ScalarMetricLogEntry]
[ "Read", "all", "measurement", "events", "since", "last", "call", "of", "the", "method", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/metrics_logger.py#L57-L69
train
IDSIA/sacred
sacred/commandline_options.py
gather_command_line_options
def gather_command_line_options(filter_disabled=None): """Get a sorted list of all CommandLineOption subclasses.""" if filter_disabled is None: filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS options = [opt for opt in get_inheritors(CommandLineOption) if not filter_d...
python
def gather_command_line_options(filter_disabled=None): """Get a sorted list of all CommandLineOption subclasses.""" if filter_disabled is None: filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS options = [opt for opt in get_inheritors(CommandLineOption) if not filter_d...
[ "def", "gather_command_line_options", "(", "filter_disabled", "=", "None", ")", ":", "if", "filter_disabled", "is", "None", ":", "filter_disabled", "=", "not", "SETTINGS", ".", "COMMAND_LINE", ".", "SHOW_DISABLED_OPTIONS", "options", "=", "[", "opt", "for", "opt",...
Get a sorted list of all CommandLineOption subclasses.
[ "Get", "a", "sorted", "list", "of", "all", "CommandLineOption", "subclasses", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L159-L165
train
IDSIA/sacred
sacred/commandline_options.py
LoglevelOption.apply
def apply(cls, args, run): """Adjust the loglevel of the root-logger of this run.""" # TODO: sacred.initialize.create_run already takes care of this try: lvl = int(args) except ValueError: lvl = args run.root_logger.setLevel(lvl)
python
def apply(cls, args, run): """Adjust the loglevel of the root-logger of this run.""" # TODO: sacred.initialize.create_run already takes care of this try: lvl = int(args) except ValueError: lvl = args run.root_logger.setLevel(lvl)
[ "def", "apply", "(", "cls", ",", "args", ",", "run", ")", ":", "# TODO: sacred.initialize.create_run already takes care of this", "try", ":", "lvl", "=", "int", "(", "args", ")", "except", "ValueError", ":", "lvl", "=", "args", "run", ".", "root_logger", ".", ...
Adjust the loglevel of the root-logger of this run.
[ "Adjust", "the", "loglevel", "of", "the", "root", "-", "logger", "of", "this", "run", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L203-L211
train
IDSIA/sacred
sacred/commandline_options.py
PriorityOption.apply
def apply(cls, args, run): """Add priority info for this run.""" try: priority = float(args) except ValueError: raise ValueError("The PRIORITY argument must be a number! " "(but was '{}')".format(args)) run.meta_info['priority'] = prio...
python
def apply(cls, args, run): """Add priority info for this run.""" try: priority = float(args) except ValueError: raise ValueError("The PRIORITY argument must be a number! " "(but was '{}')".format(args)) run.meta_info['priority'] = prio...
[ "def", "apply", "(", "cls", ",", "args", ",", "run", ")", ":", "try", ":", "priority", "=", "float", "(", "args", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"The PRIORITY argument must be a number! \"", "\"(but was '{}')\"", ".", "format", ...
Add priority info for this run.
[ "Add", "priority", "info", "for", "this", "run", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L273-L280
train
IDSIA/sacred
sacred/ingredient.py
Ingredient.capture
def capture(self, function=None, prefix=None): """ Decorator to turn a function into a captured function. The missing arguments of captured functions are automatically filled from the configuration if possible. See :ref:`captured_functions` for more information. If a ``...
python
def capture(self, function=None, prefix=None): """ Decorator to turn a function into a captured function. The missing arguments of captured functions are automatically filled from the configuration if possible. See :ref:`captured_functions` for more information. If a ``...
[ "def", "capture", "(", "self", ",", "function", "=", "None", ",", "prefix", "=", "None", ")", ":", "if", "function", "in", "self", ".", "captured_functions", ":", "return", "function", "captured_function", "=", "create_captured_function", "(", "function", ",",...
Decorator to turn a function into a captured function. The missing arguments of captured functions are automatically filled from the configuration if possible. See :ref:`captured_functions` for more information. If a ``prefix`` is specified, the search for suitable entries is p...
[ "Decorator", "to", "turn", "a", "function", "into", "a", "captured", "function", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L80-L95
train
IDSIA/sacred
sacred/ingredient.py
Ingredient.pre_run_hook
def pre_run_hook(self, func, prefix=None): """ Decorator to add a pre-run hook to this ingredient. Pre-run hooks are captured functions that are run, just before the main function is executed. """ cf = self.capture(func, prefix=prefix) self.pre_run_hooks.append(c...
python
def pre_run_hook(self, func, prefix=None): """ Decorator to add a pre-run hook to this ingredient. Pre-run hooks are captured functions that are run, just before the main function is executed. """ cf = self.capture(func, prefix=prefix) self.pre_run_hooks.append(c...
[ "def", "pre_run_hook", "(", "self", ",", "func", ",", "prefix", "=", "None", ")", ":", "cf", "=", "self", ".", "capture", "(", "func", ",", "prefix", "=", "prefix", ")", "self", ".", "pre_run_hooks", ".", "append", "(", "cf", ")", "return", "cf" ]
Decorator to add a pre-run hook to this ingredient. Pre-run hooks are captured functions that are run, just before the main function is executed.
[ "Decorator", "to", "add", "a", "pre", "-", "run", "hook", "to", "this", "ingredient", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L98-L107
train
IDSIA/sacred
sacred/ingredient.py
Ingredient.post_run_hook
def post_run_hook(self, func, prefix=None): """ Decorator to add a post-run hook to this ingredient. Post-run hooks are captured functions that are run, just after the main function is executed. """ cf = self.capture(func, prefix=prefix) self.post_run_hooks.appen...
python
def post_run_hook(self, func, prefix=None): """ Decorator to add a post-run hook to this ingredient. Post-run hooks are captured functions that are run, just after the main function is executed. """ cf = self.capture(func, prefix=prefix) self.post_run_hooks.appen...
[ "def", "post_run_hook", "(", "self", ",", "func", ",", "prefix", "=", "None", ")", ":", "cf", "=", "self", ".", "capture", "(", "func", ",", "prefix", "=", "prefix", ")", "self", ".", "post_run_hooks", ".", "append", "(", "cf", ")", "return", "cf" ]
Decorator to add a post-run hook to this ingredient. Post-run hooks are captured functions that are run, just after the main function is executed.
[ "Decorator", "to", "add", "a", "post", "-", "run", "hook", "to", "this", "ingredient", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L110-L119
train
IDSIA/sacred
sacred/ingredient.py
Ingredient.command
def command(self, function=None, prefix=None, unobserved=False): """ Decorator to define a new command for this Ingredient or Experiment. The name of the command will be the name of the function. It can be called from the command-line or by using the run_command function. Comma...
python
def command(self, function=None, prefix=None, unobserved=False): """ Decorator to define a new command for this Ingredient or Experiment. The name of the command will be the name of the function. It can be called from the command-line or by using the run_command function. Comma...
[ "def", "command", "(", "self", ",", "function", "=", "None", ",", "prefix", "=", "None", ",", "unobserved", "=", "False", ")", ":", "captured_f", "=", "self", ".", "capture", "(", "function", ",", "prefix", "=", "prefix", ")", "captured_f", ".", "unobs...
Decorator to define a new command for this Ingredient or Experiment. The name of the command will be the name of the function. It can be called from the command-line or by using the run_command function. Commands are automatically also captured functions. The command can be given a pr...
[ "Decorator", "to", "define", "a", "new", "command", "for", "this", "Ingredient", "or", "Experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L122-L140
train
IDSIA/sacred
sacred/ingredient.py
Ingredient.config
def config(self, function): """ Decorator to add a function to the configuration of the Experiment. The decorated function is turned into a :class:`~sacred.config_scope.ConfigScope` and added to the Ingredient/Experiment. When the experiment is run, this function will a...
python
def config(self, function): """ Decorator to add a function to the configuration of the Experiment. The decorated function is turned into a :class:`~sacred.config_scope.ConfigScope` and added to the Ingredient/Experiment. When the experiment is run, this function will a...
[ "def", "config", "(", "self", ",", "function", ")", ":", "self", ".", "configurations", ".", "append", "(", "ConfigScope", "(", "function", ")", ")", "return", "self", ".", "configurations", "[", "-", "1", "]" ]
Decorator to add a function to the configuration of the Experiment. The decorated function is turned into a :class:`~sacred.config_scope.ConfigScope` and added to the Ingredient/Experiment. When the experiment is run, this function will also be executed and all json-serializabl...
[ "Decorator", "to", "add", "a", "function", "to", "the", "configuration", "of", "the", "Experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L142-L155
train
IDSIA/sacred
sacred/ingredient.py
Ingredient.named_config
def named_config(self, func): """ Decorator to turn a function into a named configuration. See :ref:`named_configurations`. """ config_scope = ConfigScope(func) self._add_named_config(func.__name__, config_scope) return config_scope
python
def named_config(self, func): """ Decorator to turn a function into a named configuration. See :ref:`named_configurations`. """ config_scope = ConfigScope(func) self._add_named_config(func.__name__, config_scope) return config_scope
[ "def", "named_config", "(", "self", ",", "func", ")", ":", "config_scope", "=", "ConfigScope", "(", "func", ")", "self", ".", "_add_named_config", "(", "func", ".", "__name__", ",", "config_scope", ")", "return", "config_scope" ]
Decorator to turn a function into a named configuration. See :ref:`named_configurations`.
[ "Decorator", "to", "turn", "a", "function", "into", "a", "named", "configuration", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L157-L165
train
IDSIA/sacred
sacred/ingredient.py
Ingredient.config_hook
def config_hook(self, func): """ Decorator to add a config hook to this ingredient. Config hooks need to be a function that takes 3 parameters and returns a dictionary: (config, command_name, logger) --> dict Config hooks are run after the configuration of this Ingredie...
python
def config_hook(self, func): """ Decorator to add a config hook to this ingredient. Config hooks need to be a function that takes 3 parameters and returns a dictionary: (config, command_name, logger) --> dict Config hooks are run after the configuration of this Ingredie...
[ "def", "config_hook", "(", "self", ",", "func", ")", ":", "argspec", "=", "inspect", ".", "getargspec", "(", "func", ")", "args", "=", "[", "'config'", ",", "'command_name'", ",", "'logger'", "]", "if", "not", "(", "argspec", ".", "args", "==", "args",...
Decorator to add a config hook to this ingredient. Config hooks need to be a function that takes 3 parameters and returns a dictionary: (config, command_name, logger) --> dict Config hooks are run after the configuration of this Ingredient, but before any further ingredient-con...
[ "Decorator", "to", "add", "a", "config", "hook", "to", "this", "ingredient", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L167-L189
train
IDSIA/sacred
sacred/ingredient.py
Ingredient.add_package_dependency
def add_package_dependency(self, package_name, version): """ Add a package to the list of dependencies. :param package_name: The name of the package dependency :type package_name: str :param version: The (minimum) version of the package :type version: str """ ...
python
def add_package_dependency(self, package_name, version): """ Add a package to the list of dependencies. :param package_name: The name of the package dependency :type package_name: str :param version: The (minimum) version of the package :type version: str """ ...
[ "def", "add_package_dependency", "(", "self", ",", "package_name", ",", "version", ")", ":", "if", "not", "PEP440_VERSION_PATTERN", ".", "match", "(", "version", ")", ":", "raise", "ValueError", "(", "'Invalid Version: \"{}\"'", ".", "format", "(", "version", ")...
Add a package to the list of dependencies. :param package_name: The name of the package dependency :type package_name: str :param version: The (minimum) version of the package :type version: str
[ "Add", "a", "package", "to", "the", "list", "of", "dependencies", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L272-L283
train
IDSIA/sacred
sacred/ingredient.py
Ingredient._gather
def _gather(self, func): """ Function needed and used by gathering functions through the decorator `gather_from_ingredients` in `Ingredient`. Don't use this function by itself outside of the decorator! By overwriting this function you can filter what is visible when gath...
python
def _gather(self, func): """ Function needed and used by gathering functions through the decorator `gather_from_ingredients` in `Ingredient`. Don't use this function by itself outside of the decorator! By overwriting this function you can filter what is visible when gath...
[ "def", "_gather", "(", "self", ",", "func", ")", ":", "for", "ingredient", ",", "_", "in", "self", ".", "traverse_ingredients", "(", ")", ":", "for", "item", "in", "func", "(", "ingredient", ")", ":", "yield", "item" ]
Function needed and used by gathering functions through the decorator `gather_from_ingredients` in `Ingredient`. Don't use this function by itself outside of the decorator! By overwriting this function you can filter what is visible when gathering something (e.g. commands). See `Experim...
[ "Function", "needed", "and", "used", "by", "gathering", "functions", "through", "the", "decorator", "gather_from_ingredients", "in", "Ingredient", ".", "Don", "t", "use", "this", "function", "by", "itself", "outside", "of", "the", "decorator!" ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L285-L297
train
IDSIA/sacred
sacred/ingredient.py
Ingredient.gather_commands
def gather_commands(self, ingredient): """Collect all commands from this ingredient and its sub-ingredients. Yields ------ cmd_name: str The full (dotted) name of the command. cmd: function The corresponding captured function. """ for comm...
python
def gather_commands(self, ingredient): """Collect all commands from this ingredient and its sub-ingredients. Yields ------ cmd_name: str The full (dotted) name of the command. cmd: function The corresponding captured function. """ for comm...
[ "def", "gather_commands", "(", "self", ",", "ingredient", ")", ":", "for", "command_name", ",", "command", "in", "ingredient", ".", "commands", ".", "items", "(", ")", ":", "yield", "join_paths", "(", "ingredient", ".", "path", ",", "command_name", ")", ",...
Collect all commands from this ingredient and its sub-ingredients. Yields ------ cmd_name: str The full (dotted) name of the command. cmd: function The corresponding captured function.
[ "Collect", "all", "commands", "from", "this", "ingredient", "and", "its", "sub", "-", "ingredients", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L300-L311
train
IDSIA/sacred
sacred/ingredient.py
Ingredient.gather_named_configs
def gather_named_configs(self, ingredient): """Collect all named configs from this ingredient and its sub-ingredients. Yields ------ config_name: str The full (dotted) name of the named config. config: ConfigScope or ConfigDict or basestring The c...
python
def gather_named_configs(self, ingredient): """Collect all named configs from this ingredient and its sub-ingredients. Yields ------ config_name: str The full (dotted) name of the named config. config: ConfigScope or ConfigDict or basestring The c...
[ "def", "gather_named_configs", "(", "self", ",", "ingredient", ")", ":", "for", "config_name", ",", "config", "in", "ingredient", ".", "named_configs", ".", "items", "(", ")", ":", "yield", "join_paths", "(", "ingredient", ".", "path", ",", "config_name", ")...
Collect all named configs from this ingredient and its sub-ingredients. Yields ------ config_name: str The full (dotted) name of the named config. config: ConfigScope or ConfigDict or basestring The corresponding named config.
[ "Collect", "all", "named", "configs", "from", "this", "ingredient", "and", "its", "sub", "-", "ingredients", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L314-L326
train
IDSIA/sacred
sacred/ingredient.py
Ingredient.get_experiment_info
def get_experiment_info(self): """Get a dictionary with information about this experiment. Contains: * *name*: the name * *sources*: a list of sources (filename, md5) * *dependencies*: a list of package dependencies (name, version) :return: experiment information ...
python
def get_experiment_info(self): """Get a dictionary with information about this experiment. Contains: * *name*: the name * *sources*: a list of sources (filename, md5) * *dependencies*: a list of package dependencies (name, version) :return: experiment information ...
[ "def", "get_experiment_info", "(", "self", ")", ":", "dependencies", "=", "set", "(", ")", "sources", "=", "set", "(", ")", "for", "ing", ",", "_", "in", "self", ".", "traverse_ingredients", "(", ")", ":", "dependencies", "|=", "ing", ".", "dependencies"...
Get a dictionary with information about this experiment. Contains: * *name*: the name * *sources*: a list of sources (filename, md5) * *dependencies*: a list of package dependencies (name, version) :return: experiment information :rtype: dict
[ "Get", "a", "dictionary", "with", "information", "about", "this", "experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L328-L362
train
IDSIA/sacred
sacred/ingredient.py
Ingredient.traverse_ingredients
def traverse_ingredients(self): """Recursively traverse this ingredient and its sub-ingredients. Yields ------ ingredient: sacred.Ingredient The ingredient as traversed in preorder. depth: int The depth of the ingredient starting from 0. Raises ...
python
def traverse_ingredients(self): """Recursively traverse this ingredient and its sub-ingredients. Yields ------ ingredient: sacred.Ingredient The ingredient as traversed in preorder. depth: int The depth of the ingredient starting from 0. Raises ...
[ "def", "traverse_ingredients", "(", "self", ")", ":", "if", "self", ".", "_is_traversing", ":", "raise", "CircularDependencyError", "(", "ingredients", "=", "[", "self", "]", ")", "else", ":", "self", ".", "_is_traversing", "=", "True", "yield", "self", ",",...
Recursively traverse this ingredient and its sub-ingredients. Yields ------ ingredient: sacred.Ingredient The ingredient as traversed in preorder. depth: int The depth of the ingredient starting from 0. Raises ------ CircularDependencyErr...
[ "Recursively", "traverse", "this", "ingredient", "and", "its", "sub", "-", "ingredients", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/ingredient.py#L364-L388
train
simonw/datasette
datasette/utils.py
path_from_row_pks
def path_from_row_pks(row, pks, use_rowid, quote=True): """ Generate an optionally URL-quoted unique identifier for a row from its primary keys.""" if use_rowid: bits = [row['rowid']] else: bits = [ row[pk]["value"] if isinstance(row[pk], dict) else row[pk] fo...
python
def path_from_row_pks(row, pks, use_rowid, quote=True): """ Generate an optionally URL-quoted unique identifier for a row from its primary keys.""" if use_rowid: bits = [row['rowid']] else: bits = [ row[pk]["value"] if isinstance(row[pk], dict) else row[pk] fo...
[ "def", "path_from_row_pks", "(", "row", ",", "pks", ",", "use_rowid", ",", "quote", "=", "True", ")", ":", "if", "use_rowid", ":", "bits", "=", "[", "row", "[", "'rowid'", "]", "]", "else", ":", "bits", "=", "[", "row", "[", "pk", "]", "[", "\"va...
Generate an optionally URL-quoted unique identifier for a row from its primary keys.
[ "Generate", "an", "optionally", "URL", "-", "quoted", "unique", "identifier", "for", "a", "row", "from", "its", "primary", "keys", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/utils.py#L75-L90
train
simonw/datasette
datasette/utils.py
detect_primary_keys
def detect_primary_keys(conn, table): " Figure out primary keys for a table. " table_info_rows = [ row for row in conn.execute( 'PRAGMA table_info("{}")'.format(table) ).fetchall() if row[-1] ] table_info_rows.sort(key=lambda row: row[-1]) return [str(r[1]...
python
def detect_primary_keys(conn, table): " Figure out primary keys for a table. " table_info_rows = [ row for row in conn.execute( 'PRAGMA table_info("{}")'.format(table) ).fetchall() if row[-1] ] table_info_rows.sort(key=lambda row: row[-1]) return [str(r[1]...
[ "def", "detect_primary_keys", "(", "conn", ",", "table", ")", ":", "table_info_rows", "=", "[", "row", "for", "row", "in", "conn", ".", "execute", "(", "'PRAGMA table_info(\"{}\")'", ".", "format", "(", "table", ")", ")", ".", "fetchall", "(", ")", "if", ...
Figure out primary keys for a table.
[ "Figure", "out", "primary", "keys", "for", "a", "table", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/utils.py#L478-L488
train
simonw/datasette
datasette/utils.py
detect_fts
def detect_fts(conn, table): "Detect if table has a corresponding FTS virtual table and return it" rows = conn.execute(detect_fts_sql(table)).fetchall() if len(rows) == 0: return None else: return rows[0][0]
python
def detect_fts(conn, table): "Detect if table has a corresponding FTS virtual table and return it" rows = conn.execute(detect_fts_sql(table)).fetchall() if len(rows) == 0: return None else: return rows[0][0]
[ "def", "detect_fts", "(", "conn", ",", "table", ")", ":", "rows", "=", "conn", ".", "execute", "(", "detect_fts_sql", "(", "table", ")", ")", ".", "fetchall", "(", ")", "if", "len", "(", "rows", ")", "==", "0", ":", "return", "None", "else", ":", ...
Detect if table has a corresponding FTS virtual table and return it
[ "Detect", "if", "table", "has", "a", "corresponding", "FTS", "virtual", "table", "and", "return", "it" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/utils.py#L545-L551
train
simonw/datasette
datasette/app.py
Datasette.metadata
def metadata(self, key=None, database=None, table=None, fallback=True): """ Looks up metadata, cascading backwards from specified level. Returns None if metadata value is not found. """ assert not (database is None and table is not None), \ "Cannot call metadata() wit...
python
def metadata(self, key=None, database=None, table=None, fallback=True): """ Looks up metadata, cascading backwards from specified level. Returns None if metadata value is not found. """ assert not (database is None and table is not None), \ "Cannot call metadata() wit...
[ "def", "metadata", "(", "self", ",", "key", "=", "None", ",", "database", "=", "None", ",", "table", "=", "None", ",", "fallback", "=", "True", ")", ":", "assert", "not", "(", "database", "is", "None", "and", "table", "is", "not", "None", ")", ",",...
Looks up metadata, cascading backwards from specified level. Returns None if metadata value is not found.
[ "Looks", "up", "metadata", "cascading", "backwards", "from", "specified", "level", ".", "Returns", "None", "if", "metadata", "value", "is", "not", "found", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L239-L269
train
simonw/datasette
datasette/app.py
Datasette.inspect
def inspect(self): " Inspect the database and return a dictionary of table metadata " if self._inspect: return self._inspect self._inspect = {} for filename in self.files: if filename is MEMORY: self._inspect[":memory:"] = { "h...
python
def inspect(self): " Inspect the database and return a dictionary of table metadata " if self._inspect: return self._inspect self._inspect = {} for filename in self.files: if filename is MEMORY: self._inspect[":memory:"] = { "h...
[ "def", "inspect", "(", "self", ")", ":", "if", "self", ".", "_inspect", ":", "return", "self", ".", "_inspect", "self", ".", "_inspect", "=", "{", "}", "for", "filename", "in", "self", ".", "files", ":", "if", "filename", "is", "MEMORY", ":", "self",...
Inspect the database and return a dictionary of table metadata
[ "Inspect", "the", "database", "and", "return", "a", "dictionary", "of", "table", "metadata" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L414-L455
train
simonw/datasette
datasette/app.py
Datasette.table_metadata
def table_metadata(self, database, table): "Fetch table-specific metadata." return (self.metadata("databases") or {}).get(database, {}).get( "tables", {} ).get( table, {} )
python
def table_metadata(self, database, table): "Fetch table-specific metadata." return (self.metadata("databases") or {}).get(database, {}).get( "tables", {} ).get( table, {} )
[ "def", "table_metadata", "(", "self", ",", "database", ",", "table", ")", ":", "return", "(", "self", ".", "metadata", "(", "\"databases\"", ")", "or", "{", "}", ")", ".", "get", "(", "database", ",", "{", "}", ")", ".", "get", "(", "\"tables\"", "...
Fetch table-specific metadata.
[ "Fetch", "table", "-", "specific", "metadata", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L521-L527
train
simonw/datasette
datasette/app.py
Datasette.execute
async def execute( self, db_name, sql, params=None, truncate=False, custom_time_limit=None, page_size=None, ): """Executes sql against db_name in a thread""" page_size = page_size or self.page_size def sql_operation_in_thread(conn): ...
python
async def execute( self, db_name, sql, params=None, truncate=False, custom_time_limit=None, page_size=None, ): """Executes sql against db_name in a thread""" page_size = page_size or self.page_size def sql_operation_in_thread(conn): ...
[ "async", "def", "execute", "(", "self", ",", "db_name", ",", "sql", ",", "params", "=", "None", ",", "truncate", "=", "False", ",", "custom_time_limit", "=", "None", ",", "page_size", "=", "None", ",", ")", ":", "page_size", "=", "page_size", "or", "se...
Executes sql against db_name in a thread
[ "Executes", "sql", "against", "db_name", "in", "a", "thread" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/app.py#L580-L631
train
simonw/datasette
datasette/inspect.py
inspect_hash
def inspect_hash(path): " Calculate the hash of a database, efficiently. " m = hashlib.sha256() with path.open("rb") as fp: while True: data = fp.read(HASH_BLOCK_SIZE) if not data: break m.update(data) return m.hexdigest()
python
def inspect_hash(path): " Calculate the hash of a database, efficiently. " m = hashlib.sha256() with path.open("rb") as fp: while True: data = fp.read(HASH_BLOCK_SIZE) if not data: break m.update(data) return m.hexdigest()
[ "def", "inspect_hash", "(", "path", ")", ":", "m", "=", "hashlib", ".", "sha256", "(", ")", "with", "path", ".", "open", "(", "\"rb\"", ")", "as", "fp", ":", "while", "True", ":", "data", "=", "fp", ".", "read", "(", "HASH_BLOCK_SIZE", ")", "if", ...
Calculate the hash of a database, efficiently.
[ "Calculate", "the", "hash", "of", "a", "database", "efficiently", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/inspect.py#L17-L27
train
simonw/datasette
datasette/inspect.py
inspect_tables
def inspect_tables(conn, database_metadata): " List tables and their row counts, excluding uninteresting tables. " tables = {} table_names = [ r["name"] for r in conn.execute( 'select * from sqlite_master where type="table"' ) ] for table in table_names: ...
python
def inspect_tables(conn, database_metadata): " List tables and their row counts, excluding uninteresting tables. " tables = {} table_names = [ r["name"] for r in conn.execute( 'select * from sqlite_master where type="table"' ) ] for table in table_names: ...
[ "def", "inspect_tables", "(", "conn", ",", "database_metadata", ")", ":", "tables", "=", "{", "}", "table_names", "=", "[", "r", "[", "\"name\"", "]", "for", "r", "in", "conn", ".", "execute", "(", "'select * from sqlite_master where type=\"table\"'", ")", "]"...
List tables and their row counts, excluding uninteresting tables.
[ "List", "tables", "and", "their", "row", "counts", "excluding", "uninteresting", "tables", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/inspect.py#L35-L115
train
simonw/datasette
datasette/filters.py
Filters.convert_unit
def convert_unit(self, column, value): "If the user has provided a unit in the query, convert it into the column unit, if present." if column not in self.units: return value # Try to interpret the value as a unit value = self.ureg(value) if isinstance(value, numbers....
python
def convert_unit(self, column, value): "If the user has provided a unit in the query, convert it into the column unit, if present." if column not in self.units: return value # Try to interpret the value as a unit value = self.ureg(value) if isinstance(value, numbers....
[ "def", "convert_unit", "(", "self", ",", "column", ",", "value", ")", ":", "if", "column", "not", "in", "self", ".", "units", ":", "return", "value", "# Try to interpret the value as a unit", "value", "=", "self", ".", "ureg", "(", "value", ")", "if", "isi...
If the user has provided a unit in the query, convert it into the column unit, if present.
[ "If", "the", "user", "has", "provided", "a", "unit", "in", "the", "query", "convert", "it", "into", "the", "column", "unit", "if", "present", "." ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/filters.py#L156-L168
train
simonw/datasette
datasette/cli.py
skeleton
def skeleton(files, metadata, sqlite_extensions): "Generate a skeleton metadata.json file for specified SQLite databases" if os.path.exists(metadata): click.secho( "File {} already exists, will not over-write".format(metadata), bg="red", fg="white", bold=T...
python
def skeleton(files, metadata, sqlite_extensions): "Generate a skeleton metadata.json file for specified SQLite databases" if os.path.exists(metadata): click.secho( "File {} already exists, will not over-write".format(metadata), bg="red", fg="white", bold=T...
[ "def", "skeleton", "(", "files", ",", "metadata", ",", "sqlite_extensions", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "metadata", ")", ":", "click", ".", "secho", "(", "\"File {} already exists, will not over-write\"", ".", "format", "(", "metadat...
Generate a skeleton metadata.json file for specified SQLite databases
[ "Generate", "a", "skeleton", "metadata", ".", "json", "file", "for", "specified", "SQLite", "databases" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L107-L159
train
simonw/datasette
datasette/cli.py
plugins
def plugins(all, plugins_dir): "List currently available plugins" app = Datasette([], plugins_dir=plugins_dir) click.echo(json.dumps(app.plugins(all), indent=4))
python
def plugins(all, plugins_dir): "List currently available plugins" app = Datasette([], plugins_dir=plugins_dir) click.echo(json.dumps(app.plugins(all), indent=4))
[ "def", "plugins", "(", "all", ",", "plugins_dir", ")", ":", "app", "=", "Datasette", "(", "[", "]", ",", "plugins_dir", "=", "plugins_dir", ")", "click", ".", "echo", "(", "json", ".", "dumps", "(", "app", ".", "plugins", "(", "all", ")", ",", "ind...
List currently available plugins
[ "List", "currently", "available", "plugins" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L169-L172
train
simonw/datasette
datasette/cli.py
package
def package( files, tag, metadata, extra_options, branch, template_dir, plugins_dir, static, install, spatialite, version_note, **extra_metadata ): "Package specified SQLite files into a new datasette Docker container" if not shutil.which("docker"): click....
python
def package( files, tag, metadata, extra_options, branch, template_dir, plugins_dir, static, install, spatialite, version_note, **extra_metadata ): "Package specified SQLite files into a new datasette Docker container" if not shutil.which("docker"): click....
[ "def", "package", "(", "files", ",", "tag", ",", "metadata", ",", "extra_options", ",", "branch", ",", "template_dir", ",", "plugins_dir", ",", "static", ",", "install", ",", "spatialite", ",", "version_note", ",", "*", "*", "extra_metadata", ")", ":", "if...
Package specified SQLite files into a new datasette Docker container
[ "Package", "specified", "SQLite", "files", "into", "a", "new", "datasette", "Docker", "container" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L222-L265
train
simonw/datasette
datasette/cli.py
serve
def serve( files, immutable, host, port, debug, reload, cors, sqlite_extensions, inspect_file, metadata, template_dir, plugins_dir, static, memory, config, version_note, help_config, ): """Serve up specified SQLite database files with a web UI""" ...
python
def serve( files, immutable, host, port, debug, reload, cors, sqlite_extensions, inspect_file, metadata, template_dir, plugins_dir, static, memory, config, version_note, help_config, ): """Serve up specified SQLite database files with a web UI""" ...
[ "def", "serve", "(", "files", ",", "immutable", ",", "host", ",", "port", ",", "debug", ",", "reload", ",", "cors", ",", "sqlite_extensions", ",", "inspect_file", ",", "metadata", ",", "template_dir", ",", "plugins_dir", ",", "static", ",", "memory", ",", ...
Serve up specified SQLite database files with a web UI
[ "Serve", "up", "specified", "SQLite", "database", "files", "with", "a", "web", "UI" ]
11b352b4d52fd02a422776edebb14f12e4994d3b
https://github.com/simonw/datasette/blob/11b352b4d52fd02a422776edebb14f12e4994d3b/datasette/cli.py#L340-L405
train
ResidentMario/missingno
missingno/missingno.py
bar
def bar(df, figsize=(24, 10), fontsize=16, labels=None, log=False, color='dimgray', inline=False, filter=None, n=0, p=0, sort=None): """ A bar chart visualization of the nullity of the given DataFrame. :param df: The input DataFrame. :param log: Whether or not to display a logorithmic plot. Def...
python
def bar(df, figsize=(24, 10), fontsize=16, labels=None, log=False, color='dimgray', inline=False, filter=None, n=0, p=0, sort=None): """ A bar chart visualization of the nullity of the given DataFrame. :param df: The input DataFrame. :param log: Whether or not to display a logorithmic plot. Def...
[ "def", "bar", "(", "df", ",", "figsize", "=", "(", "24", ",", "10", ")", ",", "fontsize", "=", "16", ",", "labels", "=", "None", ",", "log", "=", "False", ",", "color", "=", "'dimgray'", ",", "inline", "=", "False", ",", "filter", "=", "None", ...
A bar chart visualization of the nullity of the given DataFrame. :param df: The input DataFrame. :param log: Whether or not to display a logorithmic plot. Defaults to False (linear). :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The ca...
[ "A", "bar", "chart", "visualization", "of", "the", "nullity", "of", "the", "given", "DataFrame", "." ]
1d67f91fbab0695a919c6bb72c796db57024e0ca
https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/missingno.py#L195-L263
train
ResidentMario/missingno
missingno/missingno.py
heatmap
def heatmap(df, inline=False, filter=None, n=0, p=0, sort=None, figsize=(20, 12), fontsize=16, labels=True, cmap='RdBu', vmin=-1, vmax=1, cbar=True ): """ Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame. Note that...
python
def heatmap(df, inline=False, filter=None, n=0, p=0, sort=None, figsize=(20, 12), fontsize=16, labels=True, cmap='RdBu', vmin=-1, vmax=1, cbar=True ): """ Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame. Note that...
[ "def", "heatmap", "(", "df", ",", "inline", "=", "False", ",", "filter", "=", "None", ",", "n", "=", "0", ",", "p", "=", "0", ",", "sort", "=", "None", ",", "figsize", "=", "(", "20", ",", "12", ")", ",", "fontsize", "=", "16", ",", "labels",...
Presents a `seaborn` heatmap visualization of nullity correlation in the given DataFrame. Note that this visualization has no special support for large datasets. For those, try the dendrogram instead. :param df: The DataFrame whose completeness is being heatmapped. :param filter: The filter to apply t...
[ "Presents", "a", "seaborn", "heatmap", "visualization", "of", "nullity", "correlation", "in", "the", "given", "DataFrame", ".", "Note", "that", "this", "visualization", "has", "no", "special", "support", "for", "large", "datasets", ".", "For", "those", "try", ...
1d67f91fbab0695a919c6bb72c796db57024e0ca
https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/missingno.py#L266-L346
train
ResidentMario/missingno
missingno/missingno.py
dendrogram
def dendrogram(df, method='average', filter=None, n=0, p=0, sort=None, orientation=None, figsize=None, fontsize=16, inline=False ): """ Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as ...
python
def dendrogram(df, method='average', filter=None, n=0, p=0, sort=None, orientation=None, figsize=None, fontsize=16, inline=False ): """ Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as ...
[ "def", "dendrogram", "(", "df", ",", "method", "=", "'average'", ",", "filter", "=", "None", ",", "n", "=", "0", ",", "p", "=", "0", ",", "sort", "=", "None", ",", "orientation", "=", "None", ",", "figsize", "=", "None", ",", "fontsize", "=", "16...
Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as a `scipy` dendrogram. The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is left unspecified the dendrogram will automatically swa...
[ "Fits", "a", "scipy", "hierarchical", "clustering", "algorithm", "to", "the", "given", "DataFrame", "s", "variables", "and", "visualizes", "the", "results", "as", "a", "scipy", "dendrogram", ".", "The", "default", "vertical", "display", "will", "fit", "up", "t...
1d67f91fbab0695a919c6bb72c796db57024e0ca
https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/missingno.py#L349-L434
train
ResidentMario/missingno
missingno/utils.py
nullity_sort
def nullity_sort(df, sort=None): """ Sorts a DataFrame according to its nullity, in either ascending or descending order. :param df: The DataFrame object being sorted. :param sort: The sorting method: either "ascending", "descending", or None (default). :return: The nullity-sorted DataFrame. ""...
python
def nullity_sort(df, sort=None): """ Sorts a DataFrame according to its nullity, in either ascending or descending order. :param df: The DataFrame object being sorted. :param sort: The sorting method: either "ascending", "descending", or None (default). :return: The nullity-sorted DataFrame. ""...
[ "def", "nullity_sort", "(", "df", ",", "sort", "=", "None", ")", ":", "if", "sort", "==", "'ascending'", ":", "return", "df", ".", "iloc", "[", "np", ".", "argsort", "(", "df", ".", "count", "(", "axis", "=", "'columns'", ")", ".", "values", ")", ...
Sorts a DataFrame according to its nullity, in either ascending or descending order. :param df: The DataFrame object being sorted. :param sort: The sorting method: either "ascending", "descending", or None (default). :return: The nullity-sorted DataFrame.
[ "Sorts", "a", "DataFrame", "according", "to", "its", "nullity", "in", "either", "ascending", "or", "descending", "order", "." ]
1d67f91fbab0695a919c6bb72c796db57024e0ca
https://github.com/ResidentMario/missingno/blob/1d67f91fbab0695a919c6bb72c796db57024e0ca/missingno/utils.py#L5-L18
train
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.from_service_account_file
def from_service_account_file(cls, filename, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to th...
python
def from_service_account_file(cls, filename, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to th...
[ "def", "from_service_account_file", "(", "cls", ",", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "credentials", "=", "service_account", ".", "Credentials", ".", "from_service_account_file", "(", "filename", ")", "kwargs", "[", "'credentials'...
Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the con...
[ "Creates", "an", "instance", "of", "this", "client", "using", "the", "provided", "credentials", "file", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L75-L91
train
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.session_entity_type_path
def session_entity_type_path(cls, project, session, entity_type): """Return a fully-qualified session_entity_type string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}', project=project, session=...
python
def session_entity_type_path(cls, project, session, entity_type): """Return a fully-qualified session_entity_type string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}', project=project, session=...
[ "def", "session_entity_type_path", "(", "cls", ",", "project", ",", "session", ",", "entity_type", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "'projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}'", ",", "p...
Return a fully-qualified session_entity_type string.
[ "Return", "a", "fully", "-", "qualified", "session_entity_type", "string", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L105-L112
train
googleapis/dialogflow-python-client-v2
dialogflow_v2/gapic/session_entity_types_client.py
SessionEntityTypesClient.create_session_entity_type
def create_session_entity_type( self, parent, session_entity_type, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates a session entity type. Example: ...
python
def create_session_entity_type( self, parent, session_entity_type, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Creates a session entity type. Example: ...
[ "def", "create_session_entity_type", "(", "self", ",", "parent", ",", "session_entity_type", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "...
Creates a session entity type. Example: >>> import dialogflow_v2 >>> >>> client = dialogflow_v2.SessionEntityTypesClient() >>> >>> parent = client.session_path('[PROJECT]', '[SESSION]') >>> >>> # TODO: Initialize ``session_enti...
[ "Creates", "a", "session", "entity", "type", "." ]
8c9c8709222efe427b76c9c8fcc04a0c4a0760b5
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/dialogflow_v2/gapic/session_entity_types_client.py#L351-L415
train