repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
wummel/patool
patoolib/__init__.py
run_archive_cmdlist
def run_archive_cmdlist (archive_cmdlist, verbosity=0): """Run archive command.""" # archive_cmdlist is a command list with optional keyword arguments if isinstance(archive_cmdlist, tuple): cmdlist, runkwargs = archive_cmdlist else: cmdlist, runkwargs = archive_cmdlist, {} return util.run_checked(cmdlist, verbosity=verbosity, **runkwargs)
python
def run_archive_cmdlist (archive_cmdlist, verbosity=0): """Run archive command.""" # archive_cmdlist is a command list with optional keyword arguments if isinstance(archive_cmdlist, tuple): cmdlist, runkwargs = archive_cmdlist else: cmdlist, runkwargs = archive_cmdlist, {} return util.run_checked(cmdlist, verbosity=verbosity, **runkwargs)
[ "def", "run_archive_cmdlist", "(", "archive_cmdlist", ",", "verbosity", "=", "0", ")", ":", "# archive_cmdlist is a command list with optional keyword arguments", "if", "isinstance", "(", "archive_cmdlist", ",", "tuple", ")", ":", "cmdlist", ",", "runkwargs", "=", "arch...
Run archive command.
[ "Run", "archive", "command", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L417-L424
train
212,900
wummel/patool
patoolib/__init__.py
make_file_readable
def make_file_readable (filename): """Make file user readable if it is not a link.""" if not os.path.islink(filename): util.set_mode(filename, stat.S_IRUSR)
python
def make_file_readable (filename): """Make file user readable if it is not a link.""" if not os.path.islink(filename): util.set_mode(filename, stat.S_IRUSR)
[ "def", "make_file_readable", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "islink", "(", "filename", ")", ":", "util", ".", "set_mode", "(", "filename", ",", "stat", ".", "S_IRUSR", ")" ]
Make file user readable if it is not a link.
[ "Make", "file", "user", "readable", "if", "it", "is", "not", "a", "link", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L427-L430
train
212,901
wummel/patool
patoolib/__init__.py
make_user_readable
def make_user_readable (directory): """Make all files in given directory user readable. Also recurse into subdirectories.""" for root, dirs, files in os.walk(directory, onerror=util.log_error): for filename in files: make_file_readable(os.path.join(root, filename)) for dirname in dirs: make_dir_readable(os.path.join(root, dirname))
python
def make_user_readable (directory): """Make all files in given directory user readable. Also recurse into subdirectories.""" for root, dirs, files in os.walk(directory, onerror=util.log_error): for filename in files: make_file_readable(os.path.join(root, filename)) for dirname in dirs: make_dir_readable(os.path.join(root, dirname))
[ "def", "make_user_readable", "(", "directory", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "directory", ",", "onerror", "=", "util", ".", "log_error", ")", ":", "for", "filename", "in", "files", ":", "make_file_reada...
Make all files in given directory user readable. Also recurse into subdirectories.
[ "Make", "all", "files", "in", "given", "directory", "user", "readable", ".", "Also", "recurse", "into", "subdirectories", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L438-L445
train
212,902
wummel/patool
patoolib/__init__.py
cleanup_outdir
def cleanup_outdir (outdir, archive): """Cleanup outdir after extraction and return target file name and result string.""" make_user_readable(outdir) # move single directory or file in outdir (success, msg) = move_outdir_orphan(outdir) if success: # msg is a single directory or filename return msg, "`%s'" % msg # outdir remains unchanged # rename it to something more user-friendly (basically the archive # name without extension) outdir2 = util.get_single_outfile("", archive) os.rename(outdir, outdir2) return outdir2, "`%s' (%s)" % (outdir2, msg)
python
def cleanup_outdir (outdir, archive): """Cleanup outdir after extraction and return target file name and result string.""" make_user_readable(outdir) # move single directory or file in outdir (success, msg) = move_outdir_orphan(outdir) if success: # msg is a single directory or filename return msg, "`%s'" % msg # outdir remains unchanged # rename it to something more user-friendly (basically the archive # name without extension) outdir2 = util.get_single_outfile("", archive) os.rename(outdir, outdir2) return outdir2, "`%s' (%s)" % (outdir2, msg)
[ "def", "cleanup_outdir", "(", "outdir", ",", "archive", ")", ":", "make_user_readable", "(", "outdir", ")", "# move single directory or file in outdir", "(", "success", ",", "msg", ")", "=", "move_outdir_orphan", "(", "outdir", ")", "if", "success", ":", "# msg is...
Cleanup outdir after extraction and return target file name and result string.
[ "Cleanup", "outdir", "after", "extraction", "and", "return", "target", "file", "name", "and", "result", "string", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L448-L462
train
212,903
wummel/patool
patoolib/__init__.py
_extract_archive
def _extract_archive(archive, verbosity=0, interactive=True, outdir=None, program=None, format=None, compression=None): """Extract an archive. @return: output directory if command is 'extract', else None """ if format is None: format, compression = get_archive_format(archive) check_archive_format(format, compression) program = find_archive_program(format, 'extract', program=program) check_program_compression(archive, 'extract', program, compression) get_archive_cmdlist = get_archive_cmdlist_func(program, 'extract', format) if outdir is None: outdir = util.tmpdir(dir=".") do_cleanup_outdir = True else: do_cleanup_outdir = False try: cmdlist = get_archive_cmdlist(archive, compression, program, verbosity, interactive, outdir) if cmdlist: # an empty command list means the get_archive_cmdlist() function # already handled the command (eg. when it's a builtin Python # function) run_archive_cmdlist(cmdlist, verbosity=verbosity) if do_cleanup_outdir: target, msg = cleanup_outdir(outdir, archive) else: target, msg = outdir, "`%s'" % outdir if verbosity >= 0: util.log_info("... %s extracted to %s." % (archive, msg)) return target finally: # try to remove an empty temporary output directory if do_cleanup_outdir: try: os.rmdir(outdir) except OSError: pass
python
def _extract_archive(archive, verbosity=0, interactive=True, outdir=None, program=None, format=None, compression=None): """Extract an archive. @return: output directory if command is 'extract', else None """ if format is None: format, compression = get_archive_format(archive) check_archive_format(format, compression) program = find_archive_program(format, 'extract', program=program) check_program_compression(archive, 'extract', program, compression) get_archive_cmdlist = get_archive_cmdlist_func(program, 'extract', format) if outdir is None: outdir = util.tmpdir(dir=".") do_cleanup_outdir = True else: do_cleanup_outdir = False try: cmdlist = get_archive_cmdlist(archive, compression, program, verbosity, interactive, outdir) if cmdlist: # an empty command list means the get_archive_cmdlist() function # already handled the command (eg. when it's a builtin Python # function) run_archive_cmdlist(cmdlist, verbosity=verbosity) if do_cleanup_outdir: target, msg = cleanup_outdir(outdir, archive) else: target, msg = outdir, "`%s'" % outdir if verbosity >= 0: util.log_info("... %s extracted to %s." % (archive, msg)) return target finally: # try to remove an empty temporary output directory if do_cleanup_outdir: try: os.rmdir(outdir) except OSError: pass
[ "def", "_extract_archive", "(", "archive", ",", "verbosity", "=", "0", ",", "interactive", "=", "True", ",", "outdir", "=", "None", ",", "program", "=", "None", ",", "format", "=", "None", ",", "compression", "=", "None", ")", ":", "if", "format", "is"...
Extract an archive. @return: output directory if command is 'extract', else None
[ "Extract", "an", "archive", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L465-L501
train
212,904
wummel/patool
patoolib/__init__.py
_create_archive
def _create_archive(archive, filenames, verbosity=0, interactive=True, program=None, format=None, compression=None): """Create an archive.""" if format is None: format, compression = get_archive_format(archive) check_archive_format(format, compression) program = find_archive_program(format, 'create', program=program) check_program_compression(archive, 'create', program, compression) get_archive_cmdlist = get_archive_cmdlist_func(program, 'create', format) origarchive = None if os.path.basename(program) == 'arc' and \ ".arc" in archive and not archive.endswith(".arc"): # the arc program mangles the archive name if it contains ".arc" origarchive = archive archive = util.tmpfile(dir=os.path.dirname(archive), suffix=".arc") cmdlist = get_archive_cmdlist(archive, compression, program, verbosity, interactive, filenames) if cmdlist: # an empty command list means the get_archive_cmdlist() function # already handled the command (eg. when it's a builtin Python # function) run_archive_cmdlist(cmdlist, verbosity=verbosity) if origarchive: shutil.move(archive, origarchive)
python
def _create_archive(archive, filenames, verbosity=0, interactive=True, program=None, format=None, compression=None): """Create an archive.""" if format is None: format, compression = get_archive_format(archive) check_archive_format(format, compression) program = find_archive_program(format, 'create', program=program) check_program_compression(archive, 'create', program, compression) get_archive_cmdlist = get_archive_cmdlist_func(program, 'create', format) origarchive = None if os.path.basename(program) == 'arc' and \ ".arc" in archive and not archive.endswith(".arc"): # the arc program mangles the archive name if it contains ".arc" origarchive = archive archive = util.tmpfile(dir=os.path.dirname(archive), suffix=".arc") cmdlist = get_archive_cmdlist(archive, compression, program, verbosity, interactive, filenames) if cmdlist: # an empty command list means the get_archive_cmdlist() function # already handled the command (eg. when it's a builtin Python # function) run_archive_cmdlist(cmdlist, verbosity=verbosity) if origarchive: shutil.move(archive, origarchive)
[ "def", "_create_archive", "(", "archive", ",", "filenames", ",", "verbosity", "=", "0", ",", "interactive", "=", "True", ",", "program", "=", "None", ",", "format", "=", "None", ",", "compression", "=", "None", ")", ":", "if", "format", "is", "None", "...
Create an archive.
[ "Create", "an", "archive", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L504-L526
train
212,905
wummel/patool
patoolib/__init__.py
_handle_archive
def _handle_archive(archive, command, verbosity=0, interactive=True, program=None, format=None, compression=None): """Test and list archives.""" if format is None: format, compression = get_archive_format(archive) check_archive_format(format, compression) if command not in ('list', 'test'): raise util.PatoolError("invalid archive command `%s'" % command) program = find_archive_program(format, command, program=program) check_program_compression(archive, command, program, compression) get_archive_cmdlist = get_archive_cmdlist_func(program, command, format) # prepare keyword arguments for command list cmdlist = get_archive_cmdlist(archive, compression, program, verbosity, interactive) if cmdlist: # an empty command list means the get_archive_cmdlist() function # already handled the command (eg. when it's a builtin Python # function) run_archive_cmdlist(cmdlist, verbosity=verbosity)
python
def _handle_archive(archive, command, verbosity=0, interactive=True, program=None, format=None, compression=None): """Test and list archives.""" if format is None: format, compression = get_archive_format(archive) check_archive_format(format, compression) if command not in ('list', 'test'): raise util.PatoolError("invalid archive command `%s'" % command) program = find_archive_program(format, command, program=program) check_program_compression(archive, command, program, compression) get_archive_cmdlist = get_archive_cmdlist_func(program, command, format) # prepare keyword arguments for command list cmdlist = get_archive_cmdlist(archive, compression, program, verbosity, interactive) if cmdlist: # an empty command list means the get_archive_cmdlist() function # already handled the command (eg. when it's a builtin Python # function) run_archive_cmdlist(cmdlist, verbosity=verbosity)
[ "def", "_handle_archive", "(", "archive", ",", "command", ",", "verbosity", "=", "0", ",", "interactive", "=", "True", ",", "program", "=", "None", ",", "format", "=", "None", ",", "compression", "=", "None", ")", ":", "if", "format", "is", "None", ":"...
Test and list archives.
[ "Test", "and", "list", "archives", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L529-L546
train
212,906
wummel/patool
patoolib/__init__.py
get_archive_cmdlist_func
def get_archive_cmdlist_func (program, command, format): """Get the Python function that executes the given program.""" # get python module for given archive program key = util.stripext(os.path.basename(program).lower()) modulename = ".programs." + ProgramModules.get(key, key) # import the module try: module = importlib.import_module(modulename, __name__) except ImportError as msg: raise util.PatoolError(msg) # get archive handler function (eg. patoolib.programs.star.extract_tar) try: return getattr(module, '%s_%s' % (command, format)) except AttributeError as msg: raise util.PatoolError(msg)
python
def get_archive_cmdlist_func (program, command, format): """Get the Python function that executes the given program.""" # get python module for given archive program key = util.stripext(os.path.basename(program).lower()) modulename = ".programs." + ProgramModules.get(key, key) # import the module try: module = importlib.import_module(modulename, __name__) except ImportError as msg: raise util.PatoolError(msg) # get archive handler function (eg. patoolib.programs.star.extract_tar) try: return getattr(module, '%s_%s' % (command, format)) except AttributeError as msg: raise util.PatoolError(msg)
[ "def", "get_archive_cmdlist_func", "(", "program", ",", "command", ",", "format", ")", ":", "# get python module for given archive program", "key", "=", "util", ".", "stripext", "(", "os", ".", "path", ".", "basename", "(", "program", ")", ".", "lower", "(", "...
Get the Python function that executes the given program.
[ "Get", "the", "Python", "function", "that", "executes", "the", "given", "program", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L549-L563
train
212,907
wummel/patool
patoolib/__init__.py
_diff_archives
def _diff_archives (archive1, archive2, verbosity=0, interactive=True): """Show differences between two archives. @return 0 if archives are the same, else 1 @raises: PatoolError on errors """ if util.is_same_file(archive1, archive2): return 0 diff = util.find_program("diff") if not diff: msg = "The diff(1) program is required for showing archive differences, please install it." raise util.PatoolError(msg) tmpdir1 = util.tmpdir() try: path1 = _extract_archive(archive1, outdir=tmpdir1, verbosity=-1) tmpdir2 = util.tmpdir() try: path2 = _extract_archive(archive2, outdir=tmpdir2, verbosity=-1) return util.run_checked([diff, "-urN", path1, path2], verbosity=1, ret_ok=(0, 1)) finally: shutil.rmtree(tmpdir2, onerror=rmtree_log_error) finally: shutil.rmtree(tmpdir1, onerror=rmtree_log_error)
python
def _diff_archives (archive1, archive2, verbosity=0, interactive=True): """Show differences between two archives. @return 0 if archives are the same, else 1 @raises: PatoolError on errors """ if util.is_same_file(archive1, archive2): return 0 diff = util.find_program("diff") if not diff: msg = "The diff(1) program is required for showing archive differences, please install it." raise util.PatoolError(msg) tmpdir1 = util.tmpdir() try: path1 = _extract_archive(archive1, outdir=tmpdir1, verbosity=-1) tmpdir2 = util.tmpdir() try: path2 = _extract_archive(archive2, outdir=tmpdir2, verbosity=-1) return util.run_checked([diff, "-urN", path1, path2], verbosity=1, ret_ok=(0, 1)) finally: shutil.rmtree(tmpdir2, onerror=rmtree_log_error) finally: shutil.rmtree(tmpdir1, onerror=rmtree_log_error)
[ "def", "_diff_archives", "(", "archive1", ",", "archive2", ",", "verbosity", "=", "0", ",", "interactive", "=", "True", ")", ":", "if", "util", ".", "is_same_file", "(", "archive1", ",", "archive2", ")", ":", "return", "0", "diff", "=", "util", ".", "f...
Show differences between two archives. @return 0 if archives are the same, else 1 @raises: PatoolError on errors
[ "Show", "differences", "between", "two", "archives", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L572-L593
train
212,908
wummel/patool
patoolib/__init__.py
_search_archive
def _search_archive(pattern, archive, verbosity=0, interactive=True): """Search for given pattern in an archive.""" grep = util.find_program("grep") if not grep: msg = "The grep(1) program is required for searching archive contents, please install it." raise util.PatoolError(msg) tmpdir = util.tmpdir() try: path = _extract_archive(archive, outdir=tmpdir, verbosity=-1) return util.run_checked([grep, "-r", "-e", pattern, "."], ret_ok=(0, 1), verbosity=1, cwd=path) finally: shutil.rmtree(tmpdir, onerror=rmtree_log_error)
python
def _search_archive(pattern, archive, verbosity=0, interactive=True): """Search for given pattern in an archive.""" grep = util.find_program("grep") if not grep: msg = "The grep(1) program is required for searching archive contents, please install it." raise util.PatoolError(msg) tmpdir = util.tmpdir() try: path = _extract_archive(archive, outdir=tmpdir, verbosity=-1) return util.run_checked([grep, "-r", "-e", pattern, "."], ret_ok=(0, 1), verbosity=1, cwd=path) finally: shutil.rmtree(tmpdir, onerror=rmtree_log_error)
[ "def", "_search_archive", "(", "pattern", ",", "archive", ",", "verbosity", "=", "0", ",", "interactive", "=", "True", ")", ":", "grep", "=", "util", ".", "find_program", "(", "\"grep\"", ")", "if", "not", "grep", ":", "msg", "=", "\"The grep(1) program is...
Search for given pattern in an archive.
[ "Search", "for", "given", "pattern", "in", "an", "archive", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L596-L607
train
212,909
wummel/patool
patoolib/__init__.py
_repack_archive
def _repack_archive (archive1, archive2, verbosity=0, interactive=True): """Repackage an archive to a different format.""" format1, compression1 = get_archive_format(archive1) format2, compression2 = get_archive_format(archive2) if format1 == format2 and compression1 == compression2: # same format and compression allows to copy the file util.link_or_copy(archive1, archive2, verbosity=verbosity) return tmpdir = util.tmpdir() try: kwargs = dict(verbosity=verbosity, outdir=tmpdir) same_format = (format1 == format2 and compression1 and compression2) if same_format: # only decompress since the format is the same kwargs['format'] = compression1 path = _extract_archive(archive1, **kwargs) archive = os.path.abspath(archive2) files = tuple(os.listdir(path)) olddir = os.getcwd() os.chdir(path) try: kwargs = dict(verbosity=verbosity, interactive=interactive) if same_format: # only compress since the format is the same kwargs['format'] = compression2 _create_archive(archive, files, **kwargs) finally: os.chdir(olddir) finally: shutil.rmtree(tmpdir, onerror=rmtree_log_error)
python
def _repack_archive (archive1, archive2, verbosity=0, interactive=True): """Repackage an archive to a different format.""" format1, compression1 = get_archive_format(archive1) format2, compression2 = get_archive_format(archive2) if format1 == format2 and compression1 == compression2: # same format and compression allows to copy the file util.link_or_copy(archive1, archive2, verbosity=verbosity) return tmpdir = util.tmpdir() try: kwargs = dict(verbosity=verbosity, outdir=tmpdir) same_format = (format1 == format2 and compression1 and compression2) if same_format: # only decompress since the format is the same kwargs['format'] = compression1 path = _extract_archive(archive1, **kwargs) archive = os.path.abspath(archive2) files = tuple(os.listdir(path)) olddir = os.getcwd() os.chdir(path) try: kwargs = dict(verbosity=verbosity, interactive=interactive) if same_format: # only compress since the format is the same kwargs['format'] = compression2 _create_archive(archive, files, **kwargs) finally: os.chdir(olddir) finally: shutil.rmtree(tmpdir, onerror=rmtree_log_error)
[ "def", "_repack_archive", "(", "archive1", ",", "archive2", ",", "verbosity", "=", "0", ",", "interactive", "=", "True", ")", ":", "format1", ",", "compression1", "=", "get_archive_format", "(", "archive1", ")", "format2", ",", "compression2", "=", "get_archiv...
Repackage an archive to a different format.
[ "Repackage", "an", "archive", "to", "a", "different", "format", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L610-L639
train
212,910
wummel/patool
patoolib/__init__.py
_recompress_archive
def _recompress_archive(archive, verbosity=0, interactive=True): """Try to recompress an archive to smaller size.""" format, compression = get_archive_format(archive) if compression: # only recompress the compression itself (eg. for .tar.xz) format = compression tmpdir = util.tmpdir() tmpdir2 = util.tmpdir() base, ext = os.path.splitext(os.path.basename(archive)) archive2 = util.get_single_outfile(tmpdir2, base, extension=ext) try: # extract kwargs = dict(verbosity=verbosity, format=format, outdir=tmpdir) path = _extract_archive(archive, **kwargs) # compress to new file olddir = os.getcwd() os.chdir(path) try: kwargs = dict(verbosity=verbosity, interactive=interactive, format=format) files = tuple(os.listdir(path)) _create_archive(archive2, files, **kwargs) finally: os.chdir(olddir) # check file sizes and replace if new file is smaller filesize = util.get_filesize(archive) filesize2 = util.get_filesize(archive2) if filesize2 < filesize: # replace file os.remove(archive) shutil.move(archive2, archive) diffsize = filesize - filesize2 return "... recompressed file is now %s smaller." % util.strsize(diffsize) finally: shutil.rmtree(tmpdir, onerror=rmtree_log_error) shutil.rmtree(tmpdir2, onerror=rmtree_log_error) return "... recompressed file is not smaller, leaving archive as is."
python
def _recompress_archive(archive, verbosity=0, interactive=True): """Try to recompress an archive to smaller size.""" format, compression = get_archive_format(archive) if compression: # only recompress the compression itself (eg. for .tar.xz) format = compression tmpdir = util.tmpdir() tmpdir2 = util.tmpdir() base, ext = os.path.splitext(os.path.basename(archive)) archive2 = util.get_single_outfile(tmpdir2, base, extension=ext) try: # extract kwargs = dict(verbosity=verbosity, format=format, outdir=tmpdir) path = _extract_archive(archive, **kwargs) # compress to new file olddir = os.getcwd() os.chdir(path) try: kwargs = dict(verbosity=verbosity, interactive=interactive, format=format) files = tuple(os.listdir(path)) _create_archive(archive2, files, **kwargs) finally: os.chdir(olddir) # check file sizes and replace if new file is smaller filesize = util.get_filesize(archive) filesize2 = util.get_filesize(archive2) if filesize2 < filesize: # replace file os.remove(archive) shutil.move(archive2, archive) diffsize = filesize - filesize2 return "... recompressed file is now %s smaller." % util.strsize(diffsize) finally: shutil.rmtree(tmpdir, onerror=rmtree_log_error) shutil.rmtree(tmpdir2, onerror=rmtree_log_error) return "... recompressed file is not smaller, leaving archive as is."
[ "def", "_recompress_archive", "(", "archive", ",", "verbosity", "=", "0", ",", "interactive", "=", "True", ")", ":", "format", ",", "compression", "=", "get_archive_format", "(", "archive", ")", "if", "compression", ":", "# only recompress the compression itself (eg...
Try to recompress an archive to smaller size.
[ "Try", "to", "recompress", "an", "archive", "to", "smaller", "size", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L642-L677
train
212,911
wummel/patool
patoolib/__init__.py
extract_archive
def extract_archive(archive, verbosity=0, outdir=None, program=None, interactive=True): """Extract given archive.""" util.check_existing_filename(archive) if verbosity >= 0: util.log_info("Extracting %s ..." % archive) return _extract_archive(archive, verbosity=verbosity, interactive=interactive, outdir=outdir, program=program)
python
def extract_archive(archive, verbosity=0, outdir=None, program=None, interactive=True): """Extract given archive.""" util.check_existing_filename(archive) if verbosity >= 0: util.log_info("Extracting %s ..." % archive) return _extract_archive(archive, verbosity=verbosity, interactive=interactive, outdir=outdir, program=program)
[ "def", "extract_archive", "(", "archive", ",", "verbosity", "=", "0", ",", "outdir", "=", "None", ",", "program", "=", "None", ",", "interactive", "=", "True", ")", ":", "util", ".", "check_existing_filename", "(", "archive", ")", "if", "verbosity", ">=", ...
Extract given archive.
[ "Extract", "given", "archive", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L682-L687
train
212,912
wummel/patool
patoolib/__init__.py
list_archive
def list_archive(archive, verbosity=1, program=None, interactive=True): """List given archive.""" # Set default verbosity to 1 since the listing output should be visible. util.check_existing_filename(archive) if verbosity >= 0: util.log_info("Listing %s ..." % archive) return _handle_archive(archive, 'list', verbosity=verbosity, interactive=interactive, program=program)
python
def list_archive(archive, verbosity=1, program=None, interactive=True): """List given archive.""" # Set default verbosity to 1 since the listing output should be visible. util.check_existing_filename(archive) if verbosity >= 0: util.log_info("Listing %s ..." % archive) return _handle_archive(archive, 'list', verbosity=verbosity, interactive=interactive, program=program)
[ "def", "list_archive", "(", "archive", ",", "verbosity", "=", "1", ",", "program", "=", "None", ",", "interactive", "=", "True", ")", ":", "# Set default verbosity to 1 since the listing output should be visible.", "util", ".", "check_existing_filename", "(", "archive",...
List given archive.
[ "List", "given", "archive", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L690-L697
train
212,913
wummel/patool
patoolib/__init__.py
create_archive
def create_archive(archive, filenames, verbosity=0, program=None, interactive=True): """Create given archive with given files.""" util.check_new_filename(archive) util.check_archive_filelist(filenames) if verbosity >= 0: util.log_info("Creating %s ..." % archive) res = _create_archive(archive, filenames, verbosity=verbosity, interactive=interactive, program=program) if verbosity >= 0: util.log_info("... %s created." % archive) return res
python
def create_archive(archive, filenames, verbosity=0, program=None, interactive=True): """Create given archive with given files.""" util.check_new_filename(archive) util.check_archive_filelist(filenames) if verbosity >= 0: util.log_info("Creating %s ..." % archive) res = _create_archive(archive, filenames, verbosity=verbosity, interactive=interactive, program=program) if verbosity >= 0: util.log_info("... %s created." % archive) return res
[ "def", "create_archive", "(", "archive", ",", "filenames", ",", "verbosity", "=", "0", ",", "program", "=", "None", ",", "interactive", "=", "True", ")", ":", "util", ".", "check_new_filename", "(", "archive", ")", "util", ".", "check_archive_filelist", "(",...
Create given archive with given files.
[ "Create", "given", "archive", "with", "given", "files", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L712-L722
train
212,914
wummel/patool
patoolib/__init__.py
diff_archives
def diff_archives(archive1, archive2, verbosity=0, interactive=True): """Print differences between two archives.""" util.check_existing_filename(archive1) util.check_existing_filename(archive2) if verbosity >= 0: util.log_info("Comparing %s with %s ..." % (archive1, archive2)) res = _diff_archives(archive1, archive2, verbosity=verbosity, interactive=interactive) if res == 0 and verbosity >= 0: util.log_info("... no differences found.")
python
def diff_archives(archive1, archive2, verbosity=0, interactive=True): """Print differences between two archives.""" util.check_existing_filename(archive1) util.check_existing_filename(archive2) if verbosity >= 0: util.log_info("Comparing %s with %s ..." % (archive1, archive2)) res = _diff_archives(archive1, archive2, verbosity=verbosity, interactive=interactive) if res == 0 and verbosity >= 0: util.log_info("... no differences found.")
[ "def", "diff_archives", "(", "archive1", ",", "archive2", ",", "verbosity", "=", "0", ",", "interactive", "=", "True", ")", ":", "util", ".", "check_existing_filename", "(", "archive1", ")", "util", ".", "check_existing_filename", "(", "archive2", ")", "if", ...
Print differences between two archives.
[ "Print", "differences", "between", "two", "archives", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L725-L733
train
212,915
wummel/patool
patoolib/__init__.py
search_archive
def search_archive(pattern, archive, verbosity=0, interactive=True): """Search pattern in archive members.""" if not pattern: raise util.PatoolError("empty search pattern") util.check_existing_filename(archive) if verbosity >= 0: util.log_info("Searching %r in %s ..." % (pattern, archive)) res = _search_archive(pattern, archive, verbosity=verbosity, interactive=interactive) if res == 1 and verbosity >= 0: util.log_info("... %r not found" % pattern) return res
python
def search_archive(pattern, archive, verbosity=0, interactive=True): """Search pattern in archive members.""" if not pattern: raise util.PatoolError("empty search pattern") util.check_existing_filename(archive) if verbosity >= 0: util.log_info("Searching %r in %s ..." % (pattern, archive)) res = _search_archive(pattern, archive, verbosity=verbosity, interactive=interactive) if res == 1 and verbosity >= 0: util.log_info("... %r not found" % pattern) return res
[ "def", "search_archive", "(", "pattern", ",", "archive", ",", "verbosity", "=", "0", ",", "interactive", "=", "True", ")", ":", "if", "not", "pattern", ":", "raise", "util", ".", "PatoolError", "(", "\"empty search pattern\"", ")", "util", ".", "check_existi...
Search pattern in archive members.
[ "Search", "pattern", "in", "archive", "members", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L736-L746
train
212,916
wummel/patool
patoolib/__init__.py
recompress_archive
def recompress_archive(archive, verbosity=0, interactive=True): """Recompress an archive to hopefully smaller size.""" util.check_existing_filename(archive) util.check_writable_filename(archive) if verbosity >= 0: util.log_info("Recompressing %s ..." % (archive,)) res = _recompress_archive(archive, verbosity=verbosity, interactive=interactive) if res and verbosity >= 0: util.log_info(res) return 0
python
def recompress_archive(archive, verbosity=0, interactive=True): """Recompress an archive to hopefully smaller size.""" util.check_existing_filename(archive) util.check_writable_filename(archive) if verbosity >= 0: util.log_info("Recompressing %s ..." % (archive,)) res = _recompress_archive(archive, verbosity=verbosity, interactive=interactive) if res and verbosity >= 0: util.log_info(res) return 0
[ "def", "recompress_archive", "(", "archive", ",", "verbosity", "=", "0", ",", "interactive", "=", "True", ")", ":", "util", ".", "check_existing_filename", "(", "archive", ")", "util", ".", "check_writable_filename", "(", "archive", ")", "if", "verbosity", ">=...
Recompress an archive to hopefully smaller size.
[ "Recompress", "an", "archive", "to", "hopefully", "smaller", "size", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L761-L770
train
212,917
wummel/patool
patoolib/util.py
init_mimedb
def init_mimedb(): """Initialize the internal MIME database.""" global mimedb try: mimedb = mimetypes.MimeTypes(strict=False) except Exception as msg: log_error("could not initialize MIME database: %s" % msg) return add_mimedb_data(mimedb)
python
def init_mimedb(): """Initialize the internal MIME database.""" global mimedb try: mimedb = mimetypes.MimeTypes(strict=False) except Exception as msg: log_error("could not initialize MIME database: %s" % msg) return add_mimedb_data(mimedb)
[ "def", "init_mimedb", "(", ")", ":", "global", "mimedb", "try", ":", "mimedb", "=", "mimetypes", ".", "MimeTypes", "(", "strict", "=", "False", ")", "except", "Exception", "as", "msg", ":", "log_error", "(", "\"could not initialize MIME database: %s\"", "%", "...
Initialize the internal MIME database.
[ "Initialize", "the", "internal", "MIME", "database", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L95-L103
train
212,918
wummel/patool
patoolib/util.py
add_mimedb_data
def add_mimedb_data(mimedb): """Add missing encodings and mimetypes to MIME database.""" mimedb.encodings_map['.bz2'] = 'bzip2' mimedb.encodings_map['.lzma'] = 'lzma' mimedb.encodings_map['.xz'] = 'xz' mimedb.encodings_map['.lz'] = 'lzip' mimedb.suffix_map['.tbz2'] = '.tar.bz2' add_mimetype(mimedb, 'application/x-lzop', '.lzo') add_mimetype(mimedb, 'application/x-adf', '.adf') add_mimetype(mimedb, 'application/x-arj', '.arj') add_mimetype(mimedb, 'application/x-lzma', '.lzma') add_mimetype(mimedb, 'application/x-xz', '.xz') add_mimetype(mimedb, 'application/java-archive', '.jar') add_mimetype(mimedb, 'application/x-rar', '.rar') add_mimetype(mimedb, 'application/x-rar', '.cbr') add_mimetype(mimedb, 'application/x-7z-compressed', '.7z') add_mimetype(mimedb, 'application/x-7z-compressed', '.cb7') add_mimetype(mimedb, 'application/x-cab', '.cab') add_mimetype(mimedb, 'application/x-rpm', '.rpm') add_mimetype(mimedb, 'application/x-debian-package', '.deb') add_mimetype(mimedb, 'application/x-ace', '.ace') add_mimetype(mimedb, 'application/x-ace', '.cba') add_mimetype(mimedb, 'application/x-archive', '.a') add_mimetype(mimedb, 'application/x-alzip', '.alz') add_mimetype(mimedb, 'application/x-arc', '.arc') add_mimetype(mimedb, 'application/x-lrzip', '.lrz') add_mimetype(mimedb, 'application/x-lha', '.lha') add_mimetype(mimedb, 'application/x-lzh', '.lzh') add_mimetype(mimedb, 'application/x-rzip', '.rz') add_mimetype(mimedb, 'application/x-zoo', '.zoo') add_mimetype(mimedb, 'application/x-dms', '.dms') add_mimetype(mimedb, 'application/x-zip-compressed', '.crx') add_mimetype(mimedb, 'application/x-shar', '.shar') add_mimetype(mimedb, 'application/x-tar', '.cbt') add_mimetype(mimedb, 'application/x-vhd', '.vhd') add_mimetype(mimedb, 'audio/x-ape', '.ape') add_mimetype(mimedb, 'audio/x-shn', '.shn') add_mimetype(mimedb, 'audio/flac', '.flac') add_mimetype(mimedb, 'application/x-chm', '.chm') add_mimetype(mimedb, 'application/x-iso9660-image', '.iso') add_mimetype(mimedb, 'application/zip', '.cbz') add_mimetype(mimedb, 'application/zip', '.epub') add_mimetype(mimedb, 'application/zip', '.apk') add_mimetype(mimedb, 'application/zpaq', '.zpaq')
python
def add_mimedb_data(mimedb): """Add missing encodings and mimetypes to MIME database.""" mimedb.encodings_map['.bz2'] = 'bzip2' mimedb.encodings_map['.lzma'] = 'lzma' mimedb.encodings_map['.xz'] = 'xz' mimedb.encodings_map['.lz'] = 'lzip' mimedb.suffix_map['.tbz2'] = '.tar.bz2' add_mimetype(mimedb, 'application/x-lzop', '.lzo') add_mimetype(mimedb, 'application/x-adf', '.adf') add_mimetype(mimedb, 'application/x-arj', '.arj') add_mimetype(mimedb, 'application/x-lzma', '.lzma') add_mimetype(mimedb, 'application/x-xz', '.xz') add_mimetype(mimedb, 'application/java-archive', '.jar') add_mimetype(mimedb, 'application/x-rar', '.rar') add_mimetype(mimedb, 'application/x-rar', '.cbr') add_mimetype(mimedb, 'application/x-7z-compressed', '.7z') add_mimetype(mimedb, 'application/x-7z-compressed', '.cb7') add_mimetype(mimedb, 'application/x-cab', '.cab') add_mimetype(mimedb, 'application/x-rpm', '.rpm') add_mimetype(mimedb, 'application/x-debian-package', '.deb') add_mimetype(mimedb, 'application/x-ace', '.ace') add_mimetype(mimedb, 'application/x-ace', '.cba') add_mimetype(mimedb, 'application/x-archive', '.a') add_mimetype(mimedb, 'application/x-alzip', '.alz') add_mimetype(mimedb, 'application/x-arc', '.arc') add_mimetype(mimedb, 'application/x-lrzip', '.lrz') add_mimetype(mimedb, 'application/x-lha', '.lha') add_mimetype(mimedb, 'application/x-lzh', '.lzh') add_mimetype(mimedb, 'application/x-rzip', '.rz') add_mimetype(mimedb, 'application/x-zoo', '.zoo') add_mimetype(mimedb, 'application/x-dms', '.dms') add_mimetype(mimedb, 'application/x-zip-compressed', '.crx') add_mimetype(mimedb, 'application/x-shar', '.shar') add_mimetype(mimedb, 'application/x-tar', '.cbt') add_mimetype(mimedb, 'application/x-vhd', '.vhd') add_mimetype(mimedb, 'audio/x-ape', '.ape') add_mimetype(mimedb, 'audio/x-shn', '.shn') add_mimetype(mimedb, 'audio/flac', '.flac') add_mimetype(mimedb, 'application/x-chm', '.chm') add_mimetype(mimedb, 'application/x-iso9660-image', '.iso') add_mimetype(mimedb, 'application/zip', '.cbz') add_mimetype(mimedb, 'application/zip', '.epub') add_mimetype(mimedb, 'application/zip', '.apk') add_mimetype(mimedb, 'application/zpaq', '.zpaq')
[ "def", "add_mimedb_data", "(", "mimedb", ")", ":", "mimedb", ".", "encodings_map", "[", "'.bz2'", "]", "=", "'bzip2'", "mimedb", ".", "encodings_map", "[", "'.lzma'", "]", "=", "'lzma'", "mimedb", ".", "encodings_map", "[", "'.xz'", "]", "=", "'xz'", "mime...
Add missing encodings and mimetypes to MIME database.
[ "Add", "missing", "encodings", "and", "mimetypes", "to", "MIME", "database", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L106-L149
train
212,919
wummel/patool
patoolib/util.py
backtick
def backtick (cmd, encoding='utf-8'): """Return decoded output from command.""" data = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] return data.decode(encoding)
python
def backtick (cmd, encoding='utf-8'): """Return decoded output from command.""" data = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] return data.decode(encoding)
[ "def", "backtick", "(", "cmd", ",", "encoding", "=", "'utf-8'", ")", ":", "data", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ".", "communicate", "(", ")", "[", "0", "]", "return", "data", ".", "...
Return decoded output from command.
[ "Return", "decoded", "output", "from", "command", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L192-L195
train
212,920
wummel/patool
patoolib/util.py
run
def run (cmd, verbosity=0, **kwargs): """Run command without error checking. @return: command return code""" # Note that shell_quote_nt() result is not suitable for copy-paste # (especially on Unix systems), but it looks nicer than shell_quote(). if verbosity >= 0: log_info("running %s" % " ".join(map(shell_quote_nt, cmd))) if kwargs: if verbosity >= 0: log_info(" with %s" % ", ".join("%s=%s" % (k, shell_quote(str(v)))\ for k, v in kwargs.items())) if kwargs.get("shell"): # for shell calls the command must be a string cmd = " ".join(cmd) if verbosity < 1: # hide command output on stdout with open(os.devnull, 'wb') as devnull: kwargs['stdout'] = devnull res = subprocess.call(cmd, **kwargs) else: res = subprocess.call(cmd, **kwargs) return res
python
def run (cmd, verbosity=0, **kwargs): """Run command without error checking. @return: command return code""" # Note that shell_quote_nt() result is not suitable for copy-paste # (especially on Unix systems), but it looks nicer than shell_quote(). if verbosity >= 0: log_info("running %s" % " ".join(map(shell_quote_nt, cmd))) if kwargs: if verbosity >= 0: log_info(" with %s" % ", ".join("%s=%s" % (k, shell_quote(str(v)))\ for k, v in kwargs.items())) if kwargs.get("shell"): # for shell calls the command must be a string cmd = " ".join(cmd) if verbosity < 1: # hide command output on stdout with open(os.devnull, 'wb') as devnull: kwargs['stdout'] = devnull res = subprocess.call(cmd, **kwargs) else: res = subprocess.call(cmd, **kwargs) return res
[ "def", "run", "(", "cmd", ",", "verbosity", "=", "0", ",", "*", "*", "kwargs", ")", ":", "# Note that shell_quote_nt() result is not suitable for copy-paste", "# (especially on Unix systems), but it looks nicer than shell_quote().", "if", "verbosity", ">=", "0", ":", "log_i...
Run command without error checking. @return: command return code
[ "Run", "command", "without", "error", "checking", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L198-L219
train
212,921
wummel/patool
patoolib/util.py
run_checked
def run_checked (cmd, ret_ok=(0,), **kwargs): """Run command and raise PatoolError on error.""" retcode = run(cmd, **kwargs) if retcode not in ret_ok: msg = "Command `%s' returned non-zero exit status %d" % (cmd, retcode) raise PatoolError(msg) return retcode
python
def run_checked (cmd, ret_ok=(0,), **kwargs): """Run command and raise PatoolError on error.""" retcode = run(cmd, **kwargs) if retcode not in ret_ok: msg = "Command `%s' returned non-zero exit status %d" % (cmd, retcode) raise PatoolError(msg) return retcode
[ "def", "run_checked", "(", "cmd", ",", "ret_ok", "=", "(", "0", ",", ")", ",", "*", "*", "kwargs", ")", ":", "retcode", "=", "run", "(", "cmd", ",", "*", "*", "kwargs", ")", "if", "retcode", "not", "in", "ret_ok", ":", "msg", "=", "\"Command `%s'...
Run command and raise PatoolError on error.
[ "Run", "command", "and", "raise", "PatoolError", "on", "error", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L222-L228
train
212,922
wummel/patool
patoolib/util.py
guess_mime_mimedb
def guess_mime_mimedb (filename): """Guess MIME type from given filename. @return: tuple (mime, encoding) """ mime, encoding = None, None if mimedb is not None: mime, encoding = mimedb.guess_type(filename, strict=False) if mime not in ArchiveMimetypes and encoding in ArchiveCompressions: # Files like 't.txt.gz' are recognized with encoding as format, and # an unsupported mime-type like 'text/plain'. Fix this. mime = Encoding2Mime[encoding] encoding = None return mime, encoding
python
def guess_mime_mimedb (filename): """Guess MIME type from given filename. @return: tuple (mime, encoding) """ mime, encoding = None, None if mimedb is not None: mime, encoding = mimedb.guess_type(filename, strict=False) if mime not in ArchiveMimetypes and encoding in ArchiveCompressions: # Files like 't.txt.gz' are recognized with encoding as format, and # an unsupported mime-type like 'text/plain'. Fix this. mime = Encoding2Mime[encoding] encoding = None return mime, encoding
[ "def", "guess_mime_mimedb", "(", "filename", ")", ":", "mime", ",", "encoding", "=", "None", ",", "None", "if", "mimedb", "is", "not", "None", ":", "mime", ",", "encoding", "=", "mimedb", ".", "guess_type", "(", "filename", ",", "strict", "=", "False", ...
Guess MIME type from given filename. @return: tuple (mime, encoding)
[ "Guess", "MIME", "type", "from", "given", "filename", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L259-L271
train
212,923
wummel/patool
patoolib/util.py
check_existing_filename
def check_existing_filename (filename, onlyfiles=True): """Ensure that given filename is a valid, existing file.""" if not os.path.exists(filename): raise PatoolError("file `%s' was not found" % filename) if not os.access(filename, os.R_OK): raise PatoolError("file `%s' is not readable" % filename) if onlyfiles and not os.path.isfile(filename): raise PatoolError("`%s' is not a file" % filename)
python
def check_existing_filename (filename, onlyfiles=True): """Ensure that given filename is a valid, existing file.""" if not os.path.exists(filename): raise PatoolError("file `%s' was not found" % filename) if not os.access(filename, os.R_OK): raise PatoolError("file `%s' is not readable" % filename) if onlyfiles and not os.path.isfile(filename): raise PatoolError("`%s' is not a file" % filename)
[ "def", "check_existing_filename", "(", "filename", ",", "onlyfiles", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "PatoolError", "(", "\"file `%s' was not found\"", "%", "filename", ")", "if", "not...
Ensure that given filename is a valid, existing file.
[ "Ensure", "that", "given", "filename", "is", "a", "valid", "existing", "file", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L400-L407
train
212,924
wummel/patool
patoolib/util.py
check_archive_filelist
def check_archive_filelist (filenames): """Check that file list is not empty and contains only existing files.""" if not filenames: raise PatoolError("cannot create archive with empty filelist") for filename in filenames: check_existing_filename(filename, onlyfiles=False)
python
def check_archive_filelist (filenames): """Check that file list is not empty and contains only existing files.""" if not filenames: raise PatoolError("cannot create archive with empty filelist") for filename in filenames: check_existing_filename(filename, onlyfiles=False)
[ "def", "check_archive_filelist", "(", "filenames", ")", ":", "if", "not", "filenames", ":", "raise", "PatoolError", "(", "\"cannot create archive with empty filelist\"", ")", "for", "filename", "in", "filenames", ":", "check_existing_filename", "(", "filename", ",", "...
Check that file list is not empty and contains only existing files.
[ "Check", "that", "file", "list", "is", "not", "empty", "and", "contains", "only", "existing", "files", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L422-L427
train
212,925
wummel/patool
patoolib/util.py
set_mode
def set_mode (filename, flags): """Set mode flags for given filename if not already set.""" try: mode = os.lstat(filename).st_mode except OSError: # ignore return if not (mode & flags): try: os.chmod(filename, flags | mode) except OSError as msg: log_error("could not set mode flags for `%s': %s" % (filename, msg))
python
def set_mode (filename, flags): """Set mode flags for given filename if not already set.""" try: mode = os.lstat(filename).st_mode except OSError: # ignore return if not (mode & flags): try: os.chmod(filename, flags | mode) except OSError as msg: log_error("could not set mode flags for `%s': %s" % (filename, msg))
[ "def", "set_mode", "(", "filename", ",", "flags", ")", ":", "try", ":", "mode", "=", "os", ".", "lstat", "(", "filename", ")", ".", "st_mode", "except", "OSError", ":", "# ignore", "return", "if", "not", "(", "mode", "&", "flags", ")", ":", "try", ...
Set mode flags for given filename if not already set.
[ "Set", "mode", "flags", "for", "given", "filename", "if", "not", "already", "set", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L430-L441
train
212,926
wummel/patool
patoolib/util.py
tmpfile
def tmpfile (dir=None, prefix="temp", suffix=None): """Return a temporary file.""" return tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)[1]
python
def tmpfile (dir=None, prefix="temp", suffix=None): """Return a temporary file.""" return tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)[1]
[ "def", "tmpfile", "(", "dir", "=", "None", ",", "prefix", "=", "\"temp\"", ",", "suffix", "=", "None", ")", ":", "return", "tempfile", ".", "mkstemp", "(", "suffix", "=", "suffix", ",", "prefix", "=", "prefix", ",", "dir", "=", "dir", ")", "[", "1"...
Return a temporary file.
[ "Return", "a", "temporary", "file", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L474-L476
train
212,927
wummel/patool
patoolib/util.py
get_single_outfile
def get_single_outfile (directory, archive, extension=""): """Get output filename if archive is in a single file format like gzip.""" outfile = os.path.join(directory, stripext(archive)) if os.path.exists(outfile + extension): # prevent overwriting existing files i = 1 newfile = "%s%d" % (outfile, i) while os.path.exists(newfile + extension): newfile = "%s%d" % (outfile, i) i += 1 outfile = newfile return outfile + extension
python
def get_single_outfile (directory, archive, extension=""): """Get output filename if archive is in a single file format like gzip.""" outfile = os.path.join(directory, stripext(archive)) if os.path.exists(outfile + extension): # prevent overwriting existing files i = 1 newfile = "%s%d" % (outfile, i) while os.path.exists(newfile + extension): newfile = "%s%d" % (outfile, i) i += 1 outfile = newfile return outfile + extension
[ "def", "get_single_outfile", "(", "directory", ",", "archive", ",", "extension", "=", "\"\"", ")", ":", "outfile", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "stripext", "(", "archive", ")", ")", "if", "os", ".", "path", ".", "exists",...
Get output filename if archive is in a single file format like gzip.
[ "Get", "output", "filename", "if", "archive", "is", "in", "a", "single", "file", "format", "like", "gzip", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L500-L511
train
212,928
wummel/patool
patoolib/util.py
print_env_info
def print_env_info(key, out=sys.stderr): """If given environment key is defined, print it out.""" value = os.getenv(key) if value is not None: print(key, "=", repr(value), file=out)
python
def print_env_info(key, out=sys.stderr): """If given environment key is defined, print it out.""" value = os.getenv(key) if value is not None: print(key, "=", repr(value), file=out)
[ "def", "print_env_info", "(", "key", ",", "out", "=", "sys", ".", "stderr", ")", ":", "value", "=", "os", ".", "getenv", "(", "key", ")", "if", "value", "is", "not", "None", ":", "print", "(", "key", ",", "\"=\"", ",", "repr", "(", "value", ")", ...
If given environment key is defined, print it out.
[ "If", "given", "environment", "key", "is", "defined", "print", "it", "out", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L549-L553
train
212,929
wummel/patool
patoolib/util.py
p7zip_supports_rar
def p7zip_supports_rar(): """Determine if the RAR codec is installed for 7z program.""" if os.name == 'nt': # Assume RAR support is compiled into the binary. return True # the subdirectory and codec name codecname = 'p7zip/Codecs/Rar29.so' # search canonical user library dirs for libdir in ('/usr/lib', '/usr/local/lib', '/usr/lib64', '/usr/local/lib64', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu'): fname = os.path.join(libdir, codecname) if os.path.exists(fname): return True return False
python
def p7zip_supports_rar(): """Determine if the RAR codec is installed for 7z program.""" if os.name == 'nt': # Assume RAR support is compiled into the binary. return True # the subdirectory and codec name codecname = 'p7zip/Codecs/Rar29.so' # search canonical user library dirs for libdir in ('/usr/lib', '/usr/local/lib', '/usr/lib64', '/usr/local/lib64', '/usr/lib/i386-linux-gnu', '/usr/lib/x86_64-linux-gnu'): fname = os.path.join(libdir, codecname) if os.path.exists(fname): return True return False
[ "def", "p7zip_supports_rar", "(", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "# Assume RAR support is compiled into the binary.", "return", "True", "# the subdirectory and codec name", "codecname", "=", "'p7zip/Codecs/Rar29.so'", "# search canonical user library dirs...
Determine if the RAR codec is installed for 7z program.
[ "Determine", "if", "the", "RAR", "codec", "is", "installed", "for", "7z", "program", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L589-L601
train
212,930
wummel/patool
patoolib/util.py
find_program
def find_program (program): """Look for program in environment PATH variable.""" if os.name == 'nt': # Add some well-known archiver programs to the search path path = os.environ['PATH'] path = append_to_path(path, get_nt_7z_dir()) path = append_to_path(path, get_nt_mac_dir()) path = append_to_path(path, get_nt_winrar_dir()) else: # use default path path = None return which(program, path=path)
python
def find_program (program): """Look for program in environment PATH variable.""" if os.name == 'nt': # Add some well-known archiver programs to the search path path = os.environ['PATH'] path = append_to_path(path, get_nt_7z_dir()) path = append_to_path(path, get_nt_mac_dir()) path = append_to_path(path, get_nt_winrar_dir()) else: # use default path path = None return which(program, path=path)
[ "def", "find_program", "(", "program", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "# Add some well-known archiver programs to the search path", "path", "=", "os", ".", "environ", "[", "'PATH'", "]", "path", "=", "append_to_path", "(", "path", ",", "...
Look for program in environment PATH variable.
[ "Look", "for", "program", "in", "environment", "PATH", "variable", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L605-L616
train
212,931
wummel/patool
patoolib/util.py
append_to_path
def append_to_path (path, directory): """Add a directory to the PATH environment variable, if it is a valid directory.""" if not os.path.isdir(directory) or directory in path: return path if not path.endswith(os.pathsep): path += os.pathsep return path + directory
python
def append_to_path (path, directory): """Add a directory to the PATH environment variable, if it is a valid directory.""" if not os.path.isdir(directory) or directory in path: return path if not path.endswith(os.pathsep): path += os.pathsep return path + directory
[ "def", "append_to_path", "(", "path", ",", "directory", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "directory", ")", "or", "directory", "in", "path", ":", "return", "path", "if", "not", "path", ".", "endswith", "(", "os", ".", "path...
Add a directory to the PATH environment variable, if it is a valid directory.
[ "Add", "a", "directory", "to", "the", "PATH", "environment", "variable", "if", "it", "is", "a", "valid", "directory", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L619-L626
train
212,932
wummel/patool
patoolib/util.py
get_nt_7z_dir
def get_nt_7z_dir (): """Return 7-Zip directory from registry, or an empty string.""" # Python 3.x renamed the _winreg module to winreg try: import _winreg as winreg except ImportError: import winreg try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\7-Zip") try: return winreg.QueryValueEx(key, "Path")[0] finally: winreg.CloseKey(key) except WindowsError: return ""
python
def get_nt_7z_dir (): """Return 7-Zip directory from registry, or an empty string.""" # Python 3.x renamed the _winreg module to winreg try: import _winreg as winreg except ImportError: import winreg try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\7-Zip") try: return winreg.QueryValueEx(key, "Path")[0] finally: winreg.CloseKey(key) except WindowsError: return ""
[ "def", "get_nt_7z_dir", "(", ")", ":", "# Python 3.x renamed the _winreg module to winreg", "try", ":", "import", "_winreg", "as", "winreg", "except", "ImportError", ":", "import", "winreg", "try", ":", "key", "=", "winreg", ".", "OpenKey", "(", "winreg", ".", "...
Return 7-Zip directory from registry, or an empty string.
[ "Return", "7", "-", "Zip", "directory", "from", "registry", "or", "an", "empty", "string", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L629-L643
train
212,933
wummel/patool
patoolib/util.py
is_same_file
def is_same_file (filename1, filename2): """Check if filename1 and filename2 point to the same file object. There can be false negatives, ie. the result is False, but it is the same file anyway. Reason is that network filesystems can create different paths to the same physical file. """ if filename1 == filename2: return True if os.name == 'posix': return os.path.samefile(filename1, filename2) return is_same_filename(filename1, filename2)
python
def is_same_file (filename1, filename2): """Check if filename1 and filename2 point to the same file object. There can be false negatives, ie. the result is False, but it is the same file anyway. Reason is that network filesystems can create different paths to the same physical file. """ if filename1 == filename2: return True if os.name == 'posix': return os.path.samefile(filename1, filename2) return is_same_filename(filename1, filename2)
[ "def", "is_same_file", "(", "filename1", ",", "filename2", ")", ":", "if", "filename1", "==", "filename2", ":", "return", "True", "if", "os", ".", "name", "==", "'posix'", ":", "return", "os", ".", "path", ".", "samefile", "(", "filename1", ",", "filenam...
Check if filename1 and filename2 point to the same file object. There can be false negatives, ie. the result is False, but it is the same file anyway. Reason is that network filesystems can create different paths to the same physical file.
[ "Check", "if", "filename1", "and", "filename2", "point", "to", "the", "same", "file", "object", ".", "There", "can", "be", "false", "negatives", "ie", ".", "the", "result", "is", "False", "but", "it", "is", "the", "same", "file", "anyway", ".", "Reason",...
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L669-L679
train
212,934
wummel/patool
patoolib/util.py
is_same_filename
def is_same_filename (filename1, filename2): """Check if filename1 and filename2 are the same filename.""" return os.path.realpath(filename1) == os.path.realpath(filename2)
python
def is_same_filename (filename1, filename2): """Check if filename1 and filename2 are the same filename.""" return os.path.realpath(filename1) == os.path.realpath(filename2)
[ "def", "is_same_filename", "(", "filename1", ",", "filename2", ")", ":", "return", "os", ".", "path", ".", "realpath", "(", "filename1", ")", "==", "os", ".", "path", ".", "realpath", "(", "filename2", ")" ]
Check if filename1 and filename2 are the same filename.
[ "Check", "if", "filename1", "and", "filename2", "are", "the", "same", "filename", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L682-L684
train
212,935
wummel/patool
patoolib/util.py
link_or_copy
def link_or_copy(src, dst, verbosity=0): """Try to make a hard link from src to dst and if that fails copy the file. Hard links save some disk space and linking should fail fast since no copying is involved. """ if verbosity > 0: log_info("Copying %s -> %s" % (src, dst)) try: os.link(src, dst) except (AttributeError, OSError): try: shutil.copy(src, dst) except OSError as msg: raise PatoolError(msg)
python
def link_or_copy(src, dst, verbosity=0): """Try to make a hard link from src to dst and if that fails copy the file. Hard links save some disk space and linking should fail fast since no copying is involved. """ if verbosity > 0: log_info("Copying %s -> %s" % (src, dst)) try: os.link(src, dst) except (AttributeError, OSError): try: shutil.copy(src, dst) except OSError as msg: raise PatoolError(msg)
[ "def", "link_or_copy", "(", "src", ",", "dst", ",", "verbosity", "=", "0", ")", ":", "if", "verbosity", ">", "0", ":", "log_info", "(", "\"Copying %s -> %s\"", "%", "(", "src", ",", "dst", ")", ")", "try", ":", "os", ".", "link", "(", "src", ",", ...
Try to make a hard link from src to dst and if that fails copy the file. Hard links save some disk space and linking should fail fast since no copying is involved.
[ "Try", "to", "make", "a", "hard", "link", "from", "src", "to", "dst", "and", "if", "that", "fails", "copy", "the", "file", ".", "Hard", "links", "save", "some", "disk", "space", "and", "linking", "should", "fail", "fast", "since", "no", "copying", "is"...
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/util.py#L687-L700
train
212,936
wummel/patool
patoolib/programs/flac.py
extract_flac
def extract_flac (archive, compression, cmd, verbosity, interactive, outdir): """Decompress a FLAC archive to a WAV file.""" outfile = util.get_single_outfile(outdir, archive, extension=".wav") cmdlist = [cmd, '--decode', archive, '--output-name', outfile] return cmdlist
python
def extract_flac (archive, compression, cmd, verbosity, interactive, outdir): """Decompress a FLAC archive to a WAV file.""" outfile = util.get_single_outfile(outdir, archive, extension=".wav") cmdlist = [cmd, '--decode', archive, '--output-name', outfile] return cmdlist
[ "def", "extract_flac", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "outdir", ")", ":", "outfile", "=", "util", ".", "get_single_outfile", "(", "outdir", ",", "archive", ",", "extension", "=", "\".wav\"", ")", ...
Decompress a FLAC archive to a WAV file.
[ "Decompress", "a", "FLAC", "archive", "to", "a", "WAV", "file", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/flac.py#L19-L23
train
212,937
wummel/patool
patoolib/programs/flac.py
create_flac
def create_flac (archive, compression, cmd, verbosity, interactive, filenames): """Compress a WAV file to a FLAC archive.""" cmdlist = [cmd, filenames[0], '--best', '--output-name', archive] return cmdlist
python
def create_flac (archive, compression, cmd, verbosity, interactive, filenames): """Compress a WAV file to a FLAC archive.""" cmdlist = [cmd, filenames[0], '--best', '--output-name', archive] return cmdlist
[ "def", "create_flac", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "filenames", ")", ":", "cmdlist", "=", "[", "cmd", ",", "filenames", "[", "0", "]", ",", "'--best'", ",", "'--output-name'", ",", "archive", ...
Compress a WAV file to a FLAC archive.
[ "Compress", "a", "WAV", "file", "to", "a", "FLAC", "archive", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/flac.py#L26-L29
train
212,938
wummel/patool
patoolib/programs/rar.py
extract_rar
def extract_rar (archive, compression, cmd, verbosity, interactive, outdir): """Extract a RAR archive.""" cmdlist = [cmd, 'x'] if not interactive: cmdlist.extend(['-p-', '-y']) cmdlist.extend(['--', os.path.abspath(archive)]) return (cmdlist, {'cwd': outdir})
python
def extract_rar (archive, compression, cmd, verbosity, interactive, outdir): """Extract a RAR archive.""" cmdlist = [cmd, 'x'] if not interactive: cmdlist.extend(['-p-', '-y']) cmdlist.extend(['--', os.path.abspath(archive)]) return (cmdlist, {'cwd': outdir})
[ "def", "extract_rar", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "outdir", ")", ":", "cmdlist", "=", "[", "cmd", ",", "'x'", "]", "if", "not", "interactive", ":", "cmdlist", ".", "extend", "(", "[", "'-p-...
Extract a RAR archive.
[ "Extract", "a", "RAR", "archive", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/rar.py#L19-L25
train
212,939
wummel/patool
patoolib/programs/cpio.py
extract_cpio
def extract_cpio (archive, compression, cmd, verbosity, interactive, outdir): """Extract a CPIO archive.""" cmdlist = [util.shell_quote(cmd), '--extract', '--make-directories', '--preserve-modification-time'] if sys.platform.startswith('linux') and not cmd.endswith('bsdcpio'): cmdlist.extend(['--no-absolute-filenames', '--force-local', '--nonmatching', r'"*\.\.*"']) if verbosity > 1: cmdlist.append('-v') cmdlist.extend(['<', util.shell_quote(os.path.abspath(archive))]) return (cmdlist, {'cwd': outdir, 'shell': True})
python
def extract_cpio (archive, compression, cmd, verbosity, interactive, outdir): """Extract a CPIO archive.""" cmdlist = [util.shell_quote(cmd), '--extract', '--make-directories', '--preserve-modification-time'] if sys.platform.startswith('linux') and not cmd.endswith('bsdcpio'): cmdlist.extend(['--no-absolute-filenames', '--force-local', '--nonmatching', r'"*\.\.*"']) if verbosity > 1: cmdlist.append('-v') cmdlist.extend(['<', util.shell_quote(os.path.abspath(archive))]) return (cmdlist, {'cwd': outdir, 'shell': True})
[ "def", "extract_cpio", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "outdir", ")", ":", "cmdlist", "=", "[", "util", ".", "shell_quote", "(", "cmd", ")", ",", "'--extract'", ",", "'--make-directories'", ",", "'...
Extract a CPIO archive.
[ "Extract", "a", "CPIO", "archive", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/cpio.py#L21-L31
train
212,940
wummel/patool
patoolib/programs/cpio.py
create_cpio
def create_cpio(archive, compression, cmd, verbosity, interactive, filenames): """Create a CPIO archive.""" cmdlist = [util.shell_quote(cmd), '--create'] if verbosity > 1: cmdlist.append('-v') if len(filenames) != 0: findcmd = ['find'] findcmd.extend([util.shell_quote(x) for x in filenames]) findcmd.extend(['-print0', '|']) cmdlist[0:0] = findcmd cmdlist.append('-0') cmdlist.extend([">", util.shell_quote(archive)]) return (cmdlist, {'shell': True})
python
def create_cpio(archive, compression, cmd, verbosity, interactive, filenames): """Create a CPIO archive.""" cmdlist = [util.shell_quote(cmd), '--create'] if verbosity > 1: cmdlist.append('-v') if len(filenames) != 0: findcmd = ['find'] findcmd.extend([util.shell_quote(x) for x in filenames]) findcmd.extend(['-print0', '|']) cmdlist[0:0] = findcmd cmdlist.append('-0') cmdlist.extend([">", util.shell_quote(archive)]) return (cmdlist, {'shell': True})
[ "def", "create_cpio", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "filenames", ")", ":", "cmdlist", "=", "[", "util", ".", "shell_quote", "(", "cmd", ")", ",", "'--create'", "]", "if", "verbosity", ">", "1",...
Create a CPIO archive.
[ "Create", "a", "CPIO", "archive", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/cpio.py#L44-L56
train
212,941
wummel/patool
patoolib/programs/arc.py
extract_arc
def extract_arc (archive, compression, cmd, verbosity, interactive, outdir): """Extract a ARC archive.""" # Since extracted files will be placed in the current directory, # the cwd argument has to be the output directory. cmdlist = [cmd, 'x', os.path.abspath(archive)] return (cmdlist, {'cwd': outdir})
python
def extract_arc (archive, compression, cmd, verbosity, interactive, outdir): """Extract a ARC archive.""" # Since extracted files will be placed in the current directory, # the cwd argument has to be the output directory. cmdlist = [cmd, 'x', os.path.abspath(archive)] return (cmdlist, {'cwd': outdir})
[ "def", "extract_arc", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "outdir", ")", ":", "# Since extracted files will be placed in the current directory,", "# the cwd argument has to be the output directory.", "cmdlist", "=", "[", ...
Extract a ARC archive.
[ "Extract", "a", "ARC", "archive", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/arc.py#L19-L24
train
212,942
wummel/patool
patoolib/programs/arc.py
list_arc
def list_arc (archive, compression, cmd, verbosity, interactive): """List a ARC archive.""" cmdlist = [cmd] if verbosity > 1: cmdlist.append('v') else: cmdlist.append('l') cmdlist.append(archive) return cmdlist
python
def list_arc (archive, compression, cmd, verbosity, interactive): """List a ARC archive.""" cmdlist = [cmd] if verbosity > 1: cmdlist.append('v') else: cmdlist.append('l') cmdlist.append(archive) return cmdlist
[ "def", "list_arc", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ")", ":", "cmdlist", "=", "[", "cmd", "]", "if", "verbosity", ">", "1", ":", "cmdlist", ".", "append", "(", "'v'", ")", "else", ":", "cmdlist", "...
List a ARC archive.
[ "List", "a", "ARC", "archive", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/arc.py#L26-L34
train
212,943
wummel/patool
patoolib/programs/py_gzip.py
extract_gzip
def extract_gzip (archive, compression, cmd, verbosity, interactive, outdir): """Extract a GZIP archive with the gzip Python module.""" targetname = util.get_single_outfile(outdir, archive) try: with gzip.GzipFile(archive) as gzipfile: with open(targetname, 'wb') as targetfile: data = gzipfile.read(READ_SIZE_BYTES) while data: targetfile.write(data) data = gzipfile.read(READ_SIZE_BYTES) except Exception as err: msg = "error extracting %s to %s: %s" % (archive, targetname, err) raise util.PatoolError(msg) return None
python
def extract_gzip (archive, compression, cmd, verbosity, interactive, outdir): """Extract a GZIP archive with the gzip Python module.""" targetname = util.get_single_outfile(outdir, archive) try: with gzip.GzipFile(archive) as gzipfile: with open(targetname, 'wb') as targetfile: data = gzipfile.read(READ_SIZE_BYTES) while data: targetfile.write(data) data = gzipfile.read(READ_SIZE_BYTES) except Exception as err: msg = "error extracting %s to %s: %s" % (archive, targetname, err) raise util.PatoolError(msg) return None
[ "def", "extract_gzip", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "outdir", ")", ":", "targetname", "=", "util", ".", "get_single_outfile", "(", "outdir", ",", "archive", ")", "try", ":", "with", "gzip", ".",...
Extract a GZIP archive with the gzip Python module.
[ "Extract", "a", "GZIP", "archive", "with", "the", "gzip", "Python", "module", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_gzip.py#L24-L37
train
212,944
wummel/patool
patoolib/programs/py_gzip.py
create_gzip
def create_gzip (archive, compression, cmd, verbosity, interactive, filenames): """Create a GZIP archive with the gzip Python module.""" if len(filenames) > 1: raise util.PatoolError('multi-file compression not supported in Python gzip') try: with gzip.GzipFile(archive, 'wb') as gzipfile: filename = filenames[0] with open(filename, 'rb') as srcfile: data = srcfile.read(READ_SIZE_BYTES) while data: gzipfile.write(data) data = srcfile.read(READ_SIZE_BYTES) except Exception as err: msg = "error creating %s: %s" % (archive, err) raise util.PatoolError(msg) return None
python
def create_gzip (archive, compression, cmd, verbosity, interactive, filenames): """Create a GZIP archive with the gzip Python module.""" if len(filenames) > 1: raise util.PatoolError('multi-file compression not supported in Python gzip') try: with gzip.GzipFile(archive, 'wb') as gzipfile: filename = filenames[0] with open(filename, 'rb') as srcfile: data = srcfile.read(READ_SIZE_BYTES) while data: gzipfile.write(data) data = srcfile.read(READ_SIZE_BYTES) except Exception as err: msg = "error creating %s: %s" % (archive, err) raise util.PatoolError(msg) return None
[ "def", "create_gzip", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "filenames", ")", ":", "if", "len", "(", "filenames", ")", ">", "1", ":", "raise", "util", ".", "PatoolError", "(", "'multi-file compression not ...
Create a GZIP archive with the gzip Python module.
[ "Create", "a", "GZIP", "archive", "with", "the", "gzip", "Python", "module", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_gzip.py#L40-L55
train
212,945
wummel/patool
patoolib/programs/py_lzma.py
_extract
def _extract(archive, compression, cmd, format, verbosity, outdir): """Extract an LZMA or XZ archive with the lzma Python module.""" targetname = util.get_single_outfile(outdir, archive) try: with lzma.LZMAFile(archive, **_get_lzma_options(format)) as lzmafile: with open(targetname, 'wb') as targetfile: data = lzmafile.read(READ_SIZE_BYTES) while data: targetfile.write(data) data = lzmafile.read(READ_SIZE_BYTES) except Exception as err: msg = "error extracting %s to %s: %s" % (archive, targetname, err) raise util.PatoolError(msg) return None
python
def _extract(archive, compression, cmd, format, verbosity, outdir): """Extract an LZMA or XZ archive with the lzma Python module.""" targetname = util.get_single_outfile(outdir, archive) try: with lzma.LZMAFile(archive, **_get_lzma_options(format)) as lzmafile: with open(targetname, 'wb') as targetfile: data = lzmafile.read(READ_SIZE_BYTES) while data: targetfile.write(data) data = lzmafile.read(READ_SIZE_BYTES) except Exception as err: msg = "error extracting %s to %s: %s" % (archive, targetname, err) raise util.PatoolError(msg) return None
[ "def", "_extract", "(", "archive", ",", "compression", ",", "cmd", ",", "format", ",", "verbosity", ",", "outdir", ")", ":", "targetname", "=", "util", ".", "get_single_outfile", "(", "outdir", ",", "archive", ")", "try", ":", "with", "lzma", ".", "LZMAF...
Extract an LZMA or XZ archive with the lzma Python module.
[ "Extract", "an", "LZMA", "or", "XZ", "archive", "with", "the", "lzma", "Python", "module", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_lzma.py#L50-L63
train
212,946
wummel/patool
patoolib/programs/py_lzma.py
extract_lzma
def extract_lzma(archive, compression, cmd, verbosity, interactive, outdir): """Extract an LZMA archive with the lzma Python module.""" return _extract(archive, compression, cmd, 'alone', verbosity, outdir)
python
def extract_lzma(archive, compression, cmd, verbosity, interactive, outdir): """Extract an LZMA archive with the lzma Python module.""" return _extract(archive, compression, cmd, 'alone', verbosity, outdir)
[ "def", "extract_lzma", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "outdir", ")", ":", "return", "_extract", "(", "archive", ",", "compression", ",", "cmd", ",", "'alone'", ",", "verbosity", ",", "outdir", ")"...
Extract an LZMA archive with the lzma Python module.
[ "Extract", "an", "LZMA", "archive", "with", "the", "lzma", "Python", "module", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_lzma.py#L65-L67
train
212,947
wummel/patool
patoolib/programs/py_lzma.py
extract_xz
def extract_xz(archive, compression, cmd, verbosity, interactive, outdir): """Extract an XZ archive with the lzma Python module.""" return _extract(archive, compression, cmd, 'xz', verbosity, outdir)
python
def extract_xz(archive, compression, cmd, verbosity, interactive, outdir): """Extract an XZ archive with the lzma Python module.""" return _extract(archive, compression, cmd, 'xz', verbosity, outdir)
[ "def", "extract_xz", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "outdir", ")", ":", "return", "_extract", "(", "archive", ",", "compression", ",", "cmd", ",", "'xz'", ",", "verbosity", ",", "outdir", ")" ]
Extract an XZ archive with the lzma Python module.
[ "Extract", "an", "XZ", "archive", "with", "the", "lzma", "Python", "module", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_lzma.py#L69-L71
train
212,948
wummel/patool
patoolib/programs/py_lzma.py
_create
def _create(archive, compression, cmd, format, verbosity, filenames): """Create an LZMA or XZ archive with the lzma Python module.""" if len(filenames) > 1: raise util.PatoolError('multi-file compression not supported in Python lzma') try: with lzma.LZMAFile(archive, mode='wb', **_get_lzma_options(format, preset=9)) as lzmafile: filename = filenames[0] with open(filename, 'rb') as srcfile: data = srcfile.read(READ_SIZE_BYTES) while data: lzmafile.write(data) data = srcfile.read(READ_SIZE_BYTES) except Exception as err: msg = "error creating %s: %s" % (archive, err) raise util.PatoolError(msg) return None
python
def _create(archive, compression, cmd, format, verbosity, filenames): """Create an LZMA or XZ archive with the lzma Python module.""" if len(filenames) > 1: raise util.PatoolError('multi-file compression not supported in Python lzma') try: with lzma.LZMAFile(archive, mode='wb', **_get_lzma_options(format, preset=9)) as lzmafile: filename = filenames[0] with open(filename, 'rb') as srcfile: data = srcfile.read(READ_SIZE_BYTES) while data: lzmafile.write(data) data = srcfile.read(READ_SIZE_BYTES) except Exception as err: msg = "error creating %s: %s" % (archive, err) raise util.PatoolError(msg) return None
[ "def", "_create", "(", "archive", ",", "compression", ",", "cmd", ",", "format", ",", "verbosity", ",", "filenames", ")", ":", "if", "len", "(", "filenames", ")", ">", "1", ":", "raise", "util", ".", "PatoolError", "(", "'multi-file compression not supported...
Create an LZMA or XZ archive with the lzma Python module.
[ "Create", "an", "LZMA", "or", "XZ", "archive", "with", "the", "lzma", "Python", "module", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_lzma.py#L74-L89
train
212,949
wummel/patool
patoolib/programs/py_lzma.py
create_lzma
def create_lzma(archive, compression, cmd, verbosity, interactive, filenames): """Create an LZMA archive with the lzma Python module.""" return _create(archive, compression, cmd, 'alone', verbosity, filenames)
python
def create_lzma(archive, compression, cmd, verbosity, interactive, filenames): """Create an LZMA archive with the lzma Python module.""" return _create(archive, compression, cmd, 'alone', verbosity, filenames)
[ "def", "create_lzma", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "filenames", ")", ":", "return", "_create", "(", "archive", ",", "compression", ",", "cmd", ",", "'alone'", ",", "verbosity", ",", "filenames", ...
Create an LZMA archive with the lzma Python module.
[ "Create", "an", "LZMA", "archive", "with", "the", "lzma", "Python", "module", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_lzma.py#L91-L93
train
212,950
wummel/patool
patoolib/programs/py_lzma.py
create_xz
def create_xz(archive, compression, cmd, verbosity, interactive, filenames): """Create an XZ archive with the lzma Python module.""" return _create(archive, compression, cmd, 'xz', verbosity, filenames)
python
def create_xz(archive, compression, cmd, verbosity, interactive, filenames): """Create an XZ archive with the lzma Python module.""" return _create(archive, compression, cmd, 'xz', verbosity, filenames)
[ "def", "create_xz", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "filenames", ")", ":", "return", "_create", "(", "archive", ",", "compression", ",", "cmd", ",", "'xz'", ",", "verbosity", ",", "filenames", ")" ...
Create an XZ archive with the lzma Python module.
[ "Create", "an", "XZ", "archive", "with", "the", "lzma", "Python", "module", "." ]
d7e64d9fd60faaa4b3f824bd97c43ce59b185c40
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_lzma.py#L95-L97
train
212,951
Tivix/django-common
django_common/decorators.py
ssl_required
def ssl_required(allow_non_ssl=False): """ Views decorated with this will always get redirected to https except when allow_non_ssl is set to true. """ def wrapper(view_func): def _checkssl(request, *args, **kwargs): # allow_non_ssl=True lets non-https requests to come # through to this view (and hence not redirect) if hasattr(settings, 'SSL_ENABLED') and settings.SSL_ENABLED \ and not request.is_secure() and not allow_non_ssl: return HttpResponseRedirect( request.build_absolute_uri().replace('http://', 'https://')) return view_func(request, *args, **kwargs) return _checkssl return wrapper
python
def ssl_required(allow_non_ssl=False): """ Views decorated with this will always get redirected to https except when allow_non_ssl is set to true. """ def wrapper(view_func): def _checkssl(request, *args, **kwargs): # allow_non_ssl=True lets non-https requests to come # through to this view (and hence not redirect) if hasattr(settings, 'SSL_ENABLED') and settings.SSL_ENABLED \ and not request.is_secure() and not allow_non_ssl: return HttpResponseRedirect( request.build_absolute_uri().replace('http://', 'https://')) return view_func(request, *args, **kwargs) return _checkssl return wrapper
[ "def", "ssl_required", "(", "allow_non_ssl", "=", "False", ")", ":", "def", "wrapper", "(", "view_func", ")", ":", "def", "_checkssl", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# allow_non_ssl=True lets non-https requests to come", ...
Views decorated with this will always get redirected to https except when allow_non_ssl is set to true.
[ "Views", "decorated", "with", "this", "will", "always", "get", "redirected", "to", "https", "except", "when", "allow_non_ssl", "is", "set", "to", "true", "." ]
407d208121011a8425139e541629554114d96c18
https://github.com/Tivix/django-common/blob/407d208121011a8425139e541629554114d96c18/django_common/decorators.py#L14-L30
train
212,952
Tivix/django-common
django_common/decorators.py
anonymous_required
def anonymous_required(view, redirect_to=None): """ Only allow if user is NOT authenticated. """ if redirect_to is None: redirect_to = settings.LOGIN_REDIRECT_URL @wraps(view) def wrapper(request, *a, **k): if request.user and request.user.is_authenticated(): return HttpResponseRedirect(redirect_to) return view(request, *a, **k) return wrapper
python
def anonymous_required(view, redirect_to=None): """ Only allow if user is NOT authenticated. """ if redirect_to is None: redirect_to = settings.LOGIN_REDIRECT_URL @wraps(view) def wrapper(request, *a, **k): if request.user and request.user.is_authenticated(): return HttpResponseRedirect(redirect_to) return view(request, *a, **k) return wrapper
[ "def", "anonymous_required", "(", "view", ",", "redirect_to", "=", "None", ")", ":", "if", "redirect_to", "is", "None", ":", "redirect_to", "=", "settings", ".", "LOGIN_REDIRECT_URL", "@", "wraps", "(", "view", ")", "def", "wrapper", "(", "request", ",", "...
Only allow if user is NOT authenticated.
[ "Only", "allow", "if", "user", "is", "NOT", "authenticated", "." ]
407d208121011a8425139e541629554114d96c18
https://github.com/Tivix/django-common/blob/407d208121011a8425139e541629554114d96c18/django_common/decorators.py#L47-L59
train
212,953
Tivix/django-common
django_common/session.py
SessionManager.generic_var
def generic_var(self, key, value=None): """ Stores generic variables in the session prepending it with _GENERIC_VAR_KEY_PREFIX. """ return self._get_or_set('{0}{1}'.format(self._GENERIC_VAR_KEY_PREFIX, key), value)
python
def generic_var(self, key, value=None): """ Stores generic variables in the session prepending it with _GENERIC_VAR_KEY_PREFIX. """ return self._get_or_set('{0}{1}'.format(self._GENERIC_VAR_KEY_PREFIX, key), value)
[ "def", "generic_var", "(", "self", ",", "key", ",", "value", "=", "None", ")", ":", "return", "self", ".", "_get_or_set", "(", "'{0}{1}'", ".", "format", "(", "self", ".", "_GENERIC_VAR_KEY_PREFIX", ",", "key", ")", ",", "value", ")" ]
Stores generic variables in the session prepending it with _GENERIC_VAR_KEY_PREFIX.
[ "Stores", "generic", "variables", "in", "the", "session", "prepending", "it", "with", "_GENERIC_VAR_KEY_PREFIX", "." ]
407d208121011a8425139e541629554114d96c18
https://github.com/Tivix/django-common/blob/407d208121011a8425139e541629554114d96c18/django_common/session.py#L79-L83
train
212,954
Tivix/django-common
django_common/auth_backends.py
EmailBackend.authenticate
def authenticate(self, username=None, password=None, **kwargs): """ "username" being passed is really email address and being compared to as such. """ try: user = User.objects.get(email=username) if user.check_password(password): return user except (User.DoesNotExist, User.MultipleObjectsReturned): logging.warning('Unsuccessful login attempt using username/email: {0}'.format(username)) return None
python
def authenticate(self, username=None, password=None, **kwargs): """ "username" being passed is really email address and being compared to as such. """ try: user = User.objects.get(email=username) if user.check_password(password): return user except (User.DoesNotExist, User.MultipleObjectsReturned): logging.warning('Unsuccessful login attempt using username/email: {0}'.format(username)) return None
[ "def", "authenticate", "(", "self", ",", "username", "=", "None", ",", "password", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "email", "=", "username", ")", "if", "user", ".", ...
"username" being passed is really email address and being compared to as such.
[ "username", "being", "passed", "is", "really", "email", "address", "and", "being", "compared", "to", "as", "such", "." ]
407d208121011a8425139e541629554114d96c18
https://github.com/Tivix/django-common/blob/407d208121011a8425139e541629554114d96c18/django_common/auth_backends.py#L12-L23
train
212,955
Tivix/django-common
django_common/management/commands/generate_secret_key.py
Command.add_arguments
def add_arguments(self, parser): """ Define optional arguments with default values """ parser.add_argument('--length', default=self.length, type=int, help=_('SECRET_KEY length default=%d' % self.length)) parser.add_argument('--alphabet', default=self.allowed_chars, type=str, help=_('alphabet to use default=%s' % self.allowed_chars))
python
def add_arguments(self, parser): """ Define optional arguments with default values """ parser.add_argument('--length', default=self.length, type=int, help=_('SECRET_KEY length default=%d' % self.length)) parser.add_argument('--alphabet', default=self.allowed_chars, type=str, help=_('alphabet to use default=%s' % self.allowed_chars))
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "parser", ".", "add_argument", "(", "'--length'", ",", "default", "=", "self", ".", "length", ",", "type", "=", "int", ",", "help", "=", "_", "(", "'SECRET_KEY length default=%d'", "%", "self", ...
Define optional arguments with default values
[ "Define", "optional", "arguments", "with", "default", "values" ]
407d208121011a8425139e541629554114d96c18
https://github.com/Tivix/django-common/blob/407d208121011a8425139e541629554114d96c18/django_common/management/commands/generate_secret_key.py#L19-L27
train
212,956
Tivix/django-common
django_common/helper.py
send_mail
def send_mail(subject, message, from_email, recipient_emails, files=None, html=False, reply_to=None, bcc=None, cc=None, files_manually=None): """ Sends email with advanced optional parameters To attach non-file content (e.g. content not saved on disk), use files_manually parameter and provide list of 3 element tuples, e.g. [('design.png', img_data, 'image/png'),] which will be passed to email.attach(). """ import django.core.mail try: logging.debug('Sending mail to: {0}'.format(', '.join(r for r in recipient_emails))) logging.debug('Message: {0}'.format(message)) email = django.core.mail.EmailMessage(subject, message, from_email, recipient_emails, bcc, cc=cc) if html: email.content_subtype = "html" if files: for file in files: email.attach_file(file) if files_manually: for filename, content, mimetype in files_manually: email.attach(filename, content, mimetype) if reply_to: email.extra_headers = {'Reply-To': reply_to} email.send() except Exception as e: # TODO: Raise error again so that more information is included in the logs? logging.error('Error sending message [{0}] from {1} to {2} {3}'.format( subject, from_email, recipient_emails, e))
python
def send_mail(subject, message, from_email, recipient_emails, files=None, html=False, reply_to=None, bcc=None, cc=None, files_manually=None): """ Sends email with advanced optional parameters To attach non-file content (e.g. content not saved on disk), use files_manually parameter and provide list of 3 element tuples, e.g. [('design.png', img_data, 'image/png'),] which will be passed to email.attach(). """ import django.core.mail try: logging.debug('Sending mail to: {0}'.format(', '.join(r for r in recipient_emails))) logging.debug('Message: {0}'.format(message)) email = django.core.mail.EmailMessage(subject, message, from_email, recipient_emails, bcc, cc=cc) if html: email.content_subtype = "html" if files: for file in files: email.attach_file(file) if files_manually: for filename, content, mimetype in files_manually: email.attach(filename, content, mimetype) if reply_to: email.extra_headers = {'Reply-To': reply_to} email.send() except Exception as e: # TODO: Raise error again so that more information is included in the logs? logging.error('Error sending message [{0}] from {1} to {2} {3}'.format( subject, from_email, recipient_emails, e))
[ "def", "send_mail", "(", "subject", ",", "message", ",", "from_email", ",", "recipient_emails", ",", "files", "=", "None", ",", "html", "=", "False", ",", "reply_to", "=", "None", ",", "bcc", "=", "None", ",", "cc", "=", "None", ",", "files_manually", ...
Sends email with advanced optional parameters To attach non-file content (e.g. content not saved on disk), use files_manually parameter and provide list of 3 element tuples, e.g. [('design.png', img_data, 'image/png'),] which will be passed to email.attach().
[ "Sends", "email", "with", "advanced", "optional", "parameters" ]
407d208121011a8425139e541629554114d96c18
https://github.com/Tivix/django-common/blob/407d208121011a8425139e541629554114d96c18/django_common/helper.py#L124-L154
train
212,957
Tivix/django-common
django_common/classmaker.py
skip_redundant
def skip_redundant(iterable, skipset=None): """ Redundant items are repeated items or items in the original skipset. """ if skipset is None: skipset = set() for item in iterable: if item not in skipset: skipset.add(item) yield item
python
def skip_redundant(iterable, skipset=None): """ Redundant items are repeated items or items in the original skipset. """ if skipset is None: skipset = set() for item in iterable: if item not in skipset: skipset.add(item) yield item
[ "def", "skip_redundant", "(", "iterable", ",", "skipset", "=", "None", ")", ":", "if", "skipset", "is", "None", ":", "skipset", "=", "set", "(", ")", "for", "item", "in", "iterable", ":", "if", "item", "not", "in", "skipset", ":", "skipset", ".", "ad...
Redundant items are repeated items or items in the original skipset.
[ "Redundant", "items", "are", "repeated", "items", "or", "items", "in", "the", "original", "skipset", "." ]
407d208121011a8425139e541629554114d96c18
https://github.com/Tivix/django-common/blob/407d208121011a8425139e541629554114d96c18/django_common/classmaker.py#L10-L19
train
212,958
Tivix/django-common
django_common/classmaker.py
get_noconflict_metaclass
def get_noconflict_metaclass(bases, left_metas, right_metas): """ Not intended to be used outside of this module, unless you know what you are doing. """ # make tuple of needed metaclasses in specified priority order metas = left_metas + tuple(map(type, bases)) + right_metas needed_metas = remove_redundant(metas) # return existing confict-solving meta, if any if needed_metas in memoized_metaclasses_map: return memoized_metaclasses_map[needed_metas] # nope: compute, memoize and return needed conflict-solving meta elif not needed_metas: # wee, a trivial case, happy us meta = type elif len(needed_metas) == 1: # another trivial case meta = needed_metas[0] # check for recursion, can happen i.e. for Zope ExtensionClasses elif needed_metas == bases: raise TypeError("Incompatible root metatypes", needed_metas) else: # gotta work ... metaname = '_' + ''.join([m.__name__ for m in needed_metas]) meta = classmaker()(metaname, needed_metas, {}) memoized_metaclasses_map[needed_metas] = meta return meta
python
def get_noconflict_metaclass(bases, left_metas, right_metas): """ Not intended to be used outside of this module, unless you know what you are doing. """ # make tuple of needed metaclasses in specified priority order metas = left_metas + tuple(map(type, bases)) + right_metas needed_metas = remove_redundant(metas) # return existing confict-solving meta, if any if needed_metas in memoized_metaclasses_map: return memoized_metaclasses_map[needed_metas] # nope: compute, memoize and return needed conflict-solving meta elif not needed_metas: # wee, a trivial case, happy us meta = type elif len(needed_metas) == 1: # another trivial case meta = needed_metas[0] # check for recursion, can happen i.e. for Zope ExtensionClasses elif needed_metas == bases: raise TypeError("Incompatible root metatypes", needed_metas) else: # gotta work ... metaname = '_' + ''.join([m.__name__ for m in needed_metas]) meta = classmaker()(metaname, needed_metas, {}) memoized_metaclasses_map[needed_metas] = meta return meta
[ "def", "get_noconflict_metaclass", "(", "bases", ",", "left_metas", ",", "right_metas", ")", ":", "# make tuple of needed metaclasses in specified priority order", "metas", "=", "left_metas", "+", "tuple", "(", "map", "(", "type", ",", "bases", ")", ")", "+", "right...
Not intended to be used outside of this module, unless you know what you are doing.
[ "Not", "intended", "to", "be", "used", "outside", "of", "this", "module", "unless", "you", "know", "what", "you", "are", "doing", "." ]
407d208121011a8425139e541629554114d96c18
https://github.com/Tivix/django-common/blob/407d208121011a8425139e541629554114d96c18/django_common/classmaker.py#L34-L57
train
212,959
voronind/vk
vk/session.py
APIBase.on_api_error_14
def on_api_error_14(self, request): """ 14. Captcha needed """ request.method_params['captcha_key'] = self.get_captcha_key(request) request.method_params['captcha_sid'] = request.api_error.captcha_sid return self.send(request)
python
def on_api_error_14(self, request): """ 14. Captcha needed """ request.method_params['captcha_key'] = self.get_captcha_key(request) request.method_params['captcha_sid'] = request.api_error.captcha_sid return self.send(request)
[ "def", "on_api_error_14", "(", "self", ",", "request", ")", ":", "request", ".", "method_params", "[", "'captcha_key'", "]", "=", "self", ".", "get_captcha_key", "(", "request", ")", "request", ".", "method_params", "[", "'captcha_sid'", "]", "=", "request", ...
14. Captcha needed
[ "14", ".", "Captcha", "needed" ]
37f41c7634f67149d4dab8017be0adca5ea3dc24
https://github.com/voronind/vk/blob/37f41c7634f67149d4dab8017be0adca5ea3dc24/vk/session.py#L77-L84
train
212,960
voronind/vk
vk/session.py
APIBase.on_api_error_15
def on_api_error_15(self, request): """ 15. Access denied - due to scope """ logger.error('Authorization failed. Access token will be dropped') self.access_token = self.get_access_token() return self.send(request)
python
def on_api_error_15(self, request): """ 15. Access denied - due to scope """ logger.error('Authorization failed. Access token will be dropped') self.access_token = self.get_access_token() return self.send(request)
[ "def", "on_api_error_15", "(", "self", ",", "request", ")", ":", "logger", ".", "error", "(", "'Authorization failed. Access token will be dropped'", ")", "self", ".", "access_token", "=", "self", ".", "get_access_token", "(", ")", "return", "self", ".", "send", ...
15. Access denied - due to scope
[ "15", ".", "Access", "denied", "-", "due", "to", "scope" ]
37f41c7634f67149d4dab8017be0adca5ea3dc24
https://github.com/voronind/vk/blob/37f41c7634f67149d4dab8017be0adca5ea3dc24/vk/session.py#L86-L93
train
212,961
skoczen/will
will/backends/pubsub/base.py
PubSubPrivateBase.get_message
def get_message(self): """ Gets the latest object from the backend, and handles unpickling and validation. """ try: m = self.get_from_backend() if m and m["type"] not in SKIP_TYPES: return self.decrypt(m["data"]) except AttributeError: raise Exception("Tried to call get message without having subscribed first!") except (KeyboardInterrupt, SystemExit): pass except: logging.critical("Error in watching pubsub get message: \n%s" % traceback.format_exc()) return None
python
def get_message(self): """ Gets the latest object from the backend, and handles unpickling and validation. """ try: m = self.get_from_backend() if m and m["type"] not in SKIP_TYPES: return self.decrypt(m["data"]) except AttributeError: raise Exception("Tried to call get message without having subscribed first!") except (KeyboardInterrupt, SystemExit): pass except: logging.critical("Error in watching pubsub get message: \n%s" % traceback.format_exc()) return None
[ "def", "get_message", "(", "self", ")", ":", "try", ":", "m", "=", "self", ".", "get_from_backend", "(", ")", "if", "m", "and", "m", "[", "\"type\"", "]", "not", "in", "SKIP_TYPES", ":", "return", "self", ".", "decrypt", "(", "m", "[", "\"data\"", ...
Gets the latest object from the backend, and handles unpickling and validation.
[ "Gets", "the", "latest", "object", "from", "the", "backend", "and", "handles", "unpickling", "and", "validation", "." ]
778a6a78571e3ae4656b307f9e5d4d184b25627d
https://github.com/skoczen/will/blob/778a6a78571e3ae4656b307f9e5d4d184b25627d/will/backends/pubsub/base.py#L72-L88
train
212,962
akamai/AkamaiOPEN-edgegrid-python
akamai/edgegrid/edgegrid.py
EdgeGridAuth.from_edgerc
def from_edgerc(rcinput, section='default'): """Returns an EdgeGridAuth object from the configuration from the given section of the given edgerc file. :param filename: path to the edgerc file :param section: the section to use (this is the [bracketed] part of the edgerc, default is 'default') """ from .edgerc import EdgeRc if isinstance(rcinput, EdgeRc): rc = rcinput else: rc = EdgeRc(rcinput) return EdgeGridAuth( client_token=rc.get(section, 'client_token'), client_secret=rc.get(section, 'client_secret'), access_token=rc.get(section, 'access_token'), headers_to_sign=rc.getlist(section, 'headers_to_sign'), max_body=rc.getint(section, 'max_body') )
python
def from_edgerc(rcinput, section='default'): """Returns an EdgeGridAuth object from the configuration from the given section of the given edgerc file. :param filename: path to the edgerc file :param section: the section to use (this is the [bracketed] part of the edgerc, default is 'default') """ from .edgerc import EdgeRc if isinstance(rcinput, EdgeRc): rc = rcinput else: rc = EdgeRc(rcinput) return EdgeGridAuth( client_token=rc.get(section, 'client_token'), client_secret=rc.get(section, 'client_secret'), access_token=rc.get(section, 'access_token'), headers_to_sign=rc.getlist(section, 'headers_to_sign'), max_body=rc.getint(section, 'max_body') )
[ "def", "from_edgerc", "(", "rcinput", ",", "section", "=", "'default'", ")", ":", "from", ".", "edgerc", "import", "EdgeRc", "if", "isinstance", "(", "rcinput", ",", "EdgeRc", ")", ":", "rc", "=", "rcinput", "else", ":", "rc", "=", "EdgeRc", "(", "rcin...
Returns an EdgeGridAuth object from the configuration from the given section of the given edgerc file. :param filename: path to the edgerc file :param section: the section to use (this is the [bracketed] part of the edgerc, default is 'default')
[ "Returns", "an", "EdgeGridAuth", "object", "from", "the", "configuration", "from", "the", "given", "section", "of", "the", "given", "edgerc", "file", "." ]
62cd91e64439e503d3743e6aeec3953da610ca3f
https://github.com/akamai/AkamaiOPEN-edgegrid-python/blob/62cd91e64439e503d3743e6aeec3953da610ca3f/akamai/edgegrid/edgegrid.py#L105-L126
train
212,963
akamai/AkamaiOPEN-edgegrid-python
akamai/edgegrid/edgerc.py
EdgeRc.getlist
def getlist(self, section, option): """ returns the named option as a list, splitting the original value by ',' """ value = self.get(section, option) if value: return value.split(',') else: return None
python
def getlist(self, section, option): """ returns the named option as a list, splitting the original value by ',' """ value = self.get(section, option) if value: return value.split(',') else: return None
[ "def", "getlist", "(", "self", ",", "section", ",", "option", ")", ":", "value", "=", "self", ".", "get", "(", "section", ",", "option", ")", "if", "value", ":", "return", "value", ".", "split", "(", "','", ")", "else", ":", "return", "None" ]
returns the named option as a list, splitting the original value by ','
[ "returns", "the", "named", "option", "as", "a", "list", "splitting", "the", "original", "value", "by" ]
62cd91e64439e503d3743e6aeec3953da610ca3f
https://github.com/akamai/AkamaiOPEN-edgegrid-python/blob/62cd91e64439e503d3743e6aeec3953da610ca3f/akamai/edgegrid/edgerc.py#L45-L54
train
212,964
toomore/grs
grs/realtime.py
RealtimeWeight.real
def real(self): ''' Get realtime data :rtype: dict :returns: 代碼可以參考:http://goristock.appspot.com/API#apiweight ''' result = self.__raw['1'].copy() result['c'] = self.__raw['1']['value'] result['value'] = self.__raw['200']['v2'] result['date'] = self.__raw['0']['time'] return result
python
def real(self): ''' Get realtime data :rtype: dict :returns: 代碼可以參考:http://goristock.appspot.com/API#apiweight ''' result = self.__raw['1'].copy() result['c'] = self.__raw['1']['value'] result['value'] = self.__raw['200']['v2'] result['date'] = self.__raw['0']['time'] return result
[ "def", "real", "(", "self", ")", ":", "result", "=", "self", ".", "__raw", "[", "'1'", "]", ".", "copy", "(", ")", "result", "[", "'c'", "]", "=", "self", ".", "__raw", "[", "'1'", "]", "[", "'value'", "]", "result", "[", "'value'", "]", "=", ...
Get realtime data :rtype: dict :returns: 代碼可以參考:http://goristock.appspot.com/API#apiweight
[ "Get", "realtime", "data" ]
a1285cb57878284a886952968be9e31fbfa595dd
https://github.com/toomore/grs/blob/a1285cb57878284a886952968be9e31fbfa595dd/grs/realtime.py#L194-L204
train
212,965
toomore/grs
grs/twseno.py
ImportCSV.importcsv
def importcsv(self): ''' import data from csv ''' csv_path = os.path.join(os.path.dirname(__file__), self.stock_no_files) with open(csv_path) as csv_file: csv_data = csv.reader(csv_file) result = {} for i in csv_data: try: result[i[0]] = str(i[1]).decode('utf-8') except ValueError: if i[0] == 'UPDATE': self.last_update = str(i[1]).decode('utf-8') else: pass return result
python
def importcsv(self): ''' import data from csv ''' csv_path = os.path.join(os.path.dirname(__file__), self.stock_no_files) with open(csv_path) as csv_file: csv_data = csv.reader(csv_file) result = {} for i in csv_data: try: result[i[0]] = str(i[1]).decode('utf-8') except ValueError: if i[0] == 'UPDATE': self.last_update = str(i[1]).decode('utf-8') else: pass return result
[ "def", "importcsv", "(", "self", ")", ":", "csv_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "self", ".", "stock_no_files", ")", "with", "open", "(", "csv_path", ")", "as", "csv_file",...
import data from csv
[ "import", "data", "from", "csv" ]
a1285cb57878284a886952968be9e31fbfa595dd
https://github.com/toomore/grs/blob/a1285cb57878284a886952968be9e31fbfa595dd/grs/twseno.py#L39-L53
train
212,966
toomore/grs
grs/twseno.py
ImportCSV.__loadindcomps
def __loadindcomps(self): ''' import industry comps ''' csv_path = os.path.join(os.path.dirname(__file__), self.stock_no_files) with open(csv_path) as csv_file: csv_data = csv.reader(csv_file) result = {} check_words = re.compile(r'^[\d]{2,}[\w]?') for i in csv_data: if check_words.match(i[2]): try: result[i[2]].append(i[0].decode('utf-8')) except (ValueError, KeyError): try: result[i[2]] = [i[0].decode('utf-8')] except KeyError: pass return result
python
def __loadindcomps(self): ''' import industry comps ''' csv_path = os.path.join(os.path.dirname(__file__), self.stock_no_files) with open(csv_path) as csv_file: csv_data = csv.reader(csv_file) result = {} check_words = re.compile(r'^[\d]{2,}[\w]?') for i in csv_data: if check_words.match(i[2]): try: result[i[2]].append(i[0].decode('utf-8')) except (ValueError, KeyError): try: result[i[2]] = [i[0].decode('utf-8')] except KeyError: pass return result
[ "def", "__loadindcomps", "(", "self", ")", ":", "csv_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "self", ".", "stock_no_files", ")", "with", "open", "(", "csv_path", ")", "as", "csv_f...
import industry comps
[ "import", "industry", "comps" ]
a1285cb57878284a886952968be9e31fbfa595dd
https://github.com/toomore/grs/blob/a1285cb57878284a886952968be9e31fbfa595dd/grs/twseno.py#L66-L82
train
212,967
toomore/grs
grs/twseopen.py
TWSEOpen.caldata
def caldata(self, time): ''' Market open or not. :param datetime time: 欲判斷的日期 :rtype: bool :returns: True 為開市、False 為休市 ''' if time.date() in self.__ocdate['close']: # 判對是否為法定休市 return False elif time.date() in self.__ocdate['open']: # 判對是否為法定開市 return True else: if time.weekday() <= 4: # 判斷是否為平常日開市 return True else: return False
python
def caldata(self, time): ''' Market open or not. :param datetime time: 欲判斷的日期 :rtype: bool :returns: True 為開市、False 為休市 ''' if time.date() in self.__ocdate['close']: # 判對是否為法定休市 return False elif time.date() in self.__ocdate['open']: # 判對是否為法定開市 return True else: if time.weekday() <= 4: # 判斷是否為平常日開市 return True else: return False
[ "def", "caldata", "(", "self", ",", "time", ")", ":", "if", "time", ".", "date", "(", ")", "in", "self", ".", "__ocdate", "[", "'close'", "]", ":", "# 判對是否為法定休市", "return", "False", "elif", "time", ".", "date", "(", ")", "in", "self", ".", "__ocdat...
Market open or not. :param datetime time: 欲判斷的日期 :rtype: bool :returns: True 為開市、False 為休市
[ "Market", "open", "or", "not", "." ]
a1285cb57878284a886952968be9e31fbfa595dd
https://github.com/toomore/grs/blob/a1285cb57878284a886952968be9e31fbfa595dd/grs/twseopen.py#L73-L88
train
212,968
box/flaky
flaky/flaky_decorator.py
flaky
def flaky(max_runs=None, min_passes=None, rerun_filter=None): """ Decorator used to mark a test as "flaky". When used in conjuction with the flaky nosetests plugin, will cause the decorated test to be retried until min_passes successes are achieved out of up to max_runs test runs. :param max_runs: The maximum number of times the decorated test will be run. :type max_runs: `int` :param min_passes: The minimum number of times the test must pass to be a success. :type min_passes: `int` :param rerun_filter: Filter function to decide whether a test should be rerun if it fails. Function signature is as follows: (err, name, test, plugin) -> should_rerun - err (`tuple` of `class`, :class:`Exception`, `traceback`): Information about the test failure (from sys.exc_info()) - name (`unicode`): The test name - test (:class:`nose.case.Test` or :class:`Function`): The test that has raised an error - plugin (:class:`FlakyNosePlugin` or :class:`FlakyPytestPlugin`): The flaky plugin. Has a :prop:`stream` that can be written to in order to add to the Flaky Report. :type rerun_filter: `callable` :return: A wrapper function that includes attributes describing the flaky test. :rtype: `callable` """ # In case @flaky is applied to a function or class without arguments # (and without parentheses), max_runs will refer to the wrapped object. # In this case, the default value can be used. wrapped = None if hasattr(max_runs, '__call__'): wrapped, max_runs = max_runs, None attrib = default_flaky_attributes(max_runs, min_passes, rerun_filter) def wrapper(wrapped_object): for name, value in attrib.items(): setattr(wrapped_object, name, value) return wrapped_object return wrapper(wrapped) if wrapped is not None else wrapper
python
def flaky(max_runs=None, min_passes=None, rerun_filter=None): """ Decorator used to mark a test as "flaky". When used in conjuction with the flaky nosetests plugin, will cause the decorated test to be retried until min_passes successes are achieved out of up to max_runs test runs. :param max_runs: The maximum number of times the decorated test will be run. :type max_runs: `int` :param min_passes: The minimum number of times the test must pass to be a success. :type min_passes: `int` :param rerun_filter: Filter function to decide whether a test should be rerun if it fails. Function signature is as follows: (err, name, test, plugin) -> should_rerun - err (`tuple` of `class`, :class:`Exception`, `traceback`): Information about the test failure (from sys.exc_info()) - name (`unicode`): The test name - test (:class:`nose.case.Test` or :class:`Function`): The test that has raised an error - plugin (:class:`FlakyNosePlugin` or :class:`FlakyPytestPlugin`): The flaky plugin. Has a :prop:`stream` that can be written to in order to add to the Flaky Report. :type rerun_filter: `callable` :return: A wrapper function that includes attributes describing the flaky test. :rtype: `callable` """ # In case @flaky is applied to a function or class without arguments # (and without parentheses), max_runs will refer to the wrapped object. # In this case, the default value can be used. wrapped = None if hasattr(max_runs, '__call__'): wrapped, max_runs = max_runs, None attrib = default_flaky_attributes(max_runs, min_passes, rerun_filter) def wrapper(wrapped_object): for name, value in attrib.items(): setattr(wrapped_object, name, value) return wrapped_object return wrapper(wrapped) if wrapped is not None else wrapper
[ "def", "flaky", "(", "max_runs", "=", "None", ",", "min_passes", "=", "None", ",", "rerun_filter", "=", "None", ")", ":", "# In case @flaky is applied to a function or class without arguments", "# (and without parentheses), max_runs will refer to the wrapped object.", "# In this ...
Decorator used to mark a test as "flaky". When used in conjuction with the flaky nosetests plugin, will cause the decorated test to be retried until min_passes successes are achieved out of up to max_runs test runs. :param max_runs: The maximum number of times the decorated test will be run. :type max_runs: `int` :param min_passes: The minimum number of times the test must pass to be a success. :type min_passes: `int` :param rerun_filter: Filter function to decide whether a test should be rerun if it fails. Function signature is as follows: (err, name, test, plugin) -> should_rerun - err (`tuple` of `class`, :class:`Exception`, `traceback`): Information about the test failure (from sys.exc_info()) - name (`unicode`): The test name - test (:class:`nose.case.Test` or :class:`Function`): The test that has raised an error - plugin (:class:`FlakyNosePlugin` or :class:`FlakyPytestPlugin`): The flaky plugin. Has a :prop:`stream` that can be written to in order to add to the Flaky Report. :type rerun_filter: `callable` :return: A wrapper function that includes attributes describing the flaky test. :rtype: `callable`
[ "Decorator", "used", "to", "mark", "a", "test", "as", "flaky", ".", "When", "used", "in", "conjuction", "with", "the", "flaky", "nosetests", "plugin", "will", "cause", "the", "decorated", "test", "to", "be", "retried", "until", "min_passes", "successes", "ar...
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_decorator.py#L8-L56
train
212,969
box/flaky
flaky/flaky_nose_plugin.py
FlakyPlugin.options
def options(self, parser, env=os.environ): """ Base class override. Add options to the nose argument parser. """ # pylint:disable=dangerous-default-value super(FlakyPlugin, self).options(parser, env=env) self.add_report_option(parser.add_option) group = OptionGroup( parser, "Force flaky", "Force all tests to be flaky.") self.add_force_flaky_options(group.add_option) parser.add_option_group(group)
python
def options(self, parser, env=os.environ): """ Base class override. Add options to the nose argument parser. """ # pylint:disable=dangerous-default-value super(FlakyPlugin, self).options(parser, env=env) self.add_report_option(parser.add_option) group = OptionGroup( parser, "Force flaky", "Force all tests to be flaky.") self.add_force_flaky_options(group.add_option) parser.add_option_group(group)
[ "def", "options", "(", "self", ",", "parser", ",", "env", "=", "os", ".", "environ", ")", ":", "# pylint:disable=dangerous-default-value", "super", "(", "FlakyPlugin", ",", "self", ")", ".", "options", "(", "parser", ",", "env", "=", "env", ")", "self", ...
Base class override. Add options to the nose argument parser.
[ "Base", "class", "override", ".", "Add", "options", "to", "the", "nose", "argument", "parser", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_nose_plugin.py#L35-L46
train
212,970
box/flaky
flaky/flaky_nose_plugin.py
FlakyPlugin._get_stream
def _get_stream(self, multiprocess=False): """ Get the stream used to store the flaky report. If this nose run is going to use the multiprocess plugin, then use a multiprocess-list backed StringIO proxy; otherwise, use the default stream. :param multiprocess: Whether or not this test run is configured for multiprocessing. :type multiprocess: `bool` :return: The stream to use for storing the flaky report. :rtype: :class:`StringIO` or :class:`MultiprocessingStringIO` """ if multiprocess: from flaky.multiprocess_string_io import MultiprocessingStringIO return MultiprocessingStringIO() return self._stream
python
def _get_stream(self, multiprocess=False): """ Get the stream used to store the flaky report. If this nose run is going to use the multiprocess plugin, then use a multiprocess-list backed StringIO proxy; otherwise, use the default stream. :param multiprocess: Whether or not this test run is configured for multiprocessing. :type multiprocess: `bool` :return: The stream to use for storing the flaky report. :rtype: :class:`StringIO` or :class:`MultiprocessingStringIO` """ if multiprocess: from flaky.multiprocess_string_io import MultiprocessingStringIO return MultiprocessingStringIO() return self._stream
[ "def", "_get_stream", "(", "self", ",", "multiprocess", "=", "False", ")", ":", "if", "multiprocess", ":", "from", "flaky", ".", "multiprocess_string_io", "import", "MultiprocessingStringIO", "return", "MultiprocessingStringIO", "(", ")", "return", "self", ".", "_...
Get the stream used to store the flaky report. If this nose run is going to use the multiprocess plugin, then use a multiprocess-list backed StringIO proxy; otherwise, use the default stream. :param multiprocess: Whether or not this test run is configured for multiprocessing. :type multiprocess: `bool` :return: The stream to use for storing the flaky report. :rtype: :class:`StringIO` or :class:`MultiprocessingStringIO`
[ "Get", "the", "stream", "used", "to", "store", "the", "flaky", "report", ".", "If", "this", "nose", "run", "is", "going", "to", "use", "the", "multiprocess", "plugin", "then", "use", "a", "multiprocess", "-", "list", "backed", "StringIO", "proxy", ";", "...
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_nose_plugin.py#L48-L67
train
212,971
box/flaky
flaky/flaky_nose_plugin.py
FlakyPlugin.configure
def configure(self, options, conf): """Base class override.""" super(FlakyPlugin, self).configure(options, conf) if not self.enabled: return is_multiprocess = int(getattr(options, 'multiprocess_workers', 0)) > 0 self._stream = self._get_stream(is_multiprocess) self._flaky_result = TextTestResult(self._stream, [], 0) self._flaky_report = options.flaky_report self._flaky_success_report = options.flaky_success_report self._force_flaky = options.force_flaky self._max_runs = options.max_runs self._min_passes = options.min_passes
python
def configure(self, options, conf): """Base class override.""" super(FlakyPlugin, self).configure(options, conf) if not self.enabled: return is_multiprocess = int(getattr(options, 'multiprocess_workers', 0)) > 0 self._stream = self._get_stream(is_multiprocess) self._flaky_result = TextTestResult(self._stream, [], 0) self._flaky_report = options.flaky_report self._flaky_success_report = options.flaky_success_report self._force_flaky = options.force_flaky self._max_runs = options.max_runs self._min_passes = options.min_passes
[ "def", "configure", "(", "self", ",", "options", ",", "conf", ")", ":", "super", "(", "FlakyPlugin", ",", "self", ")", ".", "configure", "(", "options", ",", "conf", ")", "if", "not", "self", ".", "enabled", ":", "return", "is_multiprocess", "=", "int"...
Base class override.
[ "Base", "class", "override", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_nose_plugin.py#L69-L81
train
212,972
box/flaky
flaky/flaky_nose_plugin.py
FlakyPlugin.handleError
def handleError(self, test, err): """ Baseclass override. Called when a test raises an exception. If the test isn't going to be rerun again, then report the error to the nose test result. :param test: The test that has raised an error :type test: :class:`nose.case.Test` :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :return: True, if the test will be rerun; False, if nose should handle it. :rtype: `bool` """ # pylint:disable=invalid-name want_error = self._handle_test_error_or_failure(test, err) if not want_error and id(test) in self._tests_that_reran: self._nose_result.addError(test, err) return want_error or None
python
def handleError(self, test, err): """ Baseclass override. Called when a test raises an exception. If the test isn't going to be rerun again, then report the error to the nose test result. :param test: The test that has raised an error :type test: :class:`nose.case.Test` :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :return: True, if the test will be rerun; False, if nose should handle it. :rtype: `bool` """ # pylint:disable=invalid-name want_error = self._handle_test_error_or_failure(test, err) if not want_error and id(test) in self._tests_that_reran: self._nose_result.addError(test, err) return want_error or None
[ "def", "handleError", "(", "self", ",", "test", ",", "err", ")", ":", "# pylint:disable=invalid-name", "want_error", "=", "self", ".", "_handle_test_error_or_failure", "(", "test", ",", "err", ")", "if", "not", "want_error", "and", "id", "(", "test", ")", "i...
Baseclass override. Called when a test raises an exception. If the test isn't going to be rerun again, then report the error to the nose test result. :param test: The test that has raised an error :type test: :class:`nose.case.Test` :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :return: True, if the test will be rerun; False, if nose should handle it. :rtype: `bool`
[ "Baseclass", "override", ".", "Called", "when", "a", "test", "raises", "an", "exception", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_nose_plugin.py#L129-L153
train
212,973
box/flaky
flaky/flaky_nose_plugin.py
FlakyPlugin.handleFailure
def handleFailure(self, test, err): """ Baseclass override. Called when a test fails. If the test isn't going to be rerun again, then report the failure to the nose test result. :param test: The test that has raised an error :type test: :class:`nose.case.Test` :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :return: True, if the test will be rerun; False, if nose should handle it. :rtype: `bool` """ # pylint:disable=invalid-name want_failure = self._handle_test_error_or_failure(test, err) if not want_failure and id(test) in self._tests_that_reran: self._nose_result.addFailure(test, err) return want_failure or None
python
def handleFailure(self, test, err): """ Baseclass override. Called when a test fails. If the test isn't going to be rerun again, then report the failure to the nose test result. :param test: The test that has raised an error :type test: :class:`nose.case.Test` :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :return: True, if the test will be rerun; False, if nose should handle it. :rtype: `bool` """ # pylint:disable=invalid-name want_failure = self._handle_test_error_or_failure(test, err) if not want_failure and id(test) in self._tests_that_reran: self._nose_result.addFailure(test, err) return want_failure or None
[ "def", "handleFailure", "(", "self", ",", "test", ",", "err", ")", ":", "# pylint:disable=invalid-name", "want_failure", "=", "self", ".", "_handle_test_error_or_failure", "(", "test", ",", "err", ")", "if", "not", "want_failure", "and", "id", "(", "test", ")"...
Baseclass override. Called when a test fails. If the test isn't going to be rerun again, then report the failure to the nose test result. :param test: The test that has raised an error :type test: :class:`nose.case.Test` :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :return: True, if the test will be rerun; False, if nose should handle it. :rtype: `bool`
[ "Baseclass", "override", ".", "Called", "when", "a", "test", "fails", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_nose_plugin.py#L155-L179
train
212,974
box/flaky
flaky/flaky_nose_plugin.py
FlakyPlugin.addSuccess
def addSuccess(self, test): """ Baseclass override. Called when a test succeeds. Count remaining retries and compare with number of required successes that have not yet been achieved; retry if necessary. Returning True from this method keeps the test runner from reporting the test as a success; this way we can retry and only report as a success if we have achieved the required number of successes. :param test: The test that has succeeded :type test: :class:`nose.case.Test` :return: True, if the test will be rerun; False, if nose should handle it. :rtype: `bool` """ # pylint:disable=invalid-name will_handle = self._handle_test_success(test) test_id = id(test) # If this isn't a rerun, the builtin reporter is going to report it as a success if will_handle and test_id not in self._tests_that_reran: self._tests_that_have_been_reported.add(test_id) # If this test hasn't already been reported as successful, then do it now if not will_handle and test_id in self._tests_that_reran and test_id not in self._tests_that_have_been_reported: self._nose_result.addSuccess(test) return will_handle or None
python
def addSuccess(self, test): """ Baseclass override. Called when a test succeeds. Count remaining retries and compare with number of required successes that have not yet been achieved; retry if necessary. Returning True from this method keeps the test runner from reporting the test as a success; this way we can retry and only report as a success if we have achieved the required number of successes. :param test: The test that has succeeded :type test: :class:`nose.case.Test` :return: True, if the test will be rerun; False, if nose should handle it. :rtype: `bool` """ # pylint:disable=invalid-name will_handle = self._handle_test_success(test) test_id = id(test) # If this isn't a rerun, the builtin reporter is going to report it as a success if will_handle and test_id not in self._tests_that_reran: self._tests_that_have_been_reported.add(test_id) # If this test hasn't already been reported as successful, then do it now if not will_handle and test_id in self._tests_that_reran and test_id not in self._tests_that_have_been_reported: self._nose_result.addSuccess(test) return will_handle or None
[ "def", "addSuccess", "(", "self", ",", "test", ")", ":", "# pylint:disable=invalid-name", "will_handle", "=", "self", ".", "_handle_test_success", "(", "test", ")", "test_id", "=", "id", "(", "test", ")", "# If this isn't a rerun, the builtin reporter is going to report...
Baseclass override. Called when a test succeeds. Count remaining retries and compare with number of required successes that have not yet been achieved; retry if necessary. Returning True from this method keeps the test runner from reporting the test as a success; this way we can retry and only report as a success if we have achieved the required number of successes. :param test: The test that has succeeded :type test: :class:`nose.case.Test` :return: True, if the test will be rerun; False, if nose should handle it. :rtype: `bool`
[ "Baseclass", "override", ".", "Called", "when", "a", "test", "succeeds", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/flaky_nose_plugin.py#L181-L210
train
212,975
box/flaky
flaky/defaults.py
default_flaky_attributes
def default_flaky_attributes(max_runs=None, min_passes=None, rerun_filter=None): """ Returns the default flaky attributes to set on a flaky test. :param max_runs: The value of the FlakyNames.MAX_RUNS attribute to use. :type max_runs: `int` :param min_passes: The value of the FlakyNames.MIN_PASSES attribute to use. :type min_passes: `int` :param rerun_filter: Filter function to decide whether a test should be rerun if it fails. :type rerun_filter: `callable` :return: Default flaky attributes to set on a flaky test. :rtype: `dict` """ if max_runs is None: max_runs = 2 if min_passes is None: min_passes = 1 if min_passes <= 0: raise ValueError('min_passes must be positive') if max_runs < min_passes: raise ValueError('min_passes cannot be greater than max_runs!') return { FlakyNames.MAX_RUNS: max_runs, FlakyNames.MIN_PASSES: min_passes, FlakyNames.CURRENT_RUNS: 0, FlakyNames.CURRENT_PASSES: 0, FlakyNames.RERUN_FILTER: FilterWrapper(rerun_filter or _true), }
python
def default_flaky_attributes(max_runs=None, min_passes=None, rerun_filter=None): """ Returns the default flaky attributes to set on a flaky test. :param max_runs: The value of the FlakyNames.MAX_RUNS attribute to use. :type max_runs: `int` :param min_passes: The value of the FlakyNames.MIN_PASSES attribute to use. :type min_passes: `int` :param rerun_filter: Filter function to decide whether a test should be rerun if it fails. :type rerun_filter: `callable` :return: Default flaky attributes to set on a flaky test. :rtype: `dict` """ if max_runs is None: max_runs = 2 if min_passes is None: min_passes = 1 if min_passes <= 0: raise ValueError('min_passes must be positive') if max_runs < min_passes: raise ValueError('min_passes cannot be greater than max_runs!') return { FlakyNames.MAX_RUNS: max_runs, FlakyNames.MIN_PASSES: min_passes, FlakyNames.CURRENT_RUNS: 0, FlakyNames.CURRENT_PASSES: 0, FlakyNames.RERUN_FILTER: FilterWrapper(rerun_filter or _true), }
[ "def", "default_flaky_attributes", "(", "max_runs", "=", "None", ",", "min_passes", "=", "None", ",", "rerun_filter", "=", "None", ")", ":", "if", "max_runs", "is", "None", ":", "max_runs", "=", "2", "if", "min_passes", "is", "None", ":", "min_passes", "="...
Returns the default flaky attributes to set on a flaky test. :param max_runs: The value of the FlakyNames.MAX_RUNS attribute to use. :type max_runs: `int` :param min_passes: The value of the FlakyNames.MIN_PASSES attribute to use. :type min_passes: `int` :param rerun_filter: Filter function to decide whether a test should be rerun if it fails. :type rerun_filter: `callable` :return: Default flaky attributes to set on a flaky test. :rtype: `dict`
[ "Returns", "the", "default", "flaky", "attributes", "to", "set", "on", "a", "flaky", "test", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/defaults.py#L27-L63
train
212,976
box/flaky
flaky/utils.py
ensure_unicode_string
def ensure_unicode_string(obj): """ Return a unicode string representation of the given obj. :param obj: The obj we want to represent in unicode :type obj: varies :rtype: `unicode` """ try: return unicode_type(obj) except UnicodeDecodeError: if hasattr(obj, 'decode'): return obj.decode('utf-8', 'replace') return str(obj).decode('utf-8', 'replace')
python
def ensure_unicode_string(obj): """ Return a unicode string representation of the given obj. :param obj: The obj we want to represent in unicode :type obj: varies :rtype: `unicode` """ try: return unicode_type(obj) except UnicodeDecodeError: if hasattr(obj, 'decode'): return obj.decode('utf-8', 'replace') return str(obj).decode('utf-8', 'replace')
[ "def", "ensure_unicode_string", "(", "obj", ")", ":", "try", ":", "return", "unicode_type", "(", "obj", ")", "except", "UnicodeDecodeError", ":", "if", "hasattr", "(", "obj", ",", "'decode'", ")", ":", "return", "obj", ".", "decode", "(", "'utf-8'", ",", ...
Return a unicode string representation of the given obj. :param obj: The obj we want to represent in unicode :type obj: varies :rtype: `unicode`
[ "Return", "a", "unicode", "string", "representation", "of", "the", "given", "obj", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/utils.py#L12-L28
train
212,977
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._report_final_failure
def _report_final_failure(self, err, flaky, name): """ Report that the test has failed too many times to pass at least min_passes times. By default, this means that the test has failed twice. :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :param flaky: Dictionary of flaky attributes :type flaky: `dict` of `unicode` to varies :param name: The test name :type name: `unicode` """ min_passes = flaky[FlakyNames.MIN_PASSES] current_passes = flaky[FlakyNames.CURRENT_PASSES] message = self._failure_message.format( current_passes, min_passes, ) self._log_test_failure(name, err, message)
python
def _report_final_failure(self, err, flaky, name): """ Report that the test has failed too many times to pass at least min_passes times. By default, this means that the test has failed twice. :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :param flaky: Dictionary of flaky attributes :type flaky: `dict` of `unicode` to varies :param name: The test name :type name: `unicode` """ min_passes = flaky[FlakyNames.MIN_PASSES] current_passes = flaky[FlakyNames.CURRENT_PASSES] message = self._failure_message.format( current_passes, min_passes, ) self._log_test_failure(name, err, message)
[ "def", "_report_final_failure", "(", "self", ",", "err", ",", "flaky", ",", "name", ")", ":", "min_passes", "=", "flaky", "[", "FlakyNames", ".", "MIN_PASSES", "]", "current_passes", "=", "flaky", "[", "FlakyNames", ".", "CURRENT_PASSES", "]", "message", "="...
Report that the test has failed too many times to pass at least min_passes times. By default, this means that the test has failed twice. :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :param flaky: Dictionary of flaky attributes :type flaky: `dict` of `unicode` to varies :param name: The test name :type name: `unicode`
[ "Report", "that", "the", "test", "has", "failed", "too", "many", "times", "to", "pass", "at", "least", "min_passes", "times", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L50-L76
train
212,978
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._log_intermediate_failure
def _log_intermediate_failure(self, err, flaky, name): """ Report that the test has failed, but still has reruns left. Then rerun the test. :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :param flaky: Dictionary of flaky attributes :type flaky: `dict` of `unicode` to varies :param name: The test name :type name: `unicode` """ max_runs = flaky[FlakyNames.MAX_RUNS] runs_left = max_runs - flaky[FlakyNames.CURRENT_RUNS] message = self._retry_failure_message.format( runs_left, max_runs, ) self._log_test_failure(name, err, message)
python
def _log_intermediate_failure(self, err, flaky, name): """ Report that the test has failed, but still has reruns left. Then rerun the test. :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :param flaky: Dictionary of flaky attributes :type flaky: `dict` of `unicode` to varies :param name: The test name :type name: `unicode` """ max_runs = flaky[FlakyNames.MAX_RUNS] runs_left = max_runs - flaky[FlakyNames.CURRENT_RUNS] message = self._retry_failure_message.format( runs_left, max_runs, ) self._log_test_failure(name, err, message)
[ "def", "_log_intermediate_failure", "(", "self", ",", "err", ",", "flaky", ",", "name", ")", ":", "max_runs", "=", "flaky", "[", "FlakyNames", ".", "MAX_RUNS", "]", "runs_left", "=", "max_runs", "-", "flaky", "[", "FlakyNames", ".", "CURRENT_RUNS", "]", "m...
Report that the test has failed, but still has reruns left. Then rerun the test. :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :param flaky: Dictionary of flaky attributes :type flaky: `dict` of `unicode` to varies :param name: The test name :type name: `unicode`
[ "Report", "that", "the", "test", "has", "failed", "but", "still", "has", "reruns", "left", ".", "Then", "rerun", "the", "test", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L78-L102
train
212,979
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin.add_report_option
def add_report_option(add_option): """ Add an option to the test runner to suppress the flaky report. :param add_option: A function that can add an option to the test runner. Its argspec should equal that of argparse.add_option. :type add_option: `callable` """ add_option( '--no-flaky-report', action='store_false', dest='flaky_report', default=True, help="Suppress the report at the end of the " "run detailing flaky test results.", ) add_option( '--no-success-flaky-report', action='store_false', dest='flaky_success_report', default=True, help="Suppress reporting flaky test successes" "in the report at the end of the " "run detailing flaky test results.", )
python
def add_report_option(add_option): """ Add an option to the test runner to suppress the flaky report. :param add_option: A function that can add an option to the test runner. Its argspec should equal that of argparse.add_option. :type add_option: `callable` """ add_option( '--no-flaky-report', action='store_false', dest='flaky_report', default=True, help="Suppress the report at the end of the " "run detailing flaky test results.", ) add_option( '--no-success-flaky-report', action='store_false', dest='flaky_success_report', default=True, help="Suppress reporting flaky test successes" "in the report at the end of the " "run detailing flaky test results.", )
[ "def", "add_report_option", "(", "add_option", ")", ":", "add_option", "(", "'--no-flaky-report'", ",", "action", "=", "'store_false'", ",", "dest", "=", "'flaky_report'", ",", "default", "=", "True", ",", "help", "=", "\"Suppress the report at the end of the \"", "...
Add an option to the test runner to suppress the flaky report. :param add_option: A function that can add an option to the test runner. Its argspec should equal that of argparse.add_option. :type add_option: `callable`
[ "Add", "an", "option", "to", "the", "test", "runner", "to", "suppress", "the", "flaky", "report", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L300-L326
train
212,980
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin.add_force_flaky_options
def add_force_flaky_options(add_option): """ Add options to the test runner that force all tests to be flaky. :param add_option: A function that can add an option to the test runner. Its argspec should equal that of argparse.add_option. :type add_option: `callable` """ add_option( '--force-flaky', action="store_true", dest="force_flaky", default=False, help="If this option is specified, we will treat all tests as " "flaky." ) add_option( '--max-runs', action="store", dest="max_runs", type=int, default=2, help="If --force-flaky is specified, we will run each test at " "most this many times (unless the test has its own flaky " "decorator)." ) add_option( '--min-passes', action="store", dest="min_passes", type=int, default=1, help="If --force-flaky is specified, we will run each test at " "least this many times (unless the test has its own flaky " "decorator)." )
python
def add_force_flaky_options(add_option): """ Add options to the test runner that force all tests to be flaky. :param add_option: A function that can add an option to the test runner. Its argspec should equal that of argparse.add_option. :type add_option: `callable` """ add_option( '--force-flaky', action="store_true", dest="force_flaky", default=False, help="If this option is specified, we will treat all tests as " "flaky." ) add_option( '--max-runs', action="store", dest="max_runs", type=int, default=2, help="If --force-flaky is specified, we will run each test at " "most this many times (unless the test has its own flaky " "decorator)." ) add_option( '--min-passes', action="store", dest="min_passes", type=int, default=1, help="If --force-flaky is specified, we will run each test at " "least this many times (unless the test has its own flaky " "decorator)." )
[ "def", "add_force_flaky_options", "(", "add_option", ")", ":", "add_option", "(", "'--force-flaky'", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"force_flaky\"", ",", "default", "=", "False", ",", "help", "=", "\"If this option is specified, we will trea...
Add options to the test runner that force all tests to be flaky. :param add_option: A function that can add an option to the test runner. Its argspec should equal that of argparse.add_option. :type add_option: `callable`
[ "Add", "options", "to", "the", "test", "runner", "that", "force", "all", "tests", "to", "be", "flaky", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L329-L366
train
212,981
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._add_flaky_report
def _add_flaky_report(self, stream): """ Baseclass override. Write details about flaky tests to the test report. :param stream: The test stream to which the report can be written. :type stream: `file` """ value = self._stream.getvalue() # If everything succeeded and --no-success-flaky-report is specified # don't print anything. if not self._flaky_success_report and not value: return stream.write('===Flaky Test Report===\n\n') # Python 2 will write to the stderr stream as a byte string, whereas # Python 3 will write to the stream as text. Only encode into a byte # string if the write tries to encode it first and raises a # UnicodeEncodeError. try: stream.write(value) except UnicodeEncodeError: stream.write(value.encode('utf-8', 'replace')) stream.write('\n===End Flaky Test Report===\n')
python
def _add_flaky_report(self, stream): """ Baseclass override. Write details about flaky tests to the test report. :param stream: The test stream to which the report can be written. :type stream: `file` """ value = self._stream.getvalue() # If everything succeeded and --no-success-flaky-report is specified # don't print anything. if not self._flaky_success_report and not value: return stream.write('===Flaky Test Report===\n\n') # Python 2 will write to the stderr stream as a byte string, whereas # Python 3 will write to the stream as text. Only encode into a byte # string if the write tries to encode it first and raises a # UnicodeEncodeError. try: stream.write(value) except UnicodeEncodeError: stream.write(value.encode('utf-8', 'replace')) stream.write('\n===End Flaky Test Report===\n')
[ "def", "_add_flaky_report", "(", "self", ",", "stream", ")", ":", "value", "=", "self", ".", "_stream", ".", "getvalue", "(", ")", "# If everything succeeded and --no-success-flaky-report is specified", "# don't print anything.", "if", "not", "self", ".", "_flaky_succes...
Baseclass override. Write details about flaky tests to the test report. :param stream: The test stream to which the report can be written. :type stream: `file`
[ "Baseclass", "override", ".", "Write", "details", "about", "flaky", "tests", "to", "the", "test", "report", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L368-L395
train
212,982
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._copy_flaky_attributes
def _copy_flaky_attributes(cls, test, test_class): """ Copy flaky attributes from the test callable or class to the test. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test` """ test_callable = cls._get_test_callable(test) if test_callable is None: return for attr, value in cls._get_flaky_attributes(test_class).items(): already_set = hasattr(test, attr) if already_set: continue attr_on_callable = getattr(test_callable, attr, None) if attr_on_callable is not None: cls._set_flaky_attribute(test, attr, attr_on_callable) elif value is not None: cls._set_flaky_attribute(test, attr, value)
python
def _copy_flaky_attributes(cls, test, test_class): """ Copy flaky attributes from the test callable or class to the test. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test` """ test_callable = cls._get_test_callable(test) if test_callable is None: return for attr, value in cls._get_flaky_attributes(test_class).items(): already_set = hasattr(test, attr) if already_set: continue attr_on_callable = getattr(test_callable, attr, None) if attr_on_callable is not None: cls._set_flaky_attribute(test, attr, attr_on_callable) elif value is not None: cls._set_flaky_attribute(test, attr, value)
[ "def", "_copy_flaky_attributes", "(", "cls", ",", "test", ",", "test_class", ")", ":", "test_callable", "=", "cls", ".", "_get_test_callable", "(", "test", ")", "if", "test_callable", "is", "None", ":", "return", "for", "attr", ",", "value", "in", "cls", "...
Copy flaky attributes from the test callable or class to the test. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test`
[ "Copy", "flaky", "attributes", "from", "the", "test", "callable", "or", "class", "to", "the", "test", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L398-L418
train
212,983
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._increment_flaky_attribute
def _increment_flaky_attribute(cls, test_item, flaky_attribute): """ Increments the value of an attribute on a flaky test. :param test_item: The test callable on which to set the attribute :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` :param flaky_attribute: The name of the attribute to set :type flaky_attribute: `unicode` """ cls._set_flaky_attribute(test_item, flaky_attribute, cls._get_flaky_attribute(test_item, flaky_attribute) + 1)
python
def _increment_flaky_attribute(cls, test_item, flaky_attribute): """ Increments the value of an attribute on a flaky test. :param test_item: The test callable on which to set the attribute :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` :param flaky_attribute: The name of the attribute to set :type flaky_attribute: `unicode` """ cls._set_flaky_attribute(test_item, flaky_attribute, cls._get_flaky_attribute(test_item, flaky_attribute) + 1)
[ "def", "_increment_flaky_attribute", "(", "cls", ",", "test_item", ",", "flaky_attribute", ")", ":", "cls", ".", "_set_flaky_attribute", "(", "test_item", ",", "flaky_attribute", ",", "cls", ".", "_get_flaky_attribute", "(", "test_item", ",", "flaky_attribute", ")",...
Increments the value of an attribute on a flaky test. :param test_item: The test callable on which to set the attribute :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` :param flaky_attribute: The name of the attribute to set :type flaky_attribute: `unicode`
[ "Increments", "the", "value", "of", "an", "attribute", "on", "a", "flaky", "test", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L463-L476
train
212,984
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._has_flaky_attributes
def _has_flaky_attributes(cls, test): """ Returns True if the test callable in question is marked as flaky. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test` or :class:`Function` :return: :rtype: `bool` """ current_runs = cls._get_flaky_attribute(test, FlakyNames.CURRENT_RUNS) return current_runs is not None
python
def _has_flaky_attributes(cls, test): """ Returns True if the test callable in question is marked as flaky. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test` or :class:`Function` :return: :rtype: `bool` """ current_runs = cls._get_flaky_attribute(test, FlakyNames.CURRENT_RUNS) return current_runs is not None
[ "def", "_has_flaky_attributes", "(", "cls", ",", "test", ")", ":", "current_runs", "=", "cls", ".", "_get_flaky_attribute", "(", "test", ",", "FlakyNames", ".", "CURRENT_RUNS", ")", "return", "current_runs", "is", "not", "None" ]
Returns True if the test callable in question is marked as flaky. :param test: The test that is being prepared to run :type test: :class:`nose.case.Test` or :class:`Function` :return: :rtype: `bool`
[ "Returns", "True", "if", "the", "test", "callable", "in", "question", "is", "marked", "as", "flaky", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L479-L492
train
212,985
box/flaky
flaky/_flaky_plugin.py
_FlakyPlugin._get_flaky_attributes
def _get_flaky_attributes(cls, test_item): """ Get all the flaky related attributes from the test. :param test_item: The test callable from which to get the flaky related attributes. :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` :return: :rtype: `dict` of `unicode` to varies """ return { attr: cls._get_flaky_attribute( test_item, attr, ) for attr in FlakyNames() }
python
def _get_flaky_attributes(cls, test_item): """ Get all the flaky related attributes from the test. :param test_item: The test callable from which to get the flaky related attributes. :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` :return: :rtype: `dict` of `unicode` to varies """ return { attr: cls._get_flaky_attribute( test_item, attr, ) for attr in FlakyNames() }
[ "def", "_get_flaky_attributes", "(", "cls", ",", "test_item", ")", ":", "return", "{", "attr", ":", "cls", ".", "_get_flaky_attribute", "(", "test_item", ",", "attr", ",", ")", "for", "attr", "in", "FlakyNames", "(", ")", "}" ]
Get all the flaky related attributes from the test. :param test_item: The test callable from which to get the flaky related attributes. :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` :return: :rtype: `dict` of `unicode` to varies
[ "Get", "all", "the", "flaky", "related", "attributes", "from", "the", "test", "." ]
c23126f09b2cc5a4071cfa43a11272927e9c0fcd
https://github.com/box/flaky/blob/c23126f09b2cc5a4071cfa43a11272927e9c0fcd/flaky/_flaky_plugin.py#L495-L512
train
212,986
altair-viz/vega_datasets
vega_datasets/utils.py
connection_ok
def connection_ok(): """Check web connection. Returns True if web connection is OK, False otherwise. """ try: urlopen(Dataset.base_url, timeout=1) # if an index page is ever added, this will pass through return True except HTTPError: # There's no index for BASE_URL so Error 404 is expected return True except URLError: # This is raised if there is no internet connection return False
python
def connection_ok(): """Check web connection. Returns True if web connection is OK, False otherwise. """ try: urlopen(Dataset.base_url, timeout=1) # if an index page is ever added, this will pass through return True except HTTPError: # There's no index for BASE_URL so Error 404 is expected return True except URLError: # This is raised if there is no internet connection return False
[ "def", "connection_ok", "(", ")", ":", "try", ":", "urlopen", "(", "Dataset", ".", "base_url", ",", "timeout", "=", "1", ")", "# if an index page is ever added, this will pass through", "return", "True", "except", "HTTPError", ":", "# There's no index for BASE_URL so Er...
Check web connection. Returns True if web connection is OK, False otherwise.
[ "Check", "web", "connection", ".", "Returns", "True", "if", "web", "connection", "is", "OK", "False", "otherwise", "." ]
391243aa0ff8eecd7ec7082c747dc0a67de0ccc7
https://github.com/altair-viz/vega_datasets/blob/391243aa0ff8eecd7ec7082c747dc0a67de0ccc7/vega_datasets/utils.py#L5-L18
train
212,987
altair-viz/vega_datasets
tools/download_datasets.py
_download_datasets
def _download_datasets(): """Utility to download datasets into package source""" def filepath(*args): return abspath(join(dirname(__file__), '..', 'vega_datasets', *args)) dataset_listing = {} for name in DATASETS_TO_DOWNLOAD: data = Dataset(name) url = data.url filename = filepath('_data', data.filename) print("retrieving data {0} -> {1}".format(url, filename)) urlretrieve(url, filename) dataset_listing[name] = '_data/{0}'.format(data.filename) with open(filepath('local_datasets.json'), 'w') as f: json.dump(dataset_listing, f, indent=2, sort_keys=True)
python
def _download_datasets(): """Utility to download datasets into package source""" def filepath(*args): return abspath(join(dirname(__file__), '..', 'vega_datasets', *args)) dataset_listing = {} for name in DATASETS_TO_DOWNLOAD: data = Dataset(name) url = data.url filename = filepath('_data', data.filename) print("retrieving data {0} -> {1}".format(url, filename)) urlretrieve(url, filename) dataset_listing[name] = '_data/{0}'.format(data.filename) with open(filepath('local_datasets.json'), 'w') as f: json.dump(dataset_listing, f, indent=2, sort_keys=True)
[ "def", "_download_datasets", "(", ")", ":", "def", "filepath", "(", "*", "args", ")", ":", "return", "abspath", "(", "join", "(", "dirname", "(", "__file__", ")", ",", "'..'", ",", "'vega_datasets'", ",", "*", "args", ")", ")", "dataset_listing", "=", ...
Utility to download datasets into package source
[ "Utility", "to", "download", "datasets", "into", "package", "source" ]
391243aa0ff8eecd7ec7082c747dc0a67de0ccc7
https://github.com/altair-viz/vega_datasets/blob/391243aa0ff8eecd7ec7082c747dc0a67de0ccc7/tools/download_datasets.py#L35-L48
train
212,988
altair-viz/vega_datasets
vega_datasets/core.py
Dataset.init
def init(cls, name): """Return an instance of this class or an appropriate subclass""" clsdict = {subcls.name: subcls for subcls in cls.__subclasses__() if hasattr(subcls, 'name')} return clsdict.get(name, cls)(name)
python
def init(cls, name): """Return an instance of this class or an appropriate subclass""" clsdict = {subcls.name: subcls for subcls in cls.__subclasses__() if hasattr(subcls, 'name')} return clsdict.get(name, cls)(name)
[ "def", "init", "(", "cls", ",", "name", ")", ":", "clsdict", "=", "{", "subcls", ".", "name", ":", "subcls", "for", "subcls", "in", "cls", ".", "__subclasses__", "(", ")", "if", "hasattr", "(", "subcls", ",", "'name'", ")", "}", "return", "clsdict", ...
Return an instance of this class or an appropriate subclass
[ "Return", "an", "instance", "of", "this", "class", "or", "an", "appropriate", "subclass" ]
391243aa0ff8eecd7ec7082c747dc0a67de0ccc7
https://github.com/altair-viz/vega_datasets/blob/391243aa0ff8eecd7ec7082c747dc0a67de0ccc7/vega_datasets/core.py#L96-L100
train
212,989
altair-viz/vega_datasets
vega_datasets/core.py
Dataset._infodict
def _infodict(cls, name): """load the info dictionary for the given name""" info = cls._dataset_info.get(name, None) if info is None: raise ValueError('No such dataset {0} exists, ' 'use list_datasets() to get a list ' 'of available datasets.'.format(name)) return info
python
def _infodict(cls, name): """load the info dictionary for the given name""" info = cls._dataset_info.get(name, None) if info is None: raise ValueError('No such dataset {0} exists, ' 'use list_datasets() to get a list ' 'of available datasets.'.format(name)) return info
[ "def", "_infodict", "(", "cls", ",", "name", ")", ":", "info", "=", "cls", ".", "_dataset_info", ".", "get", "(", "name", ",", "None", ")", "if", "info", "is", "None", ":", "raise", "ValueError", "(", "'No such dataset {0} exists, '", "'use list_datasets() t...
load the info dictionary for the given name
[ "load", "the", "info", "dictionary", "for", "the", "given", "name" ]
391243aa0ff8eecd7ec7082c747dc0a67de0ccc7
https://github.com/altair-viz/vega_datasets/blob/391243aa0ff8eecd7ec7082c747dc0a67de0ccc7/vega_datasets/core.py#L164-L171
train
212,990
altair-viz/vega_datasets
vega_datasets/core.py
Dataset.raw
def raw(self, use_local=True): """Load the raw dataset from remote URL or local file Parameters ---------- use_local : boolean If True (default), then attempt to load the dataset locally. If False or if the dataset is not available locally, then load the data from an external URL. """ if use_local and self.is_local: return pkgutil.get_data('vega_datasets', self.pkg_filename) else: return urlopen(self.url).read()
python
def raw(self, use_local=True): """Load the raw dataset from remote URL or local file Parameters ---------- use_local : boolean If True (default), then attempt to load the dataset locally. If False or if the dataset is not available locally, then load the data from an external URL. """ if use_local and self.is_local: return pkgutil.get_data('vega_datasets', self.pkg_filename) else: return urlopen(self.url).read()
[ "def", "raw", "(", "self", ",", "use_local", "=", "True", ")", ":", "if", "use_local", "and", "self", ".", "is_local", ":", "return", "pkgutil", ".", "get_data", "(", "'vega_datasets'", ",", "self", ".", "pkg_filename", ")", "else", ":", "return", "urlop...
Load the raw dataset from remote URL or local file Parameters ---------- use_local : boolean If True (default), then attempt to load the dataset locally. If False or if the dataset is not available locally, then load the data from an external URL.
[ "Load", "the", "raw", "dataset", "from", "remote", "URL", "or", "local", "file" ]
391243aa0ff8eecd7ec7082c747dc0a67de0ccc7
https://github.com/altair-viz/vega_datasets/blob/391243aa0ff8eecd7ec7082c747dc0a67de0ccc7/vega_datasets/core.py#L173-L186
train
212,991
danielkaiser/python-chromedriver-binary
setup.py
DownloadChromedriver.run
def run(self): """ Downloads, unzips and installs chromedriver. If a chromedriver binary is found in PATH it will be copied, otherwise downloaded. """ chromedriver_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'chromedriver_binary') chromedriver_filename = find_binary_in_path(get_chromedriver_filename()) if chromedriver_filename: print("\nChromedriver already installed at {}...\n".format(chromedriver_filename)) new_filename = os.path.join(chromedriver_dir, get_chromedriver_filename()) self.copy_file(chromedriver_filename, new_filename) else: chromedriver_bin = get_chromedriver_filename() chromedriver_filename = os.path.join(chromedriver_dir, chromedriver_bin) if not os.path.isfile(chromedriver_filename): print("\nDownloading Chromedriver...\n") if not os.path.isdir(chromedriver_dir): os.mkdir(chromedriver_dir) url = get_chromedriver_url() try: response = urlopen(url) if response.getcode() != 200: raise URLError('Not Found') except URLError: raise RuntimeError('Failed to download chromedriver archive: {}'.format(url)) archive = BytesIO(response.read()) with zipfile.ZipFile(archive) as zip_file: zip_file.extract(chromedriver_bin, chromedriver_dir) else: print("\nChromedriver already installed at {}...\n".format(chromedriver_filename)) if not os.access(chromedriver_filename, os.X_OK): os.chmod(chromedriver_filename, 0o744) build_py.run(self)
python
def run(self): """ Downloads, unzips and installs chromedriver. If a chromedriver binary is found in PATH it will be copied, otherwise downloaded. """ chromedriver_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'chromedriver_binary') chromedriver_filename = find_binary_in_path(get_chromedriver_filename()) if chromedriver_filename: print("\nChromedriver already installed at {}...\n".format(chromedriver_filename)) new_filename = os.path.join(chromedriver_dir, get_chromedriver_filename()) self.copy_file(chromedriver_filename, new_filename) else: chromedriver_bin = get_chromedriver_filename() chromedriver_filename = os.path.join(chromedriver_dir, chromedriver_bin) if not os.path.isfile(chromedriver_filename): print("\nDownloading Chromedriver...\n") if not os.path.isdir(chromedriver_dir): os.mkdir(chromedriver_dir) url = get_chromedriver_url() try: response = urlopen(url) if response.getcode() != 200: raise URLError('Not Found') except URLError: raise RuntimeError('Failed to download chromedriver archive: {}'.format(url)) archive = BytesIO(response.read()) with zipfile.ZipFile(archive) as zip_file: zip_file.extract(chromedriver_bin, chromedriver_dir) else: print("\nChromedriver already installed at {}...\n".format(chromedriver_filename)) if not os.access(chromedriver_filename, os.X_OK): os.chmod(chromedriver_filename, 0o744) build_py.run(self)
[ "def", "run", "(", "self", ")", ":", "chromedriver_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", ",", "'chromedriver_binary'", ")", "chromedriver_fi...
Downloads, unzips and installs chromedriver. If a chromedriver binary is found in PATH it will be copied, otherwise downloaded.
[ "Downloads", "unzips", "and", "installs", "chromedriver", ".", "If", "a", "chromedriver", "binary", "is", "found", "in", "PATH", "it", "will", "be", "copied", "otherwise", "downloaded", "." ]
1776f573956d57b3011d1d234f18fe3f2773e81f
https://github.com/danielkaiser/python-chromedriver-binary/blob/1776f573956d57b3011d1d234f18fe3f2773e81f/setup.py#L23-L55
train
212,992
danielkaiser/python-chromedriver-binary
chromedriver_binary/__init__.py
add_chromedriver_to_path
def add_chromedriver_to_path(): """ Appends the directory of the chromedriver binary file to PATH. """ chromedriver_dir = os.path.abspath(os.path.dirname(__file__)) if 'PATH' not in os.environ: os.environ['PATH'] = chromedriver_dir elif chromedriver_dir not in os.environ['PATH']: os.environ['PATH'] += utils.get_variable_separator()+chromedriver_dir
python
def add_chromedriver_to_path(): """ Appends the directory of the chromedriver binary file to PATH. """ chromedriver_dir = os.path.abspath(os.path.dirname(__file__)) if 'PATH' not in os.environ: os.environ['PATH'] = chromedriver_dir elif chromedriver_dir not in os.environ['PATH']: os.environ['PATH'] += utils.get_variable_separator()+chromedriver_dir
[ "def", "add_chromedriver_to_path", "(", ")", ":", "chromedriver_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "if", "'PATH'", "not", "in", "os", ".", "environ", ":", "os", ".", "environ...
Appends the directory of the chromedriver binary file to PATH.
[ "Appends", "the", "directory", "of", "the", "chromedriver", "binary", "file", "to", "PATH", "." ]
1776f573956d57b3011d1d234f18fe3f2773e81f
https://github.com/danielkaiser/python-chromedriver-binary/blob/1776f573956d57b3011d1d234f18fe3f2773e81f/chromedriver_binary/__init__.py#L11-L19
train
212,993
aio-libs/sockjs
sockjs/session.py
Session._remote_close
async def _remote_close(self, exc=None): """close session from remote.""" if self.state in (STATE_CLOSING, STATE_CLOSED): return log.info("close session: %s", self.id) self.state = STATE_CLOSING if exc is not None: self.exception = exc self.interrupted = True try: await self.handler(SockjsMessage(MSG_CLOSE, exc), self) except Exception: log.exception("Exception in close handler.")
python
async def _remote_close(self, exc=None): """close session from remote.""" if self.state in (STATE_CLOSING, STATE_CLOSED): return log.info("close session: %s", self.id) self.state = STATE_CLOSING if exc is not None: self.exception = exc self.interrupted = True try: await self.handler(SockjsMessage(MSG_CLOSE, exc), self) except Exception: log.exception("Exception in close handler.")
[ "async", "def", "_remote_close", "(", "self", ",", "exc", "=", "None", ")", ":", "if", "self", ".", "state", "in", "(", "STATE_CLOSING", ",", "STATE_CLOSED", ")", ":", "return", "log", ".", "info", "(", "\"close session: %s\"", ",", "self", ".", "id", ...
close session from remote.
[ "close", "session", "from", "remote", "." ]
e5d5f24f6a1377419b13199ecf631df66667bcbb
https://github.com/aio-libs/sockjs/blob/e5d5f24f6a1377419b13199ecf631df66667bcbb/sockjs/session.py#L162-L175
train
212,994
aio-libs/sockjs
sockjs/session.py
Session.send
def send(self, msg): """send message to client.""" assert isinstance(msg, str), "String is required" if self._debug: log.info("outgoing message: %s, %s", self.id, str(msg)[:200]) if self.state != STATE_OPEN: return self._feed(FRAME_MESSAGE, msg)
python
def send(self, msg): """send message to client.""" assert isinstance(msg, str), "String is required" if self._debug: log.info("outgoing message: %s, %s", self.id, str(msg)[:200]) if self.state != STATE_OPEN: return self._feed(FRAME_MESSAGE, msg)
[ "def", "send", "(", "self", ",", "msg", ")", ":", "assert", "isinstance", "(", "msg", ",", "str", ")", ",", "\"String is required\"", "if", "self", ".", "_debug", ":", "log", ".", "info", "(", "\"outgoing message: %s, %s\"", ",", "self", ".", "id", ",", ...
send message to client.
[ "send", "message", "to", "client", "." ]
e5d5f24f6a1377419b13199ecf631df66667bcbb
https://github.com/aio-libs/sockjs/blob/e5d5f24f6a1377419b13199ecf631df66667bcbb/sockjs/session.py#L219-L229
train
212,995
aio-libs/sockjs
sockjs/session.py
Session.send_frame
def send_frame(self, frm): """send message frame to client.""" if self._debug: log.info("outgoing message: %s, %s", self.id, frm[:200]) if self.state != STATE_OPEN: return self._feed(FRAME_MESSAGE_BLOB, frm)
python
def send_frame(self, frm): """send message frame to client.""" if self._debug: log.info("outgoing message: %s, %s", self.id, frm[:200]) if self.state != STATE_OPEN: return self._feed(FRAME_MESSAGE_BLOB, frm)
[ "def", "send_frame", "(", "self", ",", "frm", ")", ":", "if", "self", ".", "_debug", ":", "log", ".", "info", "(", "\"outgoing message: %s, %s\"", ",", "self", ".", "id", ",", "frm", "[", ":", "200", "]", ")", "if", "self", ".", "state", "!=", "STA...
send message frame to client.
[ "send", "message", "frame", "to", "client", "." ]
e5d5f24f6a1377419b13199ecf631df66667bcbb
https://github.com/aio-libs/sockjs/blob/e5d5f24f6a1377419b13199ecf631df66667bcbb/sockjs/session.py#L231-L239
train
212,996
aio-libs/sockjs
sockjs/session.py
SessionManager.clear
async def clear(self): """Manually expire all sessions in the pool.""" for session in list(self.values()): if session.state != STATE_CLOSED: await session._remote_closed() self.sessions.clear() super(SessionManager, self).clear()
python
async def clear(self): """Manually expire all sessions in the pool.""" for session in list(self.values()): if session.state != STATE_CLOSED: await session._remote_closed() self.sessions.clear() super(SessionManager, self).clear()
[ "async", "def", "clear", "(", "self", ")", ":", "for", "session", "in", "list", "(", "self", ".", "values", "(", ")", ")", ":", "if", "session", ".", "state", "!=", "STATE_CLOSED", ":", "await", "session", ".", "_remote_closed", "(", ")", "self", "."...
Manually expire all sessions in the pool.
[ "Manually", "expire", "all", "sessions", "in", "the", "pool", "." ]
e5d5f24f6a1377419b13199ecf631df66667bcbb
https://github.com/aio-libs/sockjs/blob/e5d5f24f6a1377419b13199ecf631df66667bcbb/sockjs/session.py#L395-L402
train
212,997
kurtbrose/pyjks
jks/jks.py
TrustedCertEntry.new
def new(cls, alias, cert): """ Helper function to create a new TrustedCertEntry. :param str alias: The alias for the Trusted Cert Entry :param str certs: The certificate, as a byte string. :returns: A loaded :class:`TrustedCertEntry` instance, ready to be placed in a keystore. """ timestamp = int(time.time()) * 1000 tke = cls(timestamp = timestamp, # Alias must be lower case or it will corrupt the keystore for Java Keytool and Keytool Explorer alias = alias.lower(), cert = cert) return tke
python
def new(cls, alias, cert): """ Helper function to create a new TrustedCertEntry. :param str alias: The alias for the Trusted Cert Entry :param str certs: The certificate, as a byte string. :returns: A loaded :class:`TrustedCertEntry` instance, ready to be placed in a keystore. """ timestamp = int(time.time()) * 1000 tke = cls(timestamp = timestamp, # Alias must be lower case or it will corrupt the keystore for Java Keytool and Keytool Explorer alias = alias.lower(), cert = cert) return tke
[ "def", "new", "(", "cls", ",", "alias", ",", "cert", ")", ":", "timestamp", "=", "int", "(", "time", ".", "time", "(", ")", ")", "*", "1000", "tke", "=", "cls", "(", "timestamp", "=", "timestamp", ",", "# Alias must be lower case or it will corrupt the key...
Helper function to create a new TrustedCertEntry. :param str alias: The alias for the Trusted Cert Entry :param str certs: The certificate, as a byte string. :returns: A loaded :class:`TrustedCertEntry` instance, ready to be placed in a keystore.
[ "Helper", "function", "to", "create", "a", "new", "TrustedCertEntry", "." ]
1cbe7f060e2ad076b6462f3273f11d635771ea3d
https://github.com/kurtbrose/pyjks/blob/1cbe7f060e2ad076b6462f3273f11d635771ea3d/jks/jks.py#L67-L83
train
212,998
kurtbrose/pyjks
jks/jks.py
PrivateKeyEntry.new
def new(cls, alias, certs, key, key_format='pkcs8'): """ Helper function to create a new PrivateKeyEntry. :param str alias: The alias for the Private Key Entry :param list certs: An list of certificates, as byte strings. The first one should be the one belonging to the private key, the others the chain (in correct order). :param str key: A byte string containing the private key in the format specified in the key_format parameter (default pkcs8). :param str key_format: The format of the provided private key. Valid options are pkcs8 or rsa_raw. Defaults to pkcs8. :returns: A loaded :class:`PrivateKeyEntry` instance, ready to be placed in a keystore. :raises UnsupportedKeyFormatException: If the key format is unsupported. """ timestamp = int(time.time()) * 1000 cert_chain = [] for cert in certs: cert_chain.append(('X.509', cert)) pke = cls(timestamp = timestamp, # Alias must be lower case or it will corrupt the keystore for Java Keytool and Keytool Explorer alias = alias.lower(), cert_chain = cert_chain) if key_format == 'pkcs8': private_key_info = decoder.decode(key, asn1Spec=rfc5208.PrivateKeyInfo())[0] pke._algorithm_oid = private_key_info['privateKeyAlgorithm']['algorithm'].asTuple() pke.pkey = private_key_info['privateKey'].asOctets() pke.pkey_pkcs8 = key elif key_format == 'rsa_raw': pke._algorithm_oid = RSA_ENCRYPTION_OID # We must encode it to pkcs8 private_key_info = rfc5208.PrivateKeyInfo() private_key_info.setComponentByName('version','v1') a = AlgorithmIdentifier() a.setComponentByName('algorithm', pke._algorithm_oid) a.setComponentByName('parameters', '\x05\x00') private_key_info.setComponentByName('privateKeyAlgorithm', a) private_key_info.setComponentByName('privateKey', key) pke.pkey_pkcs8 = encoder.encode(private_key_info, ifNotEmpty=True) pke.pkey = key else: raise UnsupportedKeyFormatException("Key Format '%s' is not supported" % key_format) return pke
python
def new(cls, alias, certs, key, key_format='pkcs8'): """ Helper function to create a new PrivateKeyEntry. :param str alias: The alias for the Private Key Entry :param list certs: An list of certificates, as byte strings. The first one should be the one belonging to the private key, the others the chain (in correct order). :param str key: A byte string containing the private key in the format specified in the key_format parameter (default pkcs8). :param str key_format: The format of the provided private key. Valid options are pkcs8 or rsa_raw. Defaults to pkcs8. :returns: A loaded :class:`PrivateKeyEntry` instance, ready to be placed in a keystore. :raises UnsupportedKeyFormatException: If the key format is unsupported. """ timestamp = int(time.time()) * 1000 cert_chain = [] for cert in certs: cert_chain.append(('X.509', cert)) pke = cls(timestamp = timestamp, # Alias must be lower case or it will corrupt the keystore for Java Keytool and Keytool Explorer alias = alias.lower(), cert_chain = cert_chain) if key_format == 'pkcs8': private_key_info = decoder.decode(key, asn1Spec=rfc5208.PrivateKeyInfo())[0] pke._algorithm_oid = private_key_info['privateKeyAlgorithm']['algorithm'].asTuple() pke.pkey = private_key_info['privateKey'].asOctets() pke.pkey_pkcs8 = key elif key_format == 'rsa_raw': pke._algorithm_oid = RSA_ENCRYPTION_OID # We must encode it to pkcs8 private_key_info = rfc5208.PrivateKeyInfo() private_key_info.setComponentByName('version','v1') a = AlgorithmIdentifier() a.setComponentByName('algorithm', pke._algorithm_oid) a.setComponentByName('parameters', '\x05\x00') private_key_info.setComponentByName('privateKeyAlgorithm', a) private_key_info.setComponentByName('privateKey', key) pke.pkey_pkcs8 = encoder.encode(private_key_info, ifNotEmpty=True) pke.pkey = key else: raise UnsupportedKeyFormatException("Key Format '%s' is not supported" % key_format) return pke
[ "def", "new", "(", "cls", ",", "alias", ",", "certs", ",", "key", ",", "key_format", "=", "'pkcs8'", ")", ":", "timestamp", "=", "int", "(", "time", ".", "time", "(", ")", ")", "*", "1000", "cert_chain", "=", "[", "]", "for", "cert", "in", "certs...
Helper function to create a new PrivateKeyEntry. :param str alias: The alias for the Private Key Entry :param list certs: An list of certificates, as byte strings. The first one should be the one belonging to the private key, the others the chain (in correct order). :param str key: A byte string containing the private key in the format specified in the key_format parameter (default pkcs8). :param str key_format: The format of the provided private key. Valid options are pkcs8 or rsa_raw. Defaults to pkcs8. :returns: A loaded :class:`PrivateKeyEntry` instance, ready to be placed in a keystore. :raises UnsupportedKeyFormatException: If the key format is unsupported.
[ "Helper", "function", "to", "create", "a", "new", "PrivateKeyEntry", "." ]
1cbe7f060e2ad076b6462f3273f11d635771ea3d
https://github.com/kurtbrose/pyjks/blob/1cbe7f060e2ad076b6462f3273f11d635771ea3d/jks/jks.py#L117-L172
train
212,999