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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
PyFilesystem/pyfilesystem2 | fs/ftpfs.py | FTPFS.ftp_url | def ftp_url(self):
# type: () -> Text
"""Get the FTP url this filesystem will open."""
url = (
"ftp://{}".format(self.host)
if self.port == 21
else "ftp://{}:{}".format(self.host, self.port)
)
return url | python | def ftp_url(self):
# type: () -> Text
"""Get the FTP url this filesystem will open."""
url = (
"ftp://{}".format(self.host)
if self.port == 21
else "ftp://{}:{}".format(self.host, self.port)
)
return url | [
"def",
"ftp_url",
"(",
"self",
")",
":",
"# type: () -> Text",
"url",
"=",
"(",
"\"ftp://{}\"",
".",
"format",
"(",
"self",
".",
"host",
")",
"if",
"self",
".",
"port",
"==",
"21",
"else",
"\"ftp://{}:{}\"",
".",
"format",
"(",
"self",
".",
"host",
","... | Get the FTP url this filesystem will open. | [
"Get",
"the",
"FTP",
"url",
"this",
"filesystem",
"will",
"open",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/ftpfs.py#L440-L448 | train | 228,500 |
PyFilesystem/pyfilesystem2 | fs/ftpfs.py | FTPFS._parse_ftp_time | def _parse_ftp_time(cls, time_text):
# type: (Text) -> Optional[int]
"""Parse a time from an ftp directory listing.
"""
try:
tm_year = int(time_text[0:4])
tm_month = int(time_text[4:6])
tm_day = int(time_text[6:8])
tm_hour = int(time_text[8:10])
tm_min = int(time_text[10:12])
tm_sec = int(time_text[12:14])
except ValueError:
return None
epoch_time = calendar.timegm(
(tm_year, tm_month, tm_day, tm_hour, tm_min, tm_sec)
)
return epoch_time | python | def _parse_ftp_time(cls, time_text):
# type: (Text) -> Optional[int]
"""Parse a time from an ftp directory listing.
"""
try:
tm_year = int(time_text[0:4])
tm_month = int(time_text[4:6])
tm_day = int(time_text[6:8])
tm_hour = int(time_text[8:10])
tm_min = int(time_text[10:12])
tm_sec = int(time_text[12:14])
except ValueError:
return None
epoch_time = calendar.timegm(
(tm_year, tm_month, tm_day, tm_hour, tm_min, tm_sec)
)
return epoch_time | [
"def",
"_parse_ftp_time",
"(",
"cls",
",",
"time_text",
")",
":",
"# type: (Text) -> Optional[int]",
"try",
":",
"tm_year",
"=",
"int",
"(",
"time_text",
"[",
"0",
":",
"4",
"]",
")",
"tm_month",
"=",
"int",
"(",
"time_text",
"[",
"4",
":",
"6",
"]",
"... | Parse a time from an ftp directory listing. | [
"Parse",
"a",
"time",
"from",
"an",
"ftp",
"directory",
"listing",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/ftpfs.py#L506-L522 | train | 228,501 |
PyFilesystem/pyfilesystem2 | fs/compress.py | write_zip | def write_zip(
src_fs, # type: FS
file, # type: Union[Text, BinaryIO]
compression=zipfile.ZIP_DEFLATED, # type: int
encoding="utf-8", # type: Text
walker=None, # type: Optional[Walker]
):
# type: (...) -> None
"""Write the contents of a filesystem to a zip file.
Arguments:
src_fs (~fs.base.FS): The source filesystem to compress.
file (str or io.IOBase): Destination file, may be a file name
or an open file object.
compression (int): Compression to use (one of the constants
defined in the `zipfile` module in the stdlib). Defaults
to `zipfile.ZIP_DEFLATED`.
encoding (str):
The encoding to use for filenames. The default is ``"utf-8"``,
use ``"CP437"`` if compatibility with WinZip is desired.
walker (~fs.walk.Walker, optional): A `Walker` instance, or `None`
to use default walker. You can use this to specify which files
you want to compress.
"""
_zip = zipfile.ZipFile(file, mode="w", compression=compression, allowZip64=True)
walker = walker or Walker()
with _zip:
gen_walk = walker.info(src_fs, namespaces=["details", "stat", "access"])
for path, info in gen_walk:
# Zip names must be relative, directory names must end
# with a slash.
zip_name = relpath(path + "/" if info.is_dir else path)
if not six.PY3:
# Python2 expects bytes filenames
zip_name = zip_name.encode(encoding, "replace")
if info.has_namespace("stat"):
# If the file has a stat namespace, get the
# zip time directory from the stat structure
st_mtime = info.get("stat", "st_mtime", None)
_mtime = time.localtime(st_mtime)
zip_time = _mtime[0:6] # type: ZipTime
else:
# Otherwise, use the modified time from details
# namespace.
mt = info.modified or datetime.utcnow()
zip_time = (mt.year, mt.month, mt.day, mt.hour, mt.minute, mt.second)
# NOTE(@althonos): typeshed's `zipfile.py` on declares
# ZipInfo.__init__ for Python < 3 ?!
zip_info = zipfile.ZipInfo(zip_name, zip_time) # type: ignore
try:
if info.permissions is not None:
zip_info.external_attr = info.permissions.mode << 16
except MissingInfoNamespace:
pass
if info.is_dir:
zip_info.external_attr |= 0x10
# This is how to record directories with zipfile
_zip.writestr(zip_info, b"")
else:
# Get a syspath if possible
try:
sys_path = src_fs.getsyspath(path)
except NoSysPath:
# Write from bytes
_zip.writestr(zip_info, src_fs.readbytes(path))
else:
# Write from a file which is (presumably)
# more memory efficient
_zip.write(sys_path, zip_name) | python | def write_zip(
src_fs, # type: FS
file, # type: Union[Text, BinaryIO]
compression=zipfile.ZIP_DEFLATED, # type: int
encoding="utf-8", # type: Text
walker=None, # type: Optional[Walker]
):
# type: (...) -> None
"""Write the contents of a filesystem to a zip file.
Arguments:
src_fs (~fs.base.FS): The source filesystem to compress.
file (str or io.IOBase): Destination file, may be a file name
or an open file object.
compression (int): Compression to use (one of the constants
defined in the `zipfile` module in the stdlib). Defaults
to `zipfile.ZIP_DEFLATED`.
encoding (str):
The encoding to use for filenames. The default is ``"utf-8"``,
use ``"CP437"`` if compatibility with WinZip is desired.
walker (~fs.walk.Walker, optional): A `Walker` instance, or `None`
to use default walker. You can use this to specify which files
you want to compress.
"""
_zip = zipfile.ZipFile(file, mode="w", compression=compression, allowZip64=True)
walker = walker or Walker()
with _zip:
gen_walk = walker.info(src_fs, namespaces=["details", "stat", "access"])
for path, info in gen_walk:
# Zip names must be relative, directory names must end
# with a slash.
zip_name = relpath(path + "/" if info.is_dir else path)
if not six.PY3:
# Python2 expects bytes filenames
zip_name = zip_name.encode(encoding, "replace")
if info.has_namespace("stat"):
# If the file has a stat namespace, get the
# zip time directory from the stat structure
st_mtime = info.get("stat", "st_mtime", None)
_mtime = time.localtime(st_mtime)
zip_time = _mtime[0:6] # type: ZipTime
else:
# Otherwise, use the modified time from details
# namespace.
mt = info.modified or datetime.utcnow()
zip_time = (mt.year, mt.month, mt.day, mt.hour, mt.minute, mt.second)
# NOTE(@althonos): typeshed's `zipfile.py` on declares
# ZipInfo.__init__ for Python < 3 ?!
zip_info = zipfile.ZipInfo(zip_name, zip_time) # type: ignore
try:
if info.permissions is not None:
zip_info.external_attr = info.permissions.mode << 16
except MissingInfoNamespace:
pass
if info.is_dir:
zip_info.external_attr |= 0x10
# This is how to record directories with zipfile
_zip.writestr(zip_info, b"")
else:
# Get a syspath if possible
try:
sys_path = src_fs.getsyspath(path)
except NoSysPath:
# Write from bytes
_zip.writestr(zip_info, src_fs.readbytes(path))
else:
# Write from a file which is (presumably)
# more memory efficient
_zip.write(sys_path, zip_name) | [
"def",
"write_zip",
"(",
"src_fs",
",",
"# type: FS",
"file",
",",
"# type: Union[Text, BinaryIO]",
"compression",
"=",
"zipfile",
".",
"ZIP_DEFLATED",
",",
"# type: int",
"encoding",
"=",
"\"utf-8\"",
",",
"# type: Text",
"walker",
"=",
"None",
",",
"# type: Option... | Write the contents of a filesystem to a zip file.
Arguments:
src_fs (~fs.base.FS): The source filesystem to compress.
file (str or io.IOBase): Destination file, may be a file name
or an open file object.
compression (int): Compression to use (one of the constants
defined in the `zipfile` module in the stdlib). Defaults
to `zipfile.ZIP_DEFLATED`.
encoding (str):
The encoding to use for filenames. The default is ``"utf-8"``,
use ``"CP437"`` if compatibility with WinZip is desired.
walker (~fs.walk.Walker, optional): A `Walker` instance, or `None`
to use default walker. You can use this to specify which files
you want to compress. | [
"Write",
"the",
"contents",
"of",
"a",
"filesystem",
"to",
"a",
"zip",
"file",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/compress.py#L32-L105 | train | 228,502 |
PyFilesystem/pyfilesystem2 | fs/compress.py | write_tar | def write_tar(
src_fs, # type: FS
file, # type: Union[Text, BinaryIO]
compression=None, # type: Optional[Text]
encoding="utf-8", # type: Text
walker=None, # type: Optional[Walker]
):
# type: (...) -> None
"""Write the contents of a filesystem to a tar file.
Arguments:
file (str or io.IOBase): Destination file, may be a file
name or an open file object.
compression (str, optional): Compression to use, or `None`
for a plain Tar archive without compression.
encoding(str): The encoding to use for filenames. The
default is ``"utf-8"``.
walker (~fs.walk.Walker, optional): A `Walker` instance, or
`None` to use default walker. You can use this to specify
which files you want to compress.
"""
type_map = {
ResourceType.block_special_file: tarfile.BLKTYPE,
ResourceType.character: tarfile.CHRTYPE,
ResourceType.directory: tarfile.DIRTYPE,
ResourceType.fifo: tarfile.FIFOTYPE,
ResourceType.file: tarfile.REGTYPE,
ResourceType.socket: tarfile.AREGTYPE, # no type for socket
ResourceType.symlink: tarfile.SYMTYPE,
ResourceType.unknown: tarfile.AREGTYPE, # no type for unknown
}
tar_attr = [("uid", "uid"), ("gid", "gid"), ("uname", "user"), ("gname", "group")]
mode = "w:{}".format(compression or "")
if isinstance(file, (six.text_type, six.binary_type)):
_tar = tarfile.open(file, mode=mode)
else:
_tar = tarfile.open(fileobj=file, mode=mode)
current_time = time.time()
walker = walker or Walker()
with _tar:
gen_walk = walker.info(src_fs, namespaces=["details", "stat", "access"])
for path, info in gen_walk:
# Tar names must be relative
tar_name = relpath(path)
if not six.PY3:
# Python2 expects bytes filenames
tar_name = tar_name.encode(encoding, "replace")
tar_info = tarfile.TarInfo(tar_name)
if info.has_namespace("stat"):
mtime = info.get("stat", "st_mtime", current_time)
else:
mtime = info.modified or current_time
if isinstance(mtime, datetime):
mtime = datetime_to_epoch(mtime)
if isinstance(mtime, float):
mtime = int(mtime)
tar_info.mtime = mtime
for tarattr, infoattr in tar_attr:
if getattr(info, infoattr, None) is not None:
setattr(tar_info, tarattr, getattr(info, infoattr, None))
if info.has_namespace("access"):
tar_info.mode = getattr(info.permissions, "mode", 0o420)
if info.is_dir:
tar_info.type = tarfile.DIRTYPE
_tar.addfile(tar_info)
else:
tar_info.type = type_map.get(info.type, tarfile.REGTYPE)
tar_info.size = info.size
with src_fs.openbin(path) as bin_file:
_tar.addfile(tar_info, bin_file) | python | def write_tar(
src_fs, # type: FS
file, # type: Union[Text, BinaryIO]
compression=None, # type: Optional[Text]
encoding="utf-8", # type: Text
walker=None, # type: Optional[Walker]
):
# type: (...) -> None
"""Write the contents of a filesystem to a tar file.
Arguments:
file (str or io.IOBase): Destination file, may be a file
name or an open file object.
compression (str, optional): Compression to use, or `None`
for a plain Tar archive without compression.
encoding(str): The encoding to use for filenames. The
default is ``"utf-8"``.
walker (~fs.walk.Walker, optional): A `Walker` instance, or
`None` to use default walker. You can use this to specify
which files you want to compress.
"""
type_map = {
ResourceType.block_special_file: tarfile.BLKTYPE,
ResourceType.character: tarfile.CHRTYPE,
ResourceType.directory: tarfile.DIRTYPE,
ResourceType.fifo: tarfile.FIFOTYPE,
ResourceType.file: tarfile.REGTYPE,
ResourceType.socket: tarfile.AREGTYPE, # no type for socket
ResourceType.symlink: tarfile.SYMTYPE,
ResourceType.unknown: tarfile.AREGTYPE, # no type for unknown
}
tar_attr = [("uid", "uid"), ("gid", "gid"), ("uname", "user"), ("gname", "group")]
mode = "w:{}".format(compression or "")
if isinstance(file, (six.text_type, six.binary_type)):
_tar = tarfile.open(file, mode=mode)
else:
_tar = tarfile.open(fileobj=file, mode=mode)
current_time = time.time()
walker = walker or Walker()
with _tar:
gen_walk = walker.info(src_fs, namespaces=["details", "stat", "access"])
for path, info in gen_walk:
# Tar names must be relative
tar_name = relpath(path)
if not six.PY3:
# Python2 expects bytes filenames
tar_name = tar_name.encode(encoding, "replace")
tar_info = tarfile.TarInfo(tar_name)
if info.has_namespace("stat"):
mtime = info.get("stat", "st_mtime", current_time)
else:
mtime = info.modified or current_time
if isinstance(mtime, datetime):
mtime = datetime_to_epoch(mtime)
if isinstance(mtime, float):
mtime = int(mtime)
tar_info.mtime = mtime
for tarattr, infoattr in tar_attr:
if getattr(info, infoattr, None) is not None:
setattr(tar_info, tarattr, getattr(info, infoattr, None))
if info.has_namespace("access"):
tar_info.mode = getattr(info.permissions, "mode", 0o420)
if info.is_dir:
tar_info.type = tarfile.DIRTYPE
_tar.addfile(tar_info)
else:
tar_info.type = type_map.get(info.type, tarfile.REGTYPE)
tar_info.size = info.size
with src_fs.openbin(path) as bin_file:
_tar.addfile(tar_info, bin_file) | [
"def",
"write_tar",
"(",
"src_fs",
",",
"# type: FS",
"file",
",",
"# type: Union[Text, BinaryIO]",
"compression",
"=",
"None",
",",
"# type: Optional[Text]",
"encoding",
"=",
"\"utf-8\"",
",",
"# type: Text",
"walker",
"=",
"None",
",",
"# type: Optional[Walker]",
")... | Write the contents of a filesystem to a tar file.
Arguments:
file (str or io.IOBase): Destination file, may be a file
name or an open file object.
compression (str, optional): Compression to use, or `None`
for a plain Tar archive without compression.
encoding(str): The encoding to use for filenames. The
default is ``"utf-8"``.
walker (~fs.walk.Walker, optional): A `Walker` instance, or
`None` to use default walker. You can use this to specify
which files you want to compress. | [
"Write",
"the",
"contents",
"of",
"a",
"filesystem",
"to",
"a",
"tar",
"file",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/compress.py#L108-L187 | train | 228,503 |
PyFilesystem/pyfilesystem2 | fs/glob.py | Globber.count_lines | def count_lines(self):
# type: () -> LineCounts
"""Count the lines in the matched files.
Returns:
`~LineCounts`: A named tuple containing line counts.
Example:
>>> import fs
>>> fs.open_fs('~/projects').glob('**/*.py').count_lines()
LineCounts(lines=5767102, non_blank=4915110)
"""
lines = 0
non_blank = 0
for path, info in self._make_iter():
if info.is_file:
for line in self.fs.open(path, "rb"):
lines += 1
if line.rstrip():
non_blank += 1
return LineCounts(lines=lines, non_blank=non_blank) | python | def count_lines(self):
# type: () -> LineCounts
"""Count the lines in the matched files.
Returns:
`~LineCounts`: A named tuple containing line counts.
Example:
>>> import fs
>>> fs.open_fs('~/projects').glob('**/*.py').count_lines()
LineCounts(lines=5767102, non_blank=4915110)
"""
lines = 0
non_blank = 0
for path, info in self._make_iter():
if info.is_file:
for line in self.fs.open(path, "rb"):
lines += 1
if line.rstrip():
non_blank += 1
return LineCounts(lines=lines, non_blank=non_blank) | [
"def",
"count_lines",
"(",
"self",
")",
":",
"# type: () -> LineCounts",
"lines",
"=",
"0",
"non_blank",
"=",
"0",
"for",
"path",
",",
"info",
"in",
"self",
".",
"_make_iter",
"(",
")",
":",
"if",
"info",
".",
"is_file",
":",
"for",
"line",
"in",
"self... | Count the lines in the matched files.
Returns:
`~LineCounts`: A named tuple containing line counts.
Example:
>>> import fs
>>> fs.open_fs('~/projects').glob('**/*.py').count_lines()
LineCounts(lines=5767102, non_blank=4915110) | [
"Count",
"the",
"lines",
"in",
"the",
"matched",
"files",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/glob.py#L190-L212 | train | 228,504 |
PyFilesystem/pyfilesystem2 | fs/glob.py | Globber.remove | def remove(self):
# type: () -> int
"""Removed all matched paths.
Returns:
int: Number of file and directories removed.
Example:
>>> import fs
>>> fs.open_fs('~/projects/my_project').glob('**/*.pyc').remove()
29
"""
removes = 0
for path, info in self._make_iter(search="depth"):
if info.is_dir:
self.fs.removetree(path)
else:
self.fs.remove(path)
removes += 1
return removes | python | def remove(self):
# type: () -> int
"""Removed all matched paths.
Returns:
int: Number of file and directories removed.
Example:
>>> import fs
>>> fs.open_fs('~/projects/my_project').glob('**/*.pyc').remove()
29
"""
removes = 0
for path, info in self._make_iter(search="depth"):
if info.is_dir:
self.fs.removetree(path)
else:
self.fs.remove(path)
removes += 1
return removes | [
"def",
"remove",
"(",
"self",
")",
":",
"# type: () -> int",
"removes",
"=",
"0",
"for",
"path",
",",
"info",
"in",
"self",
".",
"_make_iter",
"(",
"search",
"=",
"\"depth\"",
")",
":",
"if",
"info",
".",
"is_dir",
":",
"self",
".",
"fs",
".",
"remov... | Removed all matched paths.
Returns:
int: Number of file and directories removed.
Example:
>>> import fs
>>> fs.open_fs('~/projects/my_project').glob('**/*.pyc').remove()
29 | [
"Removed",
"all",
"matched",
"paths",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/glob.py#L214-L234 | train | 228,505 |
PyFilesystem/pyfilesystem2 | fs/move.py | move_file | def move_file(
src_fs, # type: Union[Text, FS]
src_path, # type: Text
dst_fs, # type: Union[Text, FS]
dst_path, # type: Text
):
# type: (...) -> None
"""Move a file from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a file on ``src_fs``.
dst_fs (FS or str); Destination filesystem (instance or URL).
dst_path (str): Path to a file on ``dst_fs``.
"""
with manage_fs(src_fs) as _src_fs:
with manage_fs(dst_fs, create=True) as _dst_fs:
if _src_fs is _dst_fs:
# Same filesystem, may be optimized
_src_fs.move(src_path, dst_path, overwrite=True)
else:
# Standard copy and delete
with _src_fs.lock(), _dst_fs.lock():
copy_file(_src_fs, src_path, _dst_fs, dst_path)
_src_fs.remove(src_path) | python | def move_file(
src_fs, # type: Union[Text, FS]
src_path, # type: Text
dst_fs, # type: Union[Text, FS]
dst_path, # type: Text
):
# type: (...) -> None
"""Move a file from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a file on ``src_fs``.
dst_fs (FS or str); Destination filesystem (instance or URL).
dst_path (str): Path to a file on ``dst_fs``.
"""
with manage_fs(src_fs) as _src_fs:
with manage_fs(dst_fs, create=True) as _dst_fs:
if _src_fs is _dst_fs:
# Same filesystem, may be optimized
_src_fs.move(src_path, dst_path, overwrite=True)
else:
# Standard copy and delete
with _src_fs.lock(), _dst_fs.lock():
copy_file(_src_fs, src_path, _dst_fs, dst_path)
_src_fs.remove(src_path) | [
"def",
"move_file",
"(",
"src_fs",
",",
"# type: Union[Text, FS]",
"src_path",
",",
"# type: Text",
"dst_fs",
",",
"# type: Union[Text, FS]",
"dst_path",
",",
"# type: Text",
")",
":",
"# type: (...) -> None",
"with",
"manage_fs",
"(",
"src_fs",
")",
"as",
"_src_fs",
... | Move a file from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a file on ``src_fs``.
dst_fs (FS or str); Destination filesystem (instance or URL).
dst_path (str): Path to a file on ``dst_fs``. | [
"Move",
"a",
"file",
"from",
"one",
"filesystem",
"to",
"another",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/move.py#L32-L57 | train | 228,506 |
PyFilesystem/pyfilesystem2 | fs/move.py | move_dir | def move_dir(
src_fs, # type: Union[Text, FS]
src_path, # type: Text
dst_fs, # type: Union[Text, FS]
dst_path, # type: Text
workers=0, # type: int
):
# type: (...) -> None
"""Move a directory from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on ``src_fs``
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a directory on ``dst_fs``.
workers (int): Use `worker` threads to copy data, or ``0`` (default) for
a single-threaded copy.
"""
def src():
return manage_fs(src_fs, writeable=False)
def dst():
return manage_fs(dst_fs, create=True)
with src() as _src_fs, dst() as _dst_fs:
with _src_fs.lock(), _dst_fs.lock():
_dst_fs.makedir(dst_path, recreate=True)
copy_dir(src_fs, src_path, dst_fs, dst_path, workers=workers)
_src_fs.removetree(src_path) | python | def move_dir(
src_fs, # type: Union[Text, FS]
src_path, # type: Text
dst_fs, # type: Union[Text, FS]
dst_path, # type: Text
workers=0, # type: int
):
# type: (...) -> None
"""Move a directory from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on ``src_fs``
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a directory on ``dst_fs``.
workers (int): Use `worker` threads to copy data, or ``0`` (default) for
a single-threaded copy.
"""
def src():
return manage_fs(src_fs, writeable=False)
def dst():
return manage_fs(dst_fs, create=True)
with src() as _src_fs, dst() as _dst_fs:
with _src_fs.lock(), _dst_fs.lock():
_dst_fs.makedir(dst_path, recreate=True)
copy_dir(src_fs, src_path, dst_fs, dst_path, workers=workers)
_src_fs.removetree(src_path) | [
"def",
"move_dir",
"(",
"src_fs",
",",
"# type: Union[Text, FS]",
"src_path",
",",
"# type: Text",
"dst_fs",
",",
"# type: Union[Text, FS]",
"dst_path",
",",
"# type: Text",
"workers",
"=",
"0",
",",
"# type: int",
")",
":",
"# type: (...) -> None",
"def",
"src",
"(... | Move a directory from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on ``src_fs``
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a directory on ``dst_fs``.
workers (int): Use `worker` threads to copy data, or ``0`` (default) for
a single-threaded copy. | [
"Move",
"a",
"directory",
"from",
"one",
"filesystem",
"to",
"another",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/move.py#L60-L90 | train | 228,507 |
PyFilesystem/pyfilesystem2 | fs/path.py | recursepath | def recursepath(path, reverse=False):
# type: (Text, bool) -> List[Text]
"""Get intermediate paths from the root to the given path.
Arguments:
path (str): A PyFilesystem path
reverse (bool): Reverses the order of the paths
(default `False`).
Returns:
list: A list of paths.
Example:
>>> recursepath('a/b/c')
['/', '/a', '/a/b', '/a/b/c']
"""
if path in "/":
return ["/"]
path = abspath(normpath(path)) + "/"
paths = ["/"]
find = path.find
append = paths.append
pos = 1
len_path = len(path)
while pos < len_path:
pos = find("/", pos)
append(path[:pos])
pos += 1
if reverse:
return paths[::-1]
return paths | python | def recursepath(path, reverse=False):
# type: (Text, bool) -> List[Text]
"""Get intermediate paths from the root to the given path.
Arguments:
path (str): A PyFilesystem path
reverse (bool): Reverses the order of the paths
(default `False`).
Returns:
list: A list of paths.
Example:
>>> recursepath('a/b/c')
['/', '/a', '/a/b', '/a/b/c']
"""
if path in "/":
return ["/"]
path = abspath(normpath(path)) + "/"
paths = ["/"]
find = path.find
append = paths.append
pos = 1
len_path = len(path)
while pos < len_path:
pos = find("/", pos)
append(path[:pos])
pos += 1
if reverse:
return paths[::-1]
return paths | [
"def",
"recursepath",
"(",
"path",
",",
"reverse",
"=",
"False",
")",
":",
"# type: (Text, bool) -> List[Text]",
"if",
"path",
"in",
"\"/\"",
":",
"return",
"[",
"\"/\"",
"]",
"path",
"=",
"abspath",
"(",
"normpath",
"(",
"path",
")",
")",
"+",
"\"/\"",
... | Get intermediate paths from the root to the given path.
Arguments:
path (str): A PyFilesystem path
reverse (bool): Reverses the order of the paths
(default `False`).
Returns:
list: A list of paths.
Example:
>>> recursepath('a/b/c')
['/', '/a', '/a/b', '/a/b/c'] | [
"Get",
"intermediate",
"paths",
"from",
"the",
"root",
"to",
"the",
"given",
"path",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/path.py#L114-L149 | train | 228,508 |
PyFilesystem/pyfilesystem2 | fs/path.py | join | def join(*paths):
# type: (*Text) -> Text
"""Join any number of paths together.
Arguments:
*paths (str): Paths to join, given as positional arguments.
Returns:
str: The joined path.
Example:
>>> join('foo', 'bar', 'baz')
'foo/bar/baz'
>>> join('foo/bar', '../baz')
'foo/baz'
>>> join('foo/bar', '/baz')
'/baz'
"""
absolute = False
relpaths = [] # type: List[Text]
for p in paths:
if p:
if p[0] == "/":
del relpaths[:]
absolute = True
relpaths.append(p)
path = normpath("/".join(relpaths))
if absolute:
path = abspath(path)
return path | python | def join(*paths):
# type: (*Text) -> Text
"""Join any number of paths together.
Arguments:
*paths (str): Paths to join, given as positional arguments.
Returns:
str: The joined path.
Example:
>>> join('foo', 'bar', 'baz')
'foo/bar/baz'
>>> join('foo/bar', '../baz')
'foo/baz'
>>> join('foo/bar', '/baz')
'/baz'
"""
absolute = False
relpaths = [] # type: List[Text]
for p in paths:
if p:
if p[0] == "/":
del relpaths[:]
absolute = True
relpaths.append(p)
path = normpath("/".join(relpaths))
if absolute:
path = abspath(path)
return path | [
"def",
"join",
"(",
"*",
"paths",
")",
":",
"# type: (*Text) -> Text",
"absolute",
"=",
"False",
"relpaths",
"=",
"[",
"]",
"# type: List[Text]",
"for",
"p",
"in",
"paths",
":",
"if",
"p",
":",
"if",
"p",
"[",
"0",
"]",
"==",
"\"/\"",
":",
"del",
"re... | Join any number of paths together.
Arguments:
*paths (str): Paths to join, given as positional arguments.
Returns:
str: The joined path.
Example:
>>> join('foo', 'bar', 'baz')
'foo/bar/baz'
>>> join('foo/bar', '../baz')
'foo/baz'
>>> join('foo/bar', '/baz')
'/baz' | [
"Join",
"any",
"number",
"of",
"paths",
"together",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/path.py#L208-L239 | train | 228,509 |
PyFilesystem/pyfilesystem2 | fs/path.py | combine | def combine(path1, path2):
# type: (Text, Text) -> Text
"""Join two paths together.
This is faster than :func:`~fs.path.join`, but only works when the
second path is relative, and there are no back references in either
path.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
str: The joint path.
Example:
>>> combine("foo/bar", "baz")
'foo/bar/baz'
"""
if not path1:
return path2.lstrip()
return "{}/{}".format(path1.rstrip("/"), path2.lstrip("/")) | python | def combine(path1, path2):
# type: (Text, Text) -> Text
"""Join two paths together.
This is faster than :func:`~fs.path.join`, but only works when the
second path is relative, and there are no back references in either
path.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
str: The joint path.
Example:
>>> combine("foo/bar", "baz")
'foo/bar/baz'
"""
if not path1:
return path2.lstrip()
return "{}/{}".format(path1.rstrip("/"), path2.lstrip("/")) | [
"def",
"combine",
"(",
"path1",
",",
"path2",
")",
":",
"# type: (Text, Text) -> Text",
"if",
"not",
"path1",
":",
"return",
"path2",
".",
"lstrip",
"(",
")",
"return",
"\"{}/{}\"",
".",
"format",
"(",
"path1",
".",
"rstrip",
"(",
"\"/\"",
")",
",",
"pat... | Join two paths together.
This is faster than :func:`~fs.path.join`, but only works when the
second path is relative, and there are no back references in either
path.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
str: The joint path.
Example:
>>> combine("foo/bar", "baz")
'foo/bar/baz' | [
"Join",
"two",
"paths",
"together",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/path.py#L242-L264 | train | 228,510 |
PyFilesystem/pyfilesystem2 | fs/path.py | parts | def parts(path):
# type: (Text) -> List[Text]
"""Split a path in to its component parts.
Arguments:
path (str): Path to split in to parts.
Returns:
list: List of components
Example:
>>> parts('/foo/bar/baz')
['/', 'foo', 'bar', 'baz']
"""
_path = normpath(path)
components = _path.strip("/")
_parts = ["/" if _path.startswith("/") else "./"]
if components:
_parts += components.split("/")
return _parts | python | def parts(path):
# type: (Text) -> List[Text]
"""Split a path in to its component parts.
Arguments:
path (str): Path to split in to parts.
Returns:
list: List of components
Example:
>>> parts('/foo/bar/baz')
['/', 'foo', 'bar', 'baz']
"""
_path = normpath(path)
components = _path.strip("/")
_parts = ["/" if _path.startswith("/") else "./"]
if components:
_parts += components.split("/")
return _parts | [
"def",
"parts",
"(",
"path",
")",
":",
"# type: (Text) -> List[Text]",
"_path",
"=",
"normpath",
"(",
"path",
")",
"components",
"=",
"_path",
".",
"strip",
"(",
"\"/\"",
")",
"_parts",
"=",
"[",
"\"/\"",
"if",
"_path",
".",
"startswith",
"(",
"\"/\"",
"... | Split a path in to its component parts.
Arguments:
path (str): Path to split in to parts.
Returns:
list: List of components
Example:
>>> parts('/foo/bar/baz')
['/', 'foo', 'bar', 'baz'] | [
"Split",
"a",
"path",
"in",
"to",
"its",
"component",
"parts",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/path.py#L267-L288 | train | 228,511 |
PyFilesystem/pyfilesystem2 | fs/path.py | splitext | def splitext(path):
# type: (Text) -> Tuple[Text, Text]
"""Split the extension from the path.
Arguments:
path (str): A path to split.
Returns:
(str, str): A tuple containing the path and the extension.
Example:
>>> splitext('baz.txt')
('baz', '.txt')
>>> splitext('foo/bar/baz.txt')
('foo/bar/baz', '.txt')
>>> splitext('foo/bar/.foo')
('foo/bar/.foo', '')
"""
parent_path, pathname = split(path)
if pathname.startswith(".") and pathname.count(".") == 1:
return path, ""
if "." not in pathname:
return path, ""
pathname, ext = pathname.rsplit(".", 1)
path = join(parent_path, pathname)
return path, "." + ext | python | def splitext(path):
# type: (Text) -> Tuple[Text, Text]
"""Split the extension from the path.
Arguments:
path (str): A path to split.
Returns:
(str, str): A tuple containing the path and the extension.
Example:
>>> splitext('baz.txt')
('baz', '.txt')
>>> splitext('foo/bar/baz.txt')
('foo/bar/baz', '.txt')
>>> splitext('foo/bar/.foo')
('foo/bar/.foo', '')
"""
parent_path, pathname = split(path)
if pathname.startswith(".") and pathname.count(".") == 1:
return path, ""
if "." not in pathname:
return path, ""
pathname, ext = pathname.rsplit(".", 1)
path = join(parent_path, pathname)
return path, "." + ext | [
"def",
"splitext",
"(",
"path",
")",
":",
"# type: (Text) -> Tuple[Text, Text]",
"parent_path",
",",
"pathname",
"=",
"split",
"(",
"path",
")",
"if",
"pathname",
".",
"startswith",
"(",
"\".\"",
")",
"and",
"pathname",
".",
"count",
"(",
"\".\"",
")",
"==",... | Split the extension from the path.
Arguments:
path (str): A path to split.
Returns:
(str, str): A tuple containing the path and the extension.
Example:
>>> splitext('baz.txt')
('baz', '.txt')
>>> splitext('foo/bar/baz.txt')
('foo/bar/baz', '.txt')
>>> splitext('foo/bar/.foo')
('foo/bar/.foo', '') | [
"Split",
"the",
"extension",
"from",
"the",
"path",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/path.py#L319-L345 | train | 228,512 |
PyFilesystem/pyfilesystem2 | fs/path.py | isbase | def isbase(path1, path2):
# type: (Text, Text) -> bool
"""Check if ``path1`` is a base of ``path2``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
bool: `True` if ``path2`` starts with ``path1``
Example:
>>> isbase('foo/bar', 'foo/bar/baz/egg.txt')
True
"""
_path1 = forcedir(abspath(path1))
_path2 = forcedir(abspath(path2))
return _path2.startswith(_path1) | python | def isbase(path1, path2):
# type: (Text, Text) -> bool
"""Check if ``path1`` is a base of ``path2``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
bool: `True` if ``path2`` starts with ``path1``
Example:
>>> isbase('foo/bar', 'foo/bar/baz/egg.txt')
True
"""
_path1 = forcedir(abspath(path1))
_path2 = forcedir(abspath(path2))
return _path2.startswith(_path1) | [
"def",
"isbase",
"(",
"path1",
",",
"path2",
")",
":",
"# type: (Text, Text) -> bool",
"_path1",
"=",
"forcedir",
"(",
"abspath",
"(",
"path1",
")",
")",
"_path2",
"=",
"forcedir",
"(",
"abspath",
"(",
"path2",
")",
")",
"return",
"_path2",
".",
"startswit... | Check if ``path1`` is a base of ``path2``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
bool: `True` if ``path2`` starts with ``path1``
Example:
>>> isbase('foo/bar', 'foo/bar/baz/egg.txt')
True | [
"Check",
"if",
"path1",
"is",
"a",
"base",
"of",
"path2",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/path.py#L441-L459 | train | 228,513 |
PyFilesystem/pyfilesystem2 | fs/path.py | isparent | def isparent(path1, path2):
# type: (Text, Text) -> bool
"""Check if ``path1`` is a parent directory of ``path2``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
bool: `True` if ``path1`` is a parent directory of ``path2``
Example:
>>> isparent("foo/bar", "foo/bar/spam.txt")
True
>>> isparent("foo/bar/", "foo/bar")
True
>>> isparent("foo/barry", "foo/baz/bar")
False
>>> isparent("foo/bar/baz/", "foo/baz/bar")
False
"""
bits1 = path1.split("/")
bits2 = path2.split("/")
while bits1 and bits1[-1] == "":
bits1.pop()
if len(bits1) > len(bits2):
return False
for (bit1, bit2) in zip(bits1, bits2):
if bit1 != bit2:
return False
return True | python | def isparent(path1, path2):
# type: (Text, Text) -> bool
"""Check if ``path1`` is a parent directory of ``path2``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
bool: `True` if ``path1`` is a parent directory of ``path2``
Example:
>>> isparent("foo/bar", "foo/bar/spam.txt")
True
>>> isparent("foo/bar/", "foo/bar")
True
>>> isparent("foo/barry", "foo/baz/bar")
False
>>> isparent("foo/bar/baz/", "foo/baz/bar")
False
"""
bits1 = path1.split("/")
bits2 = path2.split("/")
while bits1 and bits1[-1] == "":
bits1.pop()
if len(bits1) > len(bits2):
return False
for (bit1, bit2) in zip(bits1, bits2):
if bit1 != bit2:
return False
return True | [
"def",
"isparent",
"(",
"path1",
",",
"path2",
")",
":",
"# type: (Text, Text) -> bool",
"bits1",
"=",
"path1",
".",
"split",
"(",
"\"/\"",
")",
"bits2",
"=",
"path2",
".",
"split",
"(",
"\"/\"",
")",
"while",
"bits1",
"and",
"bits1",
"[",
"-",
"1",
"]... | Check if ``path1`` is a parent directory of ``path2``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
bool: `True` if ``path1`` is a parent directory of ``path2``
Example:
>>> isparent("foo/bar", "foo/bar/spam.txt")
True
>>> isparent("foo/bar/", "foo/bar")
True
>>> isparent("foo/barry", "foo/baz/bar")
False
>>> isparent("foo/bar/baz/", "foo/baz/bar")
False | [
"Check",
"if",
"path1",
"is",
"a",
"parent",
"directory",
"of",
"path2",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/path.py#L462-L493 | train | 228,514 |
PyFilesystem/pyfilesystem2 | fs/path.py | frombase | def frombase(path1, path2):
# type: (Text, Text) -> Text
"""Get the final path of ``path2`` that isn't in ``path1``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
str: the final part of ``path2``.
Example:
>>> frombase('foo/bar/', 'foo/bar/baz/egg')
'baz/egg'
"""
if not isparent(path1, path2):
raise ValueError("path1 must be a prefix of path2")
return path2[len(path1) :] | python | def frombase(path1, path2):
# type: (Text, Text) -> Text
"""Get the final path of ``path2`` that isn't in ``path1``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
str: the final part of ``path2``.
Example:
>>> frombase('foo/bar/', 'foo/bar/baz/egg')
'baz/egg'
"""
if not isparent(path1, path2):
raise ValueError("path1 must be a prefix of path2")
return path2[len(path1) :] | [
"def",
"frombase",
"(",
"path1",
",",
"path2",
")",
":",
"# type: (Text, Text) -> Text",
"if",
"not",
"isparent",
"(",
"path1",
",",
"path2",
")",
":",
"raise",
"ValueError",
"(",
"\"path1 must be a prefix of path2\"",
")",
"return",
"path2",
"[",
"len",
"(",
... | Get the final path of ``path2`` that isn't in ``path1``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
str: the final part of ``path2``.
Example:
>>> frombase('foo/bar/', 'foo/bar/baz/egg')
'baz/egg' | [
"Get",
"the",
"final",
"path",
"of",
"path2",
"that",
"isn",
"t",
"in",
"path1",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/path.py#L520-L538 | train | 228,515 |
PyFilesystem/pyfilesystem2 | fs/path.py | relativefrom | def relativefrom(base, path):
# type: (Text, Text) -> Text
"""Return a path relative from a given base path.
Insert backrefs as appropriate to reach the path from the base.
Arguments:
base (str): Path to a directory.
path (str): Path to make relative.
Returns:
str: the path to ``base`` from ``path``.
>>> relativefrom("foo/bar", "baz/index.html")
'../../baz/index.html'
"""
base_parts = list(iteratepath(base))
path_parts = list(iteratepath(path))
common = 0
for component_a, component_b in zip(base_parts, path_parts):
if component_a != component_b:
break
common += 1
return "/".join([".."] * (len(base_parts) - common) + path_parts[common:]) | python | def relativefrom(base, path):
# type: (Text, Text) -> Text
"""Return a path relative from a given base path.
Insert backrefs as appropriate to reach the path from the base.
Arguments:
base (str): Path to a directory.
path (str): Path to make relative.
Returns:
str: the path to ``base`` from ``path``.
>>> relativefrom("foo/bar", "baz/index.html")
'../../baz/index.html'
"""
base_parts = list(iteratepath(base))
path_parts = list(iteratepath(path))
common = 0
for component_a, component_b in zip(base_parts, path_parts):
if component_a != component_b:
break
common += 1
return "/".join([".."] * (len(base_parts) - common) + path_parts[common:]) | [
"def",
"relativefrom",
"(",
"base",
",",
"path",
")",
":",
"# type: (Text, Text) -> Text",
"base_parts",
"=",
"list",
"(",
"iteratepath",
"(",
"base",
")",
")",
"path_parts",
"=",
"list",
"(",
"iteratepath",
"(",
"path",
")",
")",
"common",
"=",
"0",
"for"... | Return a path relative from a given base path.
Insert backrefs as appropriate to reach the path from the base.
Arguments:
base (str): Path to a directory.
path (str): Path to make relative.
Returns:
str: the path to ``base`` from ``path``.
>>> relativefrom("foo/bar", "baz/index.html")
'../../baz/index.html' | [
"Return",
"a",
"path",
"relative",
"from",
"a",
"given",
"base",
"path",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/path.py#L541-L567 | train | 228,516 |
PyFilesystem/pyfilesystem2 | fs/error_tools.py | unwrap_errors | def unwrap_errors(path_replace):
# type: (Union[Text, Mapping[Text, Text]]) -> Iterator[None]
"""Get a context to map OS errors to their `fs.errors` counterpart.
The context will re-write the paths in resource exceptions to be
in the same context as the wrapped filesystem.
The only parameter may be the path from the parent, if only one path
is to be unwrapped. Or it may be a dictionary that maps wrapped
paths on to unwrapped paths.
"""
try:
yield
except errors.ResourceError as e:
if hasattr(e, "path"):
if isinstance(path_replace, Mapping):
e.path = path_replace.get(e.path, e.path)
else:
e.path = path_replace
reraise(type(e), e) | python | def unwrap_errors(path_replace):
# type: (Union[Text, Mapping[Text, Text]]) -> Iterator[None]
"""Get a context to map OS errors to their `fs.errors` counterpart.
The context will re-write the paths in resource exceptions to be
in the same context as the wrapped filesystem.
The only parameter may be the path from the parent, if only one path
is to be unwrapped. Or it may be a dictionary that maps wrapped
paths on to unwrapped paths.
"""
try:
yield
except errors.ResourceError as e:
if hasattr(e, "path"):
if isinstance(path_replace, Mapping):
e.path = path_replace.get(e.path, e.path)
else:
e.path = path_replace
reraise(type(e), e) | [
"def",
"unwrap_errors",
"(",
"path_replace",
")",
":",
"# type: (Union[Text, Mapping[Text, Text]]) -> Iterator[None]",
"try",
":",
"yield",
"except",
"errors",
".",
"ResourceError",
"as",
"e",
":",
"if",
"hasattr",
"(",
"e",
",",
"\"path\"",
")",
":",
"if",
"isins... | Get a context to map OS errors to their `fs.errors` counterpart.
The context will re-write the paths in resource exceptions to be
in the same context as the wrapped filesystem.
The only parameter may be the path from the parent, if only one path
is to be unwrapped. Or it may be a dictionary that maps wrapped
paths on to unwrapped paths. | [
"Get",
"a",
"context",
"to",
"map",
"OS",
"errors",
"to",
"their",
"fs",
".",
"errors",
"counterpart",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/error_tools.py#L99-L119 | train | 228,517 |
PyFilesystem/pyfilesystem2 | fs/wildcard.py | match | def match(pattern, name):
# type: (Text, Text) -> bool
"""Test whether a name matches a wildcard pattern.
Arguments:
pattern (str): A wildcard pattern, e.g. ``"*.py"``.
name (str): A filename.
Returns:
bool: `True` if the filename matches the pattern.
"""
try:
re_pat = _PATTERN_CACHE[(pattern, True)]
except KeyError:
res = "(?ms)" + _translate(pattern) + r'\Z'
_PATTERN_CACHE[(pattern, True)] = re_pat = re.compile(res)
return re_pat.match(name) is not None | python | def match(pattern, name):
# type: (Text, Text) -> bool
"""Test whether a name matches a wildcard pattern.
Arguments:
pattern (str): A wildcard pattern, e.g. ``"*.py"``.
name (str): A filename.
Returns:
bool: `True` if the filename matches the pattern.
"""
try:
re_pat = _PATTERN_CACHE[(pattern, True)]
except KeyError:
res = "(?ms)" + _translate(pattern) + r'\Z'
_PATTERN_CACHE[(pattern, True)] = re_pat = re.compile(res)
return re_pat.match(name) is not None | [
"def",
"match",
"(",
"pattern",
",",
"name",
")",
":",
"# type: (Text, Text) -> bool",
"try",
":",
"re_pat",
"=",
"_PATTERN_CACHE",
"[",
"(",
"pattern",
",",
"True",
")",
"]",
"except",
"KeyError",
":",
"res",
"=",
"\"(?ms)\"",
"+",
"_translate",
"(",
"pat... | Test whether a name matches a wildcard pattern.
Arguments:
pattern (str): A wildcard pattern, e.g. ``"*.py"``.
name (str): A filename.
Returns:
bool: `True` if the filename matches the pattern. | [
"Test",
"whether",
"a",
"name",
"matches",
"a",
"wildcard",
"pattern",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/wildcard.py#L21-L38 | train | 228,518 |
PyFilesystem/pyfilesystem2 | fs/wildcard.py | match_any | def match_any(patterns, name):
# type: (Iterable[Text], Text) -> bool
"""Test if a name matches any of a list of patterns.
Will return `True` if ``patterns`` is an empty list.
Arguments:
patterns (list): A list of wildcard pattern, e.g ``["*.py",
"*.pyc"]``
name (str): A filename.
Returns:
bool: `True` if the name matches at least one of the patterns.
"""
if not patterns:
return True
return any(match(pattern, name) for pattern in patterns) | python | def match_any(patterns, name):
# type: (Iterable[Text], Text) -> bool
"""Test if a name matches any of a list of patterns.
Will return `True` if ``patterns`` is an empty list.
Arguments:
patterns (list): A list of wildcard pattern, e.g ``["*.py",
"*.pyc"]``
name (str): A filename.
Returns:
bool: `True` if the name matches at least one of the patterns.
"""
if not patterns:
return True
return any(match(pattern, name) for pattern in patterns) | [
"def",
"match_any",
"(",
"patterns",
",",
"name",
")",
":",
"# type: (Iterable[Text], Text) -> bool",
"if",
"not",
"patterns",
":",
"return",
"True",
"return",
"any",
"(",
"match",
"(",
"pattern",
",",
"name",
")",
"for",
"pattern",
"in",
"patterns",
")"
] | Test if a name matches any of a list of patterns.
Will return `True` if ``patterns`` is an empty list.
Arguments:
patterns (list): A list of wildcard pattern, e.g ``["*.py",
"*.pyc"]``
name (str): A filename.
Returns:
bool: `True` if the name matches at least one of the patterns. | [
"Test",
"if",
"a",
"name",
"matches",
"any",
"of",
"a",
"list",
"of",
"patterns",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/wildcard.py#L61-L78 | train | 228,519 |
PyFilesystem/pyfilesystem2 | fs/wildcard.py | get_matcher | def get_matcher(patterns, case_sensitive):
# type: (Iterable[Text], bool) -> Callable[[Text], bool]
"""Get a callable that matches names against the given patterns.
Arguments:
patterns (list): A list of wildcard pattern. e.g. ``["*.py",
"*.pyc"]``
case_sensitive (bool): If ``True``, then the callable will be case
sensitive, otherwise it will be case insensitive.
Returns:
callable: a matcher that will return `True` if the name given as
an argument matches any of the given patterns.
Example:
>>> from fs import wildcard
>>> is_python = wildcard.get_matcher(['*.py'], True)
>>> is_python('__init__.py')
True
>>> is_python('foo.txt')
False
"""
if not patterns:
return lambda name: True
if case_sensitive:
return partial(match_any, patterns)
else:
return partial(imatch_any, patterns) | python | def get_matcher(patterns, case_sensitive):
# type: (Iterable[Text], bool) -> Callable[[Text], bool]
"""Get a callable that matches names against the given patterns.
Arguments:
patterns (list): A list of wildcard pattern. e.g. ``["*.py",
"*.pyc"]``
case_sensitive (bool): If ``True``, then the callable will be case
sensitive, otherwise it will be case insensitive.
Returns:
callable: a matcher that will return `True` if the name given as
an argument matches any of the given patterns.
Example:
>>> from fs import wildcard
>>> is_python = wildcard.get_matcher(['*.py'], True)
>>> is_python('__init__.py')
True
>>> is_python('foo.txt')
False
"""
if not patterns:
return lambda name: True
if case_sensitive:
return partial(match_any, patterns)
else:
return partial(imatch_any, patterns) | [
"def",
"get_matcher",
"(",
"patterns",
",",
"case_sensitive",
")",
":",
"# type: (Iterable[Text], bool) -> Callable[[Text], bool]",
"if",
"not",
"patterns",
":",
"return",
"lambda",
"name",
":",
"True",
"if",
"case_sensitive",
":",
"return",
"partial",
"(",
"match_any... | Get a callable that matches names against the given patterns.
Arguments:
patterns (list): A list of wildcard pattern. e.g. ``["*.py",
"*.pyc"]``
case_sensitive (bool): If ``True``, then the callable will be case
sensitive, otherwise it will be case insensitive.
Returns:
callable: a matcher that will return `True` if the name given as
an argument matches any of the given patterns.
Example:
>>> from fs import wildcard
>>> is_python = wildcard.get_matcher(['*.py'], True)
>>> is_python('__init__.py')
True
>>> is_python('foo.txt')
False | [
"Get",
"a",
"callable",
"that",
"matches",
"names",
"against",
"the",
"given",
"patterns",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/wildcard.py#L101-L129 | train | 228,520 |
PyFilesystem/pyfilesystem2 | fs/wildcard.py | _translate | def _translate(pattern, case_sensitive=True):
# type: (Text, bool) -> Text
"""Translate a wildcard pattern to a regular expression.
There is no way to quote meta-characters.
Arguments:
pattern (str): A wildcard pattern.
case_sensitive (bool): Set to `False` to use a case
insensitive regex (default `True`).
Returns:
str: A regex equivalent to the given pattern.
"""
if not case_sensitive:
pattern = pattern.lower()
i, n = 0, len(pattern)
res = ""
while i < n:
c = pattern[i]
i = i + 1
if c == "*":
res = res + "[^/]*"
elif c == "?":
res = res + "."
elif c == "[":
j = i
if j < n and pattern[j] == "!":
j = j + 1
if j < n and pattern[j] == "]":
j = j + 1
while j < n and pattern[j] != "]":
j = j + 1
if j >= n:
res = res + "\\["
else:
stuff = pattern[i:j].replace("\\", "\\\\")
i = j + 1
if stuff[0] == "!":
stuff = "^" + stuff[1:]
elif stuff[0] == "^":
stuff = "\\" + stuff
res = "%s[%s]" % (res, stuff)
else:
res = res + re.escape(c)
return res | python | def _translate(pattern, case_sensitive=True):
# type: (Text, bool) -> Text
"""Translate a wildcard pattern to a regular expression.
There is no way to quote meta-characters.
Arguments:
pattern (str): A wildcard pattern.
case_sensitive (bool): Set to `False` to use a case
insensitive regex (default `True`).
Returns:
str: A regex equivalent to the given pattern.
"""
if not case_sensitive:
pattern = pattern.lower()
i, n = 0, len(pattern)
res = ""
while i < n:
c = pattern[i]
i = i + 1
if c == "*":
res = res + "[^/]*"
elif c == "?":
res = res + "."
elif c == "[":
j = i
if j < n and pattern[j] == "!":
j = j + 1
if j < n and pattern[j] == "]":
j = j + 1
while j < n and pattern[j] != "]":
j = j + 1
if j >= n:
res = res + "\\["
else:
stuff = pattern[i:j].replace("\\", "\\\\")
i = j + 1
if stuff[0] == "!":
stuff = "^" + stuff[1:]
elif stuff[0] == "^":
stuff = "\\" + stuff
res = "%s[%s]" % (res, stuff)
else:
res = res + re.escape(c)
return res | [
"def",
"_translate",
"(",
"pattern",
",",
"case_sensitive",
"=",
"True",
")",
":",
"# type: (Text, bool) -> Text",
"if",
"not",
"case_sensitive",
":",
"pattern",
"=",
"pattern",
".",
"lower",
"(",
")",
"i",
",",
"n",
"=",
"0",
",",
"len",
"(",
"pattern",
... | Translate a wildcard pattern to a regular expression.
There is no way to quote meta-characters.
Arguments:
pattern (str): A wildcard pattern.
case_sensitive (bool): Set to `False` to use a case
insensitive regex (default `True`).
Returns:
str: A regex equivalent to the given pattern. | [
"Translate",
"a",
"wildcard",
"pattern",
"to",
"a",
"regular",
"expression",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/wildcard.py#L132-L178 | train | 228,521 |
PyFilesystem/pyfilesystem2 | fs/mountfs.py | MountFS._delegate | def _delegate(self, path):
# type: (Text) -> Tuple[FS, Text]
"""Get the delegate FS for a given path.
Arguments:
path (str): A path.
Returns:
(FS, str): a tuple of ``(<fs>, <path>)`` for a mounted filesystem,
or ``(None, None)`` if no filesystem is mounted on the
given ``path``.
"""
_path = forcedir(abspath(normpath(path)))
is_mounted = _path.startswith
for mount_path, fs in self.mounts:
if is_mounted(mount_path):
return fs, _path[len(mount_path) :].rstrip("/")
return self.default_fs, path | python | def _delegate(self, path):
# type: (Text) -> Tuple[FS, Text]
"""Get the delegate FS for a given path.
Arguments:
path (str): A path.
Returns:
(FS, str): a tuple of ``(<fs>, <path>)`` for a mounted filesystem,
or ``(None, None)`` if no filesystem is mounted on the
given ``path``.
"""
_path = forcedir(abspath(normpath(path)))
is_mounted = _path.startswith
for mount_path, fs in self.mounts:
if is_mounted(mount_path):
return fs, _path[len(mount_path) :].rstrip("/")
return self.default_fs, path | [
"def",
"_delegate",
"(",
"self",
",",
"path",
")",
":",
"# type: (Text) -> Tuple[FS, Text]",
"_path",
"=",
"forcedir",
"(",
"abspath",
"(",
"normpath",
"(",
"path",
")",
")",
")",
"is_mounted",
"=",
"_path",
".",
"startswith",
"for",
"mount_path",
",",
"fs",... | Get the delegate FS for a given path.
Arguments:
path (str): A path.
Returns:
(FS, str): a tuple of ``(<fs>, <path>)`` for a mounted filesystem,
or ``(None, None)`` if no filesystem is mounted on the
given ``path``. | [
"Get",
"the",
"delegate",
"FS",
"for",
"a",
"given",
"path",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/mountfs.py#L80-L100 | train | 228,522 |
PyFilesystem/pyfilesystem2 | fs/mountfs.py | MountFS.mount | def mount(self, path, fs):
# type: (Text, Union[FS, Text]) -> None
"""Mounts a host FS object on a given path.
Arguments:
path (str): A path within the MountFS.
fs (FS or str): A filesystem (instance or URL) to mount.
"""
if isinstance(fs, text_type):
from .opener import open_fs
fs = open_fs(fs)
if not isinstance(fs, FS):
raise TypeError("fs argument must be an FS object or a FS URL")
if fs is self:
raise ValueError("Unable to mount self")
_path = forcedir(abspath(normpath(path)))
for mount_path, _ in self.mounts:
if _path.startswith(mount_path):
raise MountError("mount point overlaps existing mount")
self.mounts.append((_path, fs))
self.default_fs.makedirs(_path, recreate=True) | python | def mount(self, path, fs):
# type: (Text, Union[FS, Text]) -> None
"""Mounts a host FS object on a given path.
Arguments:
path (str): A path within the MountFS.
fs (FS or str): A filesystem (instance or URL) to mount.
"""
if isinstance(fs, text_type):
from .opener import open_fs
fs = open_fs(fs)
if not isinstance(fs, FS):
raise TypeError("fs argument must be an FS object or a FS URL")
if fs is self:
raise ValueError("Unable to mount self")
_path = forcedir(abspath(normpath(path)))
for mount_path, _ in self.mounts:
if _path.startswith(mount_path):
raise MountError("mount point overlaps existing mount")
self.mounts.append((_path, fs))
self.default_fs.makedirs(_path, recreate=True) | [
"def",
"mount",
"(",
"self",
",",
"path",
",",
"fs",
")",
":",
"# type: (Text, Union[FS, Text]) -> None",
"if",
"isinstance",
"(",
"fs",
",",
"text_type",
")",
":",
"from",
".",
"opener",
"import",
"open_fs",
"fs",
"=",
"open_fs",
"(",
"fs",
")",
"if",
"... | Mounts a host FS object on a given path.
Arguments:
path (str): A path within the MountFS.
fs (FS or str): A filesystem (instance or URL) to mount. | [
"Mounts",
"a",
"host",
"FS",
"object",
"on",
"a",
"given",
"path",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/mountfs.py#L102-L128 | train | 228,523 |
PyFilesystem/pyfilesystem2 | fs/_bulk.py | Copier.start | def start(self):
"""Start the workers."""
if self.num_workers:
self.queue = Queue(maxsize=self.num_workers)
self.workers = [_Worker(self) for _ in range(self.num_workers)]
for worker in self.workers:
worker.start()
self.running = True | python | def start(self):
"""Start the workers."""
if self.num_workers:
self.queue = Queue(maxsize=self.num_workers)
self.workers = [_Worker(self) for _ in range(self.num_workers)]
for worker in self.workers:
worker.start()
self.running = True | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"num_workers",
":",
"self",
".",
"queue",
"=",
"Queue",
"(",
"maxsize",
"=",
"self",
".",
"num_workers",
")",
"self",
".",
"workers",
"=",
"[",
"_Worker",
"(",
"self",
")",
"for",
"_",
"in",... | Start the workers. | [
"Start",
"the",
"workers",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/_bulk.py#L87-L94 | train | 228,524 |
PyFilesystem/pyfilesystem2 | fs/_bulk.py | Copier.copy | def copy(self, src_fs, src_path, dst_fs, dst_path):
# type: (FS, Text, FS, Text) -> None
"""Copy a file from one fs to another."""
if self.queue is None:
# This should be the most performant for a single-thread
copy_file_internal(src_fs, src_path, dst_fs, dst_path)
else:
src_file = src_fs.openbin(src_path, "r")
try:
dst_file = dst_fs.openbin(dst_path, "w")
except Exception:
src_file.close()
raise
task = _CopyTask(src_file, dst_file)
self.queue.put(task) | python | def copy(self, src_fs, src_path, dst_fs, dst_path):
# type: (FS, Text, FS, Text) -> None
"""Copy a file from one fs to another."""
if self.queue is None:
# This should be the most performant for a single-thread
copy_file_internal(src_fs, src_path, dst_fs, dst_path)
else:
src_file = src_fs.openbin(src_path, "r")
try:
dst_file = dst_fs.openbin(dst_path, "w")
except Exception:
src_file.close()
raise
task = _CopyTask(src_file, dst_file)
self.queue.put(task) | [
"def",
"copy",
"(",
"self",
",",
"src_fs",
",",
"src_path",
",",
"dst_fs",
",",
"dst_path",
")",
":",
"# type: (FS, Text, FS, Text) -> None",
"if",
"self",
".",
"queue",
"is",
"None",
":",
"# This should be the most performant for a single-thread",
"copy_file_internal",... | Copy a file from one fs to another. | [
"Copy",
"a",
"file",
"from",
"one",
"fs",
"to",
"another",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/_bulk.py#L126-L140 | train | 228,525 |
PyFilesystem/pyfilesystem2 | fs/multifs.py | MultiFS.add_fs | def add_fs(self, name, fs, write=False, priority=0):
# type: (Text, FS, bool, int) -> None
"""Add a filesystem to the MultiFS.
Arguments:
name (str): A unique name to refer to the filesystem being
added.
fs (FS or str): The filesystem (instance or URL) to add.
write (bool): If this value is True, then the ``fs`` will
be used as the writeable FS (defaults to False).
priority (int): An integer that denotes the priority of the
filesystem being added. Filesystems will be searched in
descending priority order and then by the reverse order
they were added. So by default, the most recently added
filesystem will be looked at first.
"""
if isinstance(fs, text_type):
fs = open_fs(fs)
if not isinstance(fs, FS):
raise TypeError("fs argument should be an FS object or FS URL")
self._filesystems[name] = _PrioritizedFS(
priority=(priority, self._sort_index), fs=fs
)
self._sort_index += 1
self._resort()
if write:
self.write_fs = fs
self._write_fs_name = name | python | def add_fs(self, name, fs, write=False, priority=0):
# type: (Text, FS, bool, int) -> None
"""Add a filesystem to the MultiFS.
Arguments:
name (str): A unique name to refer to the filesystem being
added.
fs (FS or str): The filesystem (instance or URL) to add.
write (bool): If this value is True, then the ``fs`` will
be used as the writeable FS (defaults to False).
priority (int): An integer that denotes the priority of the
filesystem being added. Filesystems will be searched in
descending priority order and then by the reverse order
they were added. So by default, the most recently added
filesystem will be looked at first.
"""
if isinstance(fs, text_type):
fs = open_fs(fs)
if not isinstance(fs, FS):
raise TypeError("fs argument should be an FS object or FS URL")
self._filesystems[name] = _PrioritizedFS(
priority=(priority, self._sort_index), fs=fs
)
self._sort_index += 1
self._resort()
if write:
self.write_fs = fs
self._write_fs_name = name | [
"def",
"add_fs",
"(",
"self",
",",
"name",
",",
"fs",
",",
"write",
"=",
"False",
",",
"priority",
"=",
"0",
")",
":",
"# type: (Text, FS, bool, int) -> None",
"if",
"isinstance",
"(",
"fs",
",",
"text_type",
")",
":",
"fs",
"=",
"open_fs",
"(",
"fs",
... | Add a filesystem to the MultiFS.
Arguments:
name (str): A unique name to refer to the filesystem being
added.
fs (FS or str): The filesystem (instance or URL) to add.
write (bool): If this value is True, then the ``fs`` will
be used as the writeable FS (defaults to False).
priority (int): An integer that denotes the priority of the
filesystem being added. Filesystems will be searched in
descending priority order and then by the reverse order
they were added. So by default, the most recently added
filesystem will be looked at first. | [
"Add",
"a",
"filesystem",
"to",
"the",
"MultiFS",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/multifs.py#L79-L110 | train | 228,526 |
PyFilesystem/pyfilesystem2 | fs/multifs.py | MultiFS._delegate | def _delegate(self, path):
# type: (Text) -> Optional[FS]
"""Get a filesystem which has a given path.
"""
for _name, fs in self.iterate_fs():
if fs.exists(path):
return fs
return None | python | def _delegate(self, path):
# type: (Text) -> Optional[FS]
"""Get a filesystem which has a given path.
"""
for _name, fs in self.iterate_fs():
if fs.exists(path):
return fs
return None | [
"def",
"_delegate",
"(",
"self",
",",
"path",
")",
":",
"# type: (Text) -> Optional[FS]",
"for",
"_name",
",",
"fs",
"in",
"self",
".",
"iterate_fs",
"(",
")",
":",
"if",
"fs",
".",
"exists",
"(",
"path",
")",
":",
"return",
"fs",
"return",
"None"
] | Get a filesystem which has a given path. | [
"Get",
"a",
"filesystem",
"which",
"has",
"a",
"given",
"path",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/multifs.py#L147-L154 | train | 228,527 |
PyFilesystem/pyfilesystem2 | fs/multifs.py | MultiFS._delegate_required | def _delegate_required(self, path):
# type: (Text) -> FS
"""Check that there is a filesystem with the given ``path``.
"""
fs = self._delegate(path)
if fs is None:
raise errors.ResourceNotFound(path)
return fs | python | def _delegate_required(self, path):
# type: (Text) -> FS
"""Check that there is a filesystem with the given ``path``.
"""
fs = self._delegate(path)
if fs is None:
raise errors.ResourceNotFound(path)
return fs | [
"def",
"_delegate_required",
"(",
"self",
",",
"path",
")",
":",
"# type: (Text) -> FS",
"fs",
"=",
"self",
".",
"_delegate",
"(",
"path",
")",
"if",
"fs",
"is",
"None",
":",
"raise",
"errors",
".",
"ResourceNotFound",
"(",
"path",
")",
"return",
"fs"
] | Check that there is a filesystem with the given ``path``. | [
"Check",
"that",
"there",
"is",
"a",
"filesystem",
"with",
"the",
"given",
"path",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/multifs.py#L156-L163 | train | 228,528 |
PyFilesystem/pyfilesystem2 | fs/multifs.py | MultiFS._writable_required | def _writable_required(self, path):
# type: (Text) -> FS
"""Check that ``path`` is writeable.
"""
if self.write_fs is None:
raise errors.ResourceReadOnly(path)
return self.write_fs | python | def _writable_required(self, path):
# type: (Text) -> FS
"""Check that ``path`` is writeable.
"""
if self.write_fs is None:
raise errors.ResourceReadOnly(path)
return self.write_fs | [
"def",
"_writable_required",
"(",
"self",
",",
"path",
")",
":",
"# type: (Text) -> FS",
"if",
"self",
".",
"write_fs",
"is",
"None",
":",
"raise",
"errors",
".",
"ResourceReadOnly",
"(",
"path",
")",
"return",
"self",
".",
"write_fs"
] | Check that ``path`` is writeable. | [
"Check",
"that",
"path",
"is",
"writeable",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/multifs.py#L165-L171 | train | 228,529 |
PyFilesystem/pyfilesystem2 | fs/iotools.py | make_stream | def make_stream(
name, # type: Text
bin_file, # type: RawIOBase
mode="r", # type: Text
buffering=-1, # type: int
encoding=None, # type: Optional[Text]
errors=None, # type: Optional[Text]
newline="", # type: Optional[Text]
line_buffering=False, # type: bool
**kwargs # type: Any
):
# type: (...) -> IO
"""Take a Python 2.x binary file and return an IO Stream.
"""
reading = "r" in mode
writing = "w" in mode
appending = "a" in mode
binary = "b" in mode
if "+" in mode:
reading = True
writing = True
encoding = None if binary else (encoding or "utf-8")
io_object = RawWrapper(bin_file, mode=mode, name=name) # type: io.IOBase
if buffering >= 0:
if reading and writing:
io_object = io.BufferedRandom(
typing.cast(io.RawIOBase, io_object),
buffering or io.DEFAULT_BUFFER_SIZE,
)
elif reading:
io_object = io.BufferedReader(
typing.cast(io.RawIOBase, io_object),
buffering or io.DEFAULT_BUFFER_SIZE,
)
elif writing or appending:
io_object = io.BufferedWriter(
typing.cast(io.RawIOBase, io_object),
buffering or io.DEFAULT_BUFFER_SIZE,
)
if not binary:
io_object = io.TextIOWrapper(
io_object,
encoding=encoding,
errors=errors,
newline=newline,
line_buffering=line_buffering,
)
return io_object | python | def make_stream(
name, # type: Text
bin_file, # type: RawIOBase
mode="r", # type: Text
buffering=-1, # type: int
encoding=None, # type: Optional[Text]
errors=None, # type: Optional[Text]
newline="", # type: Optional[Text]
line_buffering=False, # type: bool
**kwargs # type: Any
):
# type: (...) -> IO
"""Take a Python 2.x binary file and return an IO Stream.
"""
reading = "r" in mode
writing = "w" in mode
appending = "a" in mode
binary = "b" in mode
if "+" in mode:
reading = True
writing = True
encoding = None if binary else (encoding or "utf-8")
io_object = RawWrapper(bin_file, mode=mode, name=name) # type: io.IOBase
if buffering >= 0:
if reading and writing:
io_object = io.BufferedRandom(
typing.cast(io.RawIOBase, io_object),
buffering or io.DEFAULT_BUFFER_SIZE,
)
elif reading:
io_object = io.BufferedReader(
typing.cast(io.RawIOBase, io_object),
buffering or io.DEFAULT_BUFFER_SIZE,
)
elif writing or appending:
io_object = io.BufferedWriter(
typing.cast(io.RawIOBase, io_object),
buffering or io.DEFAULT_BUFFER_SIZE,
)
if not binary:
io_object = io.TextIOWrapper(
io_object,
encoding=encoding,
errors=errors,
newline=newline,
line_buffering=line_buffering,
)
return io_object | [
"def",
"make_stream",
"(",
"name",
",",
"# type: Text",
"bin_file",
",",
"# type: RawIOBase",
"mode",
"=",
"\"r\"",
",",
"# type: Text",
"buffering",
"=",
"-",
"1",
",",
"# type: int",
"encoding",
"=",
"None",
",",
"# type: Optional[Text]",
"errors",
"=",
"None"... | Take a Python 2.x binary file and return an IO Stream. | [
"Take",
"a",
"Python",
"2",
".",
"x",
"binary",
"file",
"and",
"return",
"an",
"IO",
"Stream",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/iotools.py#L153-L204 | train | 228,530 |
PyFilesystem/pyfilesystem2 | fs/iotools.py | line_iterator | def line_iterator(readable_file, size=None):
# type: (IO[bytes], Optional[int]) -> Iterator[bytes]
"""Iterate over the lines of a file.
Implementation reads each char individually, which is not very
efficient.
Yields:
str: a single line in the file.
"""
read = readable_file.read
line = []
byte = b"1"
if size is None or size < 0:
while byte:
byte = read(1)
line.append(byte)
if byte in b"\n":
yield b"".join(line)
del line[:]
else:
while byte and size:
byte = read(1)
size -= len(byte)
line.append(byte)
if byte in b"\n" or not size:
yield b"".join(line)
del line[:] | python | def line_iterator(readable_file, size=None):
# type: (IO[bytes], Optional[int]) -> Iterator[bytes]
"""Iterate over the lines of a file.
Implementation reads each char individually, which is not very
efficient.
Yields:
str: a single line in the file.
"""
read = readable_file.read
line = []
byte = b"1"
if size is None or size < 0:
while byte:
byte = read(1)
line.append(byte)
if byte in b"\n":
yield b"".join(line)
del line[:]
else:
while byte and size:
byte = read(1)
size -= len(byte)
line.append(byte)
if byte in b"\n" or not size:
yield b"".join(line)
del line[:] | [
"def",
"line_iterator",
"(",
"readable_file",
",",
"size",
"=",
"None",
")",
":",
"# type: (IO[bytes], Optional[int]) -> Iterator[bytes]",
"read",
"=",
"readable_file",
".",
"read",
"line",
"=",
"[",
"]",
"byte",
"=",
"b\"1\"",
"if",
"size",
"is",
"None",
"or",
... | Iterate over the lines of a file.
Implementation reads each char individually, which is not very
efficient.
Yields:
str: a single line in the file. | [
"Iterate",
"over",
"the",
"lines",
"of",
"a",
"file",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/iotools.py#L207-L236 | train | 228,531 |
PyFilesystem/pyfilesystem2 | fs/mode.py | validate_openbin_mode | def validate_openbin_mode(mode, _valid_chars=frozenset("rwxab+")):
# type: (Text, Union[Set[Text], FrozenSet[Text]]) -> None
"""Check ``mode`` parameter of `~fs.base.FS.openbin` is valid.
Arguments:
mode (str): Mode parameter.
Raises:
`ValueError` if mode is not valid.
"""
if "t" in mode:
raise ValueError("text mode not valid in openbin")
if not mode:
raise ValueError("mode must not be empty")
if mode[0] not in "rwxa":
raise ValueError("mode must start with 'r', 'w', 'a' or 'x'")
if not _valid_chars.issuperset(mode):
raise ValueError("mode '{}' contains invalid characters".format(mode)) | python | def validate_openbin_mode(mode, _valid_chars=frozenset("rwxab+")):
# type: (Text, Union[Set[Text], FrozenSet[Text]]) -> None
"""Check ``mode`` parameter of `~fs.base.FS.openbin` is valid.
Arguments:
mode (str): Mode parameter.
Raises:
`ValueError` if mode is not valid.
"""
if "t" in mode:
raise ValueError("text mode not valid in openbin")
if not mode:
raise ValueError("mode must not be empty")
if mode[0] not in "rwxa":
raise ValueError("mode must start with 'r', 'w', 'a' or 'x'")
if not _valid_chars.issuperset(mode):
raise ValueError("mode '{}' contains invalid characters".format(mode)) | [
"def",
"validate_openbin_mode",
"(",
"mode",
",",
"_valid_chars",
"=",
"frozenset",
"(",
"\"rwxab+\"",
")",
")",
":",
"# type: (Text, Union[Set[Text], FrozenSet[Text]]) -> None",
"if",
"\"t\"",
"in",
"mode",
":",
"raise",
"ValueError",
"(",
"\"text mode not valid in openb... | Check ``mode`` parameter of `~fs.base.FS.openbin` is valid.
Arguments:
mode (str): Mode parameter.
Raises:
`ValueError` if mode is not valid. | [
"Check",
"mode",
"parameter",
"of",
"~fs",
".",
"base",
".",
"FS",
".",
"openbin",
"is",
"valid",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/mode.py#L229-L247 | train | 228,532 |
PyFilesystem/pyfilesystem2 | fs/mirror.py | _compare | def _compare(info1, info2):
# type: (Info, Info) -> bool
"""Compare two `Info` objects to see if they should be copied.
Returns:
bool: `True` if the `Info` are different in size or mtime.
"""
# Check filesize has changed
if info1.size != info2.size:
return True
# Check modified dates
date1 = info1.modified
date2 = info2.modified
return date1 is None or date2 is None or date1 > date2 | python | def _compare(info1, info2):
# type: (Info, Info) -> bool
"""Compare two `Info` objects to see if they should be copied.
Returns:
bool: `True` if the `Info` are different in size or mtime.
"""
# Check filesize has changed
if info1.size != info2.size:
return True
# Check modified dates
date1 = info1.modified
date2 = info2.modified
return date1 is None or date2 is None or date1 > date2 | [
"def",
"_compare",
"(",
"info1",
",",
"info2",
")",
":",
"# type: (Info, Info) -> bool",
"# Check filesize has changed",
"if",
"info1",
".",
"size",
"!=",
"info2",
".",
"size",
":",
"return",
"True",
"# Check modified dates",
"date1",
"=",
"info1",
".",
"modified"... | Compare two `Info` objects to see if they should be copied.
Returns:
bool: `True` if the `Info` are different in size or mtime. | [
"Compare",
"two",
"Info",
"objects",
"to",
"see",
"if",
"they",
"should",
"be",
"copied",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/mirror.py#L38-L52 | train | 228,533 |
PyFilesystem/pyfilesystem2 | fs/opener/parse.py | parse_fs_url | def parse_fs_url(fs_url):
# type: (Text) -> ParseResult
"""Parse a Filesystem URL and return a `ParseResult`.
Arguments:
fs_url (str): A filesystem URL.
Returns:
~fs.opener.parse.ParseResult: a parse result instance.
Raises:
~fs.errors.ParseError: if the FS URL is not valid.
"""
match = _RE_FS_URL.match(fs_url)
if match is None:
raise ParseError("{!r} is not a fs2 url".format(fs_url))
fs_name, credentials, url1, url2, path = match.groups()
if not credentials:
username = None # type: Optional[Text]
password = None # type: Optional[Text]
url = url2
else:
username, _, password = credentials.partition(":")
username = unquote(username)
password = unquote(password)
url = url1
url, has_qs, qs = url.partition("?")
resource = unquote(url)
if has_qs:
_params = parse_qs(qs, keep_blank_values=True)
params = {k: unquote(v[0]) for k, v in six.iteritems(_params)}
else:
params = {}
return ParseResult(fs_name, username, password, resource, params, path) | python | def parse_fs_url(fs_url):
# type: (Text) -> ParseResult
"""Parse a Filesystem URL and return a `ParseResult`.
Arguments:
fs_url (str): A filesystem URL.
Returns:
~fs.opener.parse.ParseResult: a parse result instance.
Raises:
~fs.errors.ParseError: if the FS URL is not valid.
"""
match = _RE_FS_URL.match(fs_url)
if match is None:
raise ParseError("{!r} is not a fs2 url".format(fs_url))
fs_name, credentials, url1, url2, path = match.groups()
if not credentials:
username = None # type: Optional[Text]
password = None # type: Optional[Text]
url = url2
else:
username, _, password = credentials.partition(":")
username = unquote(username)
password = unquote(password)
url = url1
url, has_qs, qs = url.partition("?")
resource = unquote(url)
if has_qs:
_params = parse_qs(qs, keep_blank_values=True)
params = {k: unquote(v[0]) for k, v in six.iteritems(_params)}
else:
params = {}
return ParseResult(fs_name, username, password, resource, params, path) | [
"def",
"parse_fs_url",
"(",
"fs_url",
")",
":",
"# type: (Text) -> ParseResult",
"match",
"=",
"_RE_FS_URL",
".",
"match",
"(",
"fs_url",
")",
"if",
"match",
"is",
"None",
":",
"raise",
"ParseError",
"(",
"\"{!r} is not a fs2 url\"",
".",
"format",
"(",
"fs_url"... | Parse a Filesystem URL and return a `ParseResult`.
Arguments:
fs_url (str): A filesystem URL.
Returns:
~fs.opener.parse.ParseResult: a parse result instance.
Raises:
~fs.errors.ParseError: if the FS URL is not valid. | [
"Parse",
"a",
"Filesystem",
"URL",
"and",
"return",
"a",
"ParseResult",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/opener/parse.py#L62-L97 | train | 228,534 |
PyFilesystem/pyfilesystem2 | fs/zipfs.py | _ZipExtFile.seek | def seek(self, offset, whence=Seek.set):
# type: (int, SupportsInt) -> int
"""Change stream position.
Change the stream position to the given byte offset. The
offset is interpreted relative to the position indicated by
``whence``.
Arguments:
offset (int): the offset to the new position, in bytes.
whence (int): the position reference. Possible values are:
* `Seek.set`: start of stream (the default).
* `Seek.current`: current position; offset may be negative.
* `Seek.end`: end of stream; offset must be negative.
Returns:
int: the new absolute position.
Raises:
ValueError: when ``whence`` is not known, or ``offset``
is invalid.
Note:
Zip compression does not support seeking, so the seeking
is emulated. Seeking somewhere else than the current position
will need to either:
* reopen the file and restart decompression
* read and discard data to advance in the file
"""
_whence = int(whence)
if _whence == Seek.current:
offset += self._pos
if _whence == Seek.current or _whence == Seek.set:
if offset < 0:
raise ValueError("Negative seek position {}".format(offset))
elif _whence == Seek.end:
if offset > 0:
raise ValueError("Positive seek position {}".format(offset))
offset += self._end
else:
raise ValueError(
"Invalid whence ({}, should be {}, {} or {})".format(
_whence, Seek.set, Seek.current, Seek.end
)
)
if offset < self._pos:
self._f = self._zip.open(self.name) # type: ignore
self._pos = 0
self.read(offset - self._pos)
return self._pos | python | def seek(self, offset, whence=Seek.set):
# type: (int, SupportsInt) -> int
"""Change stream position.
Change the stream position to the given byte offset. The
offset is interpreted relative to the position indicated by
``whence``.
Arguments:
offset (int): the offset to the new position, in bytes.
whence (int): the position reference. Possible values are:
* `Seek.set`: start of stream (the default).
* `Seek.current`: current position; offset may be negative.
* `Seek.end`: end of stream; offset must be negative.
Returns:
int: the new absolute position.
Raises:
ValueError: when ``whence`` is not known, or ``offset``
is invalid.
Note:
Zip compression does not support seeking, so the seeking
is emulated. Seeking somewhere else than the current position
will need to either:
* reopen the file and restart decompression
* read and discard data to advance in the file
"""
_whence = int(whence)
if _whence == Seek.current:
offset += self._pos
if _whence == Seek.current or _whence == Seek.set:
if offset < 0:
raise ValueError("Negative seek position {}".format(offset))
elif _whence == Seek.end:
if offset > 0:
raise ValueError("Positive seek position {}".format(offset))
offset += self._end
else:
raise ValueError(
"Invalid whence ({}, should be {}, {} or {})".format(
_whence, Seek.set, Seek.current, Seek.end
)
)
if offset < self._pos:
self._f = self._zip.open(self.name) # type: ignore
self._pos = 0
self.read(offset - self._pos)
return self._pos | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"Seek",
".",
"set",
")",
":",
"# type: (int, SupportsInt) -> int",
"_whence",
"=",
"int",
"(",
"whence",
")",
"if",
"_whence",
"==",
"Seek",
".",
"current",
":",
"offset",
"+=",
"self",
".",
... | Change stream position.
Change the stream position to the given byte offset. The
offset is interpreted relative to the position indicated by
``whence``.
Arguments:
offset (int): the offset to the new position, in bytes.
whence (int): the position reference. Possible values are:
* `Seek.set`: start of stream (the default).
* `Seek.current`: current position; offset may be negative.
* `Seek.end`: end of stream; offset must be negative.
Returns:
int: the new absolute position.
Raises:
ValueError: when ``whence`` is not known, or ``offset``
is invalid.
Note:
Zip compression does not support seeking, so the seeking
is emulated. Seeking somewhere else than the current position
will need to either:
* reopen the file and restart decompression
* read and discard data to advance in the file | [
"Change",
"stream",
"position",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/zipfs.py#L65-L116 | train | 228,535 |
PyFilesystem/pyfilesystem2 | fs/walk.py | Walker._iter_walk | def _iter_walk(
self,
fs, # type: FS
path, # type: Text
namespaces=None, # type: Optional[Collection[Text]]
):
# type: (...) -> Iterator[Tuple[Text, Optional[Info]]]
"""Get the walk generator."""
if self.search == "breadth":
return self._walk_breadth(fs, path, namespaces=namespaces)
else:
return self._walk_depth(fs, path, namespaces=namespaces) | python | def _iter_walk(
self,
fs, # type: FS
path, # type: Text
namespaces=None, # type: Optional[Collection[Text]]
):
# type: (...) -> Iterator[Tuple[Text, Optional[Info]]]
"""Get the walk generator."""
if self.search == "breadth":
return self._walk_breadth(fs, path, namespaces=namespaces)
else:
return self._walk_depth(fs, path, namespaces=namespaces) | [
"def",
"_iter_walk",
"(",
"self",
",",
"fs",
",",
"# type: FS",
"path",
",",
"# type: Text",
"namespaces",
"=",
"None",
",",
"# type: Optional[Collection[Text]]",
")",
":",
"# type: (...) -> Iterator[Tuple[Text, Optional[Info]]]",
"if",
"self",
".",
"search",
"==",
"\... | Get the walk generator. | [
"Get",
"the",
"walk",
"generator",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/walk.py#L188-L199 | train | 228,536 |
PyFilesystem/pyfilesystem2 | fs/walk.py | Walker._check_open_dir | def _check_open_dir(self, fs, path, info):
# type: (FS, Text, Info) -> bool
"""Check if a directory should be considered in the walk.
"""
if self.exclude_dirs is not None and fs.match(self.exclude_dirs, info.name):
return False
if self.filter_dirs is not None and not fs.match(self.filter_dirs, info.name):
return False
return self.check_open_dir(fs, path, info) | python | def _check_open_dir(self, fs, path, info):
# type: (FS, Text, Info) -> bool
"""Check if a directory should be considered in the walk.
"""
if self.exclude_dirs is not None and fs.match(self.exclude_dirs, info.name):
return False
if self.filter_dirs is not None and not fs.match(self.filter_dirs, info.name):
return False
return self.check_open_dir(fs, path, info) | [
"def",
"_check_open_dir",
"(",
"self",
",",
"fs",
",",
"path",
",",
"info",
")",
":",
"# type: (FS, Text, Info) -> bool",
"if",
"self",
".",
"exclude_dirs",
"is",
"not",
"None",
"and",
"fs",
".",
"match",
"(",
"self",
".",
"exclude_dirs",
",",
"info",
".",... | Check if a directory should be considered in the walk. | [
"Check",
"if",
"a",
"directory",
"should",
"be",
"considered",
"in",
"the",
"walk",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/walk.py#L201-L209 | train | 228,537 |
PyFilesystem/pyfilesystem2 | fs/walk.py | Walker._check_scan_dir | def _check_scan_dir(self, fs, path, info, depth):
# type: (FS, Text, Info, int) -> bool
"""Check if a directory contents should be scanned."""
if self.max_depth is not None and depth >= self.max_depth:
return False
return self.check_scan_dir(fs, path, info) | python | def _check_scan_dir(self, fs, path, info, depth):
# type: (FS, Text, Info, int) -> bool
"""Check if a directory contents should be scanned."""
if self.max_depth is not None and depth >= self.max_depth:
return False
return self.check_scan_dir(fs, path, info) | [
"def",
"_check_scan_dir",
"(",
"self",
",",
"fs",
",",
"path",
",",
"info",
",",
"depth",
")",
":",
"# type: (FS, Text, Info, int) -> bool",
"if",
"self",
".",
"max_depth",
"is",
"not",
"None",
"and",
"depth",
">=",
"self",
".",
"max_depth",
":",
"return",
... | Check if a directory contents should be scanned. | [
"Check",
"if",
"a",
"directory",
"contents",
"should",
"be",
"scanned",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/walk.py#L228-L233 | train | 228,538 |
PyFilesystem/pyfilesystem2 | fs/walk.py | Walker.check_file | def check_file(self, fs, info):
# type: (FS, Info) -> bool
"""Check if a filename should be included.
Override to exclude files from the walk.
Arguments:
fs (FS): A filesystem instance.
info (Info): A resource info object.
Returns:
bool: `True` if the file should be included.
"""
if self.exclude is not None and fs.match(self.exclude, info.name):
return False
return fs.match(self.filter, info.name) | python | def check_file(self, fs, info):
# type: (FS, Info) -> bool
"""Check if a filename should be included.
Override to exclude files from the walk.
Arguments:
fs (FS): A filesystem instance.
info (Info): A resource info object.
Returns:
bool: `True` if the file should be included.
"""
if self.exclude is not None and fs.match(self.exclude, info.name):
return False
return fs.match(self.filter, info.name) | [
"def",
"check_file",
"(",
"self",
",",
"fs",
",",
"info",
")",
":",
"# type: (FS, Info) -> bool",
"if",
"self",
".",
"exclude",
"is",
"not",
"None",
"and",
"fs",
".",
"match",
"(",
"self",
".",
"exclude",
",",
"info",
".",
"name",
")",
":",
"return",
... | Check if a filename should be included.
Override to exclude files from the walk.
Arguments:
fs (FS): A filesystem instance.
info (Info): A resource info object.
Returns:
bool: `True` if the file should be included. | [
"Check",
"if",
"a",
"filename",
"should",
"be",
"included",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/walk.py#L254-L271 | train | 228,539 |
PyFilesystem/pyfilesystem2 | fs/walk.py | Walker._scan | def _scan(
self,
fs, # type: FS
dir_path, # type: Text
namespaces=None, # type: Optional[Collection[Text]]
):
# type: (...) -> Iterator[Info]
"""Get an iterator of `Info` objects for a directory path.
Arguments:
fs (FS): A filesystem instance.
dir_path (str): A path to a directory on the filesystem.
namespaces (list): A list of additional namespaces to
include in the `Info` objects.
Returns:
~collections.Iterator: iterator of `Info` objects for
resources within the given path.
"""
try:
for info in fs.scandir(dir_path, namespaces=namespaces):
yield info
except FSError as error:
if not self.on_error(dir_path, error):
six.reraise(type(error), error) | python | def _scan(
self,
fs, # type: FS
dir_path, # type: Text
namespaces=None, # type: Optional[Collection[Text]]
):
# type: (...) -> Iterator[Info]
"""Get an iterator of `Info` objects for a directory path.
Arguments:
fs (FS): A filesystem instance.
dir_path (str): A path to a directory on the filesystem.
namespaces (list): A list of additional namespaces to
include in the `Info` objects.
Returns:
~collections.Iterator: iterator of `Info` objects for
resources within the given path.
"""
try:
for info in fs.scandir(dir_path, namespaces=namespaces):
yield info
except FSError as error:
if not self.on_error(dir_path, error):
six.reraise(type(error), error) | [
"def",
"_scan",
"(",
"self",
",",
"fs",
",",
"# type: FS",
"dir_path",
",",
"# type: Text",
"namespaces",
"=",
"None",
",",
"# type: Optional[Collection[Text]]",
")",
":",
"# type: (...) -> Iterator[Info]",
"try",
":",
"for",
"info",
"in",
"fs",
".",
"scandir",
... | Get an iterator of `Info` objects for a directory path.
Arguments:
fs (FS): A filesystem instance.
dir_path (str): A path to a directory on the filesystem.
namespaces (list): A list of additional namespaces to
include in the `Info` objects.
Returns:
~collections.Iterator: iterator of `Info` objects for
resources within the given path. | [
"Get",
"an",
"iterator",
"of",
"Info",
"objects",
"for",
"a",
"directory",
"path",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/walk.py#L273-L298 | train | 228,540 |
PyFilesystem/pyfilesystem2 | fs/walk.py | BoundWalker._make_walker | def _make_walker(self, *args, **kwargs):
# type: (*Any, **Any) -> Walker
"""Create a walker instance.
"""
walker = self.walker_class(*args, **kwargs)
return walker | python | def _make_walker(self, *args, **kwargs):
# type: (*Any, **Any) -> Walker
"""Create a walker instance.
"""
walker = self.walker_class(*args, **kwargs)
return walker | [
"def",
"_make_walker",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (*Any, **Any) -> Walker",
"walker",
"=",
"self",
".",
"walker_class",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"walker"
] | Create a walker instance. | [
"Create",
"a",
"walker",
"instance",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/walk.py#L529-L534 | train | 228,541 |
PyFilesystem/pyfilesystem2 | fs/walk.py | BoundWalker.dirs | def dirs(self, path="/", **kwargs):
# type: (Text, **Any) -> Iterator[Text]
"""Walk a filesystem, yielding absolute paths to directories.
Arguments:
path (str): A path to a directory.
Keyword Arguments:
ignore_errors (bool): If `True`, any errors reading a
directory will be ignored, otherwise exceptions will be
raised.
on_error (callable): If ``ignore_errors`` is `False`, then
this callable will be invoked with a path and the exception
object. It should return `True` to ignore the error, or
`False` to re-raise it.
search (str): If ``'breadth'`` then the directory will be
walked *top down*. Set to ``'depth'`` to walk *bottom up*.
filter_dirs (list, optional): A list of patterns that will be used
to match directories paths. The walk will only open directories
that match at least one of these patterns.
exclude_dirs (list): A list of patterns that will be used
to filter out directories from the walk, e.g. ``['*.svn',
'*.git']``.
max_depth (int, optional): Maximum directory depth to walk.
Returns:
~collections.Iterator: an iterator over directory paths
(absolute from the filesystem root).
This method invokes `Walker.dirs` with the bound `FS` object.
"""
walker = self._make_walker(**kwargs)
return walker.dirs(self.fs, path=path) | python | def dirs(self, path="/", **kwargs):
# type: (Text, **Any) -> Iterator[Text]
"""Walk a filesystem, yielding absolute paths to directories.
Arguments:
path (str): A path to a directory.
Keyword Arguments:
ignore_errors (bool): If `True`, any errors reading a
directory will be ignored, otherwise exceptions will be
raised.
on_error (callable): If ``ignore_errors`` is `False`, then
this callable will be invoked with a path and the exception
object. It should return `True` to ignore the error, or
`False` to re-raise it.
search (str): If ``'breadth'`` then the directory will be
walked *top down*. Set to ``'depth'`` to walk *bottom up*.
filter_dirs (list, optional): A list of patterns that will be used
to match directories paths. The walk will only open directories
that match at least one of these patterns.
exclude_dirs (list): A list of patterns that will be used
to filter out directories from the walk, e.g. ``['*.svn',
'*.git']``.
max_depth (int, optional): Maximum directory depth to walk.
Returns:
~collections.Iterator: an iterator over directory paths
(absolute from the filesystem root).
This method invokes `Walker.dirs` with the bound `FS` object.
"""
walker = self._make_walker(**kwargs)
return walker.dirs(self.fs, path=path) | [
"def",
"dirs",
"(",
"self",
",",
"path",
"=",
"\"/\"",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Text, **Any) -> Iterator[Text]",
"walker",
"=",
"self",
".",
"_make_walker",
"(",
"*",
"*",
"kwargs",
")",
"return",
"walker",
".",
"dirs",
"(",
"self",
"... | Walk a filesystem, yielding absolute paths to directories.
Arguments:
path (str): A path to a directory.
Keyword Arguments:
ignore_errors (bool): If `True`, any errors reading a
directory will be ignored, otherwise exceptions will be
raised.
on_error (callable): If ``ignore_errors`` is `False`, then
this callable will be invoked with a path and the exception
object. It should return `True` to ignore the error, or
`False` to re-raise it.
search (str): If ``'breadth'`` then the directory will be
walked *top down*. Set to ``'depth'`` to walk *bottom up*.
filter_dirs (list, optional): A list of patterns that will be used
to match directories paths. The walk will only open directories
that match at least one of these patterns.
exclude_dirs (list): A list of patterns that will be used
to filter out directories from the walk, e.g. ``['*.svn',
'*.git']``.
max_depth (int, optional): Maximum directory depth to walk.
Returns:
~collections.Iterator: an iterator over directory paths
(absolute from the filesystem root).
This method invokes `Walker.dirs` with the bound `FS` object. | [
"Walk",
"a",
"filesystem",
"yielding",
"absolute",
"paths",
"to",
"directories",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/walk.py#L641-L674 | train | 228,542 |
PyFilesystem/pyfilesystem2 | fs/walk.py | BoundWalker.info | def info(
self,
path="/", # type: Text
namespaces=None, # type: Optional[Collection[Text]]
**kwargs # type: Any
):
# type: (...) -> Iterator[Tuple[Text, Info]]
"""Walk a filesystem, yielding path and `Info` of resources.
Arguments:
path (str): A path to a directory.
namespaces (list, optional): A list of namespaces to include
in the resource information, e.g. ``['basic', 'access']``
(defaults to ``['basic']``).
Keyword Arguments:
ignore_errors (bool): If `True`, any errors reading a
directory will be ignored, otherwise exceptions will be
raised.
on_error (callable): If ``ignore_errors`` is `False`, then
this callable will be invoked with a path and the exception
object. It should return `True` to ignore the error, or
`False` to re-raise it.
search (str): If ``'breadth'`` then the directory will be
walked *top down*. Set to ``'depth'`` to walk *bottom up*.
filter (list): If supplied, this parameter should be a list
of file name patterns, e.g. ``['*.py']``. Files will only be
returned if the final component matches one of the
patterns.
exclude (list, optional): If supplied, this parameter should be
a list of filename patterns, e.g. ``['~*', '.*']``. Files matching
any of these patterns will be removed from the walk.
filter_dirs (list, optional): A list of patterns that will be used
to match directories paths. The walk will only open directories
that match at least one of these patterns.
exclude_dirs (list): A list of patterns that will be used
to filter out directories from the walk, e.g. ``['*.svn',
'*.git']``.
max_depth (int, optional): Maximum directory depth to walk.
Returns:
~collections.Iterable: an iterable yielding tuples of
``(<absolute path>, <resource info>)``.
This method invokes `Walker.info` with the bound `FS` object.
"""
walker = self._make_walker(**kwargs)
return walker.info(self.fs, path=path, namespaces=namespaces) | python | def info(
self,
path="/", # type: Text
namespaces=None, # type: Optional[Collection[Text]]
**kwargs # type: Any
):
# type: (...) -> Iterator[Tuple[Text, Info]]
"""Walk a filesystem, yielding path and `Info` of resources.
Arguments:
path (str): A path to a directory.
namespaces (list, optional): A list of namespaces to include
in the resource information, e.g. ``['basic', 'access']``
(defaults to ``['basic']``).
Keyword Arguments:
ignore_errors (bool): If `True`, any errors reading a
directory will be ignored, otherwise exceptions will be
raised.
on_error (callable): If ``ignore_errors`` is `False`, then
this callable will be invoked with a path and the exception
object. It should return `True` to ignore the error, or
`False` to re-raise it.
search (str): If ``'breadth'`` then the directory will be
walked *top down*. Set to ``'depth'`` to walk *bottom up*.
filter (list): If supplied, this parameter should be a list
of file name patterns, e.g. ``['*.py']``. Files will only be
returned if the final component matches one of the
patterns.
exclude (list, optional): If supplied, this parameter should be
a list of filename patterns, e.g. ``['~*', '.*']``. Files matching
any of these patterns will be removed from the walk.
filter_dirs (list, optional): A list of patterns that will be used
to match directories paths. The walk will only open directories
that match at least one of these patterns.
exclude_dirs (list): A list of patterns that will be used
to filter out directories from the walk, e.g. ``['*.svn',
'*.git']``.
max_depth (int, optional): Maximum directory depth to walk.
Returns:
~collections.Iterable: an iterable yielding tuples of
``(<absolute path>, <resource info>)``.
This method invokes `Walker.info` with the bound `FS` object.
"""
walker = self._make_walker(**kwargs)
return walker.info(self.fs, path=path, namespaces=namespaces) | [
"def",
"info",
"(",
"self",
",",
"path",
"=",
"\"/\"",
",",
"# type: Text",
"namespaces",
"=",
"None",
",",
"# type: Optional[Collection[Text]]",
"*",
"*",
"kwargs",
"# type: Any",
")",
":",
"# type: (...) -> Iterator[Tuple[Text, Info]]",
"walker",
"=",
"self",
".",... | Walk a filesystem, yielding path and `Info` of resources.
Arguments:
path (str): A path to a directory.
namespaces (list, optional): A list of namespaces to include
in the resource information, e.g. ``['basic', 'access']``
(defaults to ``['basic']``).
Keyword Arguments:
ignore_errors (bool): If `True`, any errors reading a
directory will be ignored, otherwise exceptions will be
raised.
on_error (callable): If ``ignore_errors`` is `False`, then
this callable will be invoked with a path and the exception
object. It should return `True` to ignore the error, or
`False` to re-raise it.
search (str): If ``'breadth'`` then the directory will be
walked *top down*. Set to ``'depth'`` to walk *bottom up*.
filter (list): If supplied, this parameter should be a list
of file name patterns, e.g. ``['*.py']``. Files will only be
returned if the final component matches one of the
patterns.
exclude (list, optional): If supplied, this parameter should be
a list of filename patterns, e.g. ``['~*', '.*']``. Files matching
any of these patterns will be removed from the walk.
filter_dirs (list, optional): A list of patterns that will be used
to match directories paths. The walk will only open directories
that match at least one of these patterns.
exclude_dirs (list): A list of patterns that will be used
to filter out directories from the walk, e.g. ``['*.svn',
'*.git']``.
max_depth (int, optional): Maximum directory depth to walk.
Returns:
~collections.Iterable: an iterable yielding tuples of
``(<absolute path>, <resource info>)``.
This method invokes `Walker.info` with the bound `FS` object. | [
"Walk",
"a",
"filesystem",
"yielding",
"path",
"and",
"Info",
"of",
"resources",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/walk.py#L676-L724 | train | 228,543 |
PyFilesystem/pyfilesystem2 | fs/tools.py | remove_empty | def remove_empty(fs, path):
# type: (FS, Text) -> None
"""Remove all empty parents.
Arguments:
fs (FS): A filesystem instance.
path (str): Path to a directory on the filesystem.
"""
path = abspath(normpath(path))
try:
while path not in ("", "/"):
fs.removedir(path)
path = dirname(path)
except DirectoryNotEmpty:
pass | python | def remove_empty(fs, path):
# type: (FS, Text) -> None
"""Remove all empty parents.
Arguments:
fs (FS): A filesystem instance.
path (str): Path to a directory on the filesystem.
"""
path = abspath(normpath(path))
try:
while path not in ("", "/"):
fs.removedir(path)
path = dirname(path)
except DirectoryNotEmpty:
pass | [
"def",
"remove_empty",
"(",
"fs",
",",
"path",
")",
":",
"# type: (FS, Text) -> None",
"path",
"=",
"abspath",
"(",
"normpath",
"(",
"path",
")",
")",
"try",
":",
"while",
"path",
"not",
"in",
"(",
"\"\"",
",",
"\"/\"",
")",
":",
"fs",
".",
"removedir"... | Remove all empty parents.
Arguments:
fs (FS): A filesystem instance.
path (str): Path to a directory on the filesystem. | [
"Remove",
"all",
"empty",
"parents",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/tools.py#L23-L38 | train | 228,544 |
PyFilesystem/pyfilesystem2 | fs/tools.py | copy_file_data | def copy_file_data(src_file, dst_file, chunk_size=None):
# type: (IO, IO, Optional[int]) -> None
"""Copy data from one file object to another.
Arguments:
src_file (io.IOBase): File open for reading.
dst_file (io.IOBase): File open for writing.
chunk_size (int): Number of bytes to copy at
a time (or `None` to use sensible default).
"""
_chunk_size = 1024 * 1024 if chunk_size is None else chunk_size
read = src_file.read
write = dst_file.write
# The 'or None' is so that it works with binary and text files
for chunk in iter(lambda: read(_chunk_size) or None, None):
write(chunk) | python | def copy_file_data(src_file, dst_file, chunk_size=None):
# type: (IO, IO, Optional[int]) -> None
"""Copy data from one file object to another.
Arguments:
src_file (io.IOBase): File open for reading.
dst_file (io.IOBase): File open for writing.
chunk_size (int): Number of bytes to copy at
a time (or `None` to use sensible default).
"""
_chunk_size = 1024 * 1024 if chunk_size is None else chunk_size
read = src_file.read
write = dst_file.write
# The 'or None' is so that it works with binary and text files
for chunk in iter(lambda: read(_chunk_size) or None, None):
write(chunk) | [
"def",
"copy_file_data",
"(",
"src_file",
",",
"dst_file",
",",
"chunk_size",
"=",
"None",
")",
":",
"# type: (IO, IO, Optional[int]) -> None",
"_chunk_size",
"=",
"1024",
"*",
"1024",
"if",
"chunk_size",
"is",
"None",
"else",
"chunk_size",
"read",
"=",
"src_file"... | Copy data from one file object to another.
Arguments:
src_file (io.IOBase): File open for reading.
dst_file (io.IOBase): File open for writing.
chunk_size (int): Number of bytes to copy at
a time (or `None` to use sensible default). | [
"Copy",
"data",
"from",
"one",
"file",
"object",
"to",
"another",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/tools.py#L41-L57 | train | 228,545 |
PyFilesystem/pyfilesystem2 | fs/tools.py | get_intermediate_dirs | def get_intermediate_dirs(fs, dir_path):
# type: (FS, Text) -> List[Text]
"""Get a list of non-existing intermediate directories.
Arguments:
fs (FS): A filesystem instance.
dir_path (str): A path to a new directory on the filesystem.
Returns:
list: A list of non-existing paths.
Raises:
~fs.errors.DirectoryExpected: If a path component
references a file and not a directory.
"""
intermediates = []
with fs.lock():
for path in recursepath(abspath(dir_path), reverse=True):
try:
resource = fs.getinfo(path)
except ResourceNotFound:
intermediates.append(abspath(path))
else:
if resource.is_dir:
break
raise errors.DirectoryExpected(dir_path)
return intermediates[::-1][:-1] | python | def get_intermediate_dirs(fs, dir_path):
# type: (FS, Text) -> List[Text]
"""Get a list of non-existing intermediate directories.
Arguments:
fs (FS): A filesystem instance.
dir_path (str): A path to a new directory on the filesystem.
Returns:
list: A list of non-existing paths.
Raises:
~fs.errors.DirectoryExpected: If a path component
references a file and not a directory.
"""
intermediates = []
with fs.lock():
for path in recursepath(abspath(dir_path), reverse=True):
try:
resource = fs.getinfo(path)
except ResourceNotFound:
intermediates.append(abspath(path))
else:
if resource.is_dir:
break
raise errors.DirectoryExpected(dir_path)
return intermediates[::-1][:-1] | [
"def",
"get_intermediate_dirs",
"(",
"fs",
",",
"dir_path",
")",
":",
"# type: (FS, Text) -> List[Text]",
"intermediates",
"=",
"[",
"]",
"with",
"fs",
".",
"lock",
"(",
")",
":",
"for",
"path",
"in",
"recursepath",
"(",
"abspath",
"(",
"dir_path",
")",
",",... | Get a list of non-existing intermediate directories.
Arguments:
fs (FS): A filesystem instance.
dir_path (str): A path to a new directory on the filesystem.
Returns:
list: A list of non-existing paths.
Raises:
~fs.errors.DirectoryExpected: If a path component
references a file and not a directory. | [
"Get",
"a",
"list",
"of",
"non",
"-",
"existing",
"intermediate",
"directories",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/tools.py#L60-L87 | train | 228,546 |
soynatan/django-easy-audit | easyaudit/admin_helpers.py | prettify_json | def prettify_json(json_string):
"""Given a JSON string, it returns it as a
safe formatted HTML"""
try:
data = json.loads(json_string)
html = '<pre>' + json.dumps(data, sort_keys=True, indent=4) + '</pre>'
except:
html = json_string
return mark_safe(html) | python | def prettify_json(json_string):
"""Given a JSON string, it returns it as a
safe formatted HTML"""
try:
data = json.loads(json_string)
html = '<pre>' + json.dumps(data, sort_keys=True, indent=4) + '</pre>'
except:
html = json_string
return mark_safe(html) | [
"def",
"prettify_json",
"(",
"json_string",
")",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"json_string",
")",
"html",
"=",
"'<pre>'",
"+",
"json",
".",
"dumps",
"(",
"data",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
")",... | Given a JSON string, it returns it as a
safe formatted HTML | [
"Given",
"a",
"JSON",
"string",
"it",
"returns",
"it",
"as",
"a",
"safe",
"formatted",
"HTML"
] | 03e05bc94beb29fc3e4ff86e313a6fef4b766b4b | https://github.com/soynatan/django-easy-audit/blob/03e05bc94beb29fc3e4ff86e313a6fef4b766b4b/easyaudit/admin_helpers.py#L21-L29 | train | 228,547 |
soynatan/django-easy-audit | easyaudit/admin_helpers.py | EasyAuditModelAdmin.purge_objects | def purge_objects(self, request):
"""
Removes all objects in this table.
This action first displays a confirmation page;
next, it deletes all objects and redirects back to the change list.
"""
def truncate_table(model):
if settings.TRUNCATE_TABLE_SQL_STATEMENT:
from django.db import connection
sql = settings.TRUNCATE_TABLE_SQL_STATEMENT.format(db_table=model._meta.db_table)
cursor = connection.cursor()
cursor.execute(sql)
else:
model.objects.all().delete()
modeladmin = self
opts = modeladmin.model._meta
# Check that the user has delete permission for the actual model
if not request.user.is_superuser:
raise PermissionDenied
if not modeladmin.has_delete_permission(request):
raise PermissionDenied
# If the user has already confirmed or cancelled the deletion,
# (eventually) do the deletion and return to the change list view again.
if request.method == 'POST':
if 'btn-confirm' in request.POST:
try:
n = modeladmin.model.objects.count()
truncate_table(modeladmin.model)
modeladmin.message_user(request, _("Successfully removed %d rows" % n), messages.SUCCESS);
except Exception as e:
modeladmin.message_user(request, _(u'ERROR') + ': %r' % e, messages.ERROR)
else:
modeladmin.message_user(request, _("Action cancelled by user"), messages.SUCCESS);
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name)))
context = {
"title": _("Purge all %s ... are you sure?") % opts.verbose_name_plural,
"opts": opts,
"app_label": opts.app_label,
}
# Display the confirmation page
return render(
request,
'admin/easyaudit/purge_confirmation.html',
context
) | python | def purge_objects(self, request):
"""
Removes all objects in this table.
This action first displays a confirmation page;
next, it deletes all objects and redirects back to the change list.
"""
def truncate_table(model):
if settings.TRUNCATE_TABLE_SQL_STATEMENT:
from django.db import connection
sql = settings.TRUNCATE_TABLE_SQL_STATEMENT.format(db_table=model._meta.db_table)
cursor = connection.cursor()
cursor.execute(sql)
else:
model.objects.all().delete()
modeladmin = self
opts = modeladmin.model._meta
# Check that the user has delete permission for the actual model
if not request.user.is_superuser:
raise PermissionDenied
if not modeladmin.has_delete_permission(request):
raise PermissionDenied
# If the user has already confirmed or cancelled the deletion,
# (eventually) do the deletion and return to the change list view again.
if request.method == 'POST':
if 'btn-confirm' in request.POST:
try:
n = modeladmin.model.objects.count()
truncate_table(modeladmin.model)
modeladmin.message_user(request, _("Successfully removed %d rows" % n), messages.SUCCESS);
except Exception as e:
modeladmin.message_user(request, _(u'ERROR') + ': %r' % e, messages.ERROR)
else:
modeladmin.message_user(request, _("Action cancelled by user"), messages.SUCCESS);
return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name)))
context = {
"title": _("Purge all %s ... are you sure?") % opts.verbose_name_plural,
"opts": opts,
"app_label": opts.app_label,
}
# Display the confirmation page
return render(
request,
'admin/easyaudit/purge_confirmation.html',
context
) | [
"def",
"purge_objects",
"(",
"self",
",",
"request",
")",
":",
"def",
"truncate_table",
"(",
"model",
")",
":",
"if",
"settings",
".",
"TRUNCATE_TABLE_SQL_STATEMENT",
":",
"from",
"django",
".",
"db",
"import",
"connection",
"sql",
"=",
"settings",
".",
"TRU... | Removes all objects in this table.
This action first displays a confirmation page;
next, it deletes all objects and redirects back to the change list. | [
"Removes",
"all",
"objects",
"in",
"this",
"table",
".",
"This",
"action",
"first",
"displays",
"a",
"confirmation",
"page",
";",
"next",
"it",
"deletes",
"all",
"objects",
"and",
"redirects",
"back",
"to",
"the",
"change",
"list",
"."
] | 03e05bc94beb29fc3e4ff86e313a6fef4b766b4b | https://github.com/soynatan/django-easy-audit/blob/03e05bc94beb29fc3e4ff86e313a6fef4b766b4b/easyaudit/admin_helpers.py#L66-L116 | train | 228,548 |
soynatan/django-easy-audit | easyaudit/settings.py | get_model_list | def get_model_list(class_list):
"""
Receives a list of strings with app_name.model_name format
and turns them into classes. If an item is already a class
it ignores it.
"""
for idx, item in enumerate(class_list):
if isinstance(item, six.string_types):
model_class = apps.get_model(item)
class_list[idx] = model_class | python | def get_model_list(class_list):
"""
Receives a list of strings with app_name.model_name format
and turns them into classes. If an item is already a class
it ignores it.
"""
for idx, item in enumerate(class_list):
if isinstance(item, six.string_types):
model_class = apps.get_model(item)
class_list[idx] = model_class | [
"def",
"get_model_list",
"(",
"class_list",
")",
":",
"for",
"idx",
",",
"item",
"in",
"enumerate",
"(",
"class_list",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"six",
".",
"string_types",
")",
":",
"model_class",
"=",
"apps",
".",
"get_model",
"("... | Receives a list of strings with app_name.model_name format
and turns them into classes. If an item is already a class
it ignores it. | [
"Receives",
"a",
"list",
"of",
"strings",
"with",
"app_name",
".",
"model_name",
"format",
"and",
"turns",
"them",
"into",
"classes",
".",
"If",
"an",
"item",
"is",
"already",
"a",
"class",
"it",
"ignores",
"it",
"."
] | 03e05bc94beb29fc3e4ff86e313a6fef4b766b4b | https://github.com/soynatan/django-easy-audit/blob/03e05bc94beb29fc3e4ff86e313a6fef4b766b4b/easyaudit/settings.py#L15-L24 | train | 228,549 |
soynatan/django-easy-audit | easyaudit/signals/model_signals.py | should_audit | def should_audit(instance):
"""Returns True or False to indicate whether the instance
should be audited or not, depending on the project settings."""
# do not audit any model listed in UNREGISTERED_CLASSES
for unregistered_class in UNREGISTERED_CLASSES:
if isinstance(instance, unregistered_class):
return False
# only audit models listed in REGISTERED_CLASSES (if it's set)
if len(REGISTERED_CLASSES) > 0:
for registered_class in REGISTERED_CLASSES:
if isinstance(instance, registered_class):
break
else:
return False
# all good
return True | python | def should_audit(instance):
"""Returns True or False to indicate whether the instance
should be audited or not, depending on the project settings."""
# do not audit any model listed in UNREGISTERED_CLASSES
for unregistered_class in UNREGISTERED_CLASSES:
if isinstance(instance, unregistered_class):
return False
# only audit models listed in REGISTERED_CLASSES (if it's set)
if len(REGISTERED_CLASSES) > 0:
for registered_class in REGISTERED_CLASSES:
if isinstance(instance, registered_class):
break
else:
return False
# all good
return True | [
"def",
"should_audit",
"(",
"instance",
")",
":",
"# do not audit any model listed in UNREGISTERED_CLASSES",
"for",
"unregistered_class",
"in",
"UNREGISTERED_CLASSES",
":",
"if",
"isinstance",
"(",
"instance",
",",
"unregistered_class",
")",
":",
"return",
"False",
"# onl... | Returns True or False to indicate whether the instance
should be audited or not, depending on the project settings. | [
"Returns",
"True",
"or",
"False",
"to",
"indicate",
"whether",
"the",
"instance",
"should",
"be",
"audited",
"or",
"not",
"depending",
"on",
"the",
"project",
"settings",
"."
] | 03e05bc94beb29fc3e4ff86e313a6fef4b766b4b | https://github.com/soynatan/django-easy-audit/blob/03e05bc94beb29fc3e4ff86e313a6fef4b766b4b/easyaudit/signals/model_signals.py#L23-L41 | train | 228,550 |
soynatan/django-easy-audit | easyaudit/signals/model_signals.py | _m2m_rev_field_name | def _m2m_rev_field_name(model1, model2):
"""Gets the name of the reverse m2m accessor from `model1` to `model2`
For example, if User has a ManyToManyField connected to Group,
`_m2m_rev_field_name(Group, User)` retrieves the name of the field on
Group that lists a group's Users. (By default, this field is called
`user_set`, but the name can be overridden).
"""
m2m_field_names = [
rel.get_accessor_name() for rel in model1._meta.get_fields()
if rel.many_to_many
and rel.auto_created
and rel.related_model == model2
]
return m2m_field_names[0] | python | def _m2m_rev_field_name(model1, model2):
"""Gets the name of the reverse m2m accessor from `model1` to `model2`
For example, if User has a ManyToManyField connected to Group,
`_m2m_rev_field_name(Group, User)` retrieves the name of the field on
Group that lists a group's Users. (By default, this field is called
`user_set`, but the name can be overridden).
"""
m2m_field_names = [
rel.get_accessor_name() for rel in model1._meta.get_fields()
if rel.many_to_many
and rel.auto_created
and rel.related_model == model2
]
return m2m_field_names[0] | [
"def",
"_m2m_rev_field_name",
"(",
"model1",
",",
"model2",
")",
":",
"m2m_field_names",
"=",
"[",
"rel",
".",
"get_accessor_name",
"(",
")",
"for",
"rel",
"in",
"model1",
".",
"_meta",
".",
"get_fields",
"(",
")",
"if",
"rel",
".",
"many_to_many",
"and",
... | Gets the name of the reverse m2m accessor from `model1` to `model2`
For example, if User has a ManyToManyField connected to Group,
`_m2m_rev_field_name(Group, User)` retrieves the name of the field on
Group that lists a group's Users. (By default, this field is called
`user_set`, but the name can be overridden). | [
"Gets",
"the",
"name",
"of",
"the",
"reverse",
"m2m",
"accessor",
"from",
"model1",
"to",
"model2"
] | 03e05bc94beb29fc3e4ff86e313a6fef4b766b4b | https://github.com/soynatan/django-easy-audit/blob/03e05bc94beb29fc3e4ff86e313a6fef4b766b4b/easyaudit/signals/model_signals.py#L174-L188 | train | 228,551 |
wookayin/gpustat | gpustat/core.py | GPUStatCollection.new_query | def new_query():
"""Query the information of all the GPUs on local machine"""
N.nvmlInit()
def _decode(b):
if isinstance(b, bytes):
return b.decode() # for python3, to unicode
return b
def get_gpu_info(handle):
"""Get one GPU information specified by nvml handle"""
def get_process_info(nv_process):
"""Get the process information of specific pid"""
process = {}
ps_process = psutil.Process(pid=nv_process.pid)
process['username'] = ps_process.username()
# cmdline returns full path;
# as in `ps -o comm`, get short cmdnames.
_cmdline = ps_process.cmdline()
if not _cmdline:
# sometimes, zombie or unknown (e.g. [kworker/8:2H])
process['command'] = '?'
else:
process['command'] = os.path.basename(_cmdline[0])
# Bytes to MBytes
process['gpu_memory_usage'] = nv_process.usedGpuMemory // MB
process['pid'] = nv_process.pid
return process
name = _decode(N.nvmlDeviceGetName(handle))
uuid = _decode(N.nvmlDeviceGetUUID(handle))
try:
temperature = N.nvmlDeviceGetTemperature(
handle, N.NVML_TEMPERATURE_GPU
)
except N.NVMLError:
temperature = None # Not supported
try:
memory = N.nvmlDeviceGetMemoryInfo(handle) # in Bytes
except N.NVMLError:
memory = None # Not supported
try:
utilization = N.nvmlDeviceGetUtilizationRates(handle)
except N.NVMLError:
utilization = None # Not supported
try:
power = N.nvmlDeviceGetPowerUsage(handle)
except N.NVMLError:
power = None
try:
power_limit = N.nvmlDeviceGetEnforcedPowerLimit(handle)
except N.NVMLError:
power_limit = None
try:
nv_comp_processes = \
N.nvmlDeviceGetComputeRunningProcesses(handle)
except N.NVMLError:
nv_comp_processes = None # Not supported
try:
nv_graphics_processes = \
N.nvmlDeviceGetGraphicsRunningProcesses(handle)
except N.NVMLError:
nv_graphics_processes = None # Not supported
if nv_comp_processes is None and nv_graphics_processes is None:
processes = None
else:
processes = []
nv_comp_processes = nv_comp_processes or []
nv_graphics_processes = nv_graphics_processes or []
for nv_process in nv_comp_processes + nv_graphics_processes:
# TODO: could be more information such as system memory
# usage, CPU percentage, create time etc.
try:
process = get_process_info(nv_process)
processes.append(process)
except psutil.NoSuchProcess:
# TODO: add some reminder for NVML broken context
# e.g. nvidia-smi reset or reboot the system
pass
index = N.nvmlDeviceGetIndex(handle)
gpu_info = {
'index': index,
'uuid': uuid,
'name': name,
'temperature.gpu': temperature,
'utilization.gpu': utilization.gpu if utilization else None,
'power.draw': power // 1000 if power is not None else None,
'enforced.power.limit': power_limit // 1000
if power_limit is not None else None,
# Convert bytes into MBytes
'memory.used': memory.used // MB if memory else None,
'memory.total': memory.total // MB if memory else None,
'processes': processes,
}
return gpu_info
# 1. get the list of gpu and status
gpu_list = []
device_count = N.nvmlDeviceGetCount()
for index in range(device_count):
handle = N.nvmlDeviceGetHandleByIndex(index)
gpu_info = get_gpu_info(handle)
gpu_stat = GPUStat(gpu_info)
gpu_list.append(gpu_stat)
# 2. additional info (driver version, etc).
try:
driver_version = _decode(N.nvmlSystemGetDriverVersion())
except N.NVMLError:
driver_version = None # N/A
N.nvmlShutdown()
return GPUStatCollection(gpu_list, driver_version=driver_version) | python | def new_query():
"""Query the information of all the GPUs on local machine"""
N.nvmlInit()
def _decode(b):
if isinstance(b, bytes):
return b.decode() # for python3, to unicode
return b
def get_gpu_info(handle):
"""Get one GPU information specified by nvml handle"""
def get_process_info(nv_process):
"""Get the process information of specific pid"""
process = {}
ps_process = psutil.Process(pid=nv_process.pid)
process['username'] = ps_process.username()
# cmdline returns full path;
# as in `ps -o comm`, get short cmdnames.
_cmdline = ps_process.cmdline()
if not _cmdline:
# sometimes, zombie or unknown (e.g. [kworker/8:2H])
process['command'] = '?'
else:
process['command'] = os.path.basename(_cmdline[0])
# Bytes to MBytes
process['gpu_memory_usage'] = nv_process.usedGpuMemory // MB
process['pid'] = nv_process.pid
return process
name = _decode(N.nvmlDeviceGetName(handle))
uuid = _decode(N.nvmlDeviceGetUUID(handle))
try:
temperature = N.nvmlDeviceGetTemperature(
handle, N.NVML_TEMPERATURE_GPU
)
except N.NVMLError:
temperature = None # Not supported
try:
memory = N.nvmlDeviceGetMemoryInfo(handle) # in Bytes
except N.NVMLError:
memory = None # Not supported
try:
utilization = N.nvmlDeviceGetUtilizationRates(handle)
except N.NVMLError:
utilization = None # Not supported
try:
power = N.nvmlDeviceGetPowerUsage(handle)
except N.NVMLError:
power = None
try:
power_limit = N.nvmlDeviceGetEnforcedPowerLimit(handle)
except N.NVMLError:
power_limit = None
try:
nv_comp_processes = \
N.nvmlDeviceGetComputeRunningProcesses(handle)
except N.NVMLError:
nv_comp_processes = None # Not supported
try:
nv_graphics_processes = \
N.nvmlDeviceGetGraphicsRunningProcesses(handle)
except N.NVMLError:
nv_graphics_processes = None # Not supported
if nv_comp_processes is None and nv_graphics_processes is None:
processes = None
else:
processes = []
nv_comp_processes = nv_comp_processes or []
nv_graphics_processes = nv_graphics_processes or []
for nv_process in nv_comp_processes + nv_graphics_processes:
# TODO: could be more information such as system memory
# usage, CPU percentage, create time etc.
try:
process = get_process_info(nv_process)
processes.append(process)
except psutil.NoSuchProcess:
# TODO: add some reminder for NVML broken context
# e.g. nvidia-smi reset or reboot the system
pass
index = N.nvmlDeviceGetIndex(handle)
gpu_info = {
'index': index,
'uuid': uuid,
'name': name,
'temperature.gpu': temperature,
'utilization.gpu': utilization.gpu if utilization else None,
'power.draw': power // 1000 if power is not None else None,
'enforced.power.limit': power_limit // 1000
if power_limit is not None else None,
# Convert bytes into MBytes
'memory.used': memory.used // MB if memory else None,
'memory.total': memory.total // MB if memory else None,
'processes': processes,
}
return gpu_info
# 1. get the list of gpu and status
gpu_list = []
device_count = N.nvmlDeviceGetCount()
for index in range(device_count):
handle = N.nvmlDeviceGetHandleByIndex(index)
gpu_info = get_gpu_info(handle)
gpu_stat = GPUStat(gpu_info)
gpu_list.append(gpu_stat)
# 2. additional info (driver version, etc).
try:
driver_version = _decode(N.nvmlSystemGetDriverVersion())
except N.NVMLError:
driver_version = None # N/A
N.nvmlShutdown()
return GPUStatCollection(gpu_list, driver_version=driver_version) | [
"def",
"new_query",
"(",
")",
":",
"N",
".",
"nvmlInit",
"(",
")",
"def",
"_decode",
"(",
"b",
")",
":",
"if",
"isinstance",
"(",
"b",
",",
"bytes",
")",
":",
"return",
"b",
".",
"decode",
"(",
")",
"# for python3, to unicode",
"return",
"b",
"def",
... | Query the information of all the GPUs on local machine | [
"Query",
"the",
"information",
"of",
"all",
"the",
"GPUs",
"on",
"local",
"machine"
] | 28299cdcf55dd627fdd9800cf344988b43188ee8 | https://github.com/wookayin/gpustat/blob/28299cdcf55dd627fdd9800cf344988b43188ee8/gpustat/core.py#L262-L385 | train | 228,552 |
wookayin/gpustat | gpustat/__main__.py | print_gpustat | def print_gpustat(json=False, debug=False, **kwargs):
'''
Display the GPU query results into standard output.
'''
try:
gpu_stats = GPUStatCollection.new_query()
except Exception as e:
sys.stderr.write('Error on querying NVIDIA devices.'
' Use --debug flag for details\n')
if debug:
try:
import traceback
traceback.print_exc(file=sys.stderr)
except Exception:
# NVMLError can't be processed by traceback:
# https://bugs.python.org/issue28603
# as a workaround, simply re-throw the exception
raise e
sys.exit(1)
if json:
gpu_stats.print_json(sys.stdout)
else:
gpu_stats.print_formatted(sys.stdout, **kwargs) | python | def print_gpustat(json=False, debug=False, **kwargs):
'''
Display the GPU query results into standard output.
'''
try:
gpu_stats = GPUStatCollection.new_query()
except Exception as e:
sys.stderr.write('Error on querying NVIDIA devices.'
' Use --debug flag for details\n')
if debug:
try:
import traceback
traceback.print_exc(file=sys.stderr)
except Exception:
# NVMLError can't be processed by traceback:
# https://bugs.python.org/issue28603
# as a workaround, simply re-throw the exception
raise e
sys.exit(1)
if json:
gpu_stats.print_json(sys.stdout)
else:
gpu_stats.print_formatted(sys.stdout, **kwargs) | [
"def",
"print_gpustat",
"(",
"json",
"=",
"False",
",",
"debug",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"gpu_stats",
"=",
"GPUStatCollection",
".",
"new_query",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"sys",
".",
"stderr"... | Display the GPU query results into standard output. | [
"Display",
"the",
"GPU",
"query",
"results",
"into",
"standard",
"output",
"."
] | 28299cdcf55dd627fdd9800cf344988b43188ee8 | https://github.com/wookayin/gpustat/blob/28299cdcf55dd627fdd9800cf344988b43188ee8/gpustat/__main__.py#L14-L37 | train | 228,553 |
westonplatter/fast_arrow | fast_arrow/resources/option.py | Option.fetch_list | def fetch_list(cls, client, ids):
"""
fetch instruments by ids
"""
results = []
request_url = "https://api.robinhood.com/options/instruments/"
for _ids in chunked_list(ids, 50):
params = {"ids": ",".join(_ids)}
data = client.get(request_url, params=params)
partial_results = data["results"]
while data["next"]:
data = client.get(data["next"])
partial_results.extend(data["results"])
results.extend(partial_results)
return results | python | def fetch_list(cls, client, ids):
"""
fetch instruments by ids
"""
results = []
request_url = "https://api.robinhood.com/options/instruments/"
for _ids in chunked_list(ids, 50):
params = {"ids": ",".join(_ids)}
data = client.get(request_url, params=params)
partial_results = data["results"]
while data["next"]:
data = client.get(data["next"])
partial_results.extend(data["results"])
results.extend(partial_results)
return results | [
"def",
"fetch_list",
"(",
"cls",
",",
"client",
",",
"ids",
")",
":",
"results",
"=",
"[",
"]",
"request_url",
"=",
"\"https://api.robinhood.com/options/instruments/\"",
"for",
"_ids",
"in",
"chunked_list",
"(",
"ids",
",",
"50",
")",
":",
"params",
"=",
"{"... | fetch instruments by ids | [
"fetch",
"instruments",
"by",
"ids"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option.py#L44-L62 | train | 228,554 |
westonplatter/fast_arrow | fast_arrow/resources/option.py | Option.in_chain | def in_chain(cls, client, chain_id, expiration_dates=[]):
"""
fetch all option instruments in an options chain
- expiration_dates = optionally scope
"""
request_url = "https://api.robinhood.com/options/instruments/"
params = {
"chain_id": chain_id,
"expiration_dates": ",".join(expiration_dates)
}
data = client.get(request_url, params=params)
results = data['results']
while data['next']:
data = client.get(data['next'])
results.extend(data['results'])
return results | python | def in_chain(cls, client, chain_id, expiration_dates=[]):
"""
fetch all option instruments in an options chain
- expiration_dates = optionally scope
"""
request_url = "https://api.robinhood.com/options/instruments/"
params = {
"chain_id": chain_id,
"expiration_dates": ",".join(expiration_dates)
}
data = client.get(request_url, params=params)
results = data['results']
while data['next']:
data = client.get(data['next'])
results.extend(data['results'])
return results | [
"def",
"in_chain",
"(",
"cls",
",",
"client",
",",
"chain_id",
",",
"expiration_dates",
"=",
"[",
"]",
")",
":",
"request_url",
"=",
"\"https://api.robinhood.com/options/instruments/\"",
"params",
"=",
"{",
"\"chain_id\"",
":",
"chain_id",
",",
"\"expiration_dates\"... | fetch all option instruments in an options chain
- expiration_dates = optionally scope | [
"fetch",
"all",
"option",
"instruments",
"in",
"an",
"options",
"chain",
"-",
"expiration_dates",
"=",
"optionally",
"scope"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option.py#L65-L83 | train | 228,555 |
westonplatter/fast_arrow | fast_arrow/option_strategies/iron_condor.py | IronCondor.generate_by_deltas | def generate_by_deltas(cls, options,
width, put_inner_lte_delta, call_inner_lte_delta):
"""
totally just playing around ideas for the API.
this IC sells
- credit put spread
- credit call spread
the approach
- set width for the wing spread (eg, 1, ie, 1 unit width spread)
- set delta for inner leg of the put credit spread (eg, -0.2)
- set delta for inner leg of the call credit spread (eg, 0.1)
"""
raise Exception("Not Implemented starting at the 0.3.0 release")
#
# put credit spread
#
put_options_unsorted = list(
filter(lambda x: x['type'] == 'put', options))
put_options = cls.sort_by_strike_price(put_options_unsorted)
deltas_as_strings = [x['delta'] for x in put_options]
deltas = cls.strings_to_np_array(deltas_as_strings)
put_inner_index = np.argmin(deltas >= put_inner_lte_delta) - 1
put_outer_index = put_inner_index - width
put_inner_leg = cls.gen_leg(
put_options[put_inner_index]["instrument"], "sell")
put_outer_leg = cls.gen_leg(
put_options[put_outer_index]["instrument"], "buy")
#
# call credit spread
#
call_options_unsorted = list(
filter(lambda x: x['type'] == 'call', options))
call_options = cls.sort_by_strike_price(call_options_unsorted)
deltas_as_strings = [x['delta'] for x in call_options]
x = np.array(deltas_as_strings)
deltas = x.astype(np.float)
# because deep ITM call options have a delta that comes up as NaN,
# but are approximately 0.99 or 1.0, I'm replacing Nan with 1.0
# so np.argmax is able to walk up the index until it finds
# "call_inner_lte_delta"
# @TODO change this so (put credit / call credit) spreads work the same
where_are_NaNs = np.isnan(deltas)
deltas[where_are_NaNs] = 1.0
call_inner_index = np.argmax(deltas <= call_inner_lte_delta)
call_outer_index = call_inner_index + width
call_inner_leg = cls.gen_leg(
call_options[call_inner_index]["instrument"], "sell")
call_outer_leg = cls.gen_leg(
call_options[call_outer_index]["instrument"], "buy")
legs = [put_outer_leg, put_inner_leg, call_inner_leg, call_outer_leg]
#
# price calcs
#
price = (
- Decimal(put_options[put_outer_index]['adjusted_mark_price'])
+ Decimal(put_options[put_inner_index]['adjusted_mark_price'])
+ Decimal(call_options[call_inner_index]['adjusted_mark_price'])
- Decimal(call_options[call_outer_index]['adjusted_mark_price'])
)
#
# provide max bid ask spread diff
#
ic_options = [
put_options[put_outer_index],
put_options[put_inner_index],
call_options[call_inner_index],
call_options[call_outer_index]
]
max_bid_ask_spread = cls.max_bid_ask_spread(ic_options)
return {"legs": legs, "price": price,
"max_bid_ask_spread": max_bid_ask_spread} | python | def generate_by_deltas(cls, options,
width, put_inner_lte_delta, call_inner_lte_delta):
"""
totally just playing around ideas for the API.
this IC sells
- credit put spread
- credit call spread
the approach
- set width for the wing spread (eg, 1, ie, 1 unit width spread)
- set delta for inner leg of the put credit spread (eg, -0.2)
- set delta for inner leg of the call credit spread (eg, 0.1)
"""
raise Exception("Not Implemented starting at the 0.3.0 release")
#
# put credit spread
#
put_options_unsorted = list(
filter(lambda x: x['type'] == 'put', options))
put_options = cls.sort_by_strike_price(put_options_unsorted)
deltas_as_strings = [x['delta'] for x in put_options]
deltas = cls.strings_to_np_array(deltas_as_strings)
put_inner_index = np.argmin(deltas >= put_inner_lte_delta) - 1
put_outer_index = put_inner_index - width
put_inner_leg = cls.gen_leg(
put_options[put_inner_index]["instrument"], "sell")
put_outer_leg = cls.gen_leg(
put_options[put_outer_index]["instrument"], "buy")
#
# call credit spread
#
call_options_unsorted = list(
filter(lambda x: x['type'] == 'call', options))
call_options = cls.sort_by_strike_price(call_options_unsorted)
deltas_as_strings = [x['delta'] for x in call_options]
x = np.array(deltas_as_strings)
deltas = x.astype(np.float)
# because deep ITM call options have a delta that comes up as NaN,
# but are approximately 0.99 or 1.0, I'm replacing Nan with 1.0
# so np.argmax is able to walk up the index until it finds
# "call_inner_lte_delta"
# @TODO change this so (put credit / call credit) spreads work the same
where_are_NaNs = np.isnan(deltas)
deltas[where_are_NaNs] = 1.0
call_inner_index = np.argmax(deltas <= call_inner_lte_delta)
call_outer_index = call_inner_index + width
call_inner_leg = cls.gen_leg(
call_options[call_inner_index]["instrument"], "sell")
call_outer_leg = cls.gen_leg(
call_options[call_outer_index]["instrument"], "buy")
legs = [put_outer_leg, put_inner_leg, call_inner_leg, call_outer_leg]
#
# price calcs
#
price = (
- Decimal(put_options[put_outer_index]['adjusted_mark_price'])
+ Decimal(put_options[put_inner_index]['adjusted_mark_price'])
+ Decimal(call_options[call_inner_index]['adjusted_mark_price'])
- Decimal(call_options[call_outer_index]['adjusted_mark_price'])
)
#
# provide max bid ask spread diff
#
ic_options = [
put_options[put_outer_index],
put_options[put_inner_index],
call_options[call_inner_index],
call_options[call_outer_index]
]
max_bid_ask_spread = cls.max_bid_ask_spread(ic_options)
return {"legs": legs, "price": price,
"max_bid_ask_spread": max_bid_ask_spread} | [
"def",
"generate_by_deltas",
"(",
"cls",
",",
"options",
",",
"width",
",",
"put_inner_lte_delta",
",",
"call_inner_lte_delta",
")",
":",
"raise",
"Exception",
"(",
"\"Not Implemented starting at the 0.3.0 release\"",
")",
"#",
"# put credit spread",
"#",
"put_options_uns... | totally just playing around ideas for the API.
this IC sells
- credit put spread
- credit call spread
the approach
- set width for the wing spread (eg, 1, ie, 1 unit width spread)
- set delta for inner leg of the put credit spread (eg, -0.2)
- set delta for inner leg of the call credit spread (eg, 0.1) | [
"totally",
"just",
"playing",
"around",
"ideas",
"for",
"the",
"API",
"."
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/option_strategies/iron_condor.py#L41-L127 | train | 228,556 |
westonplatter/fast_arrow | fast_arrow/resources/option_chain.py | OptionChain.fetch | def fetch(cls, client, _id, symbol):
"""
fetch option chain for instrument
"""
url = "https://api.robinhood.com/options/chains/"
params = {
"equity_instrument_ids": _id,
"state": "active",
"tradability": "tradable"
}
data = client.get(url, params=params)
def filter_func(x):
return x["symbol"] == symbol
results = list(filter(filter_func, data["results"]))
return results[0] | python | def fetch(cls, client, _id, symbol):
"""
fetch option chain for instrument
"""
url = "https://api.robinhood.com/options/chains/"
params = {
"equity_instrument_ids": _id,
"state": "active",
"tradability": "tradable"
}
data = client.get(url, params=params)
def filter_func(x):
return x["symbol"] == symbol
results = list(filter(filter_func, data["results"]))
return results[0] | [
"def",
"fetch",
"(",
"cls",
",",
"client",
",",
"_id",
",",
"symbol",
")",
":",
"url",
"=",
"\"https://api.robinhood.com/options/chains/\"",
"params",
"=",
"{",
"\"equity_instrument_ids\"",
":",
"_id",
",",
"\"state\"",
":",
"\"active\"",
",",
"\"tradability\"",
... | fetch option chain for instrument | [
"fetch",
"option",
"chain",
"for",
"instrument"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option_chain.py#L4-L19 | train | 228,557 |
westonplatter/fast_arrow | fast_arrow/client.py | Client.authenticate | def authenticate(self):
'''
Authenticate using data in `options`
'''
if "username" in self.options and "password" in self.options:
self.login_oauth2(
self.options["username"],
self.options["password"],
self.options.get('mfa_code'))
elif "access_token" in self.options:
if "refresh_token" in self.options:
self.access_token = self.options["access_token"]
self.refresh_token = self.options["refresh_token"]
self.__set_account_info()
else:
self.authenticated = False
return self.authenticated | python | def authenticate(self):
'''
Authenticate using data in `options`
'''
if "username" in self.options and "password" in self.options:
self.login_oauth2(
self.options["username"],
self.options["password"],
self.options.get('mfa_code'))
elif "access_token" in self.options:
if "refresh_token" in self.options:
self.access_token = self.options["access_token"]
self.refresh_token = self.options["refresh_token"]
self.__set_account_info()
else:
self.authenticated = False
return self.authenticated | [
"def",
"authenticate",
"(",
"self",
")",
":",
"if",
"\"username\"",
"in",
"self",
".",
"options",
"and",
"\"password\"",
"in",
"self",
".",
"options",
":",
"self",
".",
"login_oauth2",
"(",
"self",
".",
"options",
"[",
"\"username\"",
"]",
",",
"self",
"... | Authenticate using data in `options` | [
"Authenticate",
"using",
"data",
"in",
"options"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/client.py#L27-L43 | train | 228,558 |
westonplatter/fast_arrow | fast_arrow/client.py | Client.get | def get(self, url=None, params=None, retry=True):
'''
Execute HTTP GET
'''
headers = self._gen_headers(self.access_token, url)
attempts = 1
while attempts <= HTTP_ATTEMPTS_MAX:
try:
res = requests.get(url,
headers=headers,
params=params,
timeout=15,
verify=self.certs)
res.raise_for_status()
return res.json()
except requests.exceptions.RequestException as e:
attempts += 1
if res.status_code in [400]:
raise e
elif retry and res.status_code in [403]:
self.relogin_oauth2() | python | def get(self, url=None, params=None, retry=True):
'''
Execute HTTP GET
'''
headers = self._gen_headers(self.access_token, url)
attempts = 1
while attempts <= HTTP_ATTEMPTS_MAX:
try:
res = requests.get(url,
headers=headers,
params=params,
timeout=15,
verify=self.certs)
res.raise_for_status()
return res.json()
except requests.exceptions.RequestException as e:
attempts += 1
if res.status_code in [400]:
raise e
elif retry and res.status_code in [403]:
self.relogin_oauth2() | [
"def",
"get",
"(",
"self",
",",
"url",
"=",
"None",
",",
"params",
"=",
"None",
",",
"retry",
"=",
"True",
")",
":",
"headers",
"=",
"self",
".",
"_gen_headers",
"(",
"self",
".",
"access_token",
",",
"url",
")",
"attempts",
"=",
"1",
"while",
"att... | Execute HTTP GET | [
"Execute",
"HTTP",
"GET"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/client.py#L45-L65 | train | 228,559 |
westonplatter/fast_arrow | fast_arrow/client.py | Client._gen_headers | def _gen_headers(self, bearer, url):
'''
Generate headders, adding in Oauth2 bearer token if present
'''
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": ("en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, " +
"nl;q=0.6, it;q=0.5"),
"User-Agent": ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) " +
"AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/68.0.3440.106 Safari/537.36"),
}
if bearer:
headers["Authorization"] = "Bearer {0}".format(bearer)
if url == "https://api.robinhood.com/options/orders/":
headers["Content-Type"] = "application/json; charset=utf-8"
return headers | python | def _gen_headers(self, bearer, url):
'''
Generate headders, adding in Oauth2 bearer token if present
'''
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": ("en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, " +
"nl;q=0.6, it;q=0.5"),
"User-Agent": ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) " +
"AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/68.0.3440.106 Safari/537.36"),
}
if bearer:
headers["Authorization"] = "Bearer {0}".format(bearer)
if url == "https://api.robinhood.com/options/orders/":
headers["Content-Type"] = "application/json; charset=utf-8"
return headers | [
"def",
"_gen_headers",
"(",
"self",
",",
"bearer",
",",
"url",
")",
":",
"headers",
"=",
"{",
"\"Accept\"",
":",
"\"*/*\"",
",",
"\"Accept-Encoding\"",
":",
"\"gzip, deflate\"",
",",
"\"Accept-Language\"",
":",
"(",
"\"en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, \"",
"+",... | Generate headders, adding in Oauth2 bearer token if present | [
"Generate",
"headders",
"adding",
"in",
"Oauth2",
"bearer",
"token",
"if",
"present"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/client.py#L89-L107 | train | 228,560 |
westonplatter/fast_arrow | fast_arrow/client.py | Client.logout_oauth2 | def logout_oauth2(self):
'''
Logout for given Oauth2 bearer token
'''
url = "https://api.robinhood.com/oauth2/revoke_token/"
data = {
"client_id": CLIENT_ID,
"token": self.refresh_token,
}
res = self.post(url, payload=data)
if res is None:
self.account_id = None
self.account_url = None
self.access_token = None
self.refresh_token = None
self.mfa_code = None
self.scope = None
self.authenticated = False
return True
else:
raise AuthenticationError("fast_arrow could not log out.") | python | def logout_oauth2(self):
'''
Logout for given Oauth2 bearer token
'''
url = "https://api.robinhood.com/oauth2/revoke_token/"
data = {
"client_id": CLIENT_ID,
"token": self.refresh_token,
}
res = self.post(url, payload=data)
if res is None:
self.account_id = None
self.account_url = None
self.access_token = None
self.refresh_token = None
self.mfa_code = None
self.scope = None
self.authenticated = False
return True
else:
raise AuthenticationError("fast_arrow could not log out.") | [
"def",
"logout_oauth2",
"(",
"self",
")",
":",
"url",
"=",
"\"https://api.robinhood.com/oauth2/revoke_token/\"",
"data",
"=",
"{",
"\"client_id\"",
":",
"CLIENT_ID",
",",
"\"token\"",
":",
"self",
".",
"refresh_token",
",",
"}",
"res",
"=",
"self",
".",
"post",
... | Logout for given Oauth2 bearer token | [
"Logout",
"for",
"given",
"Oauth2",
"bearer",
"token"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/client.py#L178-L198 | train | 228,561 |
westonplatter/fast_arrow | fast_arrow/resources/stock.py | Stock.fetch | def fetch(cls, client, symbol):
"""
fetch data for stock
"""
assert(type(symbol) is str)
url = ("https://api.robinhood.com/instruments/?symbol={0}".
format(symbol))
data = client.get(url)
return data["results"][0] | python | def fetch(cls, client, symbol):
"""
fetch data for stock
"""
assert(type(symbol) is str)
url = ("https://api.robinhood.com/instruments/?symbol={0}".
format(symbol))
data = client.get(url)
return data["results"][0] | [
"def",
"fetch",
"(",
"cls",
",",
"client",
",",
"symbol",
")",
":",
"assert",
"(",
"type",
"(",
"symbol",
")",
"is",
"str",
")",
"url",
"=",
"(",
"\"https://api.robinhood.com/instruments/?symbol={0}\"",
".",
"format",
"(",
"symbol",
")",
")",
"data",
"=",
... | fetch data for stock | [
"fetch",
"data",
"for",
"stock"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/stock.py#L7-L16 | train | 228,562 |
westonplatter/fast_arrow | fast_arrow/option_strategies/vertical.py | Vertical.gen_df | def gen_df(cls, options, width, spread_type="call", spread_kind="buy"):
"""
Generate Pandas Dataframe of Vertical
:param options: python dict of options.
:param width: offset for spread. Must be integer.
:param spread_type: call or put. defaults to "call".
:param spread_kind: buy or sell. defaults to "buy".
"""
assert type(width) is int
assert spread_type in ["call", "put"]
assert spread_kind in ["buy", "sell"]
# get CALLs or PUTs
options = list(filter(lambda x: x["type"] == spread_type, options))
coef = (1 if spread_type == "put" else -1)
shift = width * coef
df = pd.DataFrame.from_dict(options)
df['expiration_date'] = pd.to_datetime(
df['expiration_date'], format="%Y-%m-%d")
df['adjusted_mark_price'] = pd.to_numeric(df['adjusted_mark_price'])
df['strike_price'] = pd.to_numeric(df['strike_price'])
df.sort_values(["expiration_date", "strike_price"], inplace=True)
for k, v in df.groupby("expiration_date"):
sdf = v.shift(shift)
df.loc[v.index, "strike_price_shifted"] = sdf["strike_price"]
df.loc[v.index, "delta_shifted"] = sdf["delta"]
df.loc[v.index, "volume_shifted"] = sdf["volume"]
df.loc[v.index, "open_interest_shifted"] = sdf["open_interest"]
df.loc[v.index, "instrument_shifted"] = sdf["instrument"]
df.loc[v.index, "adjusted_mark_price_shift"] = \
sdf["adjusted_mark_price"]
if spread_kind == "sell":
df.loc[v.index, "margin"] = \
abs(sdf["strike_price"] - v["strike_price"])
else:
df.loc[v.index, "margin"] = 0.0
if spread_kind == "buy":
df.loc[v.index, "premium_adjusted_mark_price"] = (
v["adjusted_mark_price"] - sdf["adjusted_mark_price"])
elif spread_kind == "sell":
df.loc[v.index, "premium_adjusted_mark_price"] = (
sdf["adjusted_mark_price"] - v["adjusted_mark_price"])
return df | python | def gen_df(cls, options, width, spread_type="call", spread_kind="buy"):
"""
Generate Pandas Dataframe of Vertical
:param options: python dict of options.
:param width: offset for spread. Must be integer.
:param spread_type: call or put. defaults to "call".
:param spread_kind: buy or sell. defaults to "buy".
"""
assert type(width) is int
assert spread_type in ["call", "put"]
assert spread_kind in ["buy", "sell"]
# get CALLs or PUTs
options = list(filter(lambda x: x["type"] == spread_type, options))
coef = (1 if spread_type == "put" else -1)
shift = width * coef
df = pd.DataFrame.from_dict(options)
df['expiration_date'] = pd.to_datetime(
df['expiration_date'], format="%Y-%m-%d")
df['adjusted_mark_price'] = pd.to_numeric(df['adjusted_mark_price'])
df['strike_price'] = pd.to_numeric(df['strike_price'])
df.sort_values(["expiration_date", "strike_price"], inplace=True)
for k, v in df.groupby("expiration_date"):
sdf = v.shift(shift)
df.loc[v.index, "strike_price_shifted"] = sdf["strike_price"]
df.loc[v.index, "delta_shifted"] = sdf["delta"]
df.loc[v.index, "volume_shifted"] = sdf["volume"]
df.loc[v.index, "open_interest_shifted"] = sdf["open_interest"]
df.loc[v.index, "instrument_shifted"] = sdf["instrument"]
df.loc[v.index, "adjusted_mark_price_shift"] = \
sdf["adjusted_mark_price"]
if spread_kind == "sell":
df.loc[v.index, "margin"] = \
abs(sdf["strike_price"] - v["strike_price"])
else:
df.loc[v.index, "margin"] = 0.0
if spread_kind == "buy":
df.loc[v.index, "premium_adjusted_mark_price"] = (
v["adjusted_mark_price"] - sdf["adjusted_mark_price"])
elif spread_kind == "sell":
df.loc[v.index, "premium_adjusted_mark_price"] = (
sdf["adjusted_mark_price"] - v["adjusted_mark_price"])
return df | [
"def",
"gen_df",
"(",
"cls",
",",
"options",
",",
"width",
",",
"spread_type",
"=",
"\"call\"",
",",
"spread_kind",
"=",
"\"buy\"",
")",
":",
"assert",
"type",
"(",
"width",
")",
"is",
"int",
"assert",
"spread_type",
"in",
"[",
"\"call\"",
",",
"\"put\""... | Generate Pandas Dataframe of Vertical
:param options: python dict of options.
:param width: offset for spread. Must be integer.
:param spread_type: call or put. defaults to "call".
:param spread_kind: buy or sell. defaults to "buy". | [
"Generate",
"Pandas",
"Dataframe",
"of",
"Vertical"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/option_strategies/vertical.py#L7-L57 | train | 228,563 |
westonplatter/fast_arrow | fast_arrow/resources/stock_marketdata.py | StockMarketdata.quote_by_instruments | def quote_by_instruments(cls, client, ids):
"""
create instrument urls, fetch, return results
"""
base_url = "https://api.robinhood.com/instruments"
id_urls = ["{}/{}/".format(base_url, _id) for _id in ids]
return cls.quotes_by_instrument_urls(client, id_urls) | python | def quote_by_instruments(cls, client, ids):
"""
create instrument urls, fetch, return results
"""
base_url = "https://api.robinhood.com/instruments"
id_urls = ["{}/{}/".format(base_url, _id) for _id in ids]
return cls.quotes_by_instrument_urls(client, id_urls) | [
"def",
"quote_by_instruments",
"(",
"cls",
",",
"client",
",",
"ids",
")",
":",
"base_url",
"=",
"\"https://api.robinhood.com/instruments\"",
"id_urls",
"=",
"[",
"\"{}/{}/\"",
".",
"format",
"(",
"base_url",
",",
"_id",
")",
"for",
"_id",
"in",
"ids",
"]",
... | create instrument urls, fetch, return results | [
"create",
"instrument",
"urls",
"fetch",
"return",
"results"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/stock_marketdata.py#L13-L19 | train | 228,564 |
westonplatter/fast_arrow | fast_arrow/resources/stock_marketdata.py | StockMarketdata.quotes_by_instrument_urls | def quotes_by_instrument_urls(cls, client, urls):
"""
fetch and return results
"""
instruments = ",".join(urls)
params = {"instruments": instruments}
url = "https://api.robinhood.com/marketdata/quotes/"
data = client.get(url, params=params)
results = data["results"]
while "next" in data and data["next"]:
data = client.get(data["next"])
results.extend(data["results"])
return results | python | def quotes_by_instrument_urls(cls, client, urls):
"""
fetch and return results
"""
instruments = ",".join(urls)
params = {"instruments": instruments}
url = "https://api.robinhood.com/marketdata/quotes/"
data = client.get(url, params=params)
results = data["results"]
while "next" in data and data["next"]:
data = client.get(data["next"])
results.extend(data["results"])
return results | [
"def",
"quotes_by_instrument_urls",
"(",
"cls",
",",
"client",
",",
"urls",
")",
":",
"instruments",
"=",
"\",\"",
".",
"join",
"(",
"urls",
")",
"params",
"=",
"{",
"\"instruments\"",
":",
"instruments",
"}",
"url",
"=",
"\"https://api.robinhood.com/marketdata/... | fetch and return results | [
"fetch",
"and",
"return",
"results"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/stock_marketdata.py#L22-L34 | train | 228,565 |
westonplatter/fast_arrow | fast_arrow/resources/option_position.py | OptionPosition.all | def all(cls, client, **kwargs):
"""
fetch all option positions
"""
max_date = kwargs['max_date'] if 'max_date' in kwargs else None
max_fetches = \
kwargs['max_fetches'] if 'max_fetches' in kwargs else None
url = 'https://api.robinhood.com/options/positions/'
params = {}
data = client.get(url, params=params)
results = data["results"]
if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]):
return results
if max_fetches == 1:
return results
fetches = 1
while data["next"]:
fetches = fetches + 1
data = client.get(data["next"])
results.extend(data["results"])
if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]):
return results
if max_fetches and (fetches >= max_fetches):
return results
return results | python | def all(cls, client, **kwargs):
"""
fetch all option positions
"""
max_date = kwargs['max_date'] if 'max_date' in kwargs else None
max_fetches = \
kwargs['max_fetches'] if 'max_fetches' in kwargs else None
url = 'https://api.robinhood.com/options/positions/'
params = {}
data = client.get(url, params=params)
results = data["results"]
if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]):
return results
if max_fetches == 1:
return results
fetches = 1
while data["next"]:
fetches = fetches + 1
data = client.get(data["next"])
results.extend(data["results"])
if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]):
return results
if max_fetches and (fetches >= max_fetches):
return results
return results | [
"def",
"all",
"(",
"cls",
",",
"client",
",",
"*",
"*",
"kwargs",
")",
":",
"max_date",
"=",
"kwargs",
"[",
"'max_date'",
"]",
"if",
"'max_date'",
"in",
"kwargs",
"else",
"None",
"max_fetches",
"=",
"kwargs",
"[",
"'max_fetches'",
"]",
"if",
"'max_fetche... | fetch all option positions | [
"fetch",
"all",
"option",
"positions"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option_position.py#L10-L37 | train | 228,566 |
westonplatter/fast_arrow | fast_arrow/resources/option_position.py | OptionPosition.mergein_marketdata_list | def mergein_marketdata_list(cls, client, option_positions):
"""
Fetch and merge in Marketdata for each option position
"""
ids = cls._extract_ids(option_positions)
mds = OptionMarketdata.quotes_by_instrument_ids(client, ids)
results = []
for op in option_positions:
# @TODO optimize this so it's better than O(n^2)
md = [x for x in mds if x['instrument'] == op['option']][0]
# there is no overlap in keys so this is fine
merged_dict = dict(list(op.items()) + list(md.items()))
results.append(merged_dict)
return results | python | def mergein_marketdata_list(cls, client, option_positions):
"""
Fetch and merge in Marketdata for each option position
"""
ids = cls._extract_ids(option_positions)
mds = OptionMarketdata.quotes_by_instrument_ids(client, ids)
results = []
for op in option_positions:
# @TODO optimize this so it's better than O(n^2)
md = [x for x in mds if x['instrument'] == op['option']][0]
# there is no overlap in keys so this is fine
merged_dict = dict(list(op.items()) + list(md.items()))
results.append(merged_dict)
return results | [
"def",
"mergein_marketdata_list",
"(",
"cls",
",",
"client",
",",
"option_positions",
")",
":",
"ids",
"=",
"cls",
".",
"_extract_ids",
"(",
"option_positions",
")",
"mds",
"=",
"OptionMarketdata",
".",
"quotes_by_instrument_ids",
"(",
"client",
",",
"ids",
")",... | Fetch and merge in Marketdata for each option position | [
"Fetch",
"and",
"merge",
"in",
"Marketdata",
"for",
"each",
"option",
"position"
] | 514cbca4994f52a97222058167830a302e313d04 | https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/option_position.py#L47-L61 | train | 228,567 |
etingof/snmpsim | snmpsim/record/snmprec.py | SnmprecRecord.evaluateRawString | def evaluateRawString(self, escaped):
"""Evaluates raw Python string like `ast.literal_eval` does"""
unescaped = []
hexdigit = None
escape = False
for char in escaped:
number = ord(char)
if hexdigit is not None:
if hexdigit:
number = (int(hexdigit, 16) << 4) + int(char, 16)
hexdigit = None
else:
hexdigit = char
continue
if escape:
escape = False
try:
number = self.ESCAPE_CHARS[number]
except KeyError:
if number == 120:
hexdigit = ''
continue
raise ValueError('Unknown escape character %c' % char)
elif number == 92: # '\'
escape = True
continue
unescaped.append(number)
return unescaped | python | def evaluateRawString(self, escaped):
"""Evaluates raw Python string like `ast.literal_eval` does"""
unescaped = []
hexdigit = None
escape = False
for char in escaped:
number = ord(char)
if hexdigit is not None:
if hexdigit:
number = (int(hexdigit, 16) << 4) + int(char, 16)
hexdigit = None
else:
hexdigit = char
continue
if escape:
escape = False
try:
number = self.ESCAPE_CHARS[number]
except KeyError:
if number == 120:
hexdigit = ''
continue
raise ValueError('Unknown escape character %c' % char)
elif number == 92: # '\'
escape = True
continue
unescaped.append(number)
return unescaped | [
"def",
"evaluateRawString",
"(",
"self",
",",
"escaped",
")",
":",
"unescaped",
"=",
"[",
"]",
"hexdigit",
"=",
"None",
"escape",
"=",
"False",
"for",
"char",
"in",
"escaped",
":",
"number",
"=",
"ord",
"(",
"char",
")",
"if",
"hexdigit",
"is",
"not",
... | Evaluates raw Python string like `ast.literal_eval` does | [
"Evaluates",
"raw",
"Python",
"string",
"like",
"ast",
".",
"literal_eval",
"does"
] | c6a2c2c6db39620dcdd4f60c79cd545962a1493a | https://github.com/etingof/snmpsim/blob/c6a2c2c6db39620dcdd4f60c79cd545962a1493a/snmpsim/record/snmprec.py#L42-L80 | train | 228,568 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.subnode_parse | def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None):
"""Parse the subnodes of a given node. Subnodes with tags in the
`ignore` list are ignored. If pieces is given, use this as target for
the parse results instead of self.pieces. Indent all lines by the amount
given in `indent`. Note that the initial content in `pieces` is not
indented. The final result is in any case added to self.pieces."""
if pieces is not None:
old_pieces, self.pieces = self.pieces, pieces
else:
old_pieces = []
if type(indent) is int:
indent = indent * ' '
if len(indent) > 0:
pieces = ''.join(self.pieces)
i_piece = pieces[:len(indent)]
if self.pieces[-1:] == ['']:
self.pieces = [pieces[len(indent):]] + ['']
elif self.pieces != []:
self.pieces = [pieces[len(indent):]]
self.indent += len(indent)
for n in node.childNodes:
if restrict is not None:
if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict:
self.parse(n)
elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore:
self.parse(n)
if len(indent) > 0:
self.pieces = shift(self.pieces, indent, i_piece)
self.indent -= len(indent)
old_pieces.extend(self.pieces)
self.pieces = old_pieces | python | def subnode_parse(self, node, pieces=None, indent=0, ignore=[], restrict=None):
"""Parse the subnodes of a given node. Subnodes with tags in the
`ignore` list are ignored. If pieces is given, use this as target for
the parse results instead of self.pieces. Indent all lines by the amount
given in `indent`. Note that the initial content in `pieces` is not
indented. The final result is in any case added to self.pieces."""
if pieces is not None:
old_pieces, self.pieces = self.pieces, pieces
else:
old_pieces = []
if type(indent) is int:
indent = indent * ' '
if len(indent) > 0:
pieces = ''.join(self.pieces)
i_piece = pieces[:len(indent)]
if self.pieces[-1:] == ['']:
self.pieces = [pieces[len(indent):]] + ['']
elif self.pieces != []:
self.pieces = [pieces[len(indent):]]
self.indent += len(indent)
for n in node.childNodes:
if restrict is not None:
if n.nodeType == n.ELEMENT_NODE and n.tagName in restrict:
self.parse(n)
elif n.nodeType != n.ELEMENT_NODE or n.tagName not in ignore:
self.parse(n)
if len(indent) > 0:
self.pieces = shift(self.pieces, indent, i_piece)
self.indent -= len(indent)
old_pieces.extend(self.pieces)
self.pieces = old_pieces | [
"def",
"subnode_parse",
"(",
"self",
",",
"node",
",",
"pieces",
"=",
"None",
",",
"indent",
"=",
"0",
",",
"ignore",
"=",
"[",
"]",
",",
"restrict",
"=",
"None",
")",
":",
"if",
"pieces",
"is",
"not",
"None",
":",
"old_pieces",
",",
"self",
".",
... | Parse the subnodes of a given node. Subnodes with tags in the
`ignore` list are ignored. If pieces is given, use this as target for
the parse results instead of self.pieces. Indent all lines by the amount
given in `indent`. Note that the initial content in `pieces` is not
indented. The final result is in any case added to self.pieces. | [
"Parse",
"the",
"subnodes",
"of",
"a",
"given",
"node",
".",
"Subnodes",
"with",
"tags",
"in",
"the",
"ignore",
"list",
"are",
"ignored",
".",
"If",
"pieces",
"is",
"given",
"use",
"this",
"as",
"target",
"for",
"the",
"parse",
"results",
"instead",
"of"... | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L224-L254 | train | 228,569 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.surround_parse | def surround_parse(self, node, pre_char, post_char):
"""Parse the subnodes of a given node. Subnodes with tags in the
`ignore` list are ignored. Prepend `pre_char` and append `post_char` to
the output in self.pieces."""
self.add_text(pre_char)
self.subnode_parse(node)
self.add_text(post_char) | python | def surround_parse(self, node, pre_char, post_char):
"""Parse the subnodes of a given node. Subnodes with tags in the
`ignore` list are ignored. Prepend `pre_char` and append `post_char` to
the output in self.pieces."""
self.add_text(pre_char)
self.subnode_parse(node)
self.add_text(post_char) | [
"def",
"surround_parse",
"(",
"self",
",",
"node",
",",
"pre_char",
",",
"post_char",
")",
":",
"self",
".",
"add_text",
"(",
"pre_char",
")",
"self",
".",
"subnode_parse",
"(",
"node",
")",
"self",
".",
"add_text",
"(",
"post_char",
")"
] | Parse the subnodes of a given node. Subnodes with tags in the
`ignore` list are ignored. Prepend `pre_char` and append `post_char` to
the output in self.pieces. | [
"Parse",
"the",
"subnodes",
"of",
"a",
"given",
"node",
".",
"Subnodes",
"with",
"tags",
"in",
"the",
"ignore",
"list",
"are",
"ignored",
".",
"Prepend",
"pre_char",
"and",
"append",
"post_char",
"to",
"the",
"output",
"in",
"self",
".",
"pieces",
"."
] | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L256-L262 | train | 228,570 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.get_specific_subnodes | def get_specific_subnodes(self, node, name, recursive=0):
"""Given a node and a name, return a list of child `ELEMENT_NODEs`, that
have a `tagName` matching the `name`. Search recursively for `recursive`
levels.
"""
children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE]
ret = [x for x in children if x.tagName == name]
if recursive > 0:
for x in children:
ret.extend(self.get_specific_subnodes(x, name, recursive-1))
return ret | python | def get_specific_subnodes(self, node, name, recursive=0):
"""Given a node and a name, return a list of child `ELEMENT_NODEs`, that
have a `tagName` matching the `name`. Search recursively for `recursive`
levels.
"""
children = [x for x in node.childNodes if x.nodeType == x.ELEMENT_NODE]
ret = [x for x in children if x.tagName == name]
if recursive > 0:
for x in children:
ret.extend(self.get_specific_subnodes(x, name, recursive-1))
return ret | [
"def",
"get_specific_subnodes",
"(",
"self",
",",
"node",
",",
"name",
",",
"recursive",
"=",
"0",
")",
":",
"children",
"=",
"[",
"x",
"for",
"x",
"in",
"node",
".",
"childNodes",
"if",
"x",
".",
"nodeType",
"==",
"x",
".",
"ELEMENT_NODE",
"]",
"ret... | Given a node and a name, return a list of child `ELEMENT_NODEs`, that
have a `tagName` matching the `name`. Search recursively for `recursive`
levels. | [
"Given",
"a",
"node",
"and",
"a",
"name",
"return",
"a",
"list",
"of",
"child",
"ELEMENT_NODEs",
"that",
"have",
"a",
"tagName",
"matching",
"the",
"name",
".",
"Search",
"recursively",
"for",
"recursive",
"levels",
"."
] | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L265-L275 | train | 228,571 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.get_specific_nodes | def get_specific_nodes(self, node, names):
"""Given a node and a sequence of strings in `names`, return a
dictionary containing the names as keys and child
`ELEMENT_NODEs`, that have a `tagName` equal to the name.
"""
nodes = [(x.tagName, x) for x in node.childNodes
if x.nodeType == x.ELEMENT_NODE and
x.tagName in names]
return dict(nodes) | python | def get_specific_nodes(self, node, names):
"""Given a node and a sequence of strings in `names`, return a
dictionary containing the names as keys and child
`ELEMENT_NODEs`, that have a `tagName` equal to the name.
"""
nodes = [(x.tagName, x) for x in node.childNodes
if x.nodeType == x.ELEMENT_NODE and
x.tagName in names]
return dict(nodes) | [
"def",
"get_specific_nodes",
"(",
"self",
",",
"node",
",",
"names",
")",
":",
"nodes",
"=",
"[",
"(",
"x",
".",
"tagName",
",",
"x",
")",
"for",
"x",
"in",
"node",
".",
"childNodes",
"if",
"x",
".",
"nodeType",
"==",
"x",
".",
"ELEMENT_NODE",
"and... | Given a node and a sequence of strings in `names`, return a
dictionary containing the names as keys and child
`ELEMENT_NODEs`, that have a `tagName` equal to the name. | [
"Given",
"a",
"node",
"and",
"a",
"sequence",
"of",
"strings",
"in",
"names",
"return",
"a",
"dictionary",
"containing",
"the",
"names",
"as",
"keys",
"and",
"child",
"ELEMENT_NODEs",
"that",
"have",
"a",
"tagName",
"equal",
"to",
"the",
"name",
"."
] | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L277-L286 | train | 228,572 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.add_text | def add_text(self, value):
"""Adds text corresponding to `value` into `self.pieces`."""
if isinstance(value, (list, tuple)):
self.pieces.extend(value)
else:
self.pieces.append(value) | python | def add_text(self, value):
"""Adds text corresponding to `value` into `self.pieces`."""
if isinstance(value, (list, tuple)):
self.pieces.extend(value)
else:
self.pieces.append(value) | [
"def",
"add_text",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"self",
".",
"pieces",
".",
"extend",
"(",
"value",
")",
"else",
":",
"self",
".",
"pieces",
".",
"append",
"... | Adds text corresponding to `value` into `self.pieces`. | [
"Adds",
"text",
"corresponding",
"to",
"value",
"into",
"self",
".",
"pieces",
"."
] | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L288-L293 | train | 228,573 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.start_new_paragraph | def start_new_paragraph(self):
"""Make sure to create an empty line. This is overridden, if the previous
text ends with the special marker ''. In that case, nothing is done.
"""
if self.pieces[-1:] == ['']: # respect special marker
return
elif self.pieces == []: # first paragraph, add '\n', override with ''
self.pieces = ['\n']
elif self.pieces[-1][-1:] != '\n': # previous line not ended
self.pieces.extend([' \n' ,'\n'])
else: #default
self.pieces.append('\n') | python | def start_new_paragraph(self):
"""Make sure to create an empty line. This is overridden, if the previous
text ends with the special marker ''. In that case, nothing is done.
"""
if self.pieces[-1:] == ['']: # respect special marker
return
elif self.pieces == []: # first paragraph, add '\n', override with ''
self.pieces = ['\n']
elif self.pieces[-1][-1:] != '\n': # previous line not ended
self.pieces.extend([' \n' ,'\n'])
else: #default
self.pieces.append('\n') | [
"def",
"start_new_paragraph",
"(",
"self",
")",
":",
"if",
"self",
".",
"pieces",
"[",
"-",
"1",
":",
"]",
"==",
"[",
"''",
"]",
":",
"# respect special marker",
"return",
"elif",
"self",
".",
"pieces",
"==",
"[",
"]",
":",
"# first paragraph, add '\\n', o... | Make sure to create an empty line. This is overridden, if the previous
text ends with the special marker ''. In that case, nothing is done. | [
"Make",
"sure",
"to",
"create",
"an",
"empty",
"line",
".",
"This",
"is",
"overridden",
"if",
"the",
"previous",
"text",
"ends",
"with",
"the",
"special",
"marker",
".",
"In",
"that",
"case",
"nothing",
"is",
"done",
"."
] | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L295-L306 | train | 228,574 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.add_line_with_subsequent_indent | def add_line_with_subsequent_indent(self, line, indent=4):
"""Add line of text and wrap such that subsequent lines are indented
by `indent` spaces.
"""
if isinstance(line, (list, tuple)):
line = ''.join(line)
line = line.strip()
width = self.textwidth-self.indent-indent
wrapped_lines = textwrap.wrap(line[indent:], width=width)
for i in range(len(wrapped_lines)):
if wrapped_lines[i] != '':
wrapped_lines[i] = indent * ' ' + wrapped_lines[i]
self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') | python | def add_line_with_subsequent_indent(self, line, indent=4):
"""Add line of text and wrap such that subsequent lines are indented
by `indent` spaces.
"""
if isinstance(line, (list, tuple)):
line = ''.join(line)
line = line.strip()
width = self.textwidth-self.indent-indent
wrapped_lines = textwrap.wrap(line[indent:], width=width)
for i in range(len(wrapped_lines)):
if wrapped_lines[i] != '':
wrapped_lines[i] = indent * ' ' + wrapped_lines[i]
self.pieces.append(line[:indent] + '\n'.join(wrapped_lines)[indent:] + ' \n') | [
"def",
"add_line_with_subsequent_indent",
"(",
"self",
",",
"line",
",",
"indent",
"=",
"4",
")",
":",
"if",
"isinstance",
"(",
"line",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"line",
"=",
"''",
".",
"join",
"(",
"line",
")",
"line",
"=",
"l... | Add line of text and wrap such that subsequent lines are indented
by `indent` spaces. | [
"Add",
"line",
"of",
"text",
"and",
"wrap",
"such",
"that",
"subsequent",
"lines",
"are",
"indented",
"by",
"indent",
"spaces",
"."
] | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L308-L320 | train | 228,575 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.extract_text | def extract_text(self, node):
"""Return the string representation of the node or list of nodes by parsing the
subnodes, but returning the result as a string instead of adding it to `self.pieces`.
Note that this allows extracting text even if the node is in the ignore list.
"""
if not isinstance(node, (list, tuple)):
node = [node]
pieces, self.pieces = self.pieces, ['']
for n in node:
for sn in n.childNodes:
self.parse(sn)
ret = ''.join(self.pieces)
self.pieces = pieces
return ret | python | def extract_text(self, node):
"""Return the string representation of the node or list of nodes by parsing the
subnodes, but returning the result as a string instead of adding it to `self.pieces`.
Note that this allows extracting text even if the node is in the ignore list.
"""
if not isinstance(node, (list, tuple)):
node = [node]
pieces, self.pieces = self.pieces, ['']
for n in node:
for sn in n.childNodes:
self.parse(sn)
ret = ''.join(self.pieces)
self.pieces = pieces
return ret | [
"def",
"extract_text",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"node",
"=",
"[",
"node",
"]",
"pieces",
",",
"self",
".",
"pieces",
"=",
"self",
".",
"pieces",
","... | Return the string representation of the node or list of nodes by parsing the
subnodes, but returning the result as a string instead of adding it to `self.pieces`.
Note that this allows extracting text even if the node is in the ignore list. | [
"Return",
"the",
"string",
"representation",
"of",
"the",
"node",
"or",
"list",
"of",
"nodes",
"by",
"parsing",
"the",
"subnodes",
"but",
"returning",
"the",
"result",
"as",
"a",
"string",
"instead",
"of",
"adding",
"it",
"to",
"self",
".",
"pieces",
".",
... | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L322-L335 | train | 228,576 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.get_function_signature | def get_function_signature(self, node):
"""Returns the function signature string for memberdef nodes."""
name = self.extract_text(self.get_specific_subnodes(node, 'name'))
if self.with_type_info:
argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring'))
else:
argsstring = []
param_id = 1
for n_param in self.get_specific_subnodes(node, 'param'):
declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname'))
if not declname:
declname = 'arg' + str(param_id)
defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval'))
if defval:
defval = '=' + defval
argsstring.append(declname + defval)
param_id = param_id + 1
argsstring = '(' + ', '.join(argsstring) + ')'
type = self.extract_text(self.get_specific_subnodes(node, 'type'))
function_definition = name + argsstring
if type != '' and type != 'void':
function_definition = function_definition + ' -> ' + type
return '`' + function_definition + '` ' | python | def get_function_signature(self, node):
"""Returns the function signature string for memberdef nodes."""
name = self.extract_text(self.get_specific_subnodes(node, 'name'))
if self.with_type_info:
argsstring = self.extract_text(self.get_specific_subnodes(node, 'argsstring'))
else:
argsstring = []
param_id = 1
for n_param in self.get_specific_subnodes(node, 'param'):
declname = self.extract_text(self.get_specific_subnodes(n_param, 'declname'))
if not declname:
declname = 'arg' + str(param_id)
defval = self.extract_text(self.get_specific_subnodes(n_param, 'defval'))
if defval:
defval = '=' + defval
argsstring.append(declname + defval)
param_id = param_id + 1
argsstring = '(' + ', '.join(argsstring) + ')'
type = self.extract_text(self.get_specific_subnodes(node, 'type'))
function_definition = name + argsstring
if type != '' and type != 'void':
function_definition = function_definition + ' -> ' + type
return '`' + function_definition + '` ' | [
"def",
"get_function_signature",
"(",
"self",
",",
"node",
")",
":",
"name",
"=",
"self",
".",
"extract_text",
"(",
"self",
".",
"get_specific_subnodes",
"(",
"node",
",",
"'name'",
")",
")",
"if",
"self",
".",
"with_type_info",
":",
"argsstring",
"=",
"se... | Returns the function signature string for memberdef nodes. | [
"Returns",
"the",
"function",
"signature",
"string",
"for",
"memberdef",
"nodes",
"."
] | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L337-L359 | train | 228,577 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.handle_typical_memberdefs_no_overload | def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes):
"""Produce standard documentation for memberdef_nodes."""
for n in memberdef_nodes:
self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n'])
if self.with_function_signature:
self.add_line_with_subsequent_indent(self.get_function_signature(n))
self.subnode_parse(n, pieces=[], ignore=['definition', 'name'])
self.add_text(['";', '\n']) | python | def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes):
"""Produce standard documentation for memberdef_nodes."""
for n in memberdef_nodes:
self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n'])
if self.with_function_signature:
self.add_line_with_subsequent_indent(self.get_function_signature(n))
self.subnode_parse(n, pieces=[], ignore=['definition', 'name'])
self.add_text(['";', '\n']) | [
"def",
"handle_typical_memberdefs_no_overload",
"(",
"self",
",",
"signature",
",",
"memberdef_nodes",
")",
":",
"for",
"n",
"in",
"memberdef_nodes",
":",
"self",
".",
"add_text",
"(",
"[",
"'\\n'",
",",
"'%feature(\"docstring\") '",
",",
"signature",
",",
"' \"'"... | Produce standard documentation for memberdef_nodes. | [
"Produce",
"standard",
"documentation",
"for",
"memberdef_nodes",
"."
] | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L431-L438 | train | 228,578 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.handle_typical_memberdefs | def handle_typical_memberdefs(self, signature, memberdef_nodes):
"""Produces docstring entries containing an "Overloaded function"
section with the documentation for each overload, if the function is
overloaded and self.with_overloaded_functions is set. Else, produce
normal documentation.
"""
if len(memberdef_nodes) == 1 or not self.with_overloaded_functions:
self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes)
return
self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n'])
if self.with_function_signature:
for n in memberdef_nodes:
self.add_line_with_subsequent_indent(self.get_function_signature(n))
self.add_text('\n')
self.add_text(['Overloaded function', '\n',
'-------------------'])
for n in memberdef_nodes:
self.add_text('\n')
self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n))
self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name'])
self.add_text(['";', '\n']) | python | def handle_typical_memberdefs(self, signature, memberdef_nodes):
"""Produces docstring entries containing an "Overloaded function"
section with the documentation for each overload, if the function is
overloaded and self.with_overloaded_functions is set. Else, produce
normal documentation.
"""
if len(memberdef_nodes) == 1 or not self.with_overloaded_functions:
self.handle_typical_memberdefs_no_overload(signature, memberdef_nodes)
return
self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n'])
if self.with_function_signature:
for n in memberdef_nodes:
self.add_line_with_subsequent_indent(self.get_function_signature(n))
self.add_text('\n')
self.add_text(['Overloaded function', '\n',
'-------------------'])
for n in memberdef_nodes:
self.add_text('\n')
self.add_line_with_subsequent_indent('* ' + self.get_function_signature(n))
self.subnode_parse(n, pieces=[], indent=4, ignore=['definition', 'name'])
self.add_text(['";', '\n']) | [
"def",
"handle_typical_memberdefs",
"(",
"self",
",",
"signature",
",",
"memberdef_nodes",
")",
":",
"if",
"len",
"(",
"memberdef_nodes",
")",
"==",
"1",
"or",
"not",
"self",
".",
"with_overloaded_functions",
":",
"self",
".",
"handle_typical_memberdefs_no_overload"... | Produces docstring entries containing an "Overloaded function"
section with the documentation for each overload, if the function is
overloaded and self.with_overloaded_functions is set. Else, produce
normal documentation. | [
"Produces",
"docstring",
"entries",
"containing",
"an",
"Overloaded",
"function",
"section",
"with",
"the",
"documentation",
"for",
"each",
"overload",
"if",
"the",
"function",
"is",
"overloaded",
"and",
"self",
".",
"with_overloaded_functions",
"is",
"set",
".",
... | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L440-L461 | train | 228,579 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.do_memberdef | def do_memberdef(self, node):
"""Handle cases outside of class, struct, file or namespace. These are
now dealt with by `handle_overloaded_memberfunction`.
Do these even exist???
"""
prot = node.attributes['prot'].value
id = node.attributes['id'].value
kind = node.attributes['kind'].value
tmp = node.parentNode.parentNode.parentNode
compdef = tmp.getElementsByTagName('compounddef')[0]
cdef_kind = compdef.attributes['kind'].value
if cdef_kind in ('file', 'namespace', 'class', 'struct'):
# These cases are now handled by `handle_typical_memberdefs`
return
if prot != 'public':
return
first = self.get_specific_nodes(node, ('definition', 'name'))
name = self.extract_text(first['name'])
if name[:8] == 'operator': # Don't handle operators yet.
return
if not 'definition' in first or kind in ['variable', 'typedef']:
return
data = self.extract_text(first['definition'])
self.add_text('\n')
self.add_text(['/* where did this entry come from??? */', '\n'])
self.add_text('%feature("docstring") %s "\n%s' % (data, data))
for n in node.childNodes:
if n not in first.values():
self.parse(n)
self.add_text(['";', '\n']) | python | def do_memberdef(self, node):
"""Handle cases outside of class, struct, file or namespace. These are
now dealt with by `handle_overloaded_memberfunction`.
Do these even exist???
"""
prot = node.attributes['prot'].value
id = node.attributes['id'].value
kind = node.attributes['kind'].value
tmp = node.parentNode.parentNode.parentNode
compdef = tmp.getElementsByTagName('compounddef')[0]
cdef_kind = compdef.attributes['kind'].value
if cdef_kind in ('file', 'namespace', 'class', 'struct'):
# These cases are now handled by `handle_typical_memberdefs`
return
if prot != 'public':
return
first = self.get_specific_nodes(node, ('definition', 'name'))
name = self.extract_text(first['name'])
if name[:8] == 'operator': # Don't handle operators yet.
return
if not 'definition' in first or kind in ['variable', 'typedef']:
return
data = self.extract_text(first['definition'])
self.add_text('\n')
self.add_text(['/* where did this entry come from??? */', '\n'])
self.add_text('%feature("docstring") %s "\n%s' % (data, data))
for n in node.childNodes:
if n not in first.values():
self.parse(n)
self.add_text(['";', '\n']) | [
"def",
"do_memberdef",
"(",
"self",
",",
"node",
")",
":",
"prot",
"=",
"node",
".",
"attributes",
"[",
"'prot'",
"]",
".",
"value",
"id",
"=",
"node",
".",
"attributes",
"[",
"'id'",
"]",
".",
"value",
"kind",
"=",
"node",
".",
"attributes",
"[",
... | Handle cases outside of class, struct, file or namespace. These are
now dealt with by `handle_overloaded_memberfunction`.
Do these even exist??? | [
"Handle",
"cases",
"outside",
"of",
"class",
"struct",
"file",
"or",
"namespace",
".",
"These",
"are",
"now",
"dealt",
"with",
"by",
"handle_overloaded_memberfunction",
".",
"Do",
"these",
"even",
"exist???"
] | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L699-L730 | train | 228,580 |
basler/pypylon | scripts/builddoxy2swig/doxy2swig/doxy2swig.py | Doxy2SWIG.do_header | def do_header(self, node):
"""For a user defined section def a header field is present
which should not be printed as such, so we comment it in the
output."""
data = self.extract_text(node)
self.add_text('\n/*\n %s \n*/\n' % data)
# If our immediate sibling is a 'description' node then we
# should comment that out also and remove it from the parent
# node's children.
parent = node.parentNode
idx = parent.childNodes.index(node)
if len(parent.childNodes) >= idx + 2:
nd = parent.childNodes[idx + 2]
if nd.nodeName == 'description':
nd = parent.removeChild(nd)
self.add_text('\n/*')
self.subnode_parse(nd)
self.add_text('\n*/\n') | python | def do_header(self, node):
"""For a user defined section def a header field is present
which should not be printed as such, so we comment it in the
output."""
data = self.extract_text(node)
self.add_text('\n/*\n %s \n*/\n' % data)
# If our immediate sibling is a 'description' node then we
# should comment that out also and remove it from the parent
# node's children.
parent = node.parentNode
idx = parent.childNodes.index(node)
if len(parent.childNodes) >= idx + 2:
nd = parent.childNodes[idx + 2]
if nd.nodeName == 'description':
nd = parent.removeChild(nd)
self.add_text('\n/*')
self.subnode_parse(nd)
self.add_text('\n*/\n') | [
"def",
"do_header",
"(",
"self",
",",
"node",
")",
":",
"data",
"=",
"self",
".",
"extract_text",
"(",
"node",
")",
"self",
".",
"add_text",
"(",
"'\\n/*\\n %s \\n*/\\n'",
"%",
"data",
")",
"# If our immediate sibling is a 'description' node then we",
"# should comm... | For a user defined section def a header field is present
which should not be printed as such, so we comment it in the
output. | [
"For",
"a",
"user",
"defined",
"section",
"def",
"a",
"header",
"field",
"is",
"present",
"which",
"should",
"not",
"be",
"printed",
"as",
"such",
"so",
"we",
"comment",
"it",
"in",
"the",
"output",
"."
] | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L738-L755 | train | 228,581 |
basler/pypylon | scripts/generatedoc/generatedoc.py | visiblename | def visiblename(name, all=None, obj=None):
"""Decide whether to show documentation on a variable."""
# Certain special names are redundant or internal.
# XXX Remove __initializing__?
if name in {'__author__', '__builtins__', '__cached__', '__credits__',
'__date__', '__doc__', '__file__', '__spec__',
'__loader__', '__module__', '__name__', '__package__',
'__path__', '__qualname__', '__slots__', '__version__'}:
return 0
if name.endswith("_swigregister"):
return 0
if name.startswith("__swig"):
return 0
# Private names are hidden, but special names are displayed.
if name.startswith('__') and name.endswith('__'): return 1
# Namedtuples have public fields and methods with a single leading underscore
if name.startswith('_') and hasattr(obj, '_fields'):
return True
if all is not None:
# only document that which the programmer exported in __all__
return name in all
else:
return not name.startswith('_') | python | def visiblename(name, all=None, obj=None):
"""Decide whether to show documentation on a variable."""
# Certain special names are redundant or internal.
# XXX Remove __initializing__?
if name in {'__author__', '__builtins__', '__cached__', '__credits__',
'__date__', '__doc__', '__file__', '__spec__',
'__loader__', '__module__', '__name__', '__package__',
'__path__', '__qualname__', '__slots__', '__version__'}:
return 0
if name.endswith("_swigregister"):
return 0
if name.startswith("__swig"):
return 0
# Private names are hidden, but special names are displayed.
if name.startswith('__') and name.endswith('__'): return 1
# Namedtuples have public fields and methods with a single leading underscore
if name.startswith('_') and hasattr(obj, '_fields'):
return True
if all is not None:
# only document that which the programmer exported in __all__
return name in all
else:
return not name.startswith('_') | [
"def",
"visiblename",
"(",
"name",
",",
"all",
"=",
"None",
",",
"obj",
"=",
"None",
")",
":",
"# Certain special names are redundant or internal.",
"# XXX Remove __initializing__?",
"if",
"name",
"in",
"{",
"'__author__'",
",",
"'__builtins__'",
",",
"'__cached__'",
... | Decide whether to show documentation on a variable. | [
"Decide",
"whether",
"to",
"show",
"documentation",
"on",
"a",
"variable",
"."
] | d3510fa419b1c2b17f3f0b80a5fbb720c7b84008 | https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/generatedoc/generatedoc.py#L1-L43 | train | 228,582 |
SFDO-Tooling/CumulusCI | cumulusci/tasks/bulkdata.py | _download_file | def _download_file(uri, bulk_api):
"""Download the bulk API result file for a single batch"""
resp = requests.get(uri, headers=bulk_api.headers(), stream=True)
with tempfile.TemporaryFile("w+b") as f:
for chunk in resp.iter_content(chunk_size=None):
f.write(chunk)
f.seek(0)
yield f | python | def _download_file(uri, bulk_api):
"""Download the bulk API result file for a single batch"""
resp = requests.get(uri, headers=bulk_api.headers(), stream=True)
with tempfile.TemporaryFile("w+b") as f:
for chunk in resp.iter_content(chunk_size=None):
f.write(chunk)
f.seek(0)
yield f | [
"def",
"_download_file",
"(",
"uri",
",",
"bulk_api",
")",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"uri",
",",
"headers",
"=",
"bulk_api",
".",
"headers",
"(",
")",
",",
"stream",
"=",
"True",
")",
"with",
"tempfile",
".",
"TemporaryFile",
"(",
... | Download the bulk API result file for a single batch | [
"Download",
"the",
"bulk",
"API",
"result",
"file",
"for",
"a",
"single",
"batch"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/tasks/bulkdata.py#L801-L808 | train | 228,583 |
SFDO-Tooling/CumulusCI | cumulusci/tasks/bulkdata.py | LoadData._load_mapping | def _load_mapping(self, mapping):
"""Load data for a single step."""
mapping["oid_as_pk"] = bool(mapping.get("fields", {}).get("Id"))
job_id, local_ids_for_batch = self._create_job(mapping)
result = self._wait_for_job(job_id)
# We store inserted ids even if some batches failed
self._store_inserted_ids(mapping, job_id, local_ids_for_batch)
return result | python | def _load_mapping(self, mapping):
"""Load data for a single step."""
mapping["oid_as_pk"] = bool(mapping.get("fields", {}).get("Id"))
job_id, local_ids_for_batch = self._create_job(mapping)
result = self._wait_for_job(job_id)
# We store inserted ids even if some batches failed
self._store_inserted_ids(mapping, job_id, local_ids_for_batch)
return result | [
"def",
"_load_mapping",
"(",
"self",
",",
"mapping",
")",
":",
"mapping",
"[",
"\"oid_as_pk\"",
"]",
"=",
"bool",
"(",
"mapping",
".",
"get",
"(",
"\"fields\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"Id\"",
")",
")",
"job_id",
",",
"local_ids_for_batc... | Load data for a single step. | [
"Load",
"data",
"for",
"a",
"single",
"step",
"."
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/tasks/bulkdata.py#L268-L275 | train | 228,584 |
SFDO-Tooling/CumulusCI | cumulusci/tasks/bulkdata.py | LoadData._create_job | def _create_job(self, mapping):
"""Initiate a bulk insert and upload batches to run in parallel."""
job_id = self.bulk.create_insert_job(mapping["sf_object"], contentType="CSV")
self.logger.info(" Created bulk job {}".format(job_id))
# Upload batches
local_ids_for_batch = {}
for batch_file, local_ids in self._get_batches(mapping):
batch_id = self.bulk.post_batch(job_id, batch_file)
local_ids_for_batch[batch_id] = local_ids
self.logger.info(" Uploaded batch {}".format(batch_id))
self.bulk.close_job(job_id)
return job_id, local_ids_for_batch | python | def _create_job(self, mapping):
"""Initiate a bulk insert and upload batches to run in parallel."""
job_id = self.bulk.create_insert_job(mapping["sf_object"], contentType="CSV")
self.logger.info(" Created bulk job {}".format(job_id))
# Upload batches
local_ids_for_batch = {}
for batch_file, local_ids in self._get_batches(mapping):
batch_id = self.bulk.post_batch(job_id, batch_file)
local_ids_for_batch[batch_id] = local_ids
self.logger.info(" Uploaded batch {}".format(batch_id))
self.bulk.close_job(job_id)
return job_id, local_ids_for_batch | [
"def",
"_create_job",
"(",
"self",
",",
"mapping",
")",
":",
"job_id",
"=",
"self",
".",
"bulk",
".",
"create_insert_job",
"(",
"mapping",
"[",
"\"sf_object\"",
"]",
",",
"contentType",
"=",
"\"CSV\"",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\" C... | Initiate a bulk insert and upload batches to run in parallel. | [
"Initiate",
"a",
"bulk",
"insert",
"and",
"upload",
"batches",
"to",
"run",
"in",
"parallel",
"."
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/tasks/bulkdata.py#L277-L290 | train | 228,585 |
SFDO-Tooling/CumulusCI | cumulusci/tasks/bulkdata.py | LoadData._get_batches | def _get_batches(self, mapping, batch_size=10000):
"""Get data from the local db"""
action = mapping.get("action", "insert")
fields = mapping.get("fields", {}).copy()
static = mapping.get("static", {})
lookups = mapping.get("lookups", {})
record_type = mapping.get("record_type")
# Skip Id field on insert
if action == "insert" and "Id" in fields:
del fields["Id"]
# Build the list of fields to import
columns = []
columns.extend(fields.keys())
columns.extend(lookups.keys())
columns.extend(static.keys())
if record_type:
columns.append("RecordTypeId")
# default to the profile assigned recordtype if we can't find any
# query for the RT by developer name
query = (
"SELECT Id FROM RecordType WHERE SObjectType='{0}'"
"AND DeveloperName = '{1}' LIMIT 1"
)
record_type_id = self.sf.query(
query.format(mapping.get("sf_object"), record_type)
)["records"][0]["Id"]
query = self._query_db(mapping)
total_rows = 0
batch_num = 1
def start_batch():
batch_file = io.BytesIO()
writer = unicodecsv.writer(batch_file)
writer.writerow(columns)
batch_ids = []
return batch_file, writer, batch_ids
batch_file, writer, batch_ids = start_batch()
for row in query.yield_per(batch_size):
total_rows += 1
# Add static values to row
pkey = row[0]
row = list(row[1:]) + list(static.values())
if record_type:
row.append(record_type_id)
writer.writerow([self._convert(value) for value in row])
batch_ids.append(pkey)
# Yield and start a new file every [batch_size] rows
if not total_rows % batch_size:
batch_file.seek(0)
self.logger.info(" Processing batch {}".format(batch_num))
yield batch_file, batch_ids
batch_file, writer, batch_ids = start_batch()
batch_num += 1
# Yield result file for final batch
if batch_ids:
batch_file.seek(0)
yield batch_file, batch_ids
self.logger.info(
" Prepared {} rows for import to {}".format(
total_rows, mapping["sf_object"]
)
) | python | def _get_batches(self, mapping, batch_size=10000):
"""Get data from the local db"""
action = mapping.get("action", "insert")
fields = mapping.get("fields", {}).copy()
static = mapping.get("static", {})
lookups = mapping.get("lookups", {})
record_type = mapping.get("record_type")
# Skip Id field on insert
if action == "insert" and "Id" in fields:
del fields["Id"]
# Build the list of fields to import
columns = []
columns.extend(fields.keys())
columns.extend(lookups.keys())
columns.extend(static.keys())
if record_type:
columns.append("RecordTypeId")
# default to the profile assigned recordtype if we can't find any
# query for the RT by developer name
query = (
"SELECT Id FROM RecordType WHERE SObjectType='{0}'"
"AND DeveloperName = '{1}' LIMIT 1"
)
record_type_id = self.sf.query(
query.format(mapping.get("sf_object"), record_type)
)["records"][0]["Id"]
query = self._query_db(mapping)
total_rows = 0
batch_num = 1
def start_batch():
batch_file = io.BytesIO()
writer = unicodecsv.writer(batch_file)
writer.writerow(columns)
batch_ids = []
return batch_file, writer, batch_ids
batch_file, writer, batch_ids = start_batch()
for row in query.yield_per(batch_size):
total_rows += 1
# Add static values to row
pkey = row[0]
row = list(row[1:]) + list(static.values())
if record_type:
row.append(record_type_id)
writer.writerow([self._convert(value) for value in row])
batch_ids.append(pkey)
# Yield and start a new file every [batch_size] rows
if not total_rows % batch_size:
batch_file.seek(0)
self.logger.info(" Processing batch {}".format(batch_num))
yield batch_file, batch_ids
batch_file, writer, batch_ids = start_batch()
batch_num += 1
# Yield result file for final batch
if batch_ids:
batch_file.seek(0)
yield batch_file, batch_ids
self.logger.info(
" Prepared {} rows for import to {}".format(
total_rows, mapping["sf_object"]
)
) | [
"def",
"_get_batches",
"(",
"self",
",",
"mapping",
",",
"batch_size",
"=",
"10000",
")",
":",
"action",
"=",
"mapping",
".",
"get",
"(",
"\"action\"",
",",
"\"insert\"",
")",
"fields",
"=",
"mapping",
".",
"get",
"(",
"\"fields\"",
",",
"{",
"}",
")",... | Get data from the local db | [
"Get",
"data",
"from",
"the",
"local",
"db"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/tasks/bulkdata.py#L292-L364 | train | 228,586 |
SFDO-Tooling/CumulusCI | cumulusci/tasks/bulkdata.py | LoadData._query_db | def _query_db(self, mapping):
"""Build a query to retrieve data from the local db.
Includes columns from the mapping
as well as joining to the id tables to get real SF ids
for lookups.
"""
model = self.models[mapping.get("table")]
# Use primary key instead of the field mapped to SF Id
fields = mapping.get("fields", {}).copy()
if mapping["oid_as_pk"]:
del fields["Id"]
id_column = model.__table__.primary_key.columns.keys()[0]
columns = [getattr(model, id_column)]
for f in fields.values():
columns.append(model.__table__.columns[f])
lookups = mapping.get("lookups", {}).copy()
for lookup in lookups.values():
lookup["aliased_table"] = aliased(
self.metadata.tables["{}_sf_ids".format(lookup["table"])]
)
columns.append(lookup["aliased_table"].columns.sf_id)
query = self.session.query(*columns)
if "record_type" in mapping and hasattr(model, "record_type"):
query = query.filter(model.record_type == mapping["record_type"])
if "filters" in mapping:
filter_args = []
for f in mapping["filters"]:
filter_args.append(text(f))
query = query.filter(*filter_args)
for sf_field, lookup in lookups.items():
# Outer join with lookup ids table:
# returns main obj even if lookup is null
key_field = get_lookup_key_field(lookup, sf_field)
value_column = getattr(model, key_field)
query = query.outerjoin(
lookup["aliased_table"],
lookup["aliased_table"].columns.id == value_column,
)
# Order by foreign key to minimize lock contention
# by trying to keep lookup targets in the same batch
lookup_column = getattr(model, key_field)
query = query.order_by(lookup_column)
self.logger.info(str(query))
return query | python | def _query_db(self, mapping):
"""Build a query to retrieve data from the local db.
Includes columns from the mapping
as well as joining to the id tables to get real SF ids
for lookups.
"""
model = self.models[mapping.get("table")]
# Use primary key instead of the field mapped to SF Id
fields = mapping.get("fields", {}).copy()
if mapping["oid_as_pk"]:
del fields["Id"]
id_column = model.__table__.primary_key.columns.keys()[0]
columns = [getattr(model, id_column)]
for f in fields.values():
columns.append(model.__table__.columns[f])
lookups = mapping.get("lookups", {}).copy()
for lookup in lookups.values():
lookup["aliased_table"] = aliased(
self.metadata.tables["{}_sf_ids".format(lookup["table"])]
)
columns.append(lookup["aliased_table"].columns.sf_id)
query = self.session.query(*columns)
if "record_type" in mapping and hasattr(model, "record_type"):
query = query.filter(model.record_type == mapping["record_type"])
if "filters" in mapping:
filter_args = []
for f in mapping["filters"]:
filter_args.append(text(f))
query = query.filter(*filter_args)
for sf_field, lookup in lookups.items():
# Outer join with lookup ids table:
# returns main obj even if lookup is null
key_field = get_lookup_key_field(lookup, sf_field)
value_column = getattr(model, key_field)
query = query.outerjoin(
lookup["aliased_table"],
lookup["aliased_table"].columns.id == value_column,
)
# Order by foreign key to minimize lock contention
# by trying to keep lookup targets in the same batch
lookup_column = getattr(model, key_field)
query = query.order_by(lookup_column)
self.logger.info(str(query))
return query | [
"def",
"_query_db",
"(",
"self",
",",
"mapping",
")",
":",
"model",
"=",
"self",
".",
"models",
"[",
"mapping",
".",
"get",
"(",
"\"table\"",
")",
"]",
"# Use primary key instead of the field mapped to SF Id",
"fields",
"=",
"mapping",
".",
"get",
"(",
"\"fiel... | Build a query to retrieve data from the local db.
Includes columns from the mapping
as well as joining to the id tables to get real SF ids
for lookups. | [
"Build",
"a",
"query",
"to",
"retrieve",
"data",
"from",
"the",
"local",
"db",
"."
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/tasks/bulkdata.py#L366-L413 | train | 228,587 |
SFDO-Tooling/CumulusCI | cumulusci/tasks/bulkdata.py | LoadData._store_inserted_ids | def _store_inserted_ids(self, mapping, job_id, local_ids_for_batch):
"""Get the job results and store inserted SF Ids in a new table"""
id_table_name = self._reset_id_table(mapping)
conn = self.session.connection()
for batch_id, local_ids in local_ids_for_batch.items():
try:
results_url = "{}/job/{}/batch/{}/result".format(
self.bulk.endpoint, job_id, batch_id
)
# Download entire result file to a temporary file first
# to avoid the server dropping connections
with _download_file(results_url, self.bulk) as f:
self.logger.info(
" Downloaded results for batch {}".format(batch_id)
)
self._store_inserted_ids_for_batch(
f, local_ids, id_table_name, conn
)
self.logger.info(
" Updated {} for batch {}".format(id_table_name, batch_id)
)
except Exception: # pragma: nocover
# If we can't download one result file,
# don't let that stop us from downloading the others
self.logger.error(
"Could not download batch results: {}".format(batch_id)
)
continue
self.session.commit() | python | def _store_inserted_ids(self, mapping, job_id, local_ids_for_batch):
"""Get the job results and store inserted SF Ids in a new table"""
id_table_name = self._reset_id_table(mapping)
conn = self.session.connection()
for batch_id, local_ids in local_ids_for_batch.items():
try:
results_url = "{}/job/{}/batch/{}/result".format(
self.bulk.endpoint, job_id, batch_id
)
# Download entire result file to a temporary file first
# to avoid the server dropping connections
with _download_file(results_url, self.bulk) as f:
self.logger.info(
" Downloaded results for batch {}".format(batch_id)
)
self._store_inserted_ids_for_batch(
f, local_ids, id_table_name, conn
)
self.logger.info(
" Updated {} for batch {}".format(id_table_name, batch_id)
)
except Exception: # pragma: nocover
# If we can't download one result file,
# don't let that stop us from downloading the others
self.logger.error(
"Could not download batch results: {}".format(batch_id)
)
continue
self.session.commit() | [
"def",
"_store_inserted_ids",
"(",
"self",
",",
"mapping",
",",
"job_id",
",",
"local_ids_for_batch",
")",
":",
"id_table_name",
"=",
"self",
".",
"_reset_id_table",
"(",
"mapping",
")",
"conn",
"=",
"self",
".",
"session",
".",
"connection",
"(",
")",
"for"... | Get the job results and store inserted SF Ids in a new table | [
"Get",
"the",
"job",
"results",
"and",
"store",
"inserted",
"SF",
"Ids",
"in",
"a",
"new",
"table"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/tasks/bulkdata.py#L421-L449 | train | 228,588 |
SFDO-Tooling/CumulusCI | cumulusci/tasks/bulkdata.py | LoadData._reset_id_table | def _reset_id_table(self, mapping):
"""Create an empty table to hold the inserted SF Ids"""
if not hasattr(self, "_initialized_id_tables"):
self._initialized_id_tables = set()
id_table_name = "{}_sf_ids".format(mapping["table"])
if id_table_name not in self._initialized_id_tables:
if id_table_name in self.metadata.tables:
self.metadata.remove(self.metadata.tables[id_table_name])
id_table = Table(
id_table_name,
self.metadata,
Column("id", Unicode(255), primary_key=True),
Column("sf_id", Unicode(18)),
)
if id_table.exists():
id_table.drop()
id_table.create()
self._initialized_id_tables.add(id_table_name)
return id_table_name | python | def _reset_id_table(self, mapping):
"""Create an empty table to hold the inserted SF Ids"""
if not hasattr(self, "_initialized_id_tables"):
self._initialized_id_tables = set()
id_table_name = "{}_sf_ids".format(mapping["table"])
if id_table_name not in self._initialized_id_tables:
if id_table_name in self.metadata.tables:
self.metadata.remove(self.metadata.tables[id_table_name])
id_table = Table(
id_table_name,
self.metadata,
Column("id", Unicode(255), primary_key=True),
Column("sf_id", Unicode(18)),
)
if id_table.exists():
id_table.drop()
id_table.create()
self._initialized_id_tables.add(id_table_name)
return id_table_name | [
"def",
"_reset_id_table",
"(",
"self",
",",
"mapping",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_initialized_id_tables\"",
")",
":",
"self",
".",
"_initialized_id_tables",
"=",
"set",
"(",
")",
"id_table_name",
"=",
"\"{}_sf_ids\"",
".",
"format"... | Create an empty table to hold the inserted SF Ids | [
"Create",
"an",
"empty",
"table",
"to",
"hold",
"the",
"inserted",
"SF",
"Ids"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/tasks/bulkdata.py#L451-L469 | train | 228,589 |
SFDO-Tooling/CumulusCI | cumulusci/tasks/bulkdata.py | QueryData._get_mapping_for_table | def _get_mapping_for_table(self, table):
""" Returns the first mapping for a table name """
for mapping in self.mappings.values():
if mapping["table"] == table:
return mapping | python | def _get_mapping_for_table(self, table):
""" Returns the first mapping for a table name """
for mapping in self.mappings.values():
if mapping["table"] == table:
return mapping | [
"def",
"_get_mapping_for_table",
"(",
"self",
",",
"table",
")",
":",
"for",
"mapping",
"in",
"self",
".",
"mappings",
".",
"values",
"(",
")",
":",
"if",
"mapping",
"[",
"\"table\"",
"]",
"==",
"table",
":",
"return",
"mapping"
] | Returns the first mapping for a table name | [
"Returns",
"the",
"first",
"mapping",
"for",
"a",
"table",
"name"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/tasks/bulkdata.py#L690-L694 | train | 228,590 |
SFDO-Tooling/CumulusCI | cumulusci/core/config/BaseProjectConfig.py | BaseProjectConfig._load_config | def _load_config(self):
""" Loads the configuration from YAML, if no override config was passed in initially. """
if (
self.config
): # any config being pre-set at init will short circuit out, but not a plain {}
return
# Verify that we're in a project
repo_root = self.repo_root
if not repo_root:
raise NotInProject(
"No git repository was found in the current path. You must be in a git repository to set up and use CCI for a project."
)
# Verify that the project's root has a config file
if not self.config_project_path:
raise ProjectConfigNotFound(
"The file {} was not found in the repo root: {}. Are you in a CumulusCI Project directory?".format(
self.config_filename, repo_root
)
)
# Load the project's yaml config file
with open(self.config_project_path, "r") as f_config:
project_config = ordered_yaml_load(f_config)
if project_config:
self.config_project.update(project_config)
# Load the local project yaml config file if it exists
if self.config_project_local_path:
with open(self.config_project_local_path, "r") as f_local_config:
local_config = ordered_yaml_load(f_local_config)
if local_config:
self.config_project_local.update(local_config)
# merge in any additional yaml that was passed along
if self.additional_yaml:
additional_yaml_config = ordered_yaml_load(self.additional_yaml)
if additional_yaml_config:
self.config_additional_yaml.update(additional_yaml_config)
self.config = merge_config(
OrderedDict(
[
("global_config", self.config_global),
("global_local", self.config_global_local),
("project_config", self.config_project),
("project_local_config", self.config_project_local),
("additional_yaml", self.config_additional_yaml),
]
)
) | python | def _load_config(self):
""" Loads the configuration from YAML, if no override config was passed in initially. """
if (
self.config
): # any config being pre-set at init will short circuit out, but not a plain {}
return
# Verify that we're in a project
repo_root = self.repo_root
if not repo_root:
raise NotInProject(
"No git repository was found in the current path. You must be in a git repository to set up and use CCI for a project."
)
# Verify that the project's root has a config file
if not self.config_project_path:
raise ProjectConfigNotFound(
"The file {} was not found in the repo root: {}. Are you in a CumulusCI Project directory?".format(
self.config_filename, repo_root
)
)
# Load the project's yaml config file
with open(self.config_project_path, "r") as f_config:
project_config = ordered_yaml_load(f_config)
if project_config:
self.config_project.update(project_config)
# Load the local project yaml config file if it exists
if self.config_project_local_path:
with open(self.config_project_local_path, "r") as f_local_config:
local_config = ordered_yaml_load(f_local_config)
if local_config:
self.config_project_local.update(local_config)
# merge in any additional yaml that was passed along
if self.additional_yaml:
additional_yaml_config = ordered_yaml_load(self.additional_yaml)
if additional_yaml_config:
self.config_additional_yaml.update(additional_yaml_config)
self.config = merge_config(
OrderedDict(
[
("global_config", self.config_global),
("global_local", self.config_global_local),
("project_config", self.config_project),
("project_local_config", self.config_project_local),
("additional_yaml", self.config_additional_yaml),
]
)
) | [
"def",
"_load_config",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"config",
")",
":",
"# any config being pre-set at init will short circuit out, but not a plain {}",
"return",
"# Verify that we're in a project",
"repo_root",
"=",
"self",
".",
"repo_root",
"if",
"not"... | Loads the configuration from YAML, if no override config was passed in initially. | [
"Loads",
"the",
"configuration",
"from",
"YAML",
"if",
"no",
"override",
"config",
"was",
"passed",
"in",
"initially",
"."
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/config/BaseProjectConfig.py#L58-L111 | train | 228,591 |
SFDO-Tooling/CumulusCI | cumulusci/core/config/BaseProjectConfig.py | BaseProjectConfig.init_sentry | def init_sentry(self,):
""" Initializes sentry.io error logging for this session """
if not self.use_sentry:
return
sentry_config = self.keychain.get_service("sentry")
tags = {
"repo": self.repo_name,
"branch": self.repo_branch,
"commit": self.repo_commit,
"cci version": cumulusci.__version__,
}
tags.update(self.config.get("sentry_tags", {}))
env = self.config.get("sentry_environment", "CumulusCI CLI")
self.sentry = raven.Client(
dsn=sentry_config.dsn,
environment=env,
tags=tags,
processors=("raven.processors.SanitizePasswordsProcessor",),
) | python | def init_sentry(self,):
""" Initializes sentry.io error logging for this session """
if not self.use_sentry:
return
sentry_config = self.keychain.get_service("sentry")
tags = {
"repo": self.repo_name,
"branch": self.repo_branch,
"commit": self.repo_commit,
"cci version": cumulusci.__version__,
}
tags.update(self.config.get("sentry_tags", {}))
env = self.config.get("sentry_environment", "CumulusCI CLI")
self.sentry = raven.Client(
dsn=sentry_config.dsn,
environment=env,
tags=tags,
processors=("raven.processors.SanitizePasswordsProcessor",),
) | [
"def",
"init_sentry",
"(",
"self",
",",
")",
":",
"if",
"not",
"self",
".",
"use_sentry",
":",
"return",
"sentry_config",
"=",
"self",
".",
"keychain",
".",
"get_service",
"(",
"\"sentry\"",
")",
"tags",
"=",
"{",
"\"repo\"",
":",
"self",
".",
"repo_name... | Initializes sentry.io error logging for this session | [
"Initializes",
"sentry",
".",
"io",
"error",
"logging",
"for",
"this",
"session"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/config/BaseProjectConfig.py#L361-L383 | train | 228,592 |
SFDO-Tooling/CumulusCI | cumulusci/core/config/BaseProjectConfig.py | BaseProjectConfig.get_previous_version | def get_previous_version(self):
"""Query GitHub releases to find the previous production release"""
gh = self.get_github_api()
repo = gh.repository(self.repo_owner, self.repo_name)
most_recent = None
for release in repo.releases():
# Return the second release that matches the release prefix
if release.tag_name.startswith(self.project__git__prefix_release):
if most_recent is None:
most_recent = release
else:
return LooseVersion(self.get_version_for_tag(release.tag_name)) | python | def get_previous_version(self):
"""Query GitHub releases to find the previous production release"""
gh = self.get_github_api()
repo = gh.repository(self.repo_owner, self.repo_name)
most_recent = None
for release in repo.releases():
# Return the second release that matches the release prefix
if release.tag_name.startswith(self.project__git__prefix_release):
if most_recent is None:
most_recent = release
else:
return LooseVersion(self.get_version_for_tag(release.tag_name)) | [
"def",
"get_previous_version",
"(",
"self",
")",
":",
"gh",
"=",
"self",
".",
"get_github_api",
"(",
")",
"repo",
"=",
"gh",
".",
"repository",
"(",
"self",
".",
"repo_owner",
",",
"self",
".",
"repo_name",
")",
"most_recent",
"=",
"None",
"for",
"releas... | Query GitHub releases to find the previous production release | [
"Query",
"GitHub",
"releases",
"to",
"find",
"the",
"previous",
"production",
"release"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/config/BaseProjectConfig.py#L418-L429 | train | 228,593 |
SFDO-Tooling/CumulusCI | cumulusci/core/config/BaseProjectConfig.py | BaseProjectConfig.get_static_dependencies | def get_static_dependencies(self, dependencies=None, include_beta=None):
"""Resolves the project -> dependencies section of cumulusci.yml
to convert dynamic github dependencies into static dependencies
by inspecting the referenced repositories
Keyword arguments:
:param dependencies: a list of dependencies to resolve
:param include_beta: when true, return the latest github release,
even if pre-release; else return the latest stable release
"""
if not dependencies:
dependencies = self.project__dependencies
if not dependencies:
return []
static_dependencies = []
for dependency in dependencies:
if "github" not in dependency:
static_dependencies.append(dependency)
else:
static = self.process_github_dependency(
dependency, include_beta=include_beta
)
static_dependencies.extend(static)
return static_dependencies | python | def get_static_dependencies(self, dependencies=None, include_beta=None):
"""Resolves the project -> dependencies section of cumulusci.yml
to convert dynamic github dependencies into static dependencies
by inspecting the referenced repositories
Keyword arguments:
:param dependencies: a list of dependencies to resolve
:param include_beta: when true, return the latest github release,
even if pre-release; else return the latest stable release
"""
if not dependencies:
dependencies = self.project__dependencies
if not dependencies:
return []
static_dependencies = []
for dependency in dependencies:
if "github" not in dependency:
static_dependencies.append(dependency)
else:
static = self.process_github_dependency(
dependency, include_beta=include_beta
)
static_dependencies.extend(static)
return static_dependencies | [
"def",
"get_static_dependencies",
"(",
"self",
",",
"dependencies",
"=",
"None",
",",
"include_beta",
"=",
"None",
")",
":",
"if",
"not",
"dependencies",
":",
"dependencies",
"=",
"self",
".",
"project__dependencies",
"if",
"not",
"dependencies",
":",
"return",
... | Resolves the project -> dependencies section of cumulusci.yml
to convert dynamic github dependencies into static dependencies
by inspecting the referenced repositories
Keyword arguments:
:param dependencies: a list of dependencies to resolve
:param include_beta: when true, return the latest github release,
even if pre-release; else return the latest stable release | [
"Resolves",
"the",
"project",
"-",
">",
"dependencies",
"section",
"of",
"cumulusci",
".",
"yml",
"to",
"convert",
"dynamic",
"github",
"dependencies",
"into",
"static",
"dependencies",
"by",
"inspecting",
"the",
"referenced",
"repositories"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/config/BaseProjectConfig.py#L496-L521 | train | 228,594 |
SFDO-Tooling/CumulusCI | cumulusci/core/tasks.py | BaseTask._init_logger | def _init_logger(self):
""" Initializes self.logger """
if self.flow:
self.logger = self.flow.logger.getChild(self.__class__.__name__)
else:
self.logger = logging.getLogger(__name__) | python | def _init_logger(self):
""" Initializes self.logger """
if self.flow:
self.logger = self.flow.logger.getChild(self.__class__.__name__)
else:
self.logger = logging.getLogger(__name__) | [
"def",
"_init_logger",
"(",
"self",
")",
":",
"if",
"self",
".",
"flow",
":",
"self",
".",
"logger",
"=",
"self",
".",
"flow",
".",
"logger",
".",
"getChild",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
"else",
":",
"self",
".",
"logger",
... | Initializes self.logger | [
"Initializes",
"self",
".",
"logger"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/tasks.py#L79-L84 | train | 228,595 |
SFDO-Tooling/CumulusCI | cumulusci/core/tasks.py | BaseTask._init_options | def _init_options(self, kwargs):
""" Initializes self.options """
self.options = self.task_config.options
if self.options is None:
self.options = {}
if kwargs:
self.options.update(kwargs)
# Handle dynamic lookup of project_config values via $project_config.attr
for option, value in list(self.options.items()):
try:
if value.startswith("$project_config."):
attr = value.replace("$project_config.", "", 1)
self.options[option] = getattr(self.project_config, attr, None)
except AttributeError:
pass | python | def _init_options(self, kwargs):
""" Initializes self.options """
self.options = self.task_config.options
if self.options is None:
self.options = {}
if kwargs:
self.options.update(kwargs)
# Handle dynamic lookup of project_config values via $project_config.attr
for option, value in list(self.options.items()):
try:
if value.startswith("$project_config."):
attr = value.replace("$project_config.", "", 1)
self.options[option] = getattr(self.project_config, attr, None)
except AttributeError:
pass | [
"def",
"_init_options",
"(",
"self",
",",
"kwargs",
")",
":",
"self",
".",
"options",
"=",
"self",
".",
"task_config",
".",
"options",
"if",
"self",
".",
"options",
"is",
"None",
":",
"self",
".",
"options",
"=",
"{",
"}",
"if",
"kwargs",
":",
"self"... | Initializes self.options | [
"Initializes",
"self",
".",
"options"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/tasks.py#L86-L101 | train | 228,596 |
SFDO-Tooling/CumulusCI | cumulusci/core/tasks.py | BaseTask._log_begin | def _log_begin(self):
""" Log the beginning of the task execution """
self.logger.info("Beginning task: %s", self.__class__.__name__)
if self.salesforce_task and not self.flow:
self.logger.info("%15s %s", "As user:", self.org_config.username)
self.logger.info("%15s %s", "In org:", self.org_config.org_id)
self.logger.info("") | python | def _log_begin(self):
""" Log the beginning of the task execution """
self.logger.info("Beginning task: %s", self.__class__.__name__)
if self.salesforce_task and not self.flow:
self.logger.info("%15s %s", "As user:", self.org_config.username)
self.logger.info("%15s %s", "In org:", self.org_config.org_id)
self.logger.info("") | [
"def",
"_log_begin",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Beginning task: %s\"",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"if",
"self",
".",
"salesforce_task",
"and",
"not",
"self",
".",
"flow",
":",
"self",
".",... | Log the beginning of the task execution | [
"Log",
"the",
"beginning",
"of",
"the",
"task",
"execution"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/tasks.py#L166-L172 | train | 228,597 |
SFDO-Tooling/CumulusCI | cumulusci/core/tasks.py | BaseTask._poll | def _poll(self):
""" poll for a result in a loop """
while True:
self.poll_count += 1
self._poll_action()
if self.poll_complete:
break
time.sleep(self.poll_interval_s)
self._poll_update_interval() | python | def _poll(self):
""" poll for a result in a loop """
while True:
self.poll_count += 1
self._poll_action()
if self.poll_complete:
break
time.sleep(self.poll_interval_s)
self._poll_update_interval() | [
"def",
"_poll",
"(",
"self",
")",
":",
"while",
"True",
":",
"self",
".",
"poll_count",
"+=",
"1",
"self",
".",
"_poll_action",
"(",
")",
"if",
"self",
".",
"poll_complete",
":",
"break",
"time",
".",
"sleep",
"(",
"self",
".",
"poll_interval_s",
")",
... | poll for a result in a loop | [
"poll",
"for",
"a",
"result",
"in",
"a",
"loop"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/tasks.py#L204-L212 | train | 228,598 |
SFDO-Tooling/CumulusCI | cumulusci/core/tasks.py | BaseTask._poll_update_interval | def _poll_update_interval(self):
""" update the polling interval to be used next iteration """
# Increase by 1 second every 3 polls
if old_div(self.poll_count, 3) > self.poll_interval_level:
self.poll_interval_level += 1
self.poll_interval_s += 1
self.logger.info(
"Increased polling interval to %d seconds", self.poll_interval_s
) | python | def _poll_update_interval(self):
""" update the polling interval to be used next iteration """
# Increase by 1 second every 3 polls
if old_div(self.poll_count, 3) > self.poll_interval_level:
self.poll_interval_level += 1
self.poll_interval_s += 1
self.logger.info(
"Increased polling interval to %d seconds", self.poll_interval_s
) | [
"def",
"_poll_update_interval",
"(",
"self",
")",
":",
"# Increase by 1 second every 3 polls",
"if",
"old_div",
"(",
"self",
".",
"poll_count",
",",
"3",
")",
">",
"self",
".",
"poll_interval_level",
":",
"self",
".",
"poll_interval_level",
"+=",
"1",
"self",
".... | update the polling interval to be used next iteration | [
"update",
"the",
"polling",
"interval",
"to",
"be",
"used",
"next",
"iteration"
] | e19047921ca771a297e045f22f0bb201651bb6f7 | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/tasks.py#L221-L229 | train | 228,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.