repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
bjodah/pycompilation
pycompilation/util.py
find_binary_of_command
def find_binary_of_command(candidates): """ Calls `find_executable` from distuils for provided candidates and returns first hit. If no candidate mathces, a RuntimeError is raised """ from distutils.spawn import find_executable for c in candidates: binary_path = find_executable(c) ...
python
def find_binary_of_command(candidates): """ Calls `find_executable` from distuils for provided candidates and returns first hit. If no candidate mathces, a RuntimeError is raised """ from distutils.spawn import find_executable for c in candidates: binary_path = find_executable(c) ...
[ "def", "find_binary_of_command", "(", "candidates", ")", ":", "from", "distutils", ".", "spawn", "import", "find_executable", "for", "c", "in", "candidates", ":", "binary_path", "=", "find_executable", "(", "c", ")", "if", "c", "and", "binary_path", ":", "retu...
Calls `find_executable` from distuils for provided candidates and returns first hit. If no candidate mathces, a RuntimeError is raised
[ "Calls", "find_executable", "from", "distuils", "for", "provided", "candidates", "and", "returns", "first", "hit", ".", "If", "no", "candidate", "mathces", "a", "RuntimeError", "is", "raised" ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L321-L333
bjodah/pycompilation
pycompilation/util.py
pyx_is_cplus
def pyx_is_cplus(path): """ Inspect a Cython source file (.pyx) and look for comment line like: # distutils: language = c++ Returns True if such a file is present in the file, else False. """ for line in open(path, 'rt'): if line.startswith('#') and '=' in line: splitted = ...
python
def pyx_is_cplus(path): """ Inspect a Cython source file (.pyx) and look for comment line like: # distutils: language = c++ Returns True if such a file is present in the file, else False. """ for line in open(path, 'rt'): if line.startswith('#') and '=' in line: splitted = ...
[ "def", "pyx_is_cplus", "(", "path", ")", ":", "for", "line", "in", "open", "(", "path", ",", "'rt'", ")", ":", "if", "line", ".", "startswith", "(", "'#'", ")", "and", "'='", "in", "line", ":", "splitted", "=", "line", ".", "split", "(", "'='", "...
Inspect a Cython source file (.pyx) and look for comment line like: # distutils: language = c++ Returns True if such a file is present in the file, else False.
[ "Inspect", "a", "Cython", "source", "file", "(", ".", "pyx", ")", "and", "look", "for", "comment", "line", "like", ":" ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L336-L353
bjodah/pycompilation
pycompilation/util.py
uniquify
def uniquify(l): """ Uniquify a list (skip duplicate items). """ result = [] for x in l: if x not in result: result.append(x) return result
python
def uniquify(l): """ Uniquify a list (skip duplicate items). """ result = [] for x in l: if x not in result: result.append(x) return result
[ "def", "uniquify", "(", "l", ")", ":", "result", "=", "[", "]", "for", "x", "in", "l", ":", "if", "x", "not", "in", "result", ":", "result", ".", "append", "(", "x", ")", "return", "result" ]
Uniquify a list (skip duplicate items).
[ "Uniquify", "a", "list", "(", "skip", "duplicate", "items", ")", "." ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L356-L364
bjodah/pycompilation
pycompilation/util.py
HasMetaData.get_from_metadata_file
def get_from_metadata_file(cls, dirpath, key): """ Get value of key in metadata file dict. """ fullpath = os.path.join(dirpath, cls.metadata_filename) if os.path.exists(fullpath): d = pickle.load(open(fullpath, 'rb')) return d[key] else: ...
python
def get_from_metadata_file(cls, dirpath, key): """ Get value of key in metadata file dict. """ fullpath = os.path.join(dirpath, cls.metadata_filename) if os.path.exists(fullpath): d = pickle.load(open(fullpath, 'rb')) return d[key] else: ...
[ "def", "get_from_metadata_file", "(", "cls", ",", "dirpath", ",", "key", ")", ":", "fullpath", "=", "os", ".", "path", ".", "join", "(", "dirpath", ",", "cls", ".", "metadata_filename", ")", "if", "os", ".", "path", ".", "exists", "(", "fullpath", ")",...
Get value of key in metadata file dict.
[ "Get", "value", "of", "key", "in", "metadata", "file", "dict", "." ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L249-L259
bjodah/pycompilation
pycompilation/util.py
HasMetaData.save_to_metadata_file
def save_to_metadata_file(cls, dirpath, key, value): """ Store `key: value` in metadata file dict. """ fullpath = os.path.join(dirpath, cls.metadata_filename) if os.path.exists(fullpath): d = pickle.load(open(fullpath, 'rb')) d.update({key: value}) ...
python
def save_to_metadata_file(cls, dirpath, key, value): """ Store `key: value` in metadata file dict. """ fullpath = os.path.join(dirpath, cls.metadata_filename) if os.path.exists(fullpath): d = pickle.load(open(fullpath, 'rb')) d.update({key: value}) ...
[ "def", "save_to_metadata_file", "(", "cls", ",", "dirpath", ",", "key", ",", "value", ")", ":", "fullpath", "=", "os", ".", "path", ".", "join", "(", "dirpath", ",", "cls", ".", "metadata_filename", ")", "if", "os", ".", "path", ".", "exists", "(", "...
Store `key: value` in metadata file dict.
[ "Store", "key", ":", "value", "in", "metadata", "file", "dict", "." ]
train
https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/util.py#L262-L272
chrisjsewell/jsonextended
jsonextended/plugins.py
view_interfaces
def view_interfaces(category=None): """ return a view of the plugin minimal class attribute interface(s) Parameters ---------- category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_interfaces()) {'de...
python
def view_interfaces(category=None): """ return a view of the plugin minimal class attribute interface(s) Parameters ---------- category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_interfaces()) {'de...
[ "def", "view_interfaces", "(", "category", "=", "None", ")", ":", "if", "category", "is", "not", "None", ":", "return", "sorted", "(", "_plugins_interface", "[", "category", "]", "[", ":", "]", ")", "else", ":", "return", "{", "k", ":", "v", "[", ":"...
return a view of the plugin minimal class attribute interface(s) Parameters ---------- category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_interfaces()) {'decoders': ['plugin_name', 'plugin_descript', ...
[ "return", "a", "view", "of", "the", "plugin", "minimal", "class", "attribute", "interface", "(", "s", ")" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L56-L77
chrisjsewell/jsonextended
jsonextended/plugins.py
view_plugins
def view_plugins(category=None): """ return a view of the loaded plugin names and descriptions Parameters ---------- category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, ...
python
def view_plugins(category=None): """ return a view of the loaded plugin names and descriptions Parameters ---------- category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, ...
[ "def", "view_plugins", "(", "category", "=", "None", ")", ":", "if", "category", "is", "not", "None", ":", "if", "category", "==", "'parsers'", ":", "return", "{", "name", ":", "{", "\"descript\"", ":", "klass", ".", "plugin_descript", ",", "\"regex\"", ...
return a view of the loaded plugin names and descriptions Parameters ---------- category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, 'encoders': {}, 'parsers': {}} >>> c...
[ "return", "a", "view", "of", "the", "loaded", "plugin", "names", "and", "descriptions" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L80-L127
chrisjsewell/jsonextended
jsonextended/plugins.py
unload_plugin
def unload_plugin(name, category=None): """ remove single plugin Parameters ---------- name : str plugin name category : str plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, 'encoders': {}, 'parsers': {...
python
def unload_plugin(name, category=None): """ remove single plugin Parameters ---------- name : str plugin name category : str plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, 'encoders': {}, 'parsers': {...
[ "def", "unload_plugin", "(", "name", ",", "category", "=", "None", ")", ":", "if", "category", "is", "not", "None", ":", "_all_plugins", "[", "category", "]", ".", "pop", "(", "name", ")", "else", ":", "for", "cat", "in", "_all_plugins", ":", "if", "...
remove single plugin Parameters ---------- name : str plugin name category : str plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, 'encoders': {}, 'parsers': {}} >>> class DecoderPlugin(object): ......
[ "remove", "single", "plugin" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L174-L213
chrisjsewell/jsonextended
jsonextended/plugins.py
load_plugin_classes
def load_plugin_classes(classes, category=None, overwrite=False): """ load plugins from class objects Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category overwrite : bool if True, allow existing plugins to b...
python
def load_plugin_classes(classes, category=None, overwrite=False): """ load plugins from class objects Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category overwrite : bool if True, allow existing plugins to b...
[ "def", "load_plugin_classes", "(", "classes", ",", "category", "=", "None", ",", "overwrite", "=", "False", ")", ":", "load_errors", "=", "[", "]", "for", "klass", "in", "classes", ":", "for", "pcat", ",", "pinterface", "in", "_plugins_interface", ".", "it...
load plugins from class objects Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category overwrite : bool if True, allow existing plugins to be overwritten Examples -------- >>> from pprint import pprin...
[ "load", "plugins", "from", "class", "objects" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L216-L267
chrisjsewell/jsonextended
jsonextended/plugins.py
plugins_context
def plugins_context(classes, category=None): """ context manager to load plugin class(es) then unload on exit Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import ppr...
python
def plugins_context(classes, category=None): """ context manager to load plugin class(es) then unload on exit Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import ppr...
[ "def", "plugins_context", "(", "classes", ",", "category", "=", "None", ")", ":", "original", "=", "{", "cat", ":", "list", "(", "_all_plugins", "[", "cat", "]", ".", "keys", "(", ")", ")", "for", "cat", "in", "_all_plugins", "}", "load_plugin_classes", ...
context manager to load plugin class(es) then unload on exit Parameters ---------- classes: list list of classes category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> class DecoderPlugin(object): ... ...
[ "context", "manager", "to", "load", "plugin", "class", "(", "es", ")", "then", "unload", "on", "exit" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L271-L315
chrisjsewell/jsonextended
jsonextended/plugins.py
load_plugins_dir
def load_plugins_dir(path, category=None, overwrite=False): """ load plugins from a directory Parameters ---------- path : str or path_like category : None or str if str, apply for single plugin category overwrite : bool if True, allow existing plugins to be overwritten """...
python
def load_plugins_dir(path, category=None, overwrite=False): """ load plugins from a directory Parameters ---------- path : str or path_like category : None or str if str, apply for single plugin category overwrite : bool if True, allow existing plugins to be overwritten """...
[ "def", "load_plugins_dir", "(", "path", ",", "category", "=", "None", ",", "overwrite", "=", "False", ")", ":", "# get potential plugin python files", "if", "hasattr", "(", "path", ",", "'glob'", ")", ":", "pypaths", "=", "path", ".", "glob", "(", "'*.py'", ...
load plugins from a directory Parameters ---------- path : str or path_like category : None or str if str, apply for single plugin category overwrite : bool if True, allow existing plugins to be overwritten
[ "load", "plugins", "from", "a", "directory" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L318-L365
chrisjsewell/jsonextended
jsonextended/plugins.py
load_builtin_plugins
def load_builtin_plugins(category=None, overwrite=False): """load plugins from builtin directories Parameters ---------- name: None or str category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugin...
python
def load_builtin_plugins(category=None, overwrite=False): """load plugins from builtin directories Parameters ---------- name: None or str category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugin...
[ "def", "load_builtin_plugins", "(", "category", "=", "None", ",", "overwrite", "=", "False", ")", ":", "# noqa: E501", "load_errors", "=", "[", "]", "for", "cat", ",", "path", "in", "_plugins_builtin", ".", "items", "(", ")", ":", "if", "cat", "!=", "cat...
load plugins from builtin directories Parameters ---------- name: None or str category : None or str if str, apply for single plugin category Examples -------- >>> from pprint import pprint >>> pprint(view_plugins()) {'decoders': {}, 'encoders': {}, 'parsers': {}} >>>...
[ "load", "plugins", "from", "builtin", "directories" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L368-L416
chrisjsewell/jsonextended
jsonextended/plugins.py
encode
def encode(obj, outtype='json', raise_error=False): """ encode objects, via encoder plugins, to new types Parameters ---------- outtype: str use encoder method to_<outtype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples -------- ...
python
def encode(obj, outtype='json', raise_error=False): """ encode objects, via encoder plugins, to new types Parameters ---------- outtype: str use encoder method to_<outtype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples -------- ...
[ "def", "encode", "(", "obj", ",", "outtype", "=", "'json'", ",", "raise_error", "=", "False", ")", ":", "for", "encoder", "in", "get_plugins", "(", "'encoders'", ")", ".", "values", "(", ")", ":", "if", "(", "isinstance", "(", "obj", ",", "encoder", ...
encode objects, via encoder plugins, to new types Parameters ---------- outtype: str use encoder method to_<outtype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples -------- >>> load_builtin_plugins('encoders') [] >>> fro...
[ "encode", "objects", "via", "encoder", "plugins", "to", "new", "types" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L419-L459
chrisjsewell/jsonextended
jsonextended/plugins.py
decode
def decode(dct, intype='json', raise_error=False): """ decode dict objects, via decoder plugins, to new type Parameters ---------- intype: str use decoder method from_<intype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples ------...
python
def decode(dct, intype='json', raise_error=False): """ decode dict objects, via decoder plugins, to new type Parameters ---------- intype: str use decoder method from_<intype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples ------...
[ "def", "decode", "(", "dct", ",", "intype", "=", "'json'", ",", "raise_error", "=", "False", ")", ":", "for", "decoder", "in", "get_plugins", "(", "'decoders'", ")", ".", "values", "(", ")", ":", "if", "(", "set", "(", "list", "(", "decoder", ".", ...
decode dict objects, via decoder plugins, to new type Parameters ---------- intype: str use decoder method from_<intype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples -------- >>> load_builtin_plugins('decoders') [] >>>...
[ "decode", "dict", "objects", "via", "decoder", "plugins", "to", "new", "type" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L462-L498
chrisjsewell/jsonextended
jsonextended/plugins.py
parser_available
def parser_available(fpath): """ test if parser plugin available for fpath Examples -------- >>> load_builtin_plugins('parsers') [] >>> test_file = StringIO('{"a":[1,2,3.4]}') >>> test_file.name = 'test.json' >>> parser_available(test_file) True >>> test_file.name = 'test.other...
python
def parser_available(fpath): """ test if parser plugin available for fpath Examples -------- >>> load_builtin_plugins('parsers') [] >>> test_file = StringIO('{"a":[1,2,3.4]}') >>> test_file.name = 'test.json' >>> parser_available(test_file) True >>> test_file.name = 'test.other...
[ "def", "parser_available", "(", "fpath", ")", ":", "if", "isinstance", "(", "fpath", ",", "basestring", ")", ":", "fname", "=", "fpath", "elif", "hasattr", "(", "fpath", ",", "'open'", ")", "and", "hasattr", "(", "fpath", ",", "'name'", ")", ":", "fnam...
test if parser plugin available for fpath Examples -------- >>> load_builtin_plugins('parsers') [] >>> test_file = StringIO('{"a":[1,2,3.4]}') >>> test_file.name = 'test.json' >>> parser_available(test_file) True >>> test_file.name = 'test.other' >>> parser_available(test_file)...
[ "test", "if", "parser", "plugin", "available", "for", "fpath" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L501-L534
chrisjsewell/jsonextended
jsonextended/plugins.py
parse
def parse(fpath, **kwargs): """ parse file contents, via parser plugins, to dict like object NB: the longest file regex will be used from plugins Parameters ---------- fpath : file_like string, object with 'open' and 'name' attributes, or object with 'readline' and 'name' attribut...
python
def parse(fpath, **kwargs): """ parse file contents, via parser plugins, to dict like object NB: the longest file regex will be used from plugins Parameters ---------- fpath : file_like string, object with 'open' and 'name' attributes, or object with 'readline' and 'name' attribut...
[ "def", "parse", "(", "fpath", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "fpath", ",", "basestring", ")", ":", "fname", "=", "fpath", "elif", "hasattr", "(", "fpath", ",", "'open'", ")", "and", "hasattr", "(", "fpath", ",", "'name'",...
parse file contents, via parser plugins, to dict like object NB: the longest file regex will be used from plugins Parameters ---------- fpath : file_like string, object with 'open' and 'name' attributes, or object with 'readline' and 'name' attributes kwargs : to pass to p...
[ "parse", "file", "contents", "via", "parser", "plugins", "to", "dict", "like", "object", "NB", ":", "the", "longest", "file", "regex", "will", "be", "used", "from", "plugins" ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/plugins.py#L537-L613
chrisjsewell/jsonextended
jsonextended/mockpath.py
colortxt
def colortxt(text, color=None, on_color=None, attrs=None): """Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark,...
python
def colortxt(text, color=None, on_color=None, attrs=None): """Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark,...
[ "def", "colortxt", "(", "text", ",", "color", "=", "None", ",", "on_color", "=", "None", ",", "attrs", "=", "None", ")", ":", "_RESET", "=", "'\\033[0m'", "__ISON", "=", "True", "if", "__ISON", "and", "os", ".", "getenv", "(", "'ANSI_COLORS_DISABLED'", ...
Colorize text. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes: bold, dark, underline, blink, reverse, concealed. Examples -------- ...
[ "Colorize", "text", "." ]
train
https://github.com/chrisjsewell/jsonextended/blob/c3a7a880cc09789b3c61204265dcbb127be76c8a/jsonextended/mockpath.py#L994-L1028
portfoliome/foil
foil/fileio.py
DelimitedReader.from_zipfile
def from_zipfile(cls, path, filename, encoding, dialect, fields, converters): """Read delimited text from zipfile.""" stream = ZipReader(path, filename).readlines(encoding) return cls(stream, dialect, fields, converters)
python
def from_zipfile(cls, path, filename, encoding, dialect, fields, converters): """Read delimited text from zipfile.""" stream = ZipReader(path, filename).readlines(encoding) return cls(stream, dialect, fields, converters)
[ "def", "from_zipfile", "(", "cls", ",", "path", ",", "filename", ",", "encoding", ",", "dialect", ",", "fields", ",", "converters", ")", ":", "stream", "=", "ZipReader", "(", "path", ",", "filename", ")", ".", "readlines", "(", "encoding", ")", "return",...
Read delimited text from zipfile.
[ "Read", "delimited", "text", "from", "zipfile", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/fileio.py#L77-L81
portfoliome/foil
foil/fileio.py
DelimitedSubsetReader.from_file
def from_file(cls, path, encoding, dialect, fields, converters, field_index): """Read delimited text from a text file.""" return cls(open(path, 'r', encoding=encoding), dialect, fields, converters, field_index)
python
def from_file(cls, path, encoding, dialect, fields, converters, field_index): """Read delimited text from a text file.""" return cls(open(path, 'r', encoding=encoding), dialect, fields, converters, field_index)
[ "def", "from_file", "(", "cls", ",", "path", ",", "encoding", ",", "dialect", ",", "fields", ",", "converters", ",", "field_index", ")", ":", "return", "cls", "(", "open", "(", "path", ",", "'r'", ",", "encoding", "=", "encoding", ")", ",", "dialect", ...
Read delimited text from a text file.
[ "Read", "delimited", "text", "from", "a", "text", "file", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/fileio.py#L125-L128
portfoliome/foil
foil/fileio.py
ZipReader.read_bytes
def read_bytes(self): """Read content into byte string.""" with ZipFile(self.path, mode='r') as archive: return archive.read(self.filename)
python
def read_bytes(self): """Read content into byte string.""" with ZipFile(self.path, mode='r') as archive: return archive.read(self.filename)
[ "def", "read_bytes", "(", "self", ")", ":", "with", "ZipFile", "(", "self", ".", "path", ",", "mode", "=", "'r'", ")", "as", "archive", ":", "return", "archive", ".", "read", "(", "self", ".", "filename", ")" ]
Read content into byte string.
[ "Read", "content", "into", "byte", "string", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/fileio.py#L156-L160
portfoliome/foil
foil/fileio.py
ZipReader.readlines_bytes
def readlines_bytes(self): """Read content into byte str line iterator.""" with open_zipfile_archive(self.path, self.filename) as file: for line in file: yield line.rstrip(b'\r\n')
python
def readlines_bytes(self): """Read content into byte str line iterator.""" with open_zipfile_archive(self.path, self.filename) as file: for line in file: yield line.rstrip(b'\r\n')
[ "def", "readlines_bytes", "(", "self", ")", ":", "with", "open_zipfile_archive", "(", "self", ".", "path", ",", "self", ".", "filename", ")", "as", "file", ":", "for", "line", "in", "file", ":", "yield", "line", ".", "rstrip", "(", "b'\\r\\n'", ")" ]
Read content into byte str line iterator.
[ "Read", "content", "into", "byte", "str", "line", "iterator", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/fileio.py#L167-L172
Capitains/Nautilus
capitains_nautilus/cts/resolver/base.py
ProtoNautilusCtsResolver.xmlparse
def xmlparse(self, file): """ Parse a XML file :param file: Opened File :return: Tree """ if self.CACHE_FULL_TEI is True: return self.get_or( _cache_key("Nautilus", self.name, "File", "Tree", file.name), super(ProtoNautilusCtsResolver,...
python
def xmlparse(self, file): """ Parse a XML file :param file: Opened File :return: Tree """ if self.CACHE_FULL_TEI is True: return self.get_or( _cache_key("Nautilus", self.name, "File", "Tree", file.name), super(ProtoNautilusCtsResolver,...
[ "def", "xmlparse", "(", "self", ",", "file", ")", ":", "if", "self", ".", "CACHE_FULL_TEI", "is", "True", ":", "return", "self", ".", "get_or", "(", "_cache_key", "(", "\"Nautilus\"", ",", "self", ".", "name", ",", "\"File\"", ",", "\"Tree\"", ",", "fi...
Parse a XML file :param file: Opened File :return: Tree
[ "Parse", "a", "XML", "file" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L48-L59
Capitains/Nautilus
capitains_nautilus/cts/resolver/base.py
ProtoNautilusCtsResolver.get_or
def get_or(self, cache_key, callback, *args, **kwargs): """ Get or set the cache using callback and arguments :param cache_key: Cache key for given resource :param callback: Callback if object does not exist :param args: Ordered Argument for the callback :param kwargs: Keyword a...
python
def get_or(self, cache_key, callback, *args, **kwargs): """ Get or set the cache using callback and arguments :param cache_key: Cache key for given resource :param callback: Callback if object does not exist :param args: Ordered Argument for the callback :param kwargs: Keyword a...
[ "def", "get_or", "(", "self", ",", "cache_key", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cached", "=", "self", ".", "cache", ".", "get", "(", "cache_key", ")", "if", "cached", "is", "not", "None", ":", "return", "cache...
Get or set the cache using callback and arguments :param cache_key: Cache key for given resource :param callback: Callback if object does not exist :param args: Ordered Argument for the callback :param kwargs: Keyword argument for the callback :return: Output of the callback
[ "Get", "or", "set", "the", "cache", "using", "callback", "and", "arguments" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L61-L81
Capitains/Nautilus
capitains_nautilus/cts/resolver/base.py
ProtoNautilusCtsResolver.read
def read(self, identifier, path=None): """ Read a text object given an identifier and a path :param identifier: Identifier of the text :param path: Path of the text files :return: Text """ if self.CACHE_FULL_TEI is True: o = self.cache.get(_cache_key(self.tex...
python
def read(self, identifier, path=None): """ Read a text object given an identifier and a path :param identifier: Identifier of the text :param path: Path of the text files :return: Text """ if self.CACHE_FULL_TEI is True: o = self.cache.get(_cache_key(self.tex...
[ "def", "read", "(", "self", ",", "identifier", ",", "path", "=", "None", ")", ":", "if", "self", ".", "CACHE_FULL_TEI", "is", "True", ":", "o", "=", "self", ".", "cache", ".", "get", "(", "_cache_key", "(", "self", ".", "texts_parsed_cache_key", ",", ...
Read a text object given an identifier and a path :param identifier: Identifier of the text :param path: Path of the text files :return: Text
[ "Read", "a", "text", "object", "given", "an", "identifier", "and", "a", "path" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L83-L101
Capitains/Nautilus
capitains_nautilus/cts/resolver/base.py
ProtoNautilusCtsResolver.parse
def parse(self, resource=None): """ Parse a list of directories ans :param resource: List of folders """ if resource is None: resource = self.__resources__ self.inventory = self.dispatcher.collection try: self._parse(resource) except MyC...
python
def parse(self, resource=None): """ Parse a list of directories ans :param resource: List of folders """ if resource is None: resource = self.__resources__ self.inventory = self.dispatcher.collection try: self._parse(resource) except MyC...
[ "def", "parse", "(", "self", ",", "resource", "=", "None", ")", ":", "if", "resource", "is", "None", ":", "resource", "=", "self", ".", "__resources__", "self", ".", "inventory", "=", "self", ".", "dispatcher", ".", "collection", "try", ":", "self", "....
Parse a list of directories ans :param resource: List of folders
[ "Parse", "a", "list", "of", "directories", "ans" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L103-L120
Capitains/Nautilus
capitains_nautilus/cts/resolver/base.py
ProtoNautilusCtsResolver.getReffs
def getReffs(self, textId, level=1, subreference=None): """ Retrieve the siblings of a textual node :param textId: PrototypeText Identifier :type textId: str :param level: Depth for retrieval :type level: int :param subreference: Passage Reference :type subrefere...
python
def getReffs(self, textId, level=1, subreference=None): """ Retrieve the siblings of a textual node :param textId: PrototypeText Identifier :type textId: str :param level: Depth for retrieval :type level: int :param subreference: Passage Reference :type subrefere...
[ "def", "getReffs", "(", "self", ",", "textId", ",", "level", "=", "1", ",", "subreference", "=", "None", ")", ":", "return", "self", ".", "get_or", "(", "self", ".", "__cache_key_reffs__", "(", "textId", ",", "level", ",", "subreference", ")", ",", "su...
Retrieve the siblings of a textual node :param textId: PrototypeText Identifier :type textId: str :param level: Depth for retrieval :type level: int :param subreference: Passage Reference :type subreference: str :return: List of references :rtype: [str]
[ "Retrieve", "the", "siblings", "of", "a", "textual", "node" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L186-L201
Capitains/Nautilus
capitains_nautilus/cts/resolver/base.py
ProtoNautilusCtsResolver.getTextualNode
def getTextualNode(self, textId, subreference=None, prevnext=False, metadata=False): """ Retrieve a text node from the API :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :param prevnext: Retrieve g...
python
def getTextualNode(self, textId, subreference=None, prevnext=False, metadata=False): """ Retrieve a text node from the API :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :param prevnext: Retrieve g...
[ "def", "getTextualNode", "(", "self", ",", "textId", ",", "subreference", "=", "None", ",", "prevnext", "=", "False", ",", "metadata", "=", "False", ")", ":", "key", "=", "_cache_key", "(", "\"Nautilus\"", ",", "self", ".", "name", ",", "\"Passage\"", ",...
Retrieve a text node from the API :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :param prevnext: Retrieve graph representing previous and next passage :type prevnext: boolean :param metada...
[ "Retrieve", "a", "text", "node", "from", "the", "API" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L206-L231
Capitains/Nautilus
capitains_nautilus/cts/resolver/base.py
ProtoNautilusCtsResolver.getSiblings
def getSiblings(self, textId, subreference): """ Retrieve the siblings of a textual node :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :return: Tuple of references :rtype: (str, str) ...
python
def getSiblings(self, textId, subreference): """ Retrieve the siblings of a textual node :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :return: Tuple of references :rtype: (str, str) ...
[ "def", "getSiblings", "(", "self", ",", "textId", ",", "subreference", ")", ":", "key", "=", "_cache_key", "(", "\"Nautilus\"", ",", "self", ".", "name", ",", "\"Siblings\"", ",", "textId", ",", "subreference", ")", "o", "=", "self", ".", "cache", ".", ...
Retrieve the siblings of a textual node :param textId: PrototypeText Identifier :type textId: str :param subreference: Passage Reference :type subreference: str :return: Tuple of references :rtype: (str, str)
[ "Retrieve", "the", "siblings", "of", "a", "textual", "node" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L233-L250
Capitains/Nautilus
capitains_nautilus/cts/resolver/base.py
NautilusCtsResolver.getMetadata
def getMetadata(self, objectId=None, **filters): """ Request metadata about a text or a collection :param objectId: Object Identifier to filter on :type objectId: str :param filters: Kwargs parameters. :type filters: dict :return: Collection """ return se...
python
def getMetadata(self, objectId=None, **filters): """ Request metadata about a text or a collection :param objectId: Object Identifier to filter on :type objectId: str :param filters: Kwargs parameters. :type filters: dict :return: Collection """ return se...
[ "def", "getMetadata", "(", "self", ",", "objectId", "=", "None", ",", "*", "*", "filters", ")", ":", "return", "self", ".", "get_or", "(", "_cache_key", "(", "\"Nautilus\"", ",", "self", ".", "name", ",", "\"GetMetadata\"", ",", "objectId", ")", ",", "...
Request metadata about a text or a collection :param objectId: Object Identifier to filter on :type objectId: str :param filters: Kwargs parameters. :type filters: dict :return: Collection
[ "Request", "metadata", "about", "a", "text", "or", "a", "collection" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L288-L300
Capitains/Nautilus
capitains_nautilus/cts/resolver/base.py
_SparqlSharedResolver._dispatch
def _dispatch(self, textgroup, directory): """ Sparql dispatcher do not need to dispatch works, as the link is DB stored through Textgroup :param textgroup: A Textgroup object :param directory: The path in which we found the textgroup :return: """ self.dispatcher.dispatc...
python
def _dispatch(self, textgroup, directory): """ Sparql dispatcher do not need to dispatch works, as the link is DB stored through Textgroup :param textgroup: A Textgroup object :param directory: The path in which we found the textgroup :return: """ self.dispatcher.dispatc...
[ "def", "_dispatch", "(", "self", ",", "textgroup", ",", "directory", ")", ":", "self", ".", "dispatcher", ".", "dispatch", "(", "textgroup", ",", "path", "=", "directory", ")" ]
Sparql dispatcher do not need to dispatch works, as the link is DB stored through Textgroup :param textgroup: A Textgroup object :param directory: The path in which we found the textgroup :return:
[ "Sparql", "dispatcher", "do", "not", "need", "to", "dispatch", "works", "as", "the", "link", "is", "DB", "stored", "through", "Textgroup" ]
train
https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L319-L326
PolyJIT/benchbuild
benchbuild/utils/user_interface.py
ask
def ask(question, default_answer=False, default_answer_str="no"): """ Ask for user input. This asks a yes/no question with a preset default. You can bypass the user-input and fetch the default answer, if you set Args: question: The question to ask on stdout. default_answer: The...
python
def ask(question, default_answer=False, default_answer_str="no"): """ Ask for user input. This asks a yes/no question with a preset default. You can bypass the user-input and fetch the default answer, if you set Args: question: The question to ask on stdout. default_answer: The...
[ "def", "ask", "(", "question", ",", "default_answer", "=", "False", ",", "default_answer_str", "=", "\"no\"", ")", ":", "response", "=", "default_answer", "def", "should_ignore_tty", "(", ")", ":", "\"\"\"\n Check, if we want to ignore an opened tty result.\n ...
Ask for user input. This asks a yes/no question with a preset default. You can bypass the user-input and fetch the default answer, if you set Args: question: The question to ask on stdout. default_answer: The default value to return. default_answer_str: The default ...
[ "Ask", "for", "user", "input", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/user_interface.py#L46-L84
davidhuser/dhis2.py
dhis2/utils.py
load_csv
def load_csv(path, delimiter=','): """ Load CSV file from path and yield CSV rows Usage: for row in load_csv('/path/to/file'): print(row) or list(load_csv('/path/to/file')) :param path: file path :param delimiter: CSV delimiter :return: a generator where __next__ is a row ...
python
def load_csv(path, delimiter=','): """ Load CSV file from path and yield CSV rows Usage: for row in load_csv('/path/to/file'): print(row) or list(load_csv('/path/to/file')) :param path: file path :param delimiter: CSV delimiter :return: a generator where __next__ is a row ...
[ "def", "load_csv", "(", "path", ",", "delimiter", "=", "','", ")", ":", "try", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "csvfile", ":", "reader", "=", "DictReader", "(", "csvfile", ",", "delimiter", "=", "delimiter", ")", "for", "row...
Load CSV file from path and yield CSV rows Usage: for row in load_csv('/path/to/file'): print(row) or list(load_csv('/path/to/file')) :param path: file path :param delimiter: CSV delimiter :return: a generator where __next__ is a row of the CSV
[ "Load", "CSV", "file", "from", "path", "and", "yield", "CSV", "rows" ]
train
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L25-L46
davidhuser/dhis2.py
dhis2/utils.py
load_json
def load_json(path): """ Load JSON file from path :param path: file path :return: A Python object (e.g. a dict) """ try: with open(path, 'r') as json_file: return json.load(json_file) except (OSError, IOError): raise ClientException("File not found: {}".format(pat...
python
def load_json(path): """ Load JSON file from path :param path: file path :return: A Python object (e.g. a dict) """ try: with open(path, 'r') as json_file: return json.load(json_file) except (OSError, IOError): raise ClientException("File not found: {}".format(pat...
[ "def", "load_json", "(", "path", ")", ":", "try", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "json_file", ":", "return", "json", ".", "load", "(", "json_file", ")", "except", "(", "OSError", ",", "IOError", ")", ":", "raise", "ClientExc...
Load JSON file from path :param path: file path :return: A Python object (e.g. a dict)
[ "Load", "JSON", "file", "from", "path", ":", "param", "path", ":", "file", "path", ":", "return", ":", "A", "Python", "object", "(", "e", ".", "g", ".", "a", "dict", ")" ]
train
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L49-L59
davidhuser/dhis2.py
dhis2/utils.py
partition_payload
def partition_payload(data, key, thresh): """ Yield partitions of a payload e.g. with a threshold of 2: { "dataElements": [1, 2, 3] } --> { "dataElements": [1, 2] } and { "dataElements": [3] } :param data: the payload :param key: the key of the dict to partition :param ...
python
def partition_payload(data, key, thresh): """ Yield partitions of a payload e.g. with a threshold of 2: { "dataElements": [1, 2, 3] } --> { "dataElements": [1, 2] } and { "dataElements": [3] } :param data: the payload :param key: the key of the dict to partition :param ...
[ "def", "partition_payload", "(", "data", ",", "key", ",", "thresh", ")", ":", "data", "=", "data", "[", "key", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "data", ")", ",", "thresh", ")", ":", "yield", "{", "key", ":", "data", "[...
Yield partitions of a payload e.g. with a threshold of 2: { "dataElements": [1, 2, 3] } --> { "dataElements": [1, 2] } and { "dataElements": [3] } :param data: the payload :param key: the key of the dict to partition :param thresh: the maximum value of a chunk :return: a ge...
[ "Yield", "partitions", "of", "a", "payload" ]
train
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L62-L81
davidhuser/dhis2.py
dhis2/utils.py
search_auth_file
def search_auth_file(filename='dish.json'): """ Search filename in - A) DHIS_HOME (env variable) - B) current user's home folder :param filename: the filename to search for :return: full path of filename """ if 'DHIS_HOME' in os.environ: return os.path.join(os.environ['DHIS_HOME'...
python
def search_auth_file(filename='dish.json'): """ Search filename in - A) DHIS_HOME (env variable) - B) current user's home folder :param filename: the filename to search for :return: full path of filename """ if 'DHIS_HOME' in os.environ: return os.path.join(os.environ['DHIS_HOME'...
[ "def", "search_auth_file", "(", "filename", "=", "'dish.json'", ")", ":", "if", "'DHIS_HOME'", "in", "os", ".", "environ", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'DHIS_HOME'", "]", ",", "filename", ")", "else", ...
Search filename in - A) DHIS_HOME (env variable) - B) current user's home folder :param filename: the filename to search for :return: full path of filename
[ "Search", "filename", "in", "-", "A", ")", "DHIS_HOME", "(", "env", "variable", ")", "-", "B", ")", "current", "user", "s", "home", "folder", ":", "param", "filename", ":", "the", "filename", "to", "search", "for", ":", "return", ":", "full", "path", ...
train
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L84-L99
davidhuser/dhis2.py
dhis2/utils.py
version_to_int
def version_to_int(value): """ Convert version info to integer :param value: the version received from system/info, e.g. "2.28" :return: integer from version, e.g. 28, None if it couldn't be parsed """ # remove '-SNAPSHOT' value = value.replace('-SNAPSHOT', '') # remove '-RCx' if '-R...
python
def version_to_int(value): """ Convert version info to integer :param value: the version received from system/info, e.g. "2.28" :return: integer from version, e.g. 28, None if it couldn't be parsed """ # remove '-SNAPSHOT' value = value.replace('-SNAPSHOT', '') # remove '-RCx' if '-R...
[ "def", "version_to_int", "(", "value", ")", ":", "# remove '-SNAPSHOT'", "value", "=", "value", ".", "replace", "(", "'-SNAPSHOT'", ",", "''", ")", "# remove '-RCx'", "if", "'-RC'", "in", "value", ":", "value", "=", "value", ".", "split", "(", "'-RC'", ","...
Convert version info to integer :param value: the version received from system/info, e.g. "2.28" :return: integer from version, e.g. 28, None if it couldn't be parsed
[ "Convert", "version", "info", "to", "integer", ":", "param", "value", ":", "the", "version", "received", "from", "system", "/", "info", "e", ".", "g", ".", "2", ".", "28", ":", "return", ":", "integer", "from", "version", "e", ".", "g", ".", "28", ...
train
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L102-L116
davidhuser/dhis2.py
dhis2/utils.py
generate_uid
def generate_uid(): """ Create DHIS2 UID matching to Regex ^[A-Za-z][A-Za-z0-9]{10}$ :return: UID string """ # first must be a letter first = random.choice(string.ascii_letters) # rest must be letters or numbers rest = ''.join(random.choice(string.ascii_letters + string.digits) for _...
python
def generate_uid(): """ Create DHIS2 UID matching to Regex ^[A-Za-z][A-Za-z0-9]{10}$ :return: UID string """ # first must be a letter first = random.choice(string.ascii_letters) # rest must be letters or numbers rest = ''.join(random.choice(string.ascii_letters + string.digits) for _...
[ "def", "generate_uid", "(", ")", ":", "# first must be a letter", "first", "=", "random", ".", "choice", "(", "string", ".", "ascii_letters", ")", "# rest must be letters or numbers", "rest", "=", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ...
Create DHIS2 UID matching to Regex ^[A-Za-z][A-Za-z0-9]{10}$ :return: UID string
[ "Create", "DHIS2", "UID", "matching", "to", "Regex", "^", "[", "A", "-", "Za", "-", "z", "]", "[", "A", "-", "Za", "-", "z0", "-", "9", "]", "{", "10", "}", "$", ":", "return", ":", "UID", "string" ]
train
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L119-L129
davidhuser/dhis2.py
dhis2/utils.py
is_valid_uid
def is_valid_uid(uid): """ :return: True if it is a valid DHIS2 UID, False if not """ pattern = r'^[A-Za-z][A-Za-z0-9]{10}$' if not isinstance(uid, string_types): return False return bool(re.compile(pattern).match(uid))
python
def is_valid_uid(uid): """ :return: True if it is a valid DHIS2 UID, False if not """ pattern = r'^[A-Za-z][A-Za-z0-9]{10}$' if not isinstance(uid, string_types): return False return bool(re.compile(pattern).match(uid))
[ "def", "is_valid_uid", "(", "uid", ")", ":", "pattern", "=", "r'^[A-Za-z][A-Za-z0-9]{10}$'", "if", "not", "isinstance", "(", "uid", ",", "string_types", ")", ":", "return", "False", "return", "bool", "(", "re", ".", "compile", "(", "pattern", ")", ".", "ma...
:return: True if it is a valid DHIS2 UID, False if not
[ ":", "return", ":", "True", "if", "it", "is", "a", "valid", "DHIS2", "UID", "False", "if", "not" ]
train
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L132-L139
davidhuser/dhis2.py
dhis2/utils.py
pretty_json
def pretty_json(obj): """ Print JSON with indentation and colours :param obj: the object to print - can be a dict or a string """ if isinstance(obj, string_types): try: obj = json.loads(obj) except ValueError: raise ClientException("`obj` is not a json string"...
python
def pretty_json(obj): """ Print JSON with indentation and colours :param obj: the object to print - can be a dict or a string """ if isinstance(obj, string_types): try: obj = json.loads(obj) except ValueError: raise ClientException("`obj` is not a json string"...
[ "def", "pretty_json", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "string_types", ")", ":", "try", ":", "obj", "=", "json", ".", "loads", "(", "obj", ")", "except", "ValueError", ":", "raise", "ClientException", "(", "\"`obj` is not a json s...
Print JSON with indentation and colours :param obj: the object to print - can be a dict or a string
[ "Print", "JSON", "with", "indentation", "and", "colours", ":", "param", "obj", ":", "the", "object", "to", "print", "-", "can", "be", "a", "dict", "or", "a", "string" ]
train
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L142-L153
davidhuser/dhis2.py
dhis2/utils.py
clean_obj
def clean_obj(obj, remove): """ Recursively remove keys from list/dict/dict-of-lists/list-of-keys/nested ..., e.g. remove all sharing keys or remove all 'user' fields This should result in the same as if running in bash: `jq del(.. | .publicAccess?, .userGroupAccesses?)` :param obj: the dict to rem...
python
def clean_obj(obj, remove): """ Recursively remove keys from list/dict/dict-of-lists/list-of-keys/nested ..., e.g. remove all sharing keys or remove all 'user' fields This should result in the same as if running in bash: `jq del(.. | .publicAccess?, .userGroupAccesses?)` :param obj: the dict to rem...
[ "def", "clean_obj", "(", "obj", ",", "remove", ")", ":", "if", "isinstance", "(", "remove", ",", "string_types", ")", ":", "remove", "=", "[", "remove", "]", "try", ":", "iter", "(", "remove", ")", "except", "TypeError", ":", "raise", "ClientException", ...
Recursively remove keys from list/dict/dict-of-lists/list-of-keys/nested ..., e.g. remove all sharing keys or remove all 'user' fields This should result in the same as if running in bash: `jq del(.. | .publicAccess?, .userGroupAccesses?)` :param obj: the dict to remove keys from :param remove: keys to...
[ "Recursively", "remove", "keys", "from", "list", "/", "dict", "/", "dict", "-", "of", "-", "lists", "/", "list", "-", "of", "-", "keys", "/", "nested", "...", "e", ".", "g", ".", "remove", "all", "sharing", "keys", "or", "remove", "all", "user", "f...
train
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/utils.py#L156-L183
BlueBrain/hpcbench
hpcbench/driver/benchmark.py
BenchmarkCategoryDriver.commands
def commands(self): """Get all commands of the benchmark category :return generator of string """ for child in self._children: with open(osp.join(child, YAML_REPORT_FILE)) as istr: command = yaml.safe_load(istr)['command'] yield ' '.join(map(s...
python
def commands(self): """Get all commands of the benchmark category :return generator of string """ for child in self._children: with open(osp.join(child, YAML_REPORT_FILE)) as istr: command = yaml.safe_load(istr)['command'] yield ' '.join(map(s...
[ "def", "commands", "(", "self", ")", ":", "for", "child", "in", "self", ".", "_children", ":", "with", "open", "(", "osp", ".", "join", "(", "child", ",", "YAML_REPORT_FILE", ")", ")", "as", "istr", ":", "command", "=", "yaml", ".", "safe_load", "(",...
Get all commands of the benchmark category :return generator of string
[ "Get", "all", "commands", "of", "the", "benchmark", "category" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/benchmark.py#L101-L109
BlueBrain/hpcbench
hpcbench/driver/benchmark.py
BenchmarkCategoryDriver._module_env
def _module_env(self, execution): """Set current process environment according to execution `environment` and `modules` """ env = copy.copy(os.environ) try: for mod in execution.get('modules') or []: Module.load(mod) os.environ.update(execu...
python
def _module_env(self, execution): """Set current process environment according to execution `environment` and `modules` """ env = copy.copy(os.environ) try: for mod in execution.get('modules') or []: Module.load(mod) os.environ.update(execu...
[ "def", "_module_env", "(", "self", ",", "execution", ")", ":", "env", "=", "copy", ".", "copy", "(", "os", ".", "environ", ")", "try", ":", "for", "mod", "in", "execution", ".", "get", "(", "'modules'", ")", "or", "[", "]", ":", "Module", ".", "l...
Set current process environment according to execution `environment` and `modules`
[ "Set", "current", "process", "environment", "according", "to", "execution", "environment", "and", "modules" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/benchmark.py#L245-L256
BlueBrain/hpcbench
hpcbench/driver/benchmark.py
BenchmarkCategoryDriver.gather_metrics
def gather_metrics(self, runs): """Write a JSON file with the result of every runs """ for run_dirs in runs.values(): with open(JSON_METRICS_FILE, 'w') as ostr: ostr.write('[\n') for i in range(len(run_dirs)): with open(osp.join(run...
python
def gather_metrics(self, runs): """Write a JSON file with the result of every runs """ for run_dirs in runs.values(): with open(JSON_METRICS_FILE, 'w') as ostr: ostr.write('[\n') for i in range(len(run_dirs)): with open(osp.join(run...
[ "def", "gather_metrics", "(", "self", ",", "runs", ")", ":", "for", "run_dirs", "in", "runs", ".", "values", "(", ")", ":", "with", "open", "(", "JSON_METRICS_FILE", ",", "'w'", ")", "as", "ostr", ":", "ostr", ".", "write", "(", "'[\\n'", ")", "for",...
Write a JSON file with the result of every runs
[ "Write", "a", "JSON", "file", "with", "the", "result", "of", "every", "runs" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/benchmark.py#L295-L311
BlueBrain/hpcbench
hpcbench/driver/benchmark.py
MetricsDriver._check_metrics
def _check_metrics(cls, schema, metrics): """Ensure that returned metrics are properly exposed """ for name, value in metrics.items(): metric = schema.get(name) if not metric: message = "Unexpected metric '{}' returned".format(name) raise E...
python
def _check_metrics(cls, schema, metrics): """Ensure that returned metrics are properly exposed """ for name, value in metrics.items(): metric = schema.get(name) if not metric: message = "Unexpected metric '{}' returned".format(name) raise E...
[ "def", "_check_metrics", "(", "cls", ",", "schema", ",", "metrics", ")", ":", "for", "name", ",", "value", "in", "metrics", ".", "items", "(", ")", ":", "metric", "=", "schema", ".", "get", "(", "name", ")", "if", "not", "metric", ":", "message", "...
Ensure that returned metrics are properly exposed
[ "Ensure", "that", "returned", "metrics", "are", "properly", "exposed" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/driver/benchmark.py#L400-L408
eng-tools/sfsimodels
sfsimodels/loader.py
add_inputs_to_object
def add_inputs_to_object(obj, values): """ A generic function to load object parameters based on a dictionary list. :param obj: Object :param values: Dictionary :return: """ for item in obj.inputs: if hasattr(obj, item): # print(item) setattr(obj, item, values...
python
def add_inputs_to_object(obj, values): """ A generic function to load object parameters based on a dictionary list. :param obj: Object :param values: Dictionary :return: """ for item in obj.inputs: if hasattr(obj, item): # print(item) setattr(obj, item, values...
[ "def", "add_inputs_to_object", "(", "obj", ",", "values", ")", ":", "for", "item", "in", "obj", ".", "inputs", ":", "if", "hasattr", "(", "obj", ",", "item", ")", ":", "# print(item)", "setattr", "(", "obj", ",", "item", ",", "values", "[", "item", "...
A generic function to load object parameters based on a dictionary list. :param obj: Object :param values: Dictionary :return:
[ "A", "generic", "function", "to", "load", "object", "parameters", "based", "on", "a", "dictionary", "list", ".", ":", "param", "obj", ":", "Object", ":", "param", "values", ":", "Dictionary", ":", "return", ":" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/loader.py#L7-L17
eng-tools/sfsimodels
sfsimodels/loader.py
load_sample_data
def load_sample_data(sss): """ Sample data for the SoilStructureSystem object :param sss: :return: """ load_soil_sample_data(sss.sp) # soil load_foundation_sample_data(sss.fd) # foundation load_structure_sample_data(sss.bd) # structure load_hazard_sample_data(sss.hz)
python
def load_sample_data(sss): """ Sample data for the SoilStructureSystem object :param sss: :return: """ load_soil_sample_data(sss.sp) # soil load_foundation_sample_data(sss.fd) # foundation load_structure_sample_data(sss.bd) # structure load_hazard_sample_data(sss.hz)
[ "def", "load_sample_data", "(", "sss", ")", ":", "load_soil_sample_data", "(", "sss", ".", "sp", ")", "# soil", "load_foundation_sample_data", "(", "sss", ".", "fd", ")", "# foundation", "load_structure_sample_data", "(", "sss", ".", "bd", ")", "# structure", "l...
Sample data for the SoilStructureSystem object :param sss: :return:
[ "Sample", "data", "for", "the", "SoilStructureSystem", "object", ":", "param", "sss", ":", ":", "return", ":" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/loader.py#L20-L30
eng-tools/sfsimodels
sfsimodels/loader.py
load_soil_sample_data
def load_soil_sample_data(sp): """ Sample data for the Soil object :param sp: Soil Object :return: """ # soil sp.g_mod = 60.0e6 # [Pa] sp.phi = 30 # [degrees] sp.relative_density = .40 # [decimal] sp.gwl = 2. # [m], ground water level sp.unit_dry_weight = 17000 # [N/m3] ...
python
def load_soil_sample_data(sp): """ Sample data for the Soil object :param sp: Soil Object :return: """ # soil sp.g_mod = 60.0e6 # [Pa] sp.phi = 30 # [degrees] sp.relative_density = .40 # [decimal] sp.gwl = 2. # [m], ground water level sp.unit_dry_weight = 17000 # [N/m3] ...
[ "def", "load_soil_sample_data", "(", "sp", ")", ":", "# soil", "sp", ".", "g_mod", "=", "60.0e6", "# [Pa]", "sp", ".", "phi", "=", "30", "# [degrees]", "sp", ".", "relative_density", "=", ".40", "# [decimal]", "sp", ".", "gwl", "=", "2.", "# [m], ground wa...
Sample data for the Soil object :param sp: Soil Object :return:
[ "Sample", "data", "for", "the", "Soil", "object", ":", "param", "sp", ":", "Soil", "Object", ":", "return", ":" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/loader.py#L33-L53
eng-tools/sfsimodels
sfsimodels/loader.py
load_foundation_sample_data
def load_foundation_sample_data(fd): """ Sample data for the Foundation object :param fd: Foundation Object :return: """ # foundation fd.width = 16.0 # m fd.length = 18.0 # m fd.depth = 0.0 # m fd.mass = 0.0
python
def load_foundation_sample_data(fd): """ Sample data for the Foundation object :param fd: Foundation Object :return: """ # foundation fd.width = 16.0 # m fd.length = 18.0 # m fd.depth = 0.0 # m fd.mass = 0.0
[ "def", "load_foundation_sample_data", "(", "fd", ")", ":", "# foundation", "fd", ".", "width", "=", "16.0", "# m", "fd", ".", "length", "=", "18.0", "# m", "fd", ".", "depth", "=", "0.0", "# m", "fd", ".", "mass", "=", "0.0" ]
Sample data for the Foundation object :param fd: Foundation Object :return:
[ "Sample", "data", "for", "the", "Foundation", "object", ":", "param", "fd", ":", "Foundation", "Object", ":", "return", ":" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/loader.py#L56-L66
eng-tools/sfsimodels
sfsimodels/loader.py
load_structure_sample_data
def load_structure_sample_data(st): """ Sample data for the Structure object :param st: Structure Object :return: """ # structure st.h_eff = 9.0 # m st.mass_eff = 120e3 # kg st.t_eff = 1.0 # s st.mass_ratio = 1.0
python
def load_structure_sample_data(st): """ Sample data for the Structure object :param st: Structure Object :return: """ # structure st.h_eff = 9.0 # m st.mass_eff = 120e3 # kg st.t_eff = 1.0 # s st.mass_ratio = 1.0
[ "def", "load_structure_sample_data", "(", "st", ")", ":", "# structure", "st", ".", "h_eff", "=", "9.0", "# m", "st", ".", "mass_eff", "=", "120e3", "# kg", "st", ".", "t_eff", "=", "1.0", "# s", "st", ".", "mass_ratio", "=", "1.0" ]
Sample data for the Structure object :param st: Structure Object :return:
[ "Sample", "data", "for", "the", "Structure", "object", ":", "param", "st", ":", "Structure", "Object", ":", "return", ":" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/loader.py#L69-L79
eng-tools/sfsimodels
sfsimodels/loader.py
load_hazard_sample_data
def load_hazard_sample_data(hz): """ Sample data for the Hazard object :param hz: Hazard Object :return: """ # hazard hz.z_factor = 0.3 # Hazard factor hz.r_factor = 1.0 # Return period factor hz.n_factor = 1.0 # Near-fault factor hz.magnitude = 7.5 # Magnitude of earthquake ...
python
def load_hazard_sample_data(hz): """ Sample data for the Hazard object :param hz: Hazard Object :return: """ # hazard hz.z_factor = 0.3 # Hazard factor hz.r_factor = 1.0 # Return period factor hz.n_factor = 1.0 # Near-fault factor hz.magnitude = 7.5 # Magnitude of earthquake ...
[ "def", "load_hazard_sample_data", "(", "hz", ")", ":", "# hazard", "hz", ".", "z_factor", "=", "0.3", "# Hazard factor", "hz", ".", "r_factor", "=", "1.0", "# Return period factor", "hz", ".", "n_factor", "=", "1.0", "# Near-fault factor", "hz", ".", "magnitude"...
Sample data for the Hazard object :param hz: Hazard Object :return:
[ "Sample", "data", "for", "the", "Hazard", "object", ":", "param", "hz", ":", "Hazard", "Object", ":", "return", ":" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/loader.py#L82-L95
eng-tools/sfsimodels
sfsimodels/loader.py
load_building_sample_data
def load_building_sample_data(bd): """ Sample data for the Building object :param bd: :return: """ number_of_storeys = 6 interstorey_height = 3.4 # m masses = 40.0e3 # kg bd.interstorey_heights = interstorey_height * np.ones(number_of_storeys) bd.floor_length = 18.0 # m b...
python
def load_building_sample_data(bd): """ Sample data for the Building object :param bd: :return: """ number_of_storeys = 6 interstorey_height = 3.4 # m masses = 40.0e3 # kg bd.interstorey_heights = interstorey_height * np.ones(number_of_storeys) bd.floor_length = 18.0 # m b...
[ "def", "load_building_sample_data", "(", "bd", ")", ":", "number_of_storeys", "=", "6", "interstorey_height", "=", "3.4", "# m", "masses", "=", "40.0e3", "# kg", "bd", ".", "interstorey_heights", "=", "interstorey_height", "*", "np", ".", "ones", "(", "number_of...
Sample data for the Building object :param bd: :return:
[ "Sample", "data", "for", "the", "Building", "object", ":", "param", "bd", ":", ":", "return", ":" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/loader.py#L98-L111
eng-tools/sfsimodels
sfsimodels/loader.py
load_frame_building_sample_data
def load_frame_building_sample_data(): """ Sample data for the BuildingFrame object :return: """ number_of_storeys = 6 interstorey_height = 3.4 # m masses = 40.0e3 # kg n_bays = 3 fb = models.BuildingFrame(number_of_storeys, n_bays) fb.interstorey_heights = interstorey_height...
python
def load_frame_building_sample_data(): """ Sample data for the BuildingFrame object :return: """ number_of_storeys = 6 interstorey_height = 3.4 # m masses = 40.0e3 # kg n_bays = 3 fb = models.BuildingFrame(number_of_storeys, n_bays) fb.interstorey_heights = interstorey_height...
[ "def", "load_frame_building_sample_data", "(", ")", ":", "number_of_storeys", "=", "6", "interstorey_height", "=", "3.4", "# m", "masses", "=", "40.0e3", "# kg", "n_bays", "=", "3", "fb", "=", "models", ".", "BuildingFrame", "(", "number_of_storeys", ",", "n_bay...
Sample data for the BuildingFrame object :return:
[ "Sample", "data", "for", "the", "BuildingFrame", "object" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/loader.py#L114-L138
lazygunner/xunleipy
xunleipy/fp.py
_get_random_fp_raw
def _get_random_fp_raw(): ''' 生成随机的原始指纹列表 ''' fp_list = [] fp_list.append(get_random_ua()) # ua fp_list.append('zh-CN') # language fp_list.append('24') # color depth fp_list.append(__get_random_screen_resolution()) fp_list.append('-480') # time zone offsite fp_list.append...
python
def _get_random_fp_raw(): ''' 生成随机的原始指纹列表 ''' fp_list = [] fp_list.append(get_random_ua()) # ua fp_list.append('zh-CN') # language fp_list.append('24') # color depth fp_list.append(__get_random_screen_resolution()) fp_list.append('-480') # time zone offsite fp_list.append...
[ "def", "_get_random_fp_raw", "(", ")", ":", "fp_list", "=", "[", "]", "fp_list", ".", "append", "(", "get_random_ua", "(", ")", ")", "# ua", "fp_list", ".", "append", "(", "'zh-CN'", ")", "# language", "fp_list", ".", "append", "(", "'24'", ")", "# color...
生成随机的原始指纹列表
[ "生成随机的原始指纹列表" ]
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/fp.py#L23-L47
lazygunner/xunleipy
xunleipy/fp.py
get_fp_raw
def get_fp_raw(): ''' 生成fp_raw_str ''' fp_file_path = os.path.expanduser('~/.xunleipy_fp') fp_list = [] try: with open(fp_file_path, 'r') as fp_file: fp_str = fp_file.readline() if len(fp_str) > 0: fp_list = fp_str.split('###') except IOErr...
python
def get_fp_raw(): ''' 生成fp_raw_str ''' fp_file_path = os.path.expanduser('~/.xunleipy_fp') fp_list = [] try: with open(fp_file_path, 'r') as fp_file: fp_str = fp_file.readline() if len(fp_str) > 0: fp_list = fp_str.split('###') except IOErr...
[ "def", "get_fp_raw", "(", ")", ":", "fp_file_path", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.xunleipy_fp'", ")", "fp_list", "=", "[", "]", "try", ":", "with", "open", "(", "fp_file_path", ",", "'r'", ")", "as", "fp_file", ":", "fp_str", "="...
生成fp_raw_str
[ "生成fp_raw_str" ]
train
https://github.com/lazygunner/xunleipy/blob/cded7598a7bf04495156bae2d747883d1eacb3f4/xunleipy/fp.py#L50-L75
BlueBrain/hpcbench
hpcbench/toolbox/functools_ext.py
compose
def compose(*functions): """Define functions composition like f ∘ g ∘ h :return: callable object that will perform function composition of callables given in argument. """ def _compose2(f, g): # pylint: disable=invalid-name return lambda x: f(g(x)) return functools.reduce(_compose2, f...
python
def compose(*functions): """Define functions composition like f ∘ g ∘ h :return: callable object that will perform function composition of callables given in argument. """ def _compose2(f, g): # pylint: disable=invalid-name return lambda x: f(g(x)) return functools.reduce(_compose2, f...
[ "def", "compose", "(", "*", "functions", ")", ":", "def", "_compose2", "(", "f", ",", "g", ")", ":", "# pylint: disable=invalid-name", "return", "lambda", "x", ":", "f", "(", "g", "(", "x", ")", ")", "return", "functools", ".", "reduce", "(", "_compose...
Define functions composition like f ∘ g ∘ h :return: callable object that will perform function composition of callables given in argument.
[ "Define", "functions", "composition", "like", "f", "∘", "g", "∘", "h", ":", "return", ":", "callable", "object", "that", "will", "perform", "function", "composition", "of", "callables", "given", "in", "argument", "." ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/functools_ext.py#L8-L17
BlueBrain/hpcbench
hpcbench/toolbox/functools_ext.py
chunks
def chunks(iterator, size): """Split an iterator into chunks with `size` elements each. Warning: ``size`` must be an actual iterator, if you pass this a concrete sequence will get you repeating elements. So ``chunks(iter(range(1000)), 10)`` is fine, but ``chunks(range(1000), 10)`...
python
def chunks(iterator, size): """Split an iterator into chunks with `size` elements each. Warning: ``size`` must be an actual iterator, if you pass this a concrete sequence will get you repeating elements. So ``chunks(iter(range(1000)), 10)`` is fine, but ``chunks(range(1000), 10)`...
[ "def", "chunks", "(", "iterator", ",", "size", ")", ":", "for", "item", "in", "iterator", ":", "yield", "[", "item", "]", "+", "list", "(", "islice", "(", "iterator", ",", "size", "-", "1", ")", ")" ]
Split an iterator into chunks with `size` elements each. Warning: ``size`` must be an actual iterator, if you pass this a concrete sequence will get you repeating elements. So ``chunks(iter(range(1000)), 10)`` is fine, but ``chunks(range(1000), 10)`` is not. Example: # si...
[ "Split", "an", "iterator", "into", "chunks", "with", "size", "elements", "each", ".", "Warning", ":", "size", "must", "be", "an", "actual", "iterator", "if", "you", "pass", "this", "a", "concrete", "sequence", "will", "get", "you", "repeating", "elements", ...
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/functools_ext.py#L20-L38
BlueBrain/hpcbench
hpcbench/toolbox/functools_ext.py
listify
def listify(func=None, wrapper=list): """ A decorator which wraps a function's return value in ``list(...)``. Useful when an algorithm can be expressed more cleanly as a generator but the function should return an list. Example:: >>> @listify ... def get_lengths(iterable): .....
python
def listify(func=None, wrapper=list): """ A decorator which wraps a function's return value in ``list(...)``. Useful when an algorithm can be expressed more cleanly as a generator but the function should return an list. Example:: >>> @listify ... def get_lengths(iterable): .....
[ "def", "listify", "(", "func", "=", "None", ",", "wrapper", "=", "list", ")", ":", "def", "_listify_return", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_listify_helper", "(", "*", "args", ",", "*", "*", "kw", "...
A decorator which wraps a function's return value in ``list(...)``. Useful when an algorithm can be expressed more cleanly as a generator but the function should return an list. Example:: >>> @listify ... def get_lengths(iterable): ... for i in iterable: ... yield...
[ "A", "decorator", "which", "wraps", "a", "function", "s", "return", "value", "in", "list", "(", "...", ")", ".", "Useful", "when", "an", "algorithm", "can", "be", "expressed", "more", "cleanly", "as", "a", "generator", "but", "the", "function", "should", ...
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/functools_ext.py#L41-L71
portfoliome/foil
foil/patterns.py
match_subgroup
def match_subgroup(sequence, pattern): """Yield the sub-group element dictionary that match a regex pattern.""" for element in sequence: match = re.match(pattern, element) if match: yield match.groupdict()
python
def match_subgroup(sequence, pattern): """Yield the sub-group element dictionary that match a regex pattern.""" for element in sequence: match = re.match(pattern, element) if match: yield match.groupdict()
[ "def", "match_subgroup", "(", "sequence", ",", "pattern", ")", ":", "for", "element", "in", "sequence", ":", "match", "=", "re", ".", "match", "(", "pattern", ",", "element", ")", "if", "match", ":", "yield", "match", ".", "groupdict", "(", ")" ]
Yield the sub-group element dictionary that match a regex pattern.
[ "Yield", "the", "sub", "-", "group", "element", "dictionary", "that", "match", "a", "regex", "pattern", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/patterns.py#L10-L17
portfoliome/foil
foil/patterns.py
add_regex_start_end
def add_regex_start_end(pattern_function): """Decorator for adding regex pattern start and end characters.""" @wraps(pattern_function) def func_wrapper(*args, **kwargs): return r'^{}$'.format(pattern_function(*args, **kwargs)) return func_wrapper
python
def add_regex_start_end(pattern_function): """Decorator for adding regex pattern start and end characters.""" @wraps(pattern_function) def func_wrapper(*args, **kwargs): return r'^{}$'.format(pattern_function(*args, **kwargs)) return func_wrapper
[ "def", "add_regex_start_end", "(", "pattern_function", ")", ":", "@", "wraps", "(", "pattern_function", ")", "def", "func_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "r'^{}$'", ".", "format", "(", "pattern_function", "(", "*", ...
Decorator for adding regex pattern start and end characters.
[ "Decorator", "for", "adding", "regex", "pattern", "start", "and", "end", "characters", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/patterns.py#L24-L30
eng-tools/sfsimodels
sfsimodels/functions.py
convert_stress_to_mass
def convert_stress_to_mass(q, width, length, gravity): """ Converts a foundation stress to an equivalent mass. :param q: applied stress [Pa] :param width: foundation width [m] :param length: foundation length [m] :param gravity: applied gravitational acceleration [m/s2] :return: """ ...
python
def convert_stress_to_mass(q, width, length, gravity): """ Converts a foundation stress to an equivalent mass. :param q: applied stress [Pa] :param width: foundation width [m] :param length: foundation length [m] :param gravity: applied gravitational acceleration [m/s2] :return: """ ...
[ "def", "convert_stress_to_mass", "(", "q", ",", "width", ",", "length", ",", "gravity", ")", ":", "mass", "=", "q", "*", "width", "*", "length", "/", "gravity", "return", "mass" ]
Converts a foundation stress to an equivalent mass. :param q: applied stress [Pa] :param width: foundation width [m] :param length: foundation length [m] :param gravity: applied gravitational acceleration [m/s2] :return:
[ "Converts", "a", "foundation", "stress", "to", "an", "equivalent", "mass", "." ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/functions.py#L4-L15
eng-tools/sfsimodels
sfsimodels/functions.py
add_to_obj
def add_to_obj(obj, dictionary, objs=None, exceptions=None, verbose=0): """ Cycles through a dictionary and adds the key-value pairs to an object. :param obj: :param dictionary: :param exceptions: :param verbose: :return: """ if exceptions is None: exceptions = [] for it...
python
def add_to_obj(obj, dictionary, objs=None, exceptions=None, verbose=0): """ Cycles through a dictionary and adds the key-value pairs to an object. :param obj: :param dictionary: :param exceptions: :param verbose: :return: """ if exceptions is None: exceptions = [] for it...
[ "def", "add_to_obj", "(", "obj", ",", "dictionary", ",", "objs", "=", "None", ",", "exceptions", "=", "None", ",", "verbose", "=", "0", ")", ":", "if", "exceptions", "is", "None", ":", "exceptions", "=", "[", "]", "for", "item", "in", "dictionary", "...
Cycles through a dictionary and adds the key-value pairs to an object. :param obj: :param dictionary: :param exceptions: :param verbose: :return:
[ "Cycles", "through", "a", "dictionary", "and", "adds", "the", "key", "-", "value", "pairs", "to", "an", "object", "." ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/functions.py#L76-L100
portfoliome/foil
foil/compose.py
create_quantiles
def create_quantiles(items: Sequence, lower_bound, upper_bound): """Create quantile start and end boundaries.""" interval = (upper_bound - lower_bound) / len(items) quantiles = ((g, (x - interval, x)) for g, x in zip(items, accumulate(repeat(interval, len(items))))) return quantiles
python
def create_quantiles(items: Sequence, lower_bound, upper_bound): """Create quantile start and end boundaries.""" interval = (upper_bound - lower_bound) / len(items) quantiles = ((g, (x - interval, x)) for g, x in zip(items, accumulate(repeat(interval, len(items))))) return quantiles
[ "def", "create_quantiles", "(", "items", ":", "Sequence", ",", "lower_bound", ",", "upper_bound", ")", ":", "interval", "=", "(", "upper_bound", "-", "lower_bound", ")", "/", "len", "(", "items", ")", "quantiles", "=", "(", "(", "g", ",", "(", "x", "-"...
Create quantile start and end boundaries.
[ "Create", "quantile", "start", "and", "end", "boundaries", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/compose.py#L5-L13
portfoliome/foil
foil/compose.py
tupleize
def tupleize(element, ignore_types=(str, bytes)): """Cast a single element to a tuple.""" if hasattr(element, '__iter__') and not isinstance(element, ignore_types): return element else: return tuple((element,))
python
def tupleize(element, ignore_types=(str, bytes)): """Cast a single element to a tuple.""" if hasattr(element, '__iter__') and not isinstance(element, ignore_types): return element else: return tuple((element,))
[ "def", "tupleize", "(", "element", ",", "ignore_types", "=", "(", "str", ",", "bytes", ")", ")", ":", "if", "hasattr", "(", "element", ",", "'__iter__'", ")", "and", "not", "isinstance", "(", "element", ",", "ignore_types", ")", ":", "return", "element",...
Cast a single element to a tuple.
[ "Cast", "a", "single", "element", "to", "a", "tuple", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/compose.py#L16-L21
portfoliome/foil
foil/compose.py
dictionize
def dictionize(fields: Sequence, records: Sequence) -> Generator: """Create dictionaries mapping fields to record data.""" return (dict(zip(fields, rec)) for rec in records)
python
def dictionize(fields: Sequence, records: Sequence) -> Generator: """Create dictionaries mapping fields to record data.""" return (dict(zip(fields, rec)) for rec in records)
[ "def", "dictionize", "(", "fields", ":", "Sequence", ",", "records", ":", "Sequence", ")", "->", "Generator", ":", "return", "(", "dict", "(", "zip", "(", "fields", ",", "rec", ")", ")", "for", "rec", "in", "records", ")" ]
Create dictionaries mapping fields to record data.
[ "Create", "dictionaries", "mapping", "fields", "to", "record", "data", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/compose.py#L43-L46
portfoliome/foil
foil/compose.py
flip_iterable_dict
def flip_iterable_dict(d: dict) -> dict: """Transform dictionary to unpack values to map to respective key.""" value_keys = disjoint_union((cartesian_product((v, k)) for k, v in d.items())) return dict(value_keys)
python
def flip_iterable_dict(d: dict) -> dict: """Transform dictionary to unpack values to map to respective key.""" value_keys = disjoint_union((cartesian_product((v, k)) for k, v in d.items())) return dict(value_keys)
[ "def", "flip_iterable_dict", "(", "d", ":", "dict", ")", "->", "dict", ":", "value_keys", "=", "disjoint_union", "(", "(", "cartesian_product", "(", "(", "v", ",", "k", ")", ")", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ")", ")", ...
Transform dictionary to unpack values to map to respective key.
[ "Transform", "dictionary", "to", "unpack", "values", "to", "map", "to", "respective", "key", "." ]
train
https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/compose.py#L53-L58
sci-bots/svg-model
svg_model/loop.py
Loop.get_signed_area
def get_signed_area(self): """ Return area of a simple (ie. non-self-intersecting) polygon. If verts wind anti-clockwise, this returns a negative number. Assume y-axis points up. """ accum = 0.0 for i in range(len(self.verts)): j = (i + 1) % len(self.v...
python
def get_signed_area(self): """ Return area of a simple (ie. non-self-intersecting) polygon. If verts wind anti-clockwise, this returns a negative number. Assume y-axis points up. """ accum = 0.0 for i in range(len(self.verts)): j = (i + 1) % len(self.v...
[ "def", "get_signed_area", "(", "self", ")", ":", "accum", "=", "0.0", "for", "i", "in", "range", "(", "len", "(", "self", ".", "verts", ")", ")", ":", "j", "=", "(", "i", "+", "1", ")", "%", "len", "(", "self", ".", "verts", ")", "accum", "+=...
Return area of a simple (ie. non-self-intersecting) polygon. If verts wind anti-clockwise, this returns a negative number. Assume y-axis points up.
[ "Return", "area", "of", "a", "simple", "(", "ie", ".", "non", "-", "self", "-", "intersecting", ")", "polygon", ".", "If", "verts", "wind", "anti", "-", "clockwise", "this", "returns", "a", "negative", "number", ".", "Assume", "y", "-", "axis", "points...
train
https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/loop.py#L34-L46
PolyJIT/benchbuild
benchbuild/extensions/base.py
Extension.call_next
def call_next(self, *args, **kwargs) -> t.List[run.RunInfo]: """Call all child extensions with the given arguments. This calls all child extensions and collects the results for our own parent. Use this to control the execution of your nested extensions from your own extension. ...
python
def call_next(self, *args, **kwargs) -> t.List[run.RunInfo]: """Call all child extensions with the given arguments. This calls all child extensions and collects the results for our own parent. Use this to control the execution of your nested extensions from your own extension. ...
[ "def", "call_next", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "t", ".", "List", "[", "run", ".", "RunInfo", "]", ":", "all_results", "=", "[", "]", "for", "ext", "in", "self", ".", "next_extensions", ":", "LOG", ".", "deb...
Call all child extensions with the given arguments. This calls all child extensions and collects the results for our own parent. Use this to control the execution of your nested extensions from your own extension. Returns: :obj:`list` of :obj:`RunInfo`: A list of collected ...
[ "Call", "all", "child", "extensions", "with", "the", "given", "arguments", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/extensions/base.py#L41-L67
PolyJIT/benchbuild
benchbuild/extensions/base.py
Extension.print
def print(self, indent=0): """Print a structural view of the registered extensions.""" LOG.info("%s:: %s", indent * " ", self.__class__) for ext in self.next_extensions: ext.print(indent=indent + 2)
python
def print(self, indent=0): """Print a structural view of the registered extensions.""" LOG.info("%s:: %s", indent * " ", self.__class__) for ext in self.next_extensions: ext.print(indent=indent + 2)
[ "def", "print", "(", "self", ",", "indent", "=", "0", ")", ":", "LOG", ".", "info", "(", "\"%s:: %s\"", ",", "indent", "*", "\" \"", ",", "self", ".", "__class__", ")", "for", "ext", "in", "self", ".", "next_extensions", ":", "ext", ".", "print", "...
Print a structural view of the registered extensions.
[ "Print", "a", "structural", "view", "of", "the", "registered", "extensions", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/extensions/base.py#L73-L77
mromanello/hucitlib
knowledge_base/cli.py
print_results
def print_results(matches): """ :param matches: a list of tuples. """ output = "" for n, match in enumerate(matches): matched_text = match[0][:40]+"..." if len(match[0]) > 40 else match[0] search_result = match[1] if search_result.uri==surf.ns.EFRBROO['F10_Person']: ...
python
def print_results(matches): """ :param matches: a list of tuples. """ output = "" for n, match in enumerate(matches): matched_text = match[0][:40]+"..." if len(match[0]) > 40 else match[0] search_result = match[1] if search_result.uri==surf.ns.EFRBROO['F10_Person']: ...
[ "def", "print_results", "(", "matches", ")", ":", "output", "=", "\"\"", "for", "n", ",", "match", "in", "enumerate", "(", "matches", ")", ":", "matched_text", "=", "match", "[", "0", "]", "[", ":", "40", "]", "+", "\"...\"", "if", "len", "(", "mat...
:param matches: a list of tuples.
[ ":", "param", "matches", ":", "a", "list", "of", "tuples", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/cli.py#L34-L48
mromanello/hucitlib
knowledge_base/cli.py
show_result
def show_result(resource, verbose=False): """ TODO """ if resource.uri == surf.ns.EFRBROO['F10_Person']: print("\n{} ({})\n".format(unicode(resource), resource.get_urn())) works = resource.get_works() print("Works by {} ({}):\n".format(resource, len(works))) [show_result(...
python
def show_result(resource, verbose=False): """ TODO """ if resource.uri == surf.ns.EFRBROO['F10_Person']: print("\n{} ({})\n".format(unicode(resource), resource.get_urn())) works = resource.get_works() print("Works by {} ({}):\n".format(resource, len(works))) [show_result(...
[ "def", "show_result", "(", "resource", ",", "verbose", "=", "False", ")", ":", "if", "resource", ".", "uri", "==", "surf", ".", "ns", ".", "EFRBROO", "[", "'F10_Person'", "]", ":", "print", "(", "\"\\n{} ({})\\n\"", ".", "format", "(", "unicode", "(", ...
TODO
[ "TODO" ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/cli.py#L50-L68
mromanello/hucitlib
knowledge_base/cli.py
main
def main(): """Define the CLI inteface/commands.""" arguments = docopt(__doc__) cfg_filename = pkg_resources.resource_filename( 'knowledge_base', 'config/virtuoso.ini' ) kb = KnowledgeBase(cfg_filename) # the user has issued a `find` command if arguments["find"]: sea...
python
def main(): """Define the CLI inteface/commands.""" arguments = docopt(__doc__) cfg_filename = pkg_resources.resource_filename( 'knowledge_base', 'config/virtuoso.ini' ) kb = KnowledgeBase(cfg_filename) # the user has issued a `find` command if arguments["find"]: sea...
[ "def", "main", "(", ")", ":", "arguments", "=", "docopt", "(", "__doc__", ")", "cfg_filename", "=", "pkg_resources", ".", "resource_filename", "(", "'knowledge_base'", ",", "'config/virtuoso.ini'", ")", "kb", "=", "KnowledgeBase", "(", "cfg_filename", ")", "# th...
Define the CLI inteface/commands.
[ "Define", "the", "CLI", "inteface", "/", "commands", "." ]
train
https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/cli.py#L71-L127
PolyJIT/benchbuild
benchbuild/utils/container.py
cached
def cached(func): """Memoize a function result.""" ret = None def call_or_cache(*args, **kwargs): nonlocal ret if ret is None: ret = func(*args, **kwargs) return ret return call_or_cache
python
def cached(func): """Memoize a function result.""" ret = None def call_or_cache(*args, **kwargs): nonlocal ret if ret is None: ret = func(*args, **kwargs) return ret return call_or_cache
[ "def", "cached", "(", "func", ")", ":", "ret", "=", "None", "def", "call_or_cache", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "nonlocal", "ret", "if", "ret", "is", "None", ":", "ret", "=", "func", "(", "*", "args", ",", "*", "*", "kw...
Memoize a function result.
[ "Memoize", "a", "function", "result", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/container.py#L15-L25
PolyJIT/benchbuild
benchbuild/utils/container.py
is_valid
def is_valid(container, path): """ Checks if a container exists and is unpacked. Args: path: The location where the container is expected. Returns: True if the container is valid, False if the container needs to unpacked or if the path does not exist yet. """ try: ...
python
def is_valid(container, path): """ Checks if a container exists and is unpacked. Args: path: The location where the container is expected. Returns: True if the container is valid, False if the container needs to unpacked or if the path does not exist yet. """ try: ...
[ "def", "is_valid", "(", "container", ",", "path", ")", ":", "try", ":", "tmp_hash_path", "=", "container", ".", "filename", "+", "\".hash\"", "with", "open", "(", "tmp_hash_path", ",", "'r'", ")", "as", "tmp_file", ":", "tmp_hash", "=", "tmp_file", ".", ...
Checks if a container exists and is unpacked. Args: path: The location where the container is expected. Returns: True if the container is valid, False if the container needs to unpacked or if the path does not exist yet.
[ "Checks", "if", "a", "container", "exists", "and", "is", "unpacked", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/container.py#L111-L134
PolyJIT/benchbuild
benchbuild/utils/container.py
unpack
def unpack(container, path): """ Unpack a container usable by uchroot. Method that checks if a directory for the container exists, checks if erlent support is needed and then unpacks the container accordingly. Args: path: The location where the container is, that needs to be unpacked. ...
python
def unpack(container, path): """ Unpack a container usable by uchroot. Method that checks if a directory for the container exists, checks if erlent support is needed and then unpacks the container accordingly. Args: path: The location where the container is, that needs to be unpacked. ...
[ "def", "unpack", "(", "container", ",", "path", ")", ":", "from", "benchbuild", ".", "utils", ".", "run", "import", "run", "from", "benchbuild", ".", "utils", ".", "uchroot", "import", "no_args", "path", "=", "local", ".", "path", "(", "path", ")", "c_...
Unpack a container usable by uchroot. Method that checks if a directory for the container exists, checks if erlent support is needed and then unpacks the container accordingly. Args: path: The location where the container is, that needs to be unpacked.
[ "Unpack", "a", "container", "usable", "by", "uchroot", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/container.py#L137-L182
PolyJIT/benchbuild
benchbuild/utils/container.py
Container.local
def local(self): """ Finds the current location of a container. Also unpacks the project if necessary. Returns: target: The path, where the container lies in the end. """ assert self.name in CFG["container"]["images"].value tmp_dir = local.path(str(CF...
python
def local(self): """ Finds the current location of a container. Also unpacks the project if necessary. Returns: target: The path, where the container lies in the end. """ assert self.name in CFG["container"]["images"].value tmp_dir = local.path(str(CF...
[ "def", "local", "(", "self", ")", ":", "assert", "self", ".", "name", "in", "CFG", "[", "\"container\"", "]", "[", "\"images\"", "]", ".", "value", "tmp_dir", "=", "local", ".", "path", "(", "str", "(", "CFG", "[", "\"tmp_dir\"", "]", ")", ")", "ta...
Finds the current location of a container. Also unpacks the project if necessary. Returns: target: The path, where the container lies in the end.
[ "Finds", "the", "current", "location", "of", "a", "container", ".", "Also", "unpacks", "the", "project", "if", "necessary", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/container.py#L46-L61
PolyJIT/benchbuild
benchbuild/utils/container.py
Gentoo.src_file
def src_file(self): """ Get the latest src_uri for a stage 3 tarball. Returns (str): Latest src_uri from gentoo's distfiles mirror. """ try: src_uri = (curl[Gentoo._LATEST_TXT] | tail["-n", "+3"] | cut["-f1", "-d "])().strip() ...
python
def src_file(self): """ Get the latest src_uri for a stage 3 tarball. Returns (str): Latest src_uri from gentoo's distfiles mirror. """ try: src_uri = (curl[Gentoo._LATEST_TXT] | tail["-n", "+3"] | cut["-f1", "-d "])().strip() ...
[ "def", "src_file", "(", "self", ")", ":", "try", ":", "src_uri", "=", "(", "curl", "[", "Gentoo", ".", "_LATEST_TXT", "]", "|", "tail", "[", "\"-n\"", ",", "\"+3\"", "]", "|", "cut", "[", "\"-f1\"", ",", "\"-d \"", "]", ")", "(", ")", ".", "strip...
Get the latest src_uri for a stage 3 tarball. Returns (str): Latest src_uri from gentoo's distfiles mirror.
[ "Get", "the", "latest", "src_uri", "for", "a", "stage", "3", "tarball", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/container.py#L72-L86
PolyJIT/benchbuild
benchbuild/utils/container.py
Gentoo.version
def version(self): """Return the build date of the gentoo container.""" try: _version = (curl[Gentoo._LATEST_TXT] | \ awk['NR==2{print}'] | \ cut["-f2", "-d="])().strip() _version = datetime.utcfromtimestamp(int(_version))\ ...
python
def version(self): """Return the build date of the gentoo container.""" try: _version = (curl[Gentoo._LATEST_TXT] | \ awk['NR==2{print}'] | \ cut["-f2", "-d="])().strip() _version = datetime.utcfromtimestamp(int(_version))\ ...
[ "def", "version", "(", "self", ")", ":", "try", ":", "_version", "=", "(", "curl", "[", "Gentoo", ".", "_LATEST_TXT", "]", "|", "awk", "[", "'NR==2{print}'", "]", "|", "cut", "[", "\"-f2\"", ",", "\"-d=\"", "]", ")", "(", ")", ".", "strip", "(", ...
Return the build date of the gentoo container.
[ "Return", "the", "build", "date", "of", "the", "gentoo", "container", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/container.py#L90-L102
BlueBrain/hpcbench
hpcbench/cli/bencsv.py
main
def main(argv=None): """ben-csv entry point""" arguments = cli_common(__doc__, argv=argv) csv_export = CSVExporter(arguments['CAMPAIGN-DIR'], arguments['--output']) if arguments['--peek']: csv_export.peek() else: fieldsstr = arguments.get('--fields') fields = fieldsstr.split(...
python
def main(argv=None): """ben-csv entry point""" arguments = cli_common(__doc__, argv=argv) csv_export = CSVExporter(arguments['CAMPAIGN-DIR'], arguments['--output']) if arguments['--peek']: csv_export.peek() else: fieldsstr = arguments.get('--fields') fields = fieldsstr.split(...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "arguments", "=", "cli_common", "(", "__doc__", ",", "argv", "=", "argv", ")", "csv_export", "=", "CSVExporter", "(", "arguments", "[", "'CAMPAIGN-DIR'", "]", ",", "arguments", "[", "'--output'", "]", ")...
ben-csv entry point
[ "ben", "-", "csv", "entry", "point" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/cli/bencsv.py#L24-L35
eng-tools/sfsimodels
sfsimodels/models/time.py
time_indices
def time_indices(npts, dt, start, end, index): """ Determine the new start and end indices of the time series. :param npts: Number of points in original time series :param dt: Time step of original time series :param start: int or float, optional, New start point :param end: int or float, optio...
python
def time_indices(npts, dt, start, end, index): """ Determine the new start and end indices of the time series. :param npts: Number of points in original time series :param dt: Time step of original time series :param start: int or float, optional, New start point :param end: int or float, optio...
[ "def", "time_indices", "(", "npts", ",", "dt", ",", "start", ",", "end", ",", "index", ")", ":", "if", "index", "is", "False", ":", "# Convert time values into indices", "if", "end", "!=", "-", "1", ":", "e_index", "=", "int", "(", "end", "/", "dt", ...
Determine the new start and end indices of the time series. :param npts: Number of points in original time series :param dt: Time step of original time series :param start: int or float, optional, New start point :param end: int or float, optional, New end point :param index: bool, optional, if Fal...
[ "Determine", "the", "new", "start", "and", "end", "indices", "of", "the", "time", "series", "." ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/time.py#L64-L86
eng-tools/sfsimodels
sfsimodels/models/time.py
TimeSeries.cut
def cut(self, start=0, end=-1, index=False): """ The method cuts the time series to reduce its length. :param start: int or float, optional, New start point :param end: int or float, optional, New end point :param index: bool, optional, if False then start and end are considered ...
python
def cut(self, start=0, end=-1, index=False): """ The method cuts the time series to reduce its length. :param start: int or float, optional, New start point :param end: int or float, optional, New end point :param index: bool, optional, if False then start and end are considered ...
[ "def", "cut", "(", "self", ",", "start", "=", "0", ",", "end", "=", "-", "1", ",", "index", "=", "False", ")", ":", "s_index", ",", "e_index", "=", "time_indices", "(", "self", ".", "npts", ",", "self", ".", "dt", ",", "start", ",", "end", ",",...
The method cuts the time series to reduce its length. :param start: int or float, optional, New start point :param end: int or float, optional, New end point :param index: bool, optional, if False then start and end are considered values in time.
[ "The", "method", "cuts", "the", "time", "series", "to", "reduce", "its", "length", ".", ":", "param", "start", ":", "int", "or", "float", "optional", "New", "start", "point", ":", "param", "end", ":", "int", "or", "float", "optional", "New", "end", "po...
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/time.py#L53-L61
BlueBrain/hpcbench
hpcbench/toolbox/slurm/job.py
Job.finished
def finished(cls, jobid): """Check whether a SLURM job is finished or not""" output = subprocess.check_output( [SACCT, '-n', '-X', '-o', "end", '-j', str(jobid)] ) end = output.strip().decode() return end not in {'Unknown', ''}
python
def finished(cls, jobid): """Check whether a SLURM job is finished or not""" output = subprocess.check_output( [SACCT, '-n', '-X', '-o', "end", '-j', str(jobid)] ) end = output.strip().decode() return end not in {'Unknown', ''}
[ "def", "finished", "(", "cls", ",", "jobid", ")", ":", "output", "=", "subprocess", ".", "check_output", "(", "[", "SACCT", ",", "'-n'", ",", "'-X'", ",", "'-o'", ",", "\"end\"", ",", "'-j'", ",", "str", "(", "jobid", ")", "]", ")", "end", "=", "...
Check whether a SLURM job is finished or not
[ "Check", "whether", "a", "SLURM", "job", "is", "finished", "or", "not" ]
train
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/slurm/job.py#L53-L59
PolyJIT/benchbuild
benchbuild/utils/run.py
begin_run_group
def begin_run_group(project): """ Begin a run_group in the database. A run_group groups a set of runs for a given project. This models a series of runs that form a complete binary runtime test. Args: project: The project we begin a new run_group for. Returns: ``(group, session...
python
def begin_run_group(project): """ Begin a run_group in the database. A run_group groups a set of runs for a given project. This models a series of runs that form a complete binary runtime test. Args: project: The project we begin a new run_group for. Returns: ``(group, session...
[ "def", "begin_run_group", "(", "project", ")", ":", "from", "benchbuild", ".", "utils", ".", "db", "import", "create_run_group", "from", "datetime", "import", "datetime", "group", ",", "session", "=", "create_run_group", "(", "project", ")", "group", ".", "beg...
Begin a run_group in the database. A run_group groups a set of runs for a given project. This models a series of runs that form a complete binary runtime test. Args: project: The project we begin a new run_group for. Returns: ``(group, session)`` where group is the created group in th...
[ "Begin", "a", "run_group", "in", "the", "database", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L205-L227
PolyJIT/benchbuild
benchbuild/utils/run.py
end_run_group
def end_run_group(group, session): """ End the run_group successfully. Args: group: The run_group we want to complete. session: The database transaction we will finish. """ from datetime import datetime group.end = datetime.now() group.status = 'completed' session.commi...
python
def end_run_group(group, session): """ End the run_group successfully. Args: group: The run_group we want to complete. session: The database transaction we will finish. """ from datetime import datetime group.end = datetime.now() group.status = 'completed' session.commi...
[ "def", "end_run_group", "(", "group", ",", "session", ")", ":", "from", "datetime", "import", "datetime", "group", ".", "end", "=", "datetime", ".", "now", "(", ")", "group", ".", "status", "=", "'completed'", "session", ".", "commit", "(", ")" ]
End the run_group successfully. Args: group: The run_group we want to complete. session: The database transaction we will finish.
[ "End", "the", "run_group", "successfully", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L230-L242
PolyJIT/benchbuild
benchbuild/utils/run.py
fail_run_group
def fail_run_group(group, session): """ End the run_group unsuccessfully. Args: group: The run_group we want to complete. session: The database transaction we will finish. """ from datetime import datetime group.end = datetime.now() group.status = 'failed' session.commi...
python
def fail_run_group(group, session): """ End the run_group unsuccessfully. Args: group: The run_group we want to complete. session: The database transaction we will finish. """ from datetime import datetime group.end = datetime.now() group.status = 'failed' session.commi...
[ "def", "fail_run_group", "(", "group", ",", "session", ")", ":", "from", "datetime", "import", "datetime", "group", ".", "end", "=", "datetime", ".", "now", "(", ")", "group", ".", "status", "=", "'failed'", "session", ".", "commit", "(", ")" ]
End the run_group unsuccessfully. Args: group: The run_group we want to complete. session: The database transaction we will finish.
[ "End", "the", "run_group", "unsuccessfully", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L245-L257
PolyJIT/benchbuild
benchbuild/utils/run.py
exit_code_from_run_infos
def exit_code_from_run_infos(run_infos: t.List[RunInfo]) -> int: """Generate a single exit code from a list of RunInfo objects. Takes a list of RunInfos and returns the exit code that is furthest away from 0. Args: run_infos (t.List[RunInfo]): [description] Returns: int: [descript...
python
def exit_code_from_run_infos(run_infos: t.List[RunInfo]) -> int: """Generate a single exit code from a list of RunInfo objects. Takes a list of RunInfos and returns the exit code that is furthest away from 0. Args: run_infos (t.List[RunInfo]): [description] Returns: int: [descript...
[ "def", "exit_code_from_run_infos", "(", "run_infos", ":", "t", ".", "List", "[", "RunInfo", "]", ")", "->", "int", ":", "assert", "run_infos", "is", "not", "None", "if", "not", "hasattr", "(", "run_infos", ",", "\"__iter__\"", ")", ":", "return", "run_info...
Generate a single exit code from a list of RunInfo objects. Takes a list of RunInfos and returns the exit code that is furthest away from 0. Args: run_infos (t.List[RunInfo]): [description] Returns: int: [description]
[ "Generate", "a", "single", "exit", "code", "from", "a", "list", "of", "RunInfo", "objects", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L260-L282
PolyJIT/benchbuild
benchbuild/utils/run.py
track_execution
def track_execution(cmd, project, experiment, **kwargs): """Guard the execution of the given command. The given command (`cmd`) will be executed inside a database context. As soon as you leave the context we will commit the transaction. Any necessary modifications to the database can be identified insi...
python
def track_execution(cmd, project, experiment, **kwargs): """Guard the execution of the given command. The given command (`cmd`) will be executed inside a database context. As soon as you leave the context we will commit the transaction. Any necessary modifications to the database can be identified insi...
[ "def", "track_execution", "(", "cmd", ",", "project", ",", "experiment", ",", "*", "*", "kwargs", ")", ":", "runner", "=", "RunInfo", "(", "cmd", "=", "cmd", ",", "project", "=", "project", ",", "experiment", "=", "experiment", ",", "*", "*", "kwargs",...
Guard the execution of the given command. The given command (`cmd`) will be executed inside a database context. As soon as you leave the context we will commit the transaction. Any necessary modifications to the database can be identified inside the context with the RunInfo object. Args: c...
[ "Guard", "the", "execution", "of", "the", "given", "command", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L286-L306
PolyJIT/benchbuild
benchbuild/utils/run.py
with_env_recursive
def with_env_recursive(cmd, **envvars): """ Recursively updates the environment of cmd and all its subcommands. Args: cmd - A plumbum command-like object **envvars - The environment variables to update Returns: The updated command. """ from plumbum.commands.base import ...
python
def with_env_recursive(cmd, **envvars): """ Recursively updates the environment of cmd and all its subcommands. Args: cmd - A plumbum command-like object **envvars - The environment variables to update Returns: The updated command. """ from plumbum.commands.base import ...
[ "def", "with_env_recursive", "(", "cmd", ",", "*", "*", "envvars", ")", ":", "from", "plumbum", ".", "commands", ".", "base", "import", "BoundCommand", ",", "BoundEnvCommand", "if", "isinstance", "(", "cmd", ",", "BoundCommand", ")", ":", "cmd", ".", "cmd"...
Recursively updates the environment of cmd and all its subcommands. Args: cmd - A plumbum command-like object **envvars - The environment variables to update Returns: The updated command.
[ "Recursively", "updates", "the", "environment", "of", "cmd", "and", "all", "its", "subcommands", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L318-L335
PolyJIT/benchbuild
benchbuild/utils/run.py
in_builddir
def in_builddir(sub='.'): """ Decorate a project phase with a local working directory change. Args: sub: An optional subdirectory to change into. """ from functools import wraps def wrap_in_builddir(func): """Wrap the function for the new build directory.""" @wraps(fun...
python
def in_builddir(sub='.'): """ Decorate a project phase with a local working directory change. Args: sub: An optional subdirectory to change into. """ from functools import wraps def wrap_in_builddir(func): """Wrap the function for the new build directory.""" @wraps(fun...
[ "def", "in_builddir", "(", "sub", "=", "'.'", ")", ":", "from", "functools", "import", "wraps", "def", "wrap_in_builddir", "(", "func", ")", ":", "\"\"\"Wrap the function for the new build directory.\"\"\"", "@", "wraps", "(", "func", ")", "def", "wrap_in_builddir_f...
Decorate a project phase with a local working directory change. Args: sub: An optional subdirectory to change into.
[ "Decorate", "a", "project", "phase", "with", "a", "local", "working", "directory", "change", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L338-L365
PolyJIT/benchbuild
benchbuild/utils/run.py
store_config
def store_config(func): """Decorator for storing the configuration in the project's builddir.""" from functools import wraps @wraps(func) def wrap_store_config(self, *args, **kwargs): """Wrapper that contains the actual storage call for the config.""" CFG.store(local.path(self.builddir)...
python
def store_config(func): """Decorator for storing the configuration in the project's builddir.""" from functools import wraps @wraps(func) def wrap_store_config(self, *args, **kwargs): """Wrapper that contains the actual storage call for the config.""" CFG.store(local.path(self.builddir)...
[ "def", "store_config", "(", "func", ")", ":", "from", "functools", "import", "wraps", "@", "wraps", "(", "func", ")", "def", "wrap_store_config", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapper that contains the actual storage ...
Decorator for storing the configuration in the project's builddir.
[ "Decorator", "for", "storing", "the", "configuration", "in", "the", "project", "s", "builddir", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/run.py#L368-L378
PolyJIT/benchbuild
benchbuild/container.py
clean_directories
def clean_directories(builddir, in_dir=True, out_dir=True): """Remove the in and out of the container if confirmed by the user.""" container_in = local.path(builddir) / "container-in" container_out = local.path(builddir) / "container-out" if in_dir and container_in.exists(): if ui.ask("Should I...
python
def clean_directories(builddir, in_dir=True, out_dir=True): """Remove the in and out of the container if confirmed by the user.""" container_in = local.path(builddir) / "container-in" container_out = local.path(builddir) / "container-out" if in_dir and container_in.exists(): if ui.ask("Should I...
[ "def", "clean_directories", "(", "builddir", ",", "in_dir", "=", "True", ",", "out_dir", "=", "True", ")", ":", "container_in", "=", "local", ".", "path", "(", "builddir", ")", "/", "\"container-in\"", "container_out", "=", "local", ".", "path", "(", "buil...
Remove the in and out of the container if confirmed by the user.
[ "Remove", "the", "in", "and", "out", "of", "the", "container", "if", "confirmed", "by", "the", "user", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L23-L33
PolyJIT/benchbuild
benchbuild/container.py
setup_directories
def setup_directories(builddir): """Create the in and out directories of the container.""" build_dir = local.path(builddir) in_dir = build_dir / "container-in" out_dir = build_dir / "container-out" if not in_dir.exists(): in_dir.mkdir() if not out_dir.exists(): out_dir.mkdir()
python
def setup_directories(builddir): """Create the in and out directories of the container.""" build_dir = local.path(builddir) in_dir = build_dir / "container-in" out_dir = build_dir / "container-out" if not in_dir.exists(): in_dir.mkdir() if not out_dir.exists(): out_dir.mkdir()
[ "def", "setup_directories", "(", "builddir", ")", ":", "build_dir", "=", "local", ".", "path", "(", "builddir", ")", "in_dir", "=", "build_dir", "/", "\"container-in\"", "out_dir", "=", "build_dir", "/", "\"container-out\"", "if", "not", "in_dir", ".", "exists...
Create the in and out directories of the container.
[ "Create", "the", "in", "and", "out", "directories", "of", "the", "container", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L36-L45
PolyJIT/benchbuild
benchbuild/container.py
setup_container
def setup_container(builddir, _container): """Prepare the container and returns the path where it can be found.""" build_dir = local.path(builddir) in_dir = build_dir / "container-in" container_path = local.path(_container) with local.cwd(builddir): container_bin = container_path.basename ...
python
def setup_container(builddir, _container): """Prepare the container and returns the path where it can be found.""" build_dir = local.path(builddir) in_dir = build_dir / "container-in" container_path = local.path(_container) with local.cwd(builddir): container_bin = container_path.basename ...
[ "def", "setup_container", "(", "builddir", ",", "_container", ")", ":", "build_dir", "=", "local", ".", "path", "(", "builddir", ")", "in_dir", "=", "build_dir", "/", "\"container-in\"", "container_path", "=", "local", ".", "path", "(", "_container", ")", "w...
Prepare the container and returns the path where it can be found.
[ "Prepare", "the", "container", "and", "returns", "the", "path", "where", "it", "can", "be", "found", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L48-L81
PolyJIT/benchbuild
benchbuild/container.py
run_in_container
def run_in_container(command, container_dir): """ Run a given command inside a container. Mounts a directory as a container at the given mountpoint and tries to run the given command inside the new container. """ container_p = local.path(container_dir) with local.cwd(container_p): u...
python
def run_in_container(command, container_dir): """ Run a given command inside a container. Mounts a directory as a container at the given mountpoint and tries to run the given command inside the new container. """ container_p = local.path(container_dir) with local.cwd(container_p): u...
[ "def", "run_in_container", "(", "command", ",", "container_dir", ")", ":", "container_p", "=", "local", ".", "path", "(", "container_dir", ")", "with", "local", ".", "cwd", "(", "container_p", ")", ":", "uchrt", "=", "uchroot", ".", "with_mounts", "(", ")"...
Run a given command inside a container. Mounts a directory as a container at the given mountpoint and tries to run the given command inside the new container.
[ "Run", "a", "given", "command", "inside", "a", "container", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L84-L105
PolyJIT/benchbuild
benchbuild/container.py
pack_container
def pack_container(in_container, out_file): """ Pack a container image into a .tar.bz2 archive. Args: in_container (str): Path string to the container image. out_file (str): Output file name. """ container_filename = local.path(out_file).basename out_container = local.cwd / "con...
python
def pack_container(in_container, out_file): """ Pack a container image into a .tar.bz2 archive. Args: in_container (str): Path string to the container image. out_file (str): Output file name. """ container_filename = local.path(out_file).basename out_container = local.cwd / "con...
[ "def", "pack_container", "(", "in_container", ",", "out_file", ")", ":", "container_filename", "=", "local", ".", "path", "(", "out_file", ")", ".", "basename", "out_container", "=", "local", ".", "cwd", "/", "\"container-out\"", "/", "container_filename", "out_...
Pack a container image into a .tar.bz2 archive. Args: in_container (str): Path string to the container image. out_file (str): Output file name.
[ "Pack", "a", "container", "image", "into", "a", ".", "tar", ".", "bz2", "archive", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L108-L130
PolyJIT/benchbuild
benchbuild/container.py
setup_bash_in_container
def setup_bash_in_container(builddir, _container, outfile, shell): """ Setup a bash environment inside a container. Creates a new chroot, which the user can use as a bash to run the wanted projects inside the mounted container, that also gets returned afterwards. """ with local.cwd(builddir): ...
python
def setup_bash_in_container(builddir, _container, outfile, shell): """ Setup a bash environment inside a container. Creates a new chroot, which the user can use as a bash to run the wanted projects inside the mounted container, that also gets returned afterwards. """ with local.cwd(builddir): ...
[ "def", "setup_bash_in_container", "(", "builddir", ",", "_container", ",", "outfile", ",", "shell", ")", ":", "with", "local", ".", "cwd", "(", "builddir", ")", ":", "# Switch to bash inside uchroot", "print", "(", "\"Entering bash inside User-Chroot. Prepare your image...
Setup a bash environment inside a container. Creates a new chroot, which the user can use as a bash to run the wanted projects inside the mounted container, that also gets returned afterwards.
[ "Setup", "a", "bash", "environment", "inside", "a", "container", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L133-L156
PolyJIT/benchbuild
benchbuild/container.py
set_input_container
def set_input_container(_container, cfg): """Save the input for the container in the configurations.""" if not _container: return False if _container.exists(): cfg["container"]["input"] = str(_container) return True return False
python
def set_input_container(_container, cfg): """Save the input for the container in the configurations.""" if not _container: return False if _container.exists(): cfg["container"]["input"] = str(_container) return True return False
[ "def", "set_input_container", "(", "_container", ",", "cfg", ")", ":", "if", "not", "_container", ":", "return", "False", "if", "_container", ".", "exists", "(", ")", ":", "cfg", "[", "\"container\"", "]", "[", "\"input\"", "]", "=", "str", "(", "_contai...
Save the input for the container in the configurations.
[ "Save", "the", "input", "for", "the", "container", "in", "the", "configurations", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L167-L174
PolyJIT/benchbuild
benchbuild/container.py
SetupPolyJITGentooStrategy.run
def run(self, context): """Setup a gentoo container suitable for PolyJIT.""" # Don't do something when running non-interactive. if not sys.stdout.isatty(): return with local.cwd(context.in_container): from benchbuild.projects.gentoo import gentoo gent...
python
def run(self, context): """Setup a gentoo container suitable for PolyJIT.""" # Don't do something when running non-interactive. if not sys.stdout.isatty(): return with local.cwd(context.in_container): from benchbuild.projects.gentoo import gentoo gent...
[ "def", "run", "(", "self", ",", "context", ")", ":", "# Don't do something when running non-interactive.", "if", "not", "sys", ".", "stdout", ".", "isatty", "(", ")", ":", "return", "with", "local", ".", "cwd", "(", "context", ".", "in_container", ")", ":", ...
Setup a gentoo container suitable for PolyJIT.
[ "Setup", "a", "gentoo", "container", "suitable", "for", "PolyJIT", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L213-L256
PolyJIT/benchbuild
benchbuild/container.py
Container.input_file
def input_file(self, _container): """Find the input path of a uchroot container.""" p = local.path(_container) if set_input_container(p, CFG): return p = find_hash(CFG["container"]["known"].value, container) if set_input_container(p, CFG): return ...
python
def input_file(self, _container): """Find the input path of a uchroot container.""" p = local.path(_container) if set_input_container(p, CFG): return p = find_hash(CFG["container"]["known"].value, container) if set_input_container(p, CFG): return ...
[ "def", "input_file", "(", "self", ",", "_container", ")", ":", "p", "=", "local", ".", "path", "(", "_container", ")", "if", "set_input_container", "(", "p", ",", "CFG", ")", ":", "return", "p", "=", "find_hash", "(", "CFG", "[", "\"container\"", "]", ...
Find the input path of a uchroot container.
[ "Find", "the", "input", "path", "of", "a", "uchroot", "container", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L265-L275
PolyJIT/benchbuild
benchbuild/container.py
Container.output_file
def output_file(self, _container): """Find and writes the output path of a chroot container.""" p = local.path(_container) if p.exists(): if not ui.ask("Path '{0}' already exists." " Overwrite?".format(p)): sys.exit(0) CFG["container"...
python
def output_file(self, _container): """Find and writes the output path of a chroot container.""" p = local.path(_container) if p.exists(): if not ui.ask("Path '{0}' already exists." " Overwrite?".format(p)): sys.exit(0) CFG["container"...
[ "def", "output_file", "(", "self", ",", "_container", ")", ":", "p", "=", "local", ".", "path", "(", "_container", ")", "if", "p", ".", "exists", "(", ")", ":", "if", "not", "ui", ".", "ask", "(", "\"Path '{0}' already exists.\"", "\" Overwrite?\"", ".",...
Find and writes the output path of a chroot container.
[ "Find", "and", "writes", "the", "output", "path", "of", "a", "chroot", "container", "." ]
train
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/container.py#L278-L285
eng-tools/sfsimodels
sfsimodels/models/soils.py
discretize_soil_profile
def discretize_soil_profile(sp, incs=None, target=1.0): """ Splits the soil profile into slices and stores as dictionary :param sp: SoilProfile :param incs: array_like, increments of depth to use for each layer :param target: target depth increment size :return: dict """ if incs is Non...
python
def discretize_soil_profile(sp, incs=None, target=1.0): """ Splits the soil profile into slices and stores as dictionary :param sp: SoilProfile :param incs: array_like, increments of depth to use for each layer :param target: target depth increment size :return: dict """ if incs is Non...
[ "def", "discretize_soil_profile", "(", "sp", ",", "incs", "=", "None", ",", "target", "=", "1.0", ")", ":", "if", "incs", "is", "None", ":", "incs", "=", "np", ".", "ones", "(", "sp", ".", "n_layers", ")", "*", "target", "dd", "=", "{", "}", "dd"...
Splits the soil profile into slices and stores as dictionary :param sp: SoilProfile :param incs: array_like, increments of depth to use for each layer :param target: target depth increment size :return: dict
[ "Splits", "the", "soil", "profile", "into", "slices", "and", "stores", "as", "dictionary" ]
train
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1272-L1312