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
ajslater/picopt
picopt/walk.py
_is_skippable
def _is_skippable(filename_full): """Handle things that are not optimizable files.""" # File types if not Settings.follow_symlinks and os.path.islink(filename_full): return True if os.path.basename(filename_full) == timestamp.RECORD_FILENAME: return True if not os.path.exists(filena...
python
def _is_skippable(filename_full): """Handle things that are not optimizable files.""" # File types if not Settings.follow_symlinks and os.path.islink(filename_full): return True if os.path.basename(filename_full) == timestamp.RECORD_FILENAME: return True if not os.path.exists(filena...
[ "def", "_is_skippable", "(", "filename_full", ")", ":", "# File types", "if", "not", "Settings", ".", "follow_symlinks", "and", "os", ".", "path", ".", "islink", "(", "filename_full", ")", ":", "return", "True", "if", "os", ".", "path", ".", "basename", "(...
Handle things that are not optimizable files.
[ "Handle", "things", "that", "are", "not", "optimizable", "files", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/walk.py#L48-L61
ajslater/picopt
picopt/walk.py
walk_file
def walk_file(filename, walk_after, recurse=None, archive_mtime=None): """Optimize an individual file.""" filename = os.path.normpath(filename) result_set = set() if _is_skippable(filename): return result_set walk_after = timestamp.get_walk_after(filename, walk_after) # File is a dir...
python
def walk_file(filename, walk_after, recurse=None, archive_mtime=None): """Optimize an individual file.""" filename = os.path.normpath(filename) result_set = set() if _is_skippable(filename): return result_set walk_after = timestamp.get_walk_after(filename, walk_after) # File is a dir...
[ "def", "walk_file", "(", "filename", ",", "walk_after", ",", "recurse", "=", "None", ",", "archive_mtime", "=", "None", ")", ":", "filename", "=", "os", ".", "path", ".", "normpath", "(", "filename", ")", "result_set", "=", "set", "(", ")", "if", "_is_...
Optimize an individual file.
[ "Optimize", "an", "individual", "file", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/walk.py#L78-L124
ajslater/picopt
picopt/walk.py
walk_dir
def walk_dir(dir_path, walk_after, recurse=None, archive_mtime=None): """Recursively optimize a directory.""" if recurse is None: recurse = Settings.recurse result_set = set() if not recurse: return result_set for root, _, filenames in os.walk(dir_path): for filename in fil...
python
def walk_dir(dir_path, walk_after, recurse=None, archive_mtime=None): """Recursively optimize a directory.""" if recurse is None: recurse = Settings.recurse result_set = set() if not recurse: return result_set for root, _, filenames in os.walk(dir_path): for filename in fil...
[ "def", "walk_dir", "(", "dir_path", ",", "walk_after", ",", "recurse", "=", "None", ",", "archive_mtime", "=", "None", ")", ":", "if", "recurse", "is", "None", ":", "recurse", "=", "Settings", ".", "recurse", "result_set", "=", "set", "(", ")", "if", "...
Recursively optimize a directory.
[ "Recursively", "optimize", "a", "directory", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/walk.py#L127-L147
ajslater/picopt
picopt/walk.py
_walk_all_files
def _walk_all_files(): """ Optimize the files from the arugments list in two batches. One for absolute paths which are probably outside the current working directory tree and one for relative files. """ # Init records record_dirs = set() result_set = set() for filename in Settings....
python
def _walk_all_files(): """ Optimize the files from the arugments list in two batches. One for absolute paths which are probably outside the current working directory tree and one for relative files. """ # Init records record_dirs = set() result_set = set() for filename in Settings....
[ "def", "_walk_all_files", "(", ")", ":", "# Init records", "record_dirs", "=", "set", "(", ")", "result_set", "=", "set", "(", ")", "for", "filename", "in", "Settings", ".", "paths", ":", "# Record dirs to put timestamps in later", "filename_full", "=", "os", "....
Optimize the files from the arugments list in two batches. One for absolute paths which are probably outside the current working directory tree and one for relative files.
[ "Optimize", "the", "files", "from", "the", "arugments", "list", "in", "two", "batches", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/walk.py#L150-L184
ajslater/picopt
picopt/walk.py
run
def run(): """Use preconfigured settings to optimize files.""" # Setup Multiprocessing # manager = multiprocessing.Manager() Settings.pool = multiprocessing.Pool(Settings.jobs) # Optimize Files record_dirs, bytes_in, bytes_out, nag_about_gifs, errors = \ _walk_all_files() # Shut do...
python
def run(): """Use preconfigured settings to optimize files.""" # Setup Multiprocessing # manager = multiprocessing.Manager() Settings.pool = multiprocessing.Pool(Settings.jobs) # Optimize Files record_dirs, bytes_in, bytes_out, nag_about_gifs, errors = \ _walk_all_files() # Shut do...
[ "def", "run", "(", ")", ":", "# Setup Multiprocessing", "# manager = multiprocessing.Manager()", "Settings", ".", "pool", "=", "multiprocessing", ".", "Pool", "(", "Settings", ".", "jobs", ")", "# Optimize Files", "record_dirs", ",", "bytes_in", ",", "bytes_out", ",...
Use preconfigured settings to optimize files.
[ "Use", "preconfigured", "settings", "to", "optimize", "files", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/walk.py#L187-L206
ajslater/picopt
picopt/files.py
replace_ext
def replace_ext(filename, new_ext): """Replace the file extention.""" filename_base = os.path.splitext(filename)[0] new_filename = '{}.{}'.format(filename_base, new_ext) return new_filename
python
def replace_ext(filename, new_ext): """Replace the file extention.""" filename_base = os.path.splitext(filename)[0] new_filename = '{}.{}'.format(filename_base, new_ext) return new_filename
[ "def", "replace_ext", "(", "filename", ",", "new_ext", ")", ":", "filename_base", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", "new_filename", "=", "'{}.{}'", ".", "format", "(", "filename_base", ",", "new_ext", ")", "ret...
Replace the file extention.
[ "Replace", "the", "file", "extention", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/files.py#L12-L16
ajslater/picopt
picopt/files.py
_cleanup_after_optimize_aux
def _cleanup_after_optimize_aux(filename, new_filename, old_format, new_format): """ Replace old file with better one or discard new wasteful file. """ bytes_in = 0 bytes_out = 0 final_filename = filename try: bytes_in = os.stat(filename).st_size ...
python
def _cleanup_after_optimize_aux(filename, new_filename, old_format, new_format): """ Replace old file with better one or discard new wasteful file. """ bytes_in = 0 bytes_out = 0 final_filename = filename try: bytes_in = os.stat(filename).st_size ...
[ "def", "_cleanup_after_optimize_aux", "(", "filename", ",", "new_filename", ",", "old_format", ",", "new_format", ")", ":", "bytes_in", "=", "0", "bytes_out", "=", "0", "final_filename", "=", "filename", "try", ":", "bytes_in", "=", "os", ".", "stat", "(", "...
Replace old file with better one or discard new wasteful file.
[ "Replace", "old", "file", "with", "better", "one", "or", "discard", "new", "wasteful", "file", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/files.py#L19-L48
ajslater/picopt
picopt/files.py
cleanup_after_optimize
def cleanup_after_optimize(filename, new_filename, old_format, new_format): """ Replace old file with better one or discard new wasteful file. And report results using the stats module. """ final_filename, bytes_in, bytes_out = _cleanup_after_optimize_aux( filename, new_filename, old_format...
python
def cleanup_after_optimize(filename, new_filename, old_format, new_format): """ Replace old file with better one or discard new wasteful file. And report results using the stats module. """ final_filename, bytes_in, bytes_out = _cleanup_after_optimize_aux( filename, new_filename, old_format...
[ "def", "cleanup_after_optimize", "(", "filename", ",", "new_filename", ",", "old_format", ",", "new_format", ")", ":", "final_filename", ",", "bytes_in", ",", "bytes_out", "=", "_cleanup_after_optimize_aux", "(", "filename", ",", "new_filename", ",", "old_format", "...
Replace old file with better one or discard new wasteful file. And report results using the stats module.
[ "Replace", "old", "file", "with", "better", "one", "or", "discard", "new", "wasteful", "file", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/files.py#L51-L59
ajslater/picopt
setup.py
parse_reqs
def parse_reqs(filename): """Parse setup requirements from a requirements.txt file.""" install_reqs = parse_requirements(filename, session=False) return [str(ir.req) for ir in install_reqs]
python
def parse_reqs(filename): """Parse setup requirements from a requirements.txt file.""" install_reqs = parse_requirements(filename, session=False) return [str(ir.req) for ir in install_reqs]
[ "def", "parse_reqs", "(", "filename", ")", ":", "install_reqs", "=", "parse_requirements", "(", "filename", ",", "session", "=", "False", ")", "return", "[", "str", "(", "ir", ".", "req", ")", "for", "ir", "in", "install_reqs", "]" ]
Parse setup requirements from a requirements.txt file.
[ "Parse", "setup", "requirements", "from", "a", "requirements", ".", "txt", "file", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/setup.py#L43-L46
ajslater/picopt
setup.py
get_req_list
def get_req_list(): """Get the requirements by weather we're building develop or not.""" req_list = parse_reqs(REQUIREMENTS['prod']) if len(sys.argv) > 2 and sys.argv[2] == ('develop'): req_list += parse_reqs(REQUIREMENTS['dev']) return req_list
python
def get_req_list(): """Get the requirements by weather we're building develop or not.""" req_list = parse_reqs(REQUIREMENTS['prod']) if len(sys.argv) > 2 and sys.argv[2] == ('develop'): req_list += parse_reqs(REQUIREMENTS['dev']) return req_list
[ "def", "get_req_list", "(", ")", ":", "req_list", "=", "parse_reqs", "(", "REQUIREMENTS", "[", "'prod'", "]", ")", "if", "len", "(", "sys", ".", "argv", ")", ">", "2", "and", "sys", ".", "argv", "[", "2", "]", "==", "(", "'develop'", ")", ":", "r...
Get the requirements by weather we're building develop or not.
[ "Get", "the", "requirements", "by", "weather", "we", "re", "building", "develop", "or", "not", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/setup.py#L49-L54
ajslater/picopt
picopt/formats/comic.py
get_comic_format
def get_comic_format(filename): """Return the comic format if it is a comic archive.""" image_format = None filename_ext = os.path.splitext(filename)[-1].lower() if filename_ext in _COMIC_EXTS: if zipfile.is_zipfile(filename): image_format = _CBZ_FORMAT elif rarfile.is_rarfil...
python
def get_comic_format(filename): """Return the comic format if it is a comic archive.""" image_format = None filename_ext = os.path.splitext(filename)[-1].lower() if filename_ext in _COMIC_EXTS: if zipfile.is_zipfile(filename): image_format = _CBZ_FORMAT elif rarfile.is_rarfil...
[ "def", "get_comic_format", "(", "filename", ")", ":", "image_format", "=", "None", "filename_ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "-", "1", "]", ".", "lower", "(", ")", "if", "filename_ext", "in", "_COMIC_EXTS", ":", ...
Return the comic format if it is a comic archive.
[ "Return", "the", "comic", "format", "if", "it", "is", "a", "comic", "archive", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/comic.py#L43-L52
ajslater/picopt
picopt/formats/comic.py
_get_archive_tmp_dir
def _get_archive_tmp_dir(filename): """Get the name of the working dir to use for this filename.""" head, tail = os.path.split(filename) return os.path.join(head, _ARCHIVE_TMP_DIR_TEMPLATE.format(tail))
python
def _get_archive_tmp_dir(filename): """Get the name of the working dir to use for this filename.""" head, tail = os.path.split(filename) return os.path.join(head, _ARCHIVE_TMP_DIR_TEMPLATE.format(tail))
[ "def", "_get_archive_tmp_dir", "(", "filename", ")", ":", "head", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "return", "os", ".", "path", ".", "join", "(", "head", ",", "_ARCHIVE_TMP_DIR_TEMPLATE", ".", "format", "(", "tail"...
Get the name of the working dir to use for this filename.
[ "Get", "the", "name", "of", "the", "working", "dir", "to", "use", "for", "this", "filename", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/comic.py#L55-L58
ajslater/picopt
picopt/formats/comic.py
comic_archive_uncompress
def comic_archive_uncompress(filename, image_format): """ Uncompress comic archives. Return the name of the working directory we uncompressed into. """ if not Settings.comics: report = ['Skipping archive file: {}'.format(filename)] return None, ReportStats(filename, report=report) ...
python
def comic_archive_uncompress(filename, image_format): """ Uncompress comic archives. Return the name of the working directory we uncompressed into. """ if not Settings.comics: report = ['Skipping archive file: {}'.format(filename)] return None, ReportStats(filename, report=report) ...
[ "def", "comic_archive_uncompress", "(", "filename", ",", "image_format", ")", ":", "if", "not", "Settings", ".", "comics", ":", "report", "=", "[", "'Skipping archive file: {}'", ".", "format", "(", "filename", ")", "]", "return", "None", ",", "ReportStats", "...
Uncompress comic archives. Return the name of the working directory we uncompressed into.
[ "Uncompress", "comic", "archives", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/comic.py#L61-L95
ajslater/picopt
picopt/formats/comic.py
_comic_archive_write_zipfile
def _comic_archive_write_zipfile(new_filename, tmp_dir): """Zip up the files in the tempdir into the new filename.""" if Settings.verbose: print('Rezipping archive', end='') with zipfile.ZipFile(new_filename, 'w', compression=zipfile.ZIP_DEFLATED) as new_zf: root_len...
python
def _comic_archive_write_zipfile(new_filename, tmp_dir): """Zip up the files in the tempdir into the new filename.""" if Settings.verbose: print('Rezipping archive', end='') with zipfile.ZipFile(new_filename, 'w', compression=zipfile.ZIP_DEFLATED) as new_zf: root_len...
[ "def", "_comic_archive_write_zipfile", "(", "new_filename", ",", "tmp_dir", ")", ":", "if", "Settings", ".", "verbose", ":", "print", "(", "'Rezipping archive'", ",", "end", "=", "''", ")", "with", "zipfile", ".", "ZipFile", "(", "new_filename", ",", "'w'", ...
Zip up the files in the tempdir into the new filename.
[ "Zip", "up", "the", "files", "in", "the", "tempdir", "into", "the", "new", "filename", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/comic.py#L98-L114
ajslater/picopt
picopt/formats/comic.py
comic_archive_compress
def comic_archive_compress(args): """ Called back by every optimization inside a comic archive. When they're all done it creates the new archive and cleans up. """ try: filename, old_format, settings, nag_about_gifs = args Settings.update(settings) tmp_dir = _get_archive_tmp...
python
def comic_archive_compress(args): """ Called back by every optimization inside a comic archive. When they're all done it creates the new archive and cleans up. """ try: filename, old_format, settings, nag_about_gifs = args Settings.update(settings) tmp_dir = _get_archive_tmp...
[ "def", "comic_archive_compress", "(", "args", ")", ":", "try", ":", "filename", ",", "old_format", ",", "settings", ",", "nag_about_gifs", "=", "args", "Settings", ".", "update", "(", "settings", ")", "tmp_dir", "=", "_get_archive_tmp_dir", "(", "filename", ")...
Called back by every optimization inside a comic archive. When they're all done it creates the new archive and cleans up.
[ "Called", "back", "by", "every", "optimization", "inside", "a", "comic", "archive", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/comic.py#L117-L149
ajslater/picopt
picopt/formats/jpeg.py
mozjpeg
def mozjpeg(ext_args): """Create argument list for mozjpeg.""" args = copy.copy(_MOZJPEG_ARGS) if Settings.destroy_metadata: args += ["-copy", "none"] else: args += ["-copy", "all"] args += ['-outfile'] args += [ext_args.new_filename, ext_args.old_filename] extern.run_ext(arg...
python
def mozjpeg(ext_args): """Create argument list for mozjpeg.""" args = copy.copy(_MOZJPEG_ARGS) if Settings.destroy_metadata: args += ["-copy", "none"] else: args += ["-copy", "all"] args += ['-outfile'] args += [ext_args.new_filename, ext_args.old_filename] extern.run_ext(arg...
[ "def", "mozjpeg", "(", "ext_args", ")", ":", "args", "=", "copy", ".", "copy", "(", "_MOZJPEG_ARGS", ")", "if", "Settings", ".", "destroy_metadata", ":", "args", "+=", "[", "\"-copy\"", ",", "\"none\"", "]", "else", ":", "args", "+=", "[", "\"-copy\"", ...
Create argument list for mozjpeg.
[ "Create", "argument", "list", "for", "mozjpeg", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/jpeg.py#L18-L28
ajslater/picopt
picopt/formats/jpeg.py
jpegtran
def jpegtran(ext_args): """Create argument list for jpegtran.""" args = copy.copy(_JPEGTRAN_ARGS) if Settings.destroy_metadata: args += ["-copy", "none"] else: args += ["-copy", "all"] if Settings.jpegtran_prog: args += ["-progressive"] args += ['-outfile'] args += [e...
python
def jpegtran(ext_args): """Create argument list for jpegtran.""" args = copy.copy(_JPEGTRAN_ARGS) if Settings.destroy_metadata: args += ["-copy", "none"] else: args += ["-copy", "all"] if Settings.jpegtran_prog: args += ["-progressive"] args += ['-outfile'] args += [e...
[ "def", "jpegtran", "(", "ext_args", ")", ":", "args", "=", "copy", ".", "copy", "(", "_JPEGTRAN_ARGS", ")", "if", "Settings", ".", "destroy_metadata", ":", "args", "+=", "[", "\"-copy\"", ",", "\"none\"", "]", "else", ":", "args", "+=", "[", "\"-copy\"",...
Create argument list for jpegtran.
[ "Create", "argument", "list", "for", "jpegtran", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/jpeg.py#L31-L43
ajslater/picopt
picopt/formats/jpeg.py
jpegrescan
def jpegrescan(ext_args): """Run the EXTERNAL program jpegrescan.""" args = copy.copy(_JPEGRESCAN_ARGS) if Settings.jpegrescan_multithread: args += ['-t'] if Settings.destroy_metadata: args += ['-s'] args += [ext_args.old_filename, ext_args.new_filename] extern.run_ext(args) ...
python
def jpegrescan(ext_args): """Run the EXTERNAL program jpegrescan.""" args = copy.copy(_JPEGRESCAN_ARGS) if Settings.jpegrescan_multithread: args += ['-t'] if Settings.destroy_metadata: args += ['-s'] args += [ext_args.old_filename, ext_args.new_filename] extern.run_ext(args) ...
[ "def", "jpegrescan", "(", "ext_args", ")", ":", "args", "=", "copy", ".", "copy", "(", "_JPEGRESCAN_ARGS", ")", "if", "Settings", ".", "jpegrescan_multithread", ":", "args", "+=", "[", "'-t'", "]", "if", "Settings", ".", "destroy_metadata", ":", "args", "+...
Run the EXTERNAL program jpegrescan.
[ "Run", "the", "EXTERNAL", "program", "jpegrescan", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/jpeg.py#L46-L55
ajslater/picopt
picopt/cli.py
get_arguments
def get_arguments(args): """Parse the command line.""" usage = "%(prog)s [arguments] [image files]" programs_str = ', '.join([prog.__name__ for prog in PROGRAMS]) description = "Uses "+programs_str+" if they are on the path." parser = argparse.ArgumentParser(usage=usage, description=description) ...
python
def get_arguments(args): """Parse the command line.""" usage = "%(prog)s [arguments] [image files]" programs_str = ', '.join([prog.__name__ for prog in PROGRAMS]) description = "Uses "+programs_str+" if they are on the path." parser = argparse.ArgumentParser(usage=usage, description=description) ...
[ "def", "get_arguments", "(", "args", ")", ":", "usage", "=", "\"%(prog)s [arguments] [image files]\"", "programs_str", "=", "', '", ".", "join", "(", "[", "prog", ".", "__name__", "for", "prog", "in", "PROGRAMS", "]", ")", "description", "=", "\"Uses \"", "+",...
Parse the command line.
[ "Parse", "the", "command", "line", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/cli.py#L28-L123
ajslater/picopt
picopt/cli.py
process_arguments
def process_arguments(arguments): """Recompute special cases for input arguments.""" Settings.update(arguments) Settings.config_program_reqs(PROGRAMS) Settings.verbose = arguments.verbose + 1 Settings.paths = set(arguments.paths) if arguments.formats == DEFAULT_FORMATS: Settings.forma...
python
def process_arguments(arguments): """Recompute special cases for input arguments.""" Settings.update(arguments) Settings.config_program_reqs(PROGRAMS) Settings.verbose = arguments.verbose + 1 Settings.paths = set(arguments.paths) if arguments.formats == DEFAULT_FORMATS: Settings.forma...
[ "def", "process_arguments", "(", "arguments", ")", ":", "Settings", ".", "update", "(", "arguments", ")", "Settings", ".", "config_program_reqs", "(", "PROGRAMS", ")", "Settings", ".", "verbose", "=", "arguments", ".", "verbose", "+", "1", "Settings", ".", "...
Recompute special cases for input arguments.
[ "Recompute", "special", "cases", "for", "input", "arguments", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/cli.py#L126-L170
ajslater/picopt
picopt/cli.py
run
def run(args): """Process command line arguments and walk inputs.""" raw_arguments = get_arguments(args[1:]) process_arguments(raw_arguments) walk.run() return True
python
def run(args): """Process command line arguments and walk inputs.""" raw_arguments = get_arguments(args[1:]) process_arguments(raw_arguments) walk.run() return True
[ "def", "run", "(", "args", ")", ":", "raw_arguments", "=", "get_arguments", "(", "args", "[", "1", ":", "]", ")", "process_arguments", "(", "raw_arguments", ")", "walk", ".", "run", "(", ")", "return", "True" ]
Process command line arguments and walk inputs.
[ "Process", "command", "line", "arguments", "and", "walk", "inputs", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/cli.py#L173-L178
ajslater/picopt
picopt/extern.py
does_external_program_run
def does_external_program_run(prog, verbose): """Test to see if the external programs can be run.""" try: with open('/dev/null') as null: subprocess.call([prog, '-h'], stdout=null, stderr=null) result = True except OSError: if verbose > 1: print("couldn't run ...
python
def does_external_program_run(prog, verbose): """Test to see if the external programs can be run.""" try: with open('/dev/null') as null: subprocess.call([prog, '-h'], stdout=null, stderr=null) result = True except OSError: if verbose > 1: print("couldn't run ...
[ "def", "does_external_program_run", "(", "prog", ",", "verbose", ")", ":", "try", ":", "with", "open", "(", "'/dev/null'", ")", "as", "null", ":", "subprocess", ".", "call", "(", "[", "prog", ",", "'-h'", "]", ",", "stdout", "=", "null", ",", "stderr",...
Test to see if the external programs can be run.
[ "Test", "to", "see", "if", "the", "external", "programs", "can", "be", "run", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/extern.py#L16-L27
ajslater/picopt
picopt/extern.py
run_ext
def run_ext(args): """Run EXTERNAL program.""" try: subprocess.check_call(args) except subprocess.CalledProcessError as exc: print(exc) print(exc.cmd) print(exc.returncode) print(exc.output) raise
python
def run_ext(args): """Run EXTERNAL program.""" try: subprocess.check_call(args) except subprocess.CalledProcessError as exc: print(exc) print(exc.cmd) print(exc.returncode) print(exc.output) raise
[ "def", "run_ext", "(", "args", ")", ":", "try", ":", "subprocess", ".", "check_call", "(", "args", ")", "except", "subprocess", ".", "CalledProcessError", "as", "exc", ":", "print", "(", "exc", ")", "print", "(", "exc", ".", "cmd", ")", "print", "(", ...
Run EXTERNAL program.
[ "Run", "EXTERNAL", "program", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/extern.py#L30-L39
ajslater/picopt
picopt/stats.py
_humanize_bytes
def _humanize_bytes(num_bytes, precision=1): """ Return a humanized string representation of a number of num_bytes. from: http://code.activestate.com/recipes/ 577081-humanized-representation-of-a-number-of-num_bytes/ Assumes `from __future__ import division`. >>> humanize_bytes(1) ...
python
def _humanize_bytes(num_bytes, precision=1): """ Return a humanized string representation of a number of num_bytes. from: http://code.activestate.com/recipes/ 577081-humanized-representation-of-a-number-of-num_bytes/ Assumes `from __future__ import division`. >>> humanize_bytes(1) ...
[ "def", "_humanize_bytes", "(", "num_bytes", ",", "precision", "=", "1", ")", ":", "if", "num_bytes", "==", "0", ":", "return", "'no bytes'", "if", "num_bytes", "==", "1", ":", "return", "'1 byte'", "factored_bytes", "=", "0", "factor_suffix", "=", "'bytes'",...
Return a humanized string representation of a number of num_bytes. from: http://code.activestate.com/recipes/ 577081-humanized-representation-of-a-number-of-num_bytes/ Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 byte' >>> humanize_bytes(1024) '1.0 kB' ...
[ "Return", "a", "humanized", "string", "representation", "of", "a", "number", "of", "num_bytes", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/stats.py#L46-L90
ajslater/picopt
picopt/stats.py
new_percent_saved
def new_percent_saved(report_stats): """Spit out how much space the optimization saved.""" size_in = report_stats.bytes_in if size_in > 0: size_out = report_stats.bytes_out ratio = size_out / size_in kb_saved = _humanize_bytes(size_in - size_out) else: ratio = 0 k...
python
def new_percent_saved(report_stats): """Spit out how much space the optimization saved.""" size_in = report_stats.bytes_in if size_in > 0: size_out = report_stats.bytes_out ratio = size_out / size_in kb_saved = _humanize_bytes(size_in - size_out) else: ratio = 0 k...
[ "def", "new_percent_saved", "(", "report_stats", ")", ":", "size_in", "=", "report_stats", ".", "bytes_in", "if", "size_in", ">", "0", ":", "size_out", "=", "report_stats", ".", "bytes_out", "ratio", "=", "size_out", "/", "size_in", "kb_saved", "=", "_humanize...
Spit out how much space the optimization saved.
[ "Spit", "out", "how", "much", "space", "the", "optimization", "saved", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/stats.py#L93-L106
ajslater/picopt
picopt/stats.py
truncate_cwd
def truncate_cwd(full_filename): """Remove the cwd from the full filename.""" if full_filename.startswith(os.getcwd()): truncated_filename = full_filename.split(os.getcwd(), 1)[1] truncated_filename = truncated_filename.split(os.sep, 1)[1] else: truncated_filename = full_filename ...
python
def truncate_cwd(full_filename): """Remove the cwd from the full filename.""" if full_filename.startswith(os.getcwd()): truncated_filename = full_filename.split(os.getcwd(), 1)[1] truncated_filename = truncated_filename.split(os.sep, 1)[1] else: truncated_filename = full_filename ...
[ "def", "truncate_cwd", "(", "full_filename", ")", ":", "if", "full_filename", ".", "startswith", "(", "os", ".", "getcwd", "(", ")", ")", ":", "truncated_filename", "=", "full_filename", ".", "split", "(", "os", ".", "getcwd", "(", ")", ",", "1", ")", ...
Remove the cwd from the full filename.
[ "Remove", "the", "cwd", "from", "the", "full", "filename", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/stats.py#L109-L116
ajslater/picopt
picopt/stats.py
report_saved
def report_saved(report_stats): """Record the percent saved & print it.""" if Settings.verbose: report = '' truncated_filename = truncate_cwd(report_stats.final_filename) report += '{}: '.format(truncated_filename) total = new_percent_saved(report_stats) if total: ...
python
def report_saved(report_stats): """Record the percent saved & print it.""" if Settings.verbose: report = '' truncated_filename = truncate_cwd(report_stats.final_filename) report += '{}: '.format(truncated_filename) total = new_percent_saved(report_stats) if total: ...
[ "def", "report_saved", "(", "report_stats", ")", ":", "if", "Settings", ".", "verbose", ":", "report", "=", "''", "truncated_filename", "=", "truncate_cwd", "(", "report_stats", ".", "final_filename", ")", "report", "+=", "'{}: '", ".", "format", "(", "truncat...
Record the percent saved & print it.
[ "Record", "the", "percent", "saved", "&", "print", "it", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/stats.py#L119-L137
ajslater/picopt
picopt/stats.py
report_totals
def report_totals(bytes_in, bytes_out, nag_about_gifs, errors): """Report the total number and percent of bytes saved.""" if bytes_in: bytes_saved = bytes_in - bytes_out percent_bytes_saved = bytes_saved / bytes_in * 100 msg = '' if Settings.test: if percent_bytes_sav...
python
def report_totals(bytes_in, bytes_out, nag_about_gifs, errors): """Report the total number and percent of bytes saved.""" if bytes_in: bytes_saved = bytes_in - bytes_out percent_bytes_saved = bytes_saved / bytes_in * 100 msg = '' if Settings.test: if percent_bytes_sav...
[ "def", "report_totals", "(", "bytes_in", ",", "bytes_out", ",", "nag_about_gifs", ",", "errors", ")", ":", "if", "bytes_in", ":", "bytes_saved", "=", "bytes_in", "-", "bytes_out", "percent_bytes_saved", "=", "bytes_saved", "/", "bytes_in", "*", "100", "msg", "...
Report the total number and percent of bytes saved.
[ "Report", "the", "total", "number", "and", "percent", "of", "bytes", "saved", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/stats.py#L140-L180
ajslater/picopt
picopt/stats.py
skip
def skip(type_name, filename): """Provide reporting statistics for a skipped file.""" report = ['Skipping {} file: {}'.format(type_name, filename)] report_stats = ReportStats(filename, report=report) return report_stats
python
def skip(type_name, filename): """Provide reporting statistics for a skipped file.""" report = ['Skipping {} file: {}'.format(type_name, filename)] report_stats = ReportStats(filename, report=report) return report_stats
[ "def", "skip", "(", "type_name", ",", "filename", ")", ":", "report", "=", "[", "'Skipping {} file: {}'", ".", "format", "(", "type_name", ",", "filename", ")", "]", "report_stats", "=", "ReportStats", "(", "filename", ",", "report", "=", "report", ")", "r...
Provide reporting statistics for a skipped file.
[ "Provide", "reporting", "statistics", "for", "a", "skipped", "file", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/stats.py#L183-L187
ajslater/picopt
picopt/formats/gif.py
gifsicle
def gifsicle(ext_args): """Run the EXTERNAL program gifsicle.""" args = _GIFSICLE_ARGS + [ext_args.new_filename] extern.run_ext(args) return _GIF_FORMAT
python
def gifsicle(ext_args): """Run the EXTERNAL program gifsicle.""" args = _GIFSICLE_ARGS + [ext_args.new_filename] extern.run_ext(args) return _GIF_FORMAT
[ "def", "gifsicle", "(", "ext_args", ")", ":", "args", "=", "_GIFSICLE_ARGS", "+", "[", "ext_args", ".", "new_filename", "]", "extern", ".", "run_ext", "(", "args", ")", "return", "_GIF_FORMAT" ]
Run the EXTERNAL program gifsicle.
[ "Run", "the", "EXTERNAL", "program", "gifsicle", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/gif.py#L14-L18
ajslater/picopt
picopt/optimize.py
_optimize_image_external
def _optimize_image_external(filename, func, image_format, new_ext): """Optimize the file with the external function.""" new_filename = filename + TMP_SUFFIX + new_ext new_filename = os.path.normpath(new_filename) shutil.copy2(filename, new_filename) ext_args = ExtArgs(filename, new_filename) n...
python
def _optimize_image_external(filename, func, image_format, new_ext): """Optimize the file with the external function.""" new_filename = filename + TMP_SUFFIX + new_ext new_filename = os.path.normpath(new_filename) shutil.copy2(filename, new_filename) ext_args = ExtArgs(filename, new_filename) n...
[ "def", "_optimize_image_external", "(", "filename", ",", "func", ",", "image_format", ",", "new_ext", ")", ":", "new_filename", "=", "filename", "+", "TMP_SUFFIX", "+", "new_ext", "new_filename", "=", "os", ".", "path", ".", "normpath", "(", "new_filename", ")...
Optimize the file with the external function.
[ "Optimize", "the", "file", "with", "the", "external", "function", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/optimize.py#L19-L38
ajslater/picopt
picopt/optimize.py
_optimize_with_progs
def _optimize_with_progs(format_module, filename, image_format): """ Use the correct optimizing functions in sequence. And report back statistics. """ filesize_in = os.stat(filename).st_size report_stats = None for func in format_module.PROGRAMS: if not getattr(Settings, func.__nam...
python
def _optimize_with_progs(format_module, filename, image_format): """ Use the correct optimizing functions in sequence. And report back statistics. """ filesize_in = os.stat(filename).st_size report_stats = None for func in format_module.PROGRAMS: if not getattr(Settings, func.__nam...
[ "def", "_optimize_with_progs", "(", "format_module", ",", "filename", ",", "image_format", ")", ":", "filesize_in", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_size", "report_stats", "=", "None", "for", "func", "in", "format_module", ".", "PROGRAMS"...
Use the correct optimizing functions in sequence. And report back statistics.
[ "Use", "the", "correct", "optimizing", "functions", "in", "sequence", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/optimize.py#L41-L64
ajslater/picopt
picopt/optimize.py
_get_format_module
def _get_format_module(image_format): """Get the format module to use for optimizing the image.""" format_module = None nag_about_gifs = False if detect_format.is_format_selected(image_format, Settings.to_png_formats, png.P...
python
def _get_format_module(image_format): """Get the format module to use for optimizing the image.""" format_module = None nag_about_gifs = False if detect_format.is_format_selected(image_format, Settings.to_png_formats, png.P...
[ "def", "_get_format_module", "(", "image_format", ")", ":", "format_module", "=", "None", "nag_about_gifs", "=", "False", "if", "detect_format", ".", "is_format_selected", "(", "image_format", ",", "Settings", ".", "to_png_formats", ",", "png", ".", "PROGRAMS", ")...
Get the format module to use for optimizing the image.
[ "Get", "the", "format", "module", "to", "use", "for", "optimizing", "the", "image", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/optimize.py#L67-L85
ajslater/picopt
picopt/optimize.py
optimize_image
def optimize_image(arg): """Optimize a given image from a filename.""" try: filename, image_format, settings = arg Settings.update(settings) format_module, nag_about_gifs = _get_format_module(image_format) if format_module is None: if Settings.verbose > 1: ...
python
def optimize_image(arg): """Optimize a given image from a filename.""" try: filename, image_format, settings = arg Settings.update(settings) format_module, nag_about_gifs = _get_format_module(image_format) if format_module is None: if Settings.verbose > 1: ...
[ "def", "optimize_image", "(", "arg", ")", ":", "try", ":", "filename", ",", "image_format", ",", "settings", "=", "arg", "Settings", ".", "update", "(", "settings", ")", "format_module", ",", "nag_about_gifs", "=", "_get_format_module", "(", "image_format", ")...
Optimize a given image from a filename.
[ "Optimize", "a", "given", "image", "from", "a", "filename", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/optimize.py#L88-L111
ajslater/picopt
picopt/detect_format.py
_is_program_selected
def _is_program_selected(progs): """Determine if the program is enabled in the settings.""" mode = False for prog in progs: if getattr(Settings, prog.__name__): mode = True break return mode
python
def _is_program_selected(progs): """Determine if the program is enabled in the settings.""" mode = False for prog in progs: if getattr(Settings, prog.__name__): mode = True break return mode
[ "def", "_is_program_selected", "(", "progs", ")", ":", "mode", "=", "False", "for", "prog", "in", "progs", ":", "if", "getattr", "(", "Settings", ",", "prog", ".", "__name__", ")", ":", "mode", "=", "True", "break", "return", "mode" ]
Determine if the program is enabled in the settings.
[ "Determine", "if", "the", "program", "is", "enabled", "in", "the", "settings", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/detect_format.py#L14-L21
ajslater/picopt
picopt/detect_format.py
is_format_selected
def is_format_selected(image_format, formats, progs): """Determine if the image format is selected by command line arguments.""" intersection = formats & Settings.formats mode = _is_program_selected(progs) result = (image_format in intersection) and mode return result
python
def is_format_selected(image_format, formats, progs): """Determine if the image format is selected by command line arguments.""" intersection = formats & Settings.formats mode = _is_program_selected(progs) result = (image_format in intersection) and mode return result
[ "def", "is_format_selected", "(", "image_format", ",", "formats", ",", "progs", ")", ":", "intersection", "=", "formats", "&", "Settings", ".", "formats", "mode", "=", "_is_program_selected", "(", "progs", ")", "result", "=", "(", "image_format", "in", "inters...
Determine if the image format is selected by command line arguments.
[ "Determine", "if", "the", "image", "format", "is", "selected", "by", "command", "line", "arguments", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/detect_format.py#L24-L29
ajslater/picopt
picopt/detect_format.py
_is_image_sequenced
def _is_image_sequenced(image): """Determine if the image is a sequenced image.""" try: image.seek(1) image.seek(0) result = True except EOFError: result = False return result
python
def _is_image_sequenced(image): """Determine if the image is a sequenced image.""" try: image.seek(1) image.seek(0) result = True except EOFError: result = False return result
[ "def", "_is_image_sequenced", "(", "image", ")", ":", "try", ":", "image", ".", "seek", "(", "1", ")", "image", ".", "seek", "(", "0", ")", "result", "=", "True", "except", "EOFError", ":", "result", "=", "False", "return", "result" ]
Determine if the image is a sequenced image.
[ "Determine", "if", "the", "image", "is", "a", "sequenced", "image", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/detect_format.py#L32-L41
ajslater/picopt
picopt/detect_format.py
get_image_format
def get_image_format(filename): """Get the image format.""" image = None bad_image = 1 image_format = NONE_FORMAT sequenced = False try: bad_image = Image.open(filename).verify() image = Image.open(filename) image_format = image.format sequenced = _is_image_sequen...
python
def get_image_format(filename): """Get the image format.""" image = None bad_image = 1 image_format = NONE_FORMAT sequenced = False try: bad_image = Image.open(filename).verify() image = Image.open(filename) image_format = image.format sequenced = _is_image_sequen...
[ "def", "get_image_format", "(", "filename", ")", ":", "image", "=", "None", "bad_image", "=", "1", "image_format", "=", "NONE_FORMAT", "sequenced", "=", "False", "try", ":", "bad_image", "=", "Image", ".", "open", "(", "filename", ")", ".", "verify", "(", ...
Get the image format.
[ "Get", "the", "image", "format", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/detect_format.py#L44-L68
ajslater/picopt
picopt/detect_format.py
detect_file
def detect_file(filename): """Decide what to do with the file.""" image_format = get_image_format(filename) if image_format in Settings.formats: return image_format if image_format in (NONE_FORMAT, ERROR_FORMAT): return None if Settings.verbose > 1 and not Settings.list_only: ...
python
def detect_file(filename): """Decide what to do with the file.""" image_format = get_image_format(filename) if image_format in Settings.formats: return image_format if image_format in (NONE_FORMAT, ERROR_FORMAT): return None if Settings.verbose > 1 and not Settings.list_only: ...
[ "def", "detect_file", "(", "filename", ")", ":", "image_format", "=", "get_image_format", "(", "filename", ")", "if", "image_format", "in", "Settings", ".", "formats", ":", "return", "image_format", "if", "image_format", "in", "(", "NONE_FORMAT", ",", "ERROR_FOR...
Decide what to do with the file.
[ "Decide", "what", "to", "do", "with", "the", "file", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/detect_format.py#L71-L84
ajslater/picopt
picopt/settings.py
Settings.update
def update(cls, settings): """Update settings with a dict.""" for key, val in settings.__dict__.items(): if key.startswith('_'): continue setattr(cls, key, val)
python
def update(cls, settings): """Update settings with a dict.""" for key, val in settings.__dict__.items(): if key.startswith('_'): continue setattr(cls, key, val)
[ "def", "update", "(", "cls", ",", "settings", ")", ":", "for", "key", ",", "val", "in", "settings", ".", "__dict__", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "'_'", ")", ":", "continue", "setattr", "(", "cls", ",", "key", ...
Update settings with a dict.
[ "Update", "settings", "with", "a", "dict", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/settings.py#L39-L44
ajslater/picopt
picopt/settings.py
Settings._set_program_defaults
def _set_program_defaults(cls, programs): """Run the external program tester on the required binaries.""" for program in programs: val = getattr(cls, program.__name__) \ and extern.does_external_program_run(program.__name__, ...
python
def _set_program_defaults(cls, programs): """Run the external program tester on the required binaries.""" for program in programs: val = getattr(cls, program.__name__) \ and extern.does_external_program_run(program.__name__, ...
[ "def", "_set_program_defaults", "(", "cls", ",", "programs", ")", ":", "for", "program", "in", "programs", ":", "val", "=", "getattr", "(", "cls", ",", "program", ".", "__name__", ")", "and", "extern", ".", "does_external_program_run", "(", "program", ".", ...
Run the external program tester on the required binaries.
[ "Run", "the", "external", "program", "tester", "on", "the", "required", "binaries", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/settings.py#L47-L53
ajslater/picopt
picopt/settings.py
Settings.config_program_reqs
def config_program_reqs(cls, programs): """Run the program tester and determine if we can do anything.""" cls._set_program_defaults(programs) do_png = cls.optipng or cls.pngout or cls.advpng do_jpeg = cls.mozjpeg or cls.jpegrescan or cls.jpegtran do_comics = cls.comics ...
python
def config_program_reqs(cls, programs): """Run the program tester and determine if we can do anything.""" cls._set_program_defaults(programs) do_png = cls.optipng or cls.pngout or cls.advpng do_jpeg = cls.mozjpeg or cls.jpegrescan or cls.jpegtran do_comics = cls.comics ...
[ "def", "config_program_reqs", "(", "cls", ",", "programs", ")", ":", "cls", ".", "_set_program_defaults", "(", "programs", ")", "do_png", "=", "cls", ".", "optipng", "or", "cls", ".", "pngout", "or", "cls", ".", "advpng", "do_jpeg", "=", "cls", ".", "moz...
Run the program tester and determine if we can do anything.
[ "Run", "the", "program", "tester", "and", "determine", "if", "we", "can", "do", "anything", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/settings.py#L56-L67
ajslater/picopt
picopt/formats/png.py
optipng
def optipng(ext_args): """Run the external program optipng on the file.""" args = _OPTIPNG_ARGS + [ext_args.new_filename] extern.run_ext(args) return _PNG_FORMAT
python
def optipng(ext_args): """Run the external program optipng on the file.""" args = _OPTIPNG_ARGS + [ext_args.new_filename] extern.run_ext(args) return _PNG_FORMAT
[ "def", "optipng", "(", "ext_args", ")", ":", "args", "=", "_OPTIPNG_ARGS", "+", "[", "ext_args", ".", "new_filename", "]", "extern", ".", "run_ext", "(", "args", ")", "return", "_PNG_FORMAT" ]
Run the external program optipng on the file.
[ "Run", "the", "external", "program", "optipng", "on", "the", "file", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/png.py#L17-L21
ajslater/picopt
picopt/formats/png.py
advpng
def advpng(ext_args): """Run the external program advpng on the file.""" args = _ADVPNG_ARGS + [ext_args.new_filename] extern.run_ext(args) return _PNG_FORMAT
python
def advpng(ext_args): """Run the external program advpng on the file.""" args = _ADVPNG_ARGS + [ext_args.new_filename] extern.run_ext(args) return _PNG_FORMAT
[ "def", "advpng", "(", "ext_args", ")", ":", "args", "=", "_ADVPNG_ARGS", "+", "[", "ext_args", ".", "new_filename", "]", "extern", ".", "run_ext", "(", "args", ")", "return", "_PNG_FORMAT" ]
Run the external program advpng on the file.
[ "Run", "the", "external", "program", "advpng", "on", "the", "file", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/png.py#L24-L28
ajslater/picopt
picopt/formats/png.py
pngout
def pngout(ext_args): """Run the external program pngout on the file.""" args = _PNGOUT_ARGS + [ext_args.old_filename, ext_args.new_filename] extern.run_ext(args) return _PNG_FORMAT
python
def pngout(ext_args): """Run the external program pngout on the file.""" args = _PNGOUT_ARGS + [ext_args.old_filename, ext_args.new_filename] extern.run_ext(args) return _PNG_FORMAT
[ "def", "pngout", "(", "ext_args", ")", ":", "args", "=", "_PNGOUT_ARGS", "+", "[", "ext_args", ".", "old_filename", ",", "ext_args", ".", "new_filename", "]", "extern", ".", "run_ext", "(", "args", ")", "return", "_PNG_FORMAT" ]
Run the external program pngout on the file.
[ "Run", "the", "external", "program", "pngout", "on", "the", "file", "." ]
train
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/png.py#L31-L35
datacamp/protowhat
protowhat/sct_syntax.py
F._from_func
def _from_func(cls, f, *args, _attr_scts=None, **kwargs): """Creates a function chain starting with the specified SCT (f), and its arguments.""" func_chain = cls(attr_scts=_attr_scts) func_chain._stack.append([f, args, kwargs]) return func_chain
python
def _from_func(cls, f, *args, _attr_scts=None, **kwargs): """Creates a function chain starting with the specified SCT (f), and its arguments.""" func_chain = cls(attr_scts=_attr_scts) func_chain._stack.append([f, args, kwargs]) return func_chain
[ "def", "_from_func", "(", "cls", ",", "f", ",", "*", "args", ",", "_attr_scts", "=", "None", ",", "*", "*", "kwargs", ")", ":", "func_chain", "=", "cls", "(", "attr_scts", "=", "_attr_scts", ")", "func_chain", ".", "_stack", ".", "append", "(", "[", ...
Creates a function chain starting with the specified SCT (f), and its arguments.
[ "Creates", "a", "function", "chain", "starting", "with", "the", "specified", "SCT", "(", "f", ")", "and", "its", "arguments", "." ]
train
https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/sct_syntax.py#L101-L105
AtteqCom/zsl
src/zsl/resource/guard.py
_nested_transactional
def _nested_transactional(fn): # type: (Callable) -> Callable """In a transactional method create a nested transaction.""" @wraps(fn) def wrapped(self, *args, **kwargs): # type: (SessionFactory) -> Any try: rv = fn(self, *args, **kwargs) except _TransactionalPolicyVi...
python
def _nested_transactional(fn): # type: (Callable) -> Callable """In a transactional method create a nested transaction.""" @wraps(fn) def wrapped(self, *args, **kwargs): # type: (SessionFactory) -> Any try: rv = fn(self, *args, **kwargs) except _TransactionalPolicyVi...
[ "def", "_nested_transactional", "(", "fn", ")", ":", "# type: (Callable) -> Callable", "@", "wraps", "(", "fn", ")", "def", "wrapped", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (SessionFactory) -> Any", "try", ":", "rv", "=",...
In a transactional method create a nested transaction.
[ "In", "a", "transactional", "method", "create", "a", "nested", "transaction", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/guard.py#L343-L357
datacamp/protowhat
protowhat/checks/check_files.py
check_file
def check_file( state, fname, missing_msg="Did you create a file named `{}`?", is_dir_msg="Want to check a file named `{}`, but found a directory.", parse=True, use_fs=True, use_solution=False, ): """Test whether file exists, and make its contents the student code. Note: this SCT fa...
python
def check_file( state, fname, missing_msg="Did you create a file named `{}`?", is_dir_msg="Want to check a file named `{}`, but found a directory.", parse=True, use_fs=True, use_solution=False, ): """Test whether file exists, and make its contents the student code. Note: this SCT fa...
[ "def", "check_file", "(", "state", ",", "fname", ",", "missing_msg", "=", "\"Did you create a file named `{}`?\"", ",", "is_dir_msg", "=", "\"Want to check a file named `{}`, but found a directory.\"", ",", "parse", "=", "True", ",", "use_fs", "=", "True", ",", "use_sol...
Test whether file exists, and make its contents the student code. Note: this SCT fails if the file is a directory.
[ "Test", "whether", "file", "exists", "and", "make", "its", "contents", "the", "student", "code", "." ]
train
https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_files.py#L7-L50
datacamp/protowhat
protowhat/checks/check_files.py
has_dir
def has_dir(state, fname, incorrect_msg="Did you create a directory named `{}`?"): """Test whether a directory exists.""" if not Path(fname).is_dir(): state.report(Feedback(incorrect_msg.format(fname))) return state
python
def has_dir(state, fname, incorrect_msg="Did you create a directory named `{}`?"): """Test whether a directory exists.""" if not Path(fname).is_dir(): state.report(Feedback(incorrect_msg.format(fname))) return state
[ "def", "has_dir", "(", "state", ",", "fname", ",", "incorrect_msg", "=", "\"Did you create a directory named `{}`?\"", ")", ":", "if", "not", "Path", "(", "fname", ")", ".", "is_dir", "(", ")", ":", "state", ".", "report", "(", "Feedback", "(", "incorrect_ms...
Test whether a directory exists.
[ "Test", "whether", "a", "directory", "exists", "." ]
train
https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_files.py#L63-L68
AtteqCom/zsl
src/zsl/interface/task.py
exec_task
def exec_task(task_path, data): """Execute task. :param task_path: task path :type task_path: str|Callable :param data: task's data :type data: Any :return: """ if not data: data = {'data': None, 'path': task_path} elif not isinstance(data, (str, bytes)): data = {'d...
python
def exec_task(task_path, data): """Execute task. :param task_path: task path :type task_path: str|Callable :param data: task's data :type data: Any :return: """ if not data: data = {'data': None, 'path': task_path} elif not isinstance(data, (str, bytes)): data = {'d...
[ "def", "exec_task", "(", "task_path", ",", "data", ")", ":", "if", "not", "data", ":", "data", "=", "{", "'data'", ":", "None", ",", "'path'", ":", "task_path", "}", "elif", "not", "isinstance", "(", "data", ",", "(", "str", ",", "bytes", ")", ")",...
Execute task. :param task_path: task path :type task_path: str|Callable :param data: task's data :type data: Any :return:
[ "Execute", "task", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/interface/task.py#L107-L136
datacamp/protowhat
protowhat/utils_ast.py
dump
def dump(node, config): """ Convert a node tree to a simple nested dict All steps in this conversion are configurable using DumpConfig dump dictionary node: {"type": str, "data": dict} """ if config.is_node(node): fields = OrderedDict() for name in config.fields_iter(node): ...
python
def dump(node, config): """ Convert a node tree to a simple nested dict All steps in this conversion are configurable using DumpConfig dump dictionary node: {"type": str, "data": dict} """ if config.is_node(node): fields = OrderedDict() for name in config.fields_iter(node): ...
[ "def", "dump", "(", "node", ",", "config", ")", ":", "if", "config", ".", "is_node", "(", "node", ")", ":", "fields", "=", "OrderedDict", "(", ")", "for", "name", "in", "config", ".", "fields_iter", "(", "node", ")", ":", "attr", "=", "config", "."...
Convert a node tree to a simple nested dict All steps in this conversion are configurable using DumpConfig dump dictionary node: {"type": str, "data": dict}
[ "Convert", "a", "node", "tree", "to", "a", "simple", "nested", "dict" ]
train
https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/utils_ast.py#L30-L48
AtteqCom/zsl
src/zsl/db/helpers/pagination.py
Pagination.apply_pagination
def apply_pagination(self, q): """ Filters the query so that a given page is returned. The record count must be set in advance. :param q: Query to be paged. :return: Paged query. """ # type: (Query)->Query assert self.record_count >= 0, "Record count must ...
python
def apply_pagination(self, q): """ Filters the query so that a given page is returned. The record count must be set in advance. :param q: Query to be paged. :return: Paged query. """ # type: (Query)->Query assert self.record_count >= 0, "Record count must ...
[ "def", "apply_pagination", "(", "self", ",", "q", ")", ":", "# type: (Query)->Query", "assert", "self", ".", "record_count", ">=", "0", ",", "\"Record count must be set.\"", "return", "q", ".", "limit", "(", "self", ".", "page_size", ")", ".", "offset", "(", ...
Filters the query so that a given page is returned. The record count must be set in advance. :param q: Query to be paged. :return: Paged query.
[ "Filters", "the", "query", "so", "that", "a", "given", "page", "is", "returned", ".", "The", "record", "count", "must", "be", "set", "in", "advance", ".", ":", "param", "q", ":", "Query", "to", "be", "paged", ".", ":", "return", ":", "Paged", "query"...
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/db/helpers/pagination.py#L82-L91
AtteqCom/zsl
src/zsl/db/helpers/pagination.py
Pagination.paginate
def paginate(self, q): """ Filters the query so that a given page is returned. The record count is computed automatically from query. :param q: Query to be paged. :return: Paged query. """ self.record_count = q.count() return self.apply_pagination(q).all()
python
def paginate(self, q): """ Filters the query so that a given page is returned. The record count is computed automatically from query. :param q: Query to be paged. :return: Paged query. """ self.record_count = q.count() return self.apply_pagination(q).all()
[ "def", "paginate", "(", "self", ",", "q", ")", ":", "self", ".", "record_count", "=", "q", ".", "count", "(", ")", "return", "self", ".", "apply_pagination", "(", "q", ")", ".", "all", "(", ")" ]
Filters the query so that a given page is returned. The record count is computed automatically from query. :param q: Query to be paged. :return: Paged query.
[ "Filters", "the", "query", "so", "that", "a", "given", "page", "is", "returned", ".", "The", "record", "count", "is", "computed", "automatically", "from", "query", ".", ":", "param", "q", ":", "Query", "to", "be", "paged", ".", ":", "return", ":", "Pag...
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/db/helpers/pagination.py#L93-L101
briney/abutils
abutils/utils/cluster.py
cluster
def cluster(seqs, threshold=0.975, out_file=None, temp_dir=None, make_db=True, quiet=False, threads=0, return_just_seq_ids=False, max_memory=800, debug=False): ''' Perform sequence clustering with CD-HIT. Args: seqs (list): An iterable of sequences, in any format that `abutils.utils.se...
python
def cluster(seqs, threshold=0.975, out_file=None, temp_dir=None, make_db=True, quiet=False, threads=0, return_just_seq_ids=False, max_memory=800, debug=False): ''' Perform sequence clustering with CD-HIT. Args: seqs (list): An iterable of sequences, in any format that `abutils.utils.se...
[ "def", "cluster", "(", "seqs", ",", "threshold", "=", "0.975", ",", "out_file", "=", "None", ",", "temp_dir", "=", "None", ",", "make_db", "=", "True", ",", "quiet", "=", "False", ",", "threads", "=", "0", ",", "return_just_seq_ids", "=", "False", ",",...
Perform sequence clustering with CD-HIT. Args: seqs (list): An iterable of sequences, in any format that `abutils.utils.sequence.Sequence()` can handle threshold (float): Clustering identity threshold. Default is `0.975`. out_file (str): Path to the clustering output file. De...
[ "Perform", "sequence", "clustering", "with", "CD", "-", "HIT", "." ]
train
https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/cluster.py#L233-L284
briney/abutils
abutils/utils/cluster.py
cdhit
def cdhit(seqs, out_file=None, temp_dir=None, threshold=0.975, make_db=True, quiet=False, threads=0, max_memory=800, retries=5, debug=False): ''' Run CD-HIT. Args: seqs (list): An iterable of sequences, in any format that `abutils.utils.sequence.Sequence()` can handle threshol...
python
def cdhit(seqs, out_file=None, temp_dir=None, threshold=0.975, make_db=True, quiet=False, threads=0, max_memory=800, retries=5, debug=False): ''' Run CD-HIT. Args: seqs (list): An iterable of sequences, in any format that `abutils.utils.sequence.Sequence()` can handle threshol...
[ "def", "cdhit", "(", "seqs", ",", "out_file", "=", "None", ",", "temp_dir", "=", "None", ",", "threshold", "=", "0.975", ",", "make_db", "=", "True", ",", "quiet", "=", "False", ",", "threads", "=", "0", ",", "max_memory", "=", "800", ",", "retries",...
Run CD-HIT. Args: seqs (list): An iterable of sequences, in any format that `abutils.utils.sequence.Sequence()` can handle threshold (float): Clustering identity threshold. Default is `0.975`. out_file (str): Path to the clustering output file. Default is to use `...
[ "Run", "CD", "-", "HIT", "." ]
train
https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/cluster.py#L287-L365
briney/abutils
abutils/utils/cluster.py
parse_clusters
def parse_clusters(out_file, clust_file, seq_db=None, db_path=None, seq_dict=None, return_just_seq_ids=False): ''' Parses CD-HIT output. Args: out_file (str): Path to the CD-HIT output file. Required. clust_file (str): Path to the CD-HIT cluster file. Required. seq_db (sqlite.Con...
python
def parse_clusters(out_file, clust_file, seq_db=None, db_path=None, seq_dict=None, return_just_seq_ids=False): ''' Parses CD-HIT output. Args: out_file (str): Path to the CD-HIT output file. Required. clust_file (str): Path to the CD-HIT cluster file. Required. seq_db (sqlite.Con...
[ "def", "parse_clusters", "(", "out_file", ",", "clust_file", ",", "seq_db", "=", "None", ",", "db_path", "=", "None", ",", "seq_dict", "=", "None", ",", "return_just_seq_ids", "=", "False", ")", ":", "raw_clusters", "=", "[", "c", ".", "split", "(", "'\\...
Parses CD-HIT output. Args: out_file (str): Path to the CD-HIT output file. Required. clust_file (str): Path to the CD-HIT cluster file. Required. seq_db (sqlite.Connection): SQLite3 `Connection` object. Default is `None`. If not provided and `return_just_seq_ids` is False, t...
[ "Parses", "CD", "-", "HIT", "output", "." ]
train
https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/cluster.py#L368-L429
AtteqCom/zsl
src/zsl/task/task_decorator.py
log_output
def log_output(f): """ Logs the output value. """ @wraps(f) def wrapper_fn(*args, **kwargs): res = f(*args, **kwargs) logging.debug("Logging result %s.", res) return res return wrapper_fn
python
def log_output(f): """ Logs the output value. """ @wraps(f) def wrapper_fn(*args, **kwargs): res = f(*args, **kwargs) logging.debug("Logging result %s.", res) return res return wrapper_fn
[ "def", "log_output", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "logging", ".", "debug", "(", "\"...
Logs the output value.
[ "Logs", "the", "output", "value", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L34-L45
AtteqCom/zsl
src/zsl/task/task_decorator.py
save_to_file
def save_to_file(destination_filename, append=False): """ Save the output value to file. """ def decorator_fn(f): @wraps(f) def wrapper_fn(*args, **kwargs): res = f(*args, **kwargs) makedirs(os.path.dirname(destination_filename)) mode = "a" if append...
python
def save_to_file(destination_filename, append=False): """ Save the output value to file. """ def decorator_fn(f): @wraps(f) def wrapper_fn(*args, **kwargs): res = f(*args, **kwargs) makedirs(os.path.dirname(destination_filename)) mode = "a" if append...
[ "def", "save_to_file", "(", "destination_filename", ",", "append", "=", "False", ")", ":", "def", "decorator_fn", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", ...
Save the output value to file.
[ "Save", "the", "output", "value", "to", "file", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L48-L67
AtteqCom/zsl
src/zsl/task/task_decorator.py
json_input
def json_input(f): """ Expects task input data in json format and parse this data. """ @wraps(f) def json_input_decorator(*args, **kwargs): # If the data is already transformed, we do not transform it any # further. task_data = _get_data_from_args(args) if task_data...
python
def json_input(f): """ Expects task input data in json format and parse this data. """ @wraps(f) def json_input_decorator(*args, **kwargs): # If the data is already transformed, we do not transform it any # further. task_data = _get_data_from_args(args) if task_data...
[ "def", "json_input", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "json_input_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# If the data is already transformed, we do not transform it any", "# further.", "task_data", "=", "_get_data...
Expects task input data in json format and parse this data.
[ "Expects", "task", "input", "data", "in", "json", "format", "and", "parse", "this", "data", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L70-L100
AtteqCom/zsl
src/zsl/task/task_decorator.py
json_output
def json_output(f): """ Format response to json and in case of web-request set response content type to 'application/json'. """ @wraps(f) def json_output_decorator(*args, **kwargs): @inject(config=Config) def get_config(config): return config config = get_co...
python
def json_output(f): """ Format response to json and in case of web-request set response content type to 'application/json'. """ @wraps(f) def json_output_decorator(*args, **kwargs): @inject(config=Config) def get_config(config): return config config = get_co...
[ "def", "json_output", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "json_output_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "@", "inject", "(", "config", "=", "Config", ")", "def", "get_config", "(", "config", ")", "...
Format response to json and in case of web-request set response content type to 'application/json'.
[ "Format", "response", "to", "json", "and", "in", "case", "of", "web", "-", "request", "set", "response", "content", "type", "to", "application", "/", "json", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L103-L126
AtteqCom/zsl
src/zsl/task/task_decorator.py
jsonp_wrap
def jsonp_wrap(callback_key='callback'): """ Format response to jsonp and add a callback to JSON data - a jsonp request """ def decorator_fn(f): @wraps(f) def jsonp_output_decorator(*args, **kwargs): task_data = _get_data_from_args(args) data = task_data.get_dat...
python
def jsonp_wrap(callback_key='callback'): """ Format response to jsonp and add a callback to JSON data - a jsonp request """ def decorator_fn(f): @wraps(f) def jsonp_output_decorator(*args, **kwargs): task_data = _get_data_from_args(args) data = task_data.get_dat...
[ "def", "jsonp_wrap", "(", "callback_key", "=", "'callback'", ")", ":", "def", "decorator_fn", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "jsonp_output_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "task_data", "=", "_get...
Format response to jsonp and add a callback to JSON data - a jsonp request
[ "Format", "response", "to", "jsonp", "and", "add", "a", "callback", "to", "JSON", "data", "-", "a", "jsonp", "request" ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L134-L162
AtteqCom/zsl
src/zsl/task/task_decorator.py
jsend_output
def jsend_output(fail_exception_classes=None): """ Format task result to json output in jsend specification format. See: https://github.com/omniti-labs. Task return value must be dict or None. @param fail_exception_classes: exceptions which will produce 'fail' response status. """ fail_exc...
python
def jsend_output(fail_exception_classes=None): """ Format task result to json output in jsend specification format. See: https://github.com/omniti-labs. Task return value must be dict or None. @param fail_exception_classes: exceptions which will produce 'fail' response status. """ fail_exc...
[ "def", "jsend_output", "(", "fail_exception_classes", "=", "None", ")", ":", "fail_exception_classes", "=", "fail_exception_classes", "if", "fail_exception_classes", "else", "(", ")", "def", "decorator_fn", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "@", ...
Format task result to json output in jsend specification format. See: https://github.com/omniti-labs. Task return value must be dict or None. @param fail_exception_classes: exceptions which will produce 'fail' response status.
[ "Format", "task", "result", "to", "json", "output", "in", "jsend", "specification", "format", ".", "See", ":", "https", ":", "//", "github", ".", "com", "/", "omniti", "-", "labs", ".", "Task", "return", "value", "must", "be", "dict", "or", "None", "."...
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L165-L200
AtteqCom/zsl
src/zsl/task/task_decorator.py
web_error_and_result
def web_error_and_result(f): """ Same as error_and_result decorator, except: If no exception was raised during task execution, ONLY IN CASE OF WEB REQUEST formats task result into json dictionary {'data': task return value} """ @wraps(f) def web_error_and_result_decorator(*args, **kwargs): ...
python
def web_error_and_result(f): """ Same as error_and_result decorator, except: If no exception was raised during task execution, ONLY IN CASE OF WEB REQUEST formats task result into json dictionary {'data': task return value} """ @wraps(f) def web_error_and_result_decorator(*args, **kwargs): ...
[ "def", "web_error_and_result", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "web_error_and_result_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "error_and_result_decorator_inner_fn", "(", "f", ",", "True", ",", "*", ...
Same as error_and_result decorator, except: If no exception was raised during task execution, ONLY IN CASE OF WEB REQUEST formats task result into json dictionary {'data': task return value}
[ "Same", "as", "error_and_result", "decorator", "except", ":", "If", "no", "exception", "was", "raised", "during", "task", "execution", "ONLY", "IN", "CASE", "OF", "WEB", "REQUEST", "formats", "task", "result", "into", "json", "dictionary", "{", "data", ":", ...
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L203-L214
AtteqCom/zsl
src/zsl/task/task_decorator.py
error_and_result
def error_and_result(f): """ Format task result into json dictionary `{'data': task return value}` if no exception was raised during the task execution. If there was raised an exception during task execution, formats task result into dictionary `{'error': exception message with traceback}`. """ ...
python
def error_and_result(f): """ Format task result into json dictionary `{'data': task return value}` if no exception was raised during the task execution. If there was raised an exception during task execution, formats task result into dictionary `{'error': exception message with traceback}`. """ ...
[ "def", "error_and_result", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "error_and_result_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "error_and_result_decorator_inner_fn", "(", "f", ",", "False", ",", "*", "args",...
Format task result into json dictionary `{'data': task return value}` if no exception was raised during the task execution. If there was raised an exception during task execution, formats task result into dictionary `{'error': exception message with traceback}`.
[ "Format", "task", "result", "into", "json", "dictionary", "{", "data", ":", "task", "return", "value", "}", "if", "no", "exception", "was", "raised", "during", "the", "task", "execution", ".", "If", "there", "was", "raised", "an", "exception", "during", "t...
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L217-L229
AtteqCom/zsl
src/zsl/task/task_decorator.py
required_data
def required_data(*data): """ Task decorator which checks if the given variables (indices) are stored inside the task data. """ def decorator_fn(f): @wraps(f) def required_data_decorator(*args, **kwargs): task_data = _get_data_from_args(args).get_data() for ...
python
def required_data(*data): """ Task decorator which checks if the given variables (indices) are stored inside the task data. """ def decorator_fn(f): @wraps(f) def required_data_decorator(*args, **kwargs): task_data = _get_data_from_args(args).get_data() for ...
[ "def", "required_data", "(", "*", "data", ")", ":", "def", "decorator_fn", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "required_data_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "task_data", "=", "_get_data_from_args", ...
Task decorator which checks if the given variables (indices) are stored inside the task data.
[ "Task", "decorator", "which", "checks", "if", "the", "given", "variables", "(", "indices", ")", "are", "stored", "inside", "the", "task", "data", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L248-L268
AtteqCom/zsl
src/zsl/task/task_decorator.py
append_get_parameters
def append_get_parameters(accept_only_web=True): # type: (bool) -> Callable """ Task decorator which appends the GET data to the task data. :param accept_only_web: Parameter which limits using this task only with web requests. """ def wrapper(f): @wraps(f) ...
python
def append_get_parameters(accept_only_web=True): # type: (bool) -> Callable """ Task decorator which appends the GET data to the task data. :param accept_only_web: Parameter which limits using this task only with web requests. """ def wrapper(f): @wraps(f) ...
[ "def", "append_get_parameters", "(", "accept_only_web", "=", "True", ")", ":", "# type: (bool) -> Callable", "def", "wrapper", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "append_get_parameters_wrapper_fn", "(", "*", "args", ",", "*", "*", "kwargs"...
Task decorator which appends the GET data to the task data. :param accept_only_web: Parameter which limits using this task only with web requests.
[ "Task", "decorator", "which", "appends", "the", "GET", "data", "to", "the", "task", "data", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L271-L301
AtteqCom/zsl
src/zsl/task/task_decorator.py
web_task
def web_task(f): """ Checks if the task is called through the web interface. Task return value should be in format {'data': ...}. """ @wraps(f) def web_task_decorator(*args, **kwargs): jc = JobContext.get_current_context() if not isinstance(jc, WebJobContext): raise ...
python
def web_task(f): """ Checks if the task is called through the web interface. Task return value should be in format {'data': ...}. """ @wraps(f) def web_task_decorator(*args, **kwargs): jc = JobContext.get_current_context() if not isinstance(jc, WebJobContext): raise ...
[ "def", "web_task", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "web_task_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "jc", "=", "JobContext", ".", "get_current_context", "(", ")", "if", "not", "isinstance", "(", "jc",...
Checks if the task is called through the web interface. Task return value should be in format {'data': ...}.
[ "Checks", "if", "the", "task", "is", "called", "through", "the", "web", "interface", ".", "Task", "return", "value", "should", "be", "in", "format", "{", "data", ":", "...", "}", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L304-L320
AtteqCom/zsl
src/zsl/task/task_decorator.py
secured_task
def secured_task(f): """ Secured task decorator. """ @wraps(f) def secured_task_decorator(*args, **kwargs): task_data = _get_data_from_args(args) assert isinstance(task_data, TaskData) if not verify_security_data(task_data.get_data()['security']): raise SecurityE...
python
def secured_task(f): """ Secured task decorator. """ @wraps(f) def secured_task_decorator(*args, **kwargs): task_data = _get_data_from_args(args) assert isinstance(task_data, TaskData) if not verify_security_data(task_data.get_data()['security']): raise SecurityE...
[ "def", "secured_task", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "secured_task_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "task_data", "=", "_get_data_from_args", "(", "args", ")", "assert", "isinstance", "(", "task_da...
Secured task decorator.
[ "Secured", "task", "decorator", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L323-L339
AtteqCom/zsl
src/zsl/task/task_decorator.py
xml_output
def xml_output(f): """ Set content-type for response to WEB-REQUEST to 'text/xml' """ @wraps(f) def xml_output_inner_fn(*args, **kwargs): ret_val = f(*args, **kwargs) if isinstance(JobContext.get_current_context(), WebJobContext): JobContext.get_current_context().add_re...
python
def xml_output(f): """ Set content-type for response to WEB-REQUEST to 'text/xml' """ @wraps(f) def xml_output_inner_fn(*args, **kwargs): ret_val = f(*args, **kwargs) if isinstance(JobContext.get_current_context(), WebJobContext): JobContext.get_current_context().add_re...
[ "def", "xml_output", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "xml_output_inner_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret_val", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(",...
Set content-type for response to WEB-REQUEST to 'text/xml'
[ "Set", "content", "-", "type", "for", "response", "to", "WEB", "-", "REQUEST", "to", "text", "/", "xml" ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L342-L356
AtteqCom/zsl
src/zsl/task/task_decorator.py
file_upload
def file_upload(f): """ Return list of `werkzeug.datastructures.FileStorage` objects - files to be uploaded """ @wraps(f) def file_upload_decorator(*args, **kwargs): # If the data is already transformed, we do not transform it any # further. task_data = _get_data_from_ar...
python
def file_upload(f): """ Return list of `werkzeug.datastructures.FileStorage` objects - files to be uploaded """ @wraps(f) def file_upload_decorator(*args, **kwargs): # If the data is already transformed, we do not transform it any # further. task_data = _get_data_from_ar...
[ "def", "file_upload", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "file_upload_decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# If the data is already transformed, we do not transform it any", "# further.", "task_data", "=", "_get_da...
Return list of `werkzeug.datastructures.FileStorage` objects - files to be uploaded
[ "Return", "list", "of", "werkzeug", ".", "datastructures", ".", "FileStorage", "objects", "-", "files", "to", "be", "uploaded" ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L359-L377
AtteqCom/zsl
src/zsl/task/task_decorator.py
forbid_web_access
def forbid_web_access(f): """ Forbids running task using http request. :param f: Callable :return Callable """ @wraps(f) def wrapper_fn(*args, **kwargs): if isinstance(JobContext.get_current_context(), WebJobContext): raise ForbiddenError('Access forbidden from web.') ...
python
def forbid_web_access(f): """ Forbids running task using http request. :param f: Callable :return Callable """ @wraps(f) def wrapper_fn(*args, **kwargs): if isinstance(JobContext.get_current_context(), WebJobContext): raise ForbiddenError('Access forbidden from web.') ...
[ "def", "forbid_web_access", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper_fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "JobContext", ".", "get_current_context", "(", ")", ",", "WebJobContext", ")...
Forbids running task using http request. :param f: Callable :return Callable
[ "Forbids", "running", "task", "using", "http", "request", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L490-L505
AtteqCom/zsl
src/zsl/resource/resource_helper.py
filter_from_url_arg
def filter_from_url_arg(model_cls, query, arg, query_operator=and_, arg_types=None): """ Parse filter URL argument ``arg`` and apply to ``query`` Example: 'column1<=value,column2==value' -> query.filter(Model.column1 <= value, Model.column2 == value) """ fields = arg.split(...
python
def filter_from_url_arg(model_cls, query, arg, query_operator=and_, arg_types=None): """ Parse filter URL argument ``arg`` and apply to ``query`` Example: 'column1<=value,column2==value' -> query.filter(Model.column1 <= value, Model.column2 == value) """ fields = arg.split(...
[ "def", "filter_from_url_arg", "(", "model_cls", ",", "query", ",", "arg", ",", "query_operator", "=", "and_", ",", "arg_types", "=", "None", ")", ":", "fields", "=", "arg", ".", "split", "(", "','", ")", "mapper", "=", "class_mapper", "(", "model_cls", "...
Parse filter URL argument ``arg`` and apply to ``query`` Example: 'column1<=value,column2==value' -> query.filter(Model.column1 <= value, Model.column2 == value)
[ "Parse", "filter", "URL", "argument", "arg", "and", "apply", "to", "query" ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/resource_helper.py#L16-L72
AtteqCom/zsl
src/zsl/resource/resource_helper.py
model_tree
def model_tree(name, model_cls, visited=None): """Create a simple tree of model's properties and its related models. It traverse trough relations, but ignore any loops. :param name: name of the model :type name: str :param model_cls: model class :param visited: set of visited models :type ...
python
def model_tree(name, model_cls, visited=None): """Create a simple tree of model's properties and its related models. It traverse trough relations, but ignore any loops. :param name: name of the model :type name: str :param model_cls: model class :param visited: set of visited models :type ...
[ "def", "model_tree", "(", "name", ",", "model_cls", ",", "visited", "=", "None", ")", ":", "if", "not", "visited", ":", "visited", "=", "set", "(", ")", "visited", ".", "add", "(", "model_cls", ")", "mapper", "=", "class_mapper", "(", "model_cls", ")",...
Create a simple tree of model's properties and its related models. It traverse trough relations, but ignore any loops. :param name: name of the model :type name: str :param model_cls: model class :param visited: set of visited models :type visited: list or None :return: a dictionary where ...
[ "Create", "a", "simple", "tree", "of", "model", "s", "properties", "and", "its", "related", "models", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/resource_helper.py#L147-L170
AtteqCom/zsl
src/zsl/resource/resource_helper.py
flat_model
def flat_model(tree): """Flatten the tree into a list of properties adding parents as prefixes.""" names = [] for columns in viewvalues(tree): for col in columns: if isinstance(col, dict): col_name = list(col)[0] names += [col_name + '__' + c for c in flat...
python
def flat_model(tree): """Flatten the tree into a list of properties adding parents as prefixes.""" names = [] for columns in viewvalues(tree): for col in columns: if isinstance(col, dict): col_name = list(col)[0] names += [col_name + '__' + c for c in flat...
[ "def", "flat_model", "(", "tree", ")", ":", "names", "=", "[", "]", "for", "columns", "in", "viewvalues", "(", "tree", ")", ":", "for", "col", "in", "columns", ":", "if", "isinstance", "(", "col", ",", "dict", ")", ":", "col_name", "=", "list", "("...
Flatten the tree into a list of properties adding parents as prefixes.
[ "Flatten", "the", "tree", "into", "a", "list", "of", "properties", "adding", "parents", "as", "prefixes", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/resource_helper.py#L173-L184
AtteqCom/zsl
src/zsl/interface/task_queue.py
execute_job
def execute_job(job, app=Injected, task_router=Injected): # type: (Job, Zsl, TaskRouter) -> dict """Execute a job. :param job: job to execute :type job: Job :param app: service application instance, injected :type app: ServiceApplication :param task_router: task router instance, injected ...
python
def execute_job(job, app=Injected, task_router=Injected): # type: (Job, Zsl, TaskRouter) -> dict """Execute a job. :param job: job to execute :type job: Job :param app: service application instance, injected :type app: ServiceApplication :param task_router: task router instance, injected ...
[ "def", "execute_job", "(", "job", ",", "app", "=", "Injected", ",", "task_router", "=", "Injected", ")", ":", "# type: (Job, Zsl, TaskRouter) -> dict", "app", ".", "logger", ".", "info", "(", "\"Job fetched, preparing the task '{0}'.\"", ".", "format", "(", "job", ...
Execute a job. :param job: job to execute :type job: Job :param app: service application instance, injected :type app: ServiceApplication :param task_router: task router instance, injected :type task_router: TaskRouter :return: task result :rtype: dict
[ "Execute", "a", "job", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/interface/task_queue.py#L28-L52
AtteqCom/zsl
src/zsl/interface/task_queue.py
TaskQueueWorker.handle_exception
def handle_exception(self, e, task_path): # type: (Exception, str) -> dict """Handle exception raised during task execution. :param e: exception :type e: Exception :param task_path: task path :type task_path: str :return: exception as task result :rtype: ...
python
def handle_exception(self, e, task_path): # type: (Exception, str) -> dict """Handle exception raised during task execution. :param e: exception :type e: Exception :param task_path: task path :type task_path: str :return: exception as task result :rtype: ...
[ "def", "handle_exception", "(", "self", ",", "e", ",", "task_path", ")", ":", "# type: (Exception, str) -> dict", "self", ".", "_app", ".", "logger", ".", "error", "(", "str", "(", "e", ")", "+", "\"\\n\"", "+", "traceback", ".", "format_exc", "(", ")", ...
Handle exception raised during task execution. :param e: exception :type e: Exception :param task_path: task path :type task_path: str :return: exception as task result :rtype: dict
[ "Handle", "exception", "raised", "during", "task", "execution", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/interface/task_queue.py#L80-L93
AtteqCom/zsl
src/zsl/interface/task_queue.py
TaskQueueWorker.execute_job
def execute_job(self, job): # type: (Job) -> dict """Execute job given by the task queue. :param job: job :type job: Job :return: task result :rtype: dict """ try: return execute_job(job) except KillWorkerException: self._...
python
def execute_job(self, job): # type: (Job) -> dict """Execute job given by the task queue. :param job: job :type job: Job :return: task result :rtype: dict """ try: return execute_job(job) except KillWorkerException: self._...
[ "def", "execute_job", "(", "self", ",", "job", ")", ":", "# type: (Job) -> dict", "try", ":", "return", "execute_job", "(", "job", ")", "except", "KillWorkerException", ":", "self", ".", "_app", ".", "logger", ".", "info", "(", "\"Stopping Gearman worker on dema...
Execute job given by the task queue. :param job: job :type job: Job :return: task result :rtype: dict
[ "Execute", "job", "given", "by", "the", "task", "queue", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/interface/task_queue.py#L95-L112
datacamp/protowhat
protowhat/utils.py
legacy_signature
def legacy_signature(**kwargs_mapping): """ This decorator makes it possible to call a function using old argument names when they are passed as keyword arguments. @legacy_signature(old_arg1='arg1', old_arg2='arg2') def func(arg1, arg2=1): return arg1 + arg2 func(old_arg1=1) == 2 f...
python
def legacy_signature(**kwargs_mapping): """ This decorator makes it possible to call a function using old argument names when they are passed as keyword arguments. @legacy_signature(old_arg1='arg1', old_arg2='arg2') def func(arg1, arg2=1): return arg1 + arg2 func(old_arg1=1) == 2 f...
[ "def", "legacy_signature", "(", "*", "*", "kwargs_mapping", ")", ":", "def", "signature_decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "redirected_kwargs", "=", "{", ...
This decorator makes it possible to call a function using old argument names when they are passed as keyword arguments. @legacy_signature(old_arg1='arg1', old_arg2='arg2') def func(arg1, arg2=1): return arg1 + arg2 func(old_arg1=1) == 2 func(old_arg1=1, old_arg2=2) == 3
[ "This", "decorator", "makes", "it", "possible", "to", "call", "a", "function", "using", "old", "argument", "names", "when", "they", "are", "passed", "as", "keyword", "arguments", "." ]
train
https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/utils.py#L4-L28
AtteqCom/zsl
src/zsl/application/initializers/service_initializer.py
ServiceInitializer._bind_service
def _bind_service(package_name, cls_name, binder=Injected): """Bind service to application injector. :param package_name: service package :type package_name: str :param cls_name: service class :type cls_name: str :param binder: current application binder, injected ...
python
def _bind_service(package_name, cls_name, binder=Injected): """Bind service to application injector. :param package_name: service package :type package_name: str :param cls_name: service class :type cls_name: str :param binder: current application binder, injected ...
[ "def", "_bind_service", "(", "package_name", ",", "cls_name", ",", "binder", "=", "Injected", ")", ":", "module", "=", "importlib", ".", "import_module", "(", "package_name", ")", "cls", "=", "getattr", "(", "module", ",", "cls_name", ")", "binder", ".", "...
Bind service to application injector. :param package_name: service package :type package_name: str :param cls_name: service class :type cls_name: str :param binder: current application binder, injected :type binder: Binder
[ "Bind", "service", "to", "application", "injector", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/application/initializers/service_initializer.py#L21-L39
AtteqCom/zsl
src/zsl/application/initializers/service_initializer.py
ServiceInitializer.initialize
def initialize(config): """Initialize method. :param config: current application config, injected :type config: Config """ service_injection_config = config.get('SERVICE_INJECTION', ()) if not isinstance(service_injection_config, (tuple, list)): service_inje...
python
def initialize(config): """Initialize method. :param config: current application config, injected :type config: Config """ service_injection_config = config.get('SERVICE_INJECTION', ()) if not isinstance(service_injection_config, (tuple, list)): service_inje...
[ "def", "initialize", "(", "config", ")", ":", "service_injection_config", "=", "config", ".", "get", "(", "'SERVICE_INJECTION'", ",", "(", ")", ")", "if", "not", "isinstance", "(", "service_injection_config", ",", "(", "tuple", ",", "list", ")", ")", ":", ...
Initialize method. :param config: current application config, injected :type config: Config
[ "Initialize", "method", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/application/initializers/service_initializer.py#L43-L65
AtteqCom/zsl
src/zsl/utils/background_task.py
background_task_method
def background_task_method(task): """Decorate an object method as a background task (called with help of gearman). You have to create a task which will handle the gearman call. The method arguments will be encoded as JSON. :param task: name of the task :type task: str :return: decorated fu...
python
def background_task_method(task): """Decorate an object method as a background task (called with help of gearman). You have to create a task which will handle the gearman call. The method arguments will be encoded as JSON. :param task: name of the task :type task: str :return: decorated fu...
[ "def", "background_task_method", "(", "task", ")", ":", "# TODO ako vysledok vrat nejaky JOB ID, aby sa dalo checkovat na pozadi", "# TODO vytvorit este vseobecny background_task nielen pre metody", "def", "decorator_fn", "(", "fn", ")", ":", "gearman", "=", "None", "@", "inject"...
Decorate an object method as a background task (called with help of gearman). You have to create a task which will handle the gearman call. The method arguments will be encoded as JSON. :param task: name of the task :type task: str :return: decorated function
[ "Decorate", "an", "object", "method", "as", "a", "background", "task", "(", "called", "with", "help", "of", "gearman", ")", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/background_task.py#L18-L69
AtteqCom/zsl
src/zsl/resource/json_server_resource.py
_get_link_pages
def _get_link_pages(page, per_page, count, page_url): # type: (int, int, int, str) -> Dict[str, str] """Create link header for page metadata. :param page: current page :param per_page: page limit :param count: count of all resources :param page_url: url for resources :return: dictionary wit...
python
def _get_link_pages(page, per_page, count, page_url): # type: (int, int, int, str) -> Dict[str, str] """Create link header for page metadata. :param page: current page :param per_page: page limit :param count: count of all resources :param page_url: url for resources :return: dictionary wit...
[ "def", "_get_link_pages", "(", "page", ",", "per_page", ",", "count", ",", "page_url", ")", ":", "# type: (int, int, int, str) -> Dict[str, str]", "current_page", "=", "_page_arg", "(", "page", ")", "links", "=", "{", "}", "end", "=", "page", "*", "per_page", ...
Create link header for page metadata. :param page: current page :param per_page: page limit :param count: count of all resources :param page_url: url for resources :return: dictionary with name of the link as key and its url as value
[ "Create", "link", "header", "for", "page", "metadata", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L47-L71
AtteqCom/zsl
src/zsl/resource/json_server_resource.py
JsonServerResource.to_filter
def to_filter(self, query, arg): """Json-server filter using the _or_ operator.""" return filter_from_url_arg(self.model_cls, query, arg, query_operator=or_)
python
def to_filter(self, query, arg): """Json-server filter using the _or_ operator.""" return filter_from_url_arg(self.model_cls, query, arg, query_operator=or_)
[ "def", "to_filter", "(", "self", ",", "query", ",", "arg", ")", ":", "return", "filter_from_url_arg", "(", "self", ".", "model_cls", ",", "query", ",", "arg", ",", "query_operator", "=", "or_", ")" ]
Json-server filter using the _or_ operator.
[ "Json", "-", "server", "filter", "using", "the", "_or_", "operator", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L81-L83
AtteqCom/zsl
src/zsl/resource/json_server_resource.py
JsonServerResource.create
def create(self, *args, **kwargs): """Adds created http status response and location link.""" resource = super(JsonServerResource, self).create(*args, **kwargs) return ResourceResult( body=resource, status=get_http_status_code_value(http.client.CREATED), loca...
python
def create(self, *args, **kwargs): """Adds created http status response and location link.""" resource = super(JsonServerResource, self).create(*args, **kwargs) return ResourceResult( body=resource, status=get_http_status_code_value(http.client.CREATED), loca...
[ "def", "create", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "resource", "=", "super", "(", "JsonServerResource", ",", "self", ")", ".", "create", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "ResourceResult", "(", ...
Adds created http status response and location link.
[ "Adds", "created", "http", "status", "response", "and", "location", "link", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L85-L93
AtteqCom/zsl
src/zsl/resource/json_server_resource.py
JsonServerResource._create_filter_by
def _create_filter_by(self): """Transform the json-server filter arguments to model-resource ones.""" filter_by = [] for name, values in request.args.copy().lists(): # copy.lists works in py2 and py3 if name not in _SKIPPED_ARGUMENTS: column = _re_column_name.search...
python
def _create_filter_by(self): """Transform the json-server filter arguments to model-resource ones.""" filter_by = [] for name, values in request.args.copy().lists(): # copy.lists works in py2 and py3 if name not in _SKIPPED_ARGUMENTS: column = _re_column_name.search...
[ "def", "_create_filter_by", "(", "self", ")", ":", "filter_by", "=", "[", "]", "for", "name", ",", "values", "in", "request", ".", "args", ".", "copy", "(", ")", ".", "lists", "(", ")", ":", "# copy.lists works in py2 and py3", "if", "name", "not", "in",...
Transform the json-server filter arguments to model-resource ones.
[ "Transform", "the", "json", "-", "server", "filter", "arguments", "to", "model", "-", "resource", "ones", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L95-L120
AtteqCom/zsl
src/zsl/resource/json_server_resource.py
JsonServerResource._create_related
def _create_related(args): # type: (Dict) -> None """Create related field from `_embed` arguments.""" if '_embed' in request.args: embeds = request.args.getlist('_embed') args['related'] = ','.join(embeds) del args['_embed']
python
def _create_related(args): # type: (Dict) -> None """Create related field from `_embed` arguments.""" if '_embed' in request.args: embeds = request.args.getlist('_embed') args['related'] = ','.join(embeds) del args['_embed']
[ "def", "_create_related", "(", "args", ")", ":", "# type: (Dict) -> None", "if", "'_embed'", "in", "request", ".", "args", ":", "embeds", "=", "request", ".", "args", ".", "getlist", "(", "'_embed'", ")", "args", "[", "'related'", "]", "=", "','", ".", "...
Create related field from `_embed` arguments.
[ "Create", "related", "field", "from", "_embed", "arguments", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L123-L131
AtteqCom/zsl
src/zsl/resource/json_server_resource.py
JsonServerResource._create_fulltext_query
def _create_fulltext_query(self): """Support the json-server fulltext search with a broad LIKE filter.""" filter_by = [] if 'q' in request.args: columns = flat_model(model_tree(self.__class__.__name__, self.model_cls)) for q in request.args.getlist('q'): ...
python
def _create_fulltext_query(self): """Support the json-server fulltext search with a broad LIKE filter.""" filter_by = [] if 'q' in request.args: columns = flat_model(model_tree(self.__class__.__name__, self.model_cls)) for q in request.args.getlist('q'): ...
[ "def", "_create_fulltext_query", "(", "self", ")", ":", "filter_by", "=", "[", "]", "if", "'q'", "in", "request", ".", "args", ":", "columns", "=", "flat_model", "(", "model_tree", "(", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "model_...
Support the json-server fulltext search with a broad LIKE filter.
[ "Support", "the", "json", "-", "server", "fulltext", "search", "with", "a", "broad", "LIKE", "filter", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L133-L142
AtteqCom/zsl
src/zsl/resource/json_server_resource.py
JsonServerResource._transform_list_args
def _transform_list_args(self, args): # type: (dict) -> None """Transforms all list arguments from json-server to model-resource ones. This modifies the given arguments. """ if '_limit' in args: args['limit'] = int(args['_limit']) del args['_limit'] ...
python
def _transform_list_args(self, args): # type: (dict) -> None """Transforms all list arguments from json-server to model-resource ones. This modifies the given arguments. """ if '_limit' in args: args['limit'] = int(args['_limit']) del args['_limit'] ...
[ "def", "_transform_list_args", "(", "self", ",", "args", ")", ":", "# type: (dict) -> None", "if", "'_limit'", "in", "args", ":", "args", "[", "'limit'", "]", "=", "int", "(", "args", "[", "'_limit'", "]", ")", "del", "args", "[", "'_limit'", "]", "if", ...
Transforms all list arguments from json-server to model-resource ones. This modifies the given arguments.
[ "Transforms", "all", "list", "arguments", "from", "json", "-", "server", "to", "model", "-", "resource", "ones", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L144-L186
AtteqCom/zsl
src/zsl/resource/json_server_resource.py
JsonServerResource.read
def read(self, params, args, data): """Modifies the parameters and adds metadata for read results.""" result_count = None result_links = None if params is None: params = [] if args: args = args.copy() else: args = {} ctx = sel...
python
def read(self, params, args, data): """Modifies the parameters and adds metadata for read results.""" result_count = None result_links = None if params is None: params = [] if args: args = args.copy() else: args = {} ctx = sel...
[ "def", "read", "(", "self", ",", "params", ",", "args", ",", "data", ")", ":", "result_count", "=", "None", "result_links", "=", "None", "if", "params", "is", "None", ":", "params", "=", "[", "]", "if", "args", ":", "args", "=", "args", ".", "copy"...
Modifies the parameters and adds metadata for read results.
[ "Modifies", "the", "parameters", "and", "adds", "metadata", "for", "read", "results", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L188-L231
AtteqCom/zsl
src/zsl/resource/json_server_resource.py
JsonServerResource.update
def update(self, *args, **kwargs): """Modifies the parameters and adds metadata for update results. Currently it does not support `PUT` method, which works as replacing the resource. This is somehow questionable in relation DB. """ if request.method == 'PUT': logging...
python
def update(self, *args, **kwargs): """Modifies the parameters and adds metadata for update results. Currently it does not support `PUT` method, which works as replacing the resource. This is somehow questionable in relation DB. """ if request.method == 'PUT': logging...
[ "def", "update", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "request", ".", "method", "==", "'PUT'", ":", "logging", ".", "warning", "(", "\"Called not implemented resource method PUT\"", ")", "resource", "=", "super", "(", "Js...
Modifies the parameters and adds metadata for update results. Currently it does not support `PUT` method, which works as replacing the resource. This is somehow questionable in relation DB.
[ "Modifies", "the", "parameters", "and", "adds", "metadata", "for", "update", "results", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L233-L247
AtteqCom/zsl
src/zsl/resource/json_server_resource.py
JsonServerResource.delete
def delete(self, params, args, data): """Supports only singular delete and adds proper http status.""" ctx = self._create_context(params, args, data) row_id = ctx.get_row_id() if row_id: deleted = self._delete_one(row_id, ctx) if deleted: return ...
python
def delete(self, params, args, data): """Supports only singular delete and adds proper http status.""" ctx = self._create_context(params, args, data) row_id = ctx.get_row_id() if row_id: deleted = self._delete_one(row_id, ctx) if deleted: return ...
[ "def", "delete", "(", "self", ",", "params", ",", "args", ",", "data", ")", ":", "ctx", "=", "self", ".", "_create_context", "(", "params", ",", "args", ",", "data", ")", "row_id", "=", "ctx", ".", "get_row_id", "(", ")", "if", "row_id", ":", "dele...
Supports only singular delete and adds proper http status.
[ "Supports", "only", "singular", "delete", "and", "adds", "proper", "http", "status", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L250-L263
AtteqCom/zsl
src/zsl/utils/task_helper.py
run_task
def run_task(task_cls, task_data): """Instantiate and run the perform method od given task data. :param task_cls: task class :param task_data: task data :type task_data: TaskData :return: task's result """ task = instantiate(task_cls) task_callable = get_callable(task) return task_c...
python
def run_task(task_cls, task_data): """Instantiate and run the perform method od given task data. :param task_cls: task class :param task_data: task data :type task_data: TaskData :return: task's result """ task = instantiate(task_cls) task_callable = get_callable(task) return task_c...
[ "def", "run_task", "(", "task_cls", ",", "task_data", ")", ":", "task", "=", "instantiate", "(", "task_cls", ")", "task_callable", "=", "get_callable", "(", "task", ")", "return", "task_callable", "(", "TaskData", "(", "task_data", ")", ")" ]
Instantiate and run the perform method od given task data. :param task_cls: task class :param task_data: task data :type task_data: TaskData :return: task's result
[ "Instantiate", "and", "run", "the", "perform", "method", "od", "given", "task", "data", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/task_helper.py#L20-L30
AtteqCom/zsl
src/zsl/utils/task_helper.py
run_task_json
def run_task_json(task_cls, task_data): """Instantiate and run the perform method od given task data. :param task_cls: task class :param task_data: task data :type task_data: TaskData :return: task's result """ # TODO what does set_skipping_json do? task = instantiate(task_cls) task...
python
def run_task_json(task_cls, task_data): """Instantiate and run the perform method od given task data. :param task_cls: task class :param task_data: task data :type task_data: TaskData :return: task's result """ # TODO what does set_skipping_json do? task = instantiate(task_cls) task...
[ "def", "run_task_json", "(", "task_cls", ",", "task_data", ")", ":", "# TODO what does set_skipping_json do?", "task", "=", "instantiate", "(", "task_cls", ")", "task_callable", "=", "get_callable", "(", "task", ")", "td", "=", "TaskData", "(", "task_data", ")", ...
Instantiate and run the perform method od given task data. :param task_cls: task class :param task_data: task data :type task_data: TaskData :return: task's result
[ "Instantiate", "and", "run", "the", "perform", "method", "od", "given", "task", "data", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/task_helper.py#L33-L46
briney/abutils
abutils/plots/summary.py
_aggregate
def _aggregate(data, norm=True, sort_by='value', keys=None): ''' Counts the number of occurances of each item in 'data'. Inputs data: a list of values. norm: normalize the resulting counts (as percent) sort_by: how to sort the retured data. Options are 'value' and 'count'. Output a non...
python
def _aggregate(data, norm=True, sort_by='value', keys=None): ''' Counts the number of occurances of each item in 'data'. Inputs data: a list of values. norm: normalize the resulting counts (as percent) sort_by: how to sort the retured data. Options are 'value' and 'count'. Output a non...
[ "def", "_aggregate", "(", "data", ",", "norm", "=", "True", ",", "sort_by", "=", "'value'", ",", "keys", "=", "None", ")", ":", "if", "keys", ":", "vdict", "=", "{", "k", ":", "0", "for", "k", "in", "keys", "}", "for", "d", "in", "data", ":", ...
Counts the number of occurances of each item in 'data'. Inputs data: a list of values. norm: normalize the resulting counts (as percent) sort_by: how to sort the retured data. Options are 'value' and 'count'. Output a non-redundant list of values (from 'data') and a list of counts.
[ "Counts", "the", "number", "of", "occurances", "of", "each", "item", "in", "data", "." ]
train
https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/plots/summary.py#L111-L144
AtteqCom/zsl
src/zsl/utils/deploy/apiari_doc_generator.py
generate_apiary_doc
def generate_apiary_doc(task_router): """Generate apiary documentation. Create a Apiary generator and add application packages to it. :param task_router: task router, injected :type task_router: TaskRouter :return: apiary generator :rtype: ApiaryDoc """ generator = ApiaryDoc() for...
python
def generate_apiary_doc(task_router): """Generate apiary documentation. Create a Apiary generator and add application packages to it. :param task_router: task router, injected :type task_router: TaskRouter :return: apiary generator :rtype: ApiaryDoc """ generator = ApiaryDoc() for...
[ "def", "generate_apiary_doc", "(", "task_router", ")", ":", "generator", "=", "ApiaryDoc", "(", ")", "for", "m", "in", "task_router", ".", "get_task_packages", "(", ")", "+", "get_method_packages", "(", ")", ":", "m", "=", "importlib", ".", "import_module", ...
Generate apiary documentation. Create a Apiary generator and add application packages to it. :param task_router: task router, injected :type task_router: TaskRouter :return: apiary generator :rtype: ApiaryDoc
[ "Generate", "apiary", "documentation", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/deploy/apiari_doc_generator.py#L120-L136
briney/abutils
abutils/utils/log.py
setup_logging
def setup_logging(logfile, print_log_location=True, debug=False): ''' Set up logging using the built-in ``logging`` package. A stream handler is added to all logs, so that logs at or above ``logging.INFO`` level are printed to screen as well as written to the log file. Arguments: logf...
python
def setup_logging(logfile, print_log_location=True, debug=False): ''' Set up logging using the built-in ``logging`` package. A stream handler is added to all logs, so that logs at or above ``logging.INFO`` level are printed to screen as well as written to the log file. Arguments: logf...
[ "def", "setup_logging", "(", "logfile", ",", "print_log_location", "=", "True", ",", "debug", "=", "False", ")", ":", "log_dir", "=", "os", ".", "path", ".", "dirname", "(", "logfile", ")", "make_dir", "(", "log_dir", ")", "fmt", "=", "'[%(levelname)s] %(n...
Set up logging using the built-in ``logging`` package. A stream handler is added to all logs, so that logs at or above ``logging.INFO`` level are printed to screen as well as written to the log file. Arguments: logfile (str): Path to the log file. If the parent directory does not ...
[ "Set", "up", "logging", "using", "the", "built", "-", "in", "logging", "package", "." ]
train
https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/log.py#L34-L70
briney/abutils
abutils/utils/log.py
get_logger
def get_logger(name=None): ''' Get a logging handle. As with ``setup_logging``, a stream handler is added to the log handle. Arguments: name (str): Name of the log handle. Default is ``None``. ''' logger = logging.getLogger(name) if len(logger.handlers) == 0: logger = ...
python
def get_logger(name=None): ''' Get a logging handle. As with ``setup_logging``, a stream handler is added to the log handle. Arguments: name (str): Name of the log handle. Default is ``None``. ''' logger = logging.getLogger(name) if len(logger.handlers) == 0: logger = ...
[ "def", "get_logger", "(", "name", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "if", "len", "(", "logger", ".", "handlers", ")", "==", "0", ":", "logger", "=", "add_stream_handler", "(", "logger", ")", "return", ...
Get a logging handle. As with ``setup_logging``, a stream handler is added to the log handle. Arguments: name (str): Name of the log handle. Default is ``None``.
[ "Get", "a", "logging", "handle", "." ]
train
https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/log.py#L73-L87
AtteqCom/zsl
src/zsl/utils/injection_helper.py
inject
def inject(**bindings): """ Decorator for injecting parameters for ASL objects. """ def outer_wrapper(f): def function_wrapper(ff): for key, value in viewitems(bindings): bindings[key] = BindingKey(value) @functools.wraps(ff) def _inject(*arg...
python
def inject(**bindings): """ Decorator for injecting parameters for ASL objects. """ def outer_wrapper(f): def function_wrapper(ff): for key, value in viewitems(bindings): bindings[key] = BindingKey(value) @functools.wraps(ff) def _inject(*arg...
[ "def", "inject", "(", "*", "*", "bindings", ")", ":", "def", "outer_wrapper", "(", "f", ")", ":", "def", "function_wrapper", "(", "ff", ")", ":", "for", "key", ",", "value", "in", "viewitems", "(", "bindings", ")", ":", "bindings", "[", "key", "]", ...
Decorator for injecting parameters for ASL objects.
[ "Decorator", "for", "injecting", "parameters", "for", "ASL", "objects", "." ]
train
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/injection_helper.py#L33-L81
briney/abutils
abutils/utils/phylogeny.py
phylogeny
def phylogeny(sequences=None, project_dir=None, name=None, aln_file=None, tree_file=None, seq_field=None, name_field=None, aa=False, species='human', unrooted=False, ladderize=True, root=None, root_name=None, show_root_name=False, color_dict=None, color_function=None, order_dict=None, order_func...
python
def phylogeny(sequences=None, project_dir=None, name=None, aln_file=None, tree_file=None, seq_field=None, name_field=None, aa=False, species='human', unrooted=False, ladderize=True, root=None, root_name=None, show_root_name=False, color_dict=None, color_function=None, order_dict=None, order_func...
[ "def", "phylogeny", "(", "sequences", "=", "None", ",", "project_dir", "=", "None", ",", "name", "=", "None", ",", "aln_file", "=", "None", ",", "tree_file", "=", "None", ",", "seq_field", "=", "None", ",", "name_field", "=", "None", ",", "aa", "=", ...
Generates a lineage phylogeny figure. Args: sequences (list(Sequence)): A list of ``Sequence`` objects from which a phylogeny will be calculated. Strictly speaking, they do not need to be ``Sequence`` objects, rather, any object that contains the sequence name as the ``id`` attribu...
[ "Generates", "a", "lineage", "phylogeny", "figure", "." ]
train
https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/phylogeny.py#L74-L411
briney/abutils
abutils/utils/phylogeny.py
igphyml
def igphyml(input_file=None, tree_file=None, root=None, verbose=False): ''' Computes a phylogenetic tree using IgPhyML. .. note:: IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML. Args: input_file (str): Path to a Phylip-formatted multip...
python
def igphyml(input_file=None, tree_file=None, root=None, verbose=False): ''' Computes a phylogenetic tree using IgPhyML. .. note:: IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML. Args: input_file (str): Path to a Phylip-formatted multip...
[ "def", "igphyml", "(", "input_file", "=", "None", ",", "tree_file", "=", "None", ",", "root", "=", "None", ",", "verbose", "=", "False", ")", ":", "if", "shutil", ".", "which", "(", "'igphyml'", ")", "is", "None", ":", "raise", "RuntimeError", "(", "...
Computes a phylogenetic tree using IgPhyML. .. note:: IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML. Args: input_file (str): Path to a Phylip-formatted multiple sequence alignment. Required. tree_file (str): Path to the output tree f...
[ "Computes", "a", "phylogenetic", "tree", "using", "IgPhyML", "." ]
train
https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/phylogeny.py#L452-L493