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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFilesystem.remove_object | def remove_object(self, file_path):
"""Remove an existing file or directory.
Args:
file_path: The path to the file relative to self.
Raises:
IOError: if file_path does not correspond to an existing file, or
if part of the path refers to something other than a directory.
OSError: if the directory is in use (eg, if it is '/').
"""
file_path = self.absnormpath(self._original_path(file_path))
if self._is_root_path(file_path):
self.raise_os_error(errno.EBUSY, file_path)
try:
dirname, basename = self.splitpath(file_path)
target_directory = self.resolve(dirname)
target_directory.remove_entry(basename)
except KeyError:
self.raise_io_error(errno.ENOENT, file_path)
except AttributeError:
self.raise_io_error(errno.ENOTDIR, file_path) | python | def remove_object(self, file_path):
"""Remove an existing file or directory.
Args:
file_path: The path to the file relative to self.
Raises:
IOError: if file_path does not correspond to an existing file, or
if part of the path refers to something other than a directory.
OSError: if the directory is in use (eg, if it is '/').
"""
file_path = self.absnormpath(self._original_path(file_path))
if self._is_root_path(file_path):
self.raise_os_error(errno.EBUSY, file_path)
try:
dirname, basename = self.splitpath(file_path)
target_directory = self.resolve(dirname)
target_directory.remove_entry(basename)
except KeyError:
self.raise_io_error(errno.ENOENT, file_path)
except AttributeError:
self.raise_io_error(errno.ENOTDIR, file_path) | [
"def",
"remove_object",
"(",
"self",
",",
"file_path",
")",
":",
"file_path",
"=",
"self",
".",
"absnormpath",
"(",
"self",
".",
"_original_path",
"(",
"file_path",
")",
")",
"if",
"self",
".",
"_is_root_path",
"(",
"file_path",
")",
":",
"self",
".",
"r... | Remove an existing file or directory.
Args:
file_path: The path to the file relative to self.
Raises:
IOError: if file_path does not correspond to an existing file, or
if part of the path refers to something other than a directory.
OSError: if the directory is in use (eg, if it is '/'). | [
"Remove",
"an",
"existing",
"file",
"or",
"directory",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L2276-L2297 | train | 203,500 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFilesystem.create_dir | def create_dir(self, directory_path, perm_bits=PERM_DEF):
"""Create `directory_path`, and all the parent directories.
Helper method to set up your test faster.
Args:
directory_path: The full directory path to create.
perm_bits: The permission bits as set by `chmod`.
Returns:
The newly created FakeDirectory object.
Raises:
OSError: if the directory already exists.
"""
directory_path = self.make_string_path(directory_path)
directory_path = self.absnormpath(directory_path)
self._auto_mount_drive_if_needed(directory_path)
if self.exists(directory_path, check_link=True):
self.raise_os_error(errno.EEXIST, directory_path)
path_components = self._path_components(directory_path)
current_dir = self.root
new_dirs = []
for component in path_components:
directory = self._directory_content(current_dir, component)[1]
if not directory:
new_dir = FakeDirectory(component, filesystem=self)
new_dirs.append(new_dir)
current_dir.add_entry(new_dir)
current_dir = new_dir
else:
if S_ISLNK(directory.st_mode):
directory = self.resolve(directory.contents)
current_dir = directory
if directory.st_mode & S_IFDIR != S_IFDIR:
self.raise_os_error(errno.ENOTDIR, current_dir.path)
# set the permission after creating the directories
# to allow directory creation inside a read-only directory
for new_dir in new_dirs:
new_dir.st_mode = S_IFDIR | perm_bits
self._last_ino += 1
current_dir.st_ino = self._last_ino
return current_dir | python | def create_dir(self, directory_path, perm_bits=PERM_DEF):
"""Create `directory_path`, and all the parent directories.
Helper method to set up your test faster.
Args:
directory_path: The full directory path to create.
perm_bits: The permission bits as set by `chmod`.
Returns:
The newly created FakeDirectory object.
Raises:
OSError: if the directory already exists.
"""
directory_path = self.make_string_path(directory_path)
directory_path = self.absnormpath(directory_path)
self._auto_mount_drive_if_needed(directory_path)
if self.exists(directory_path, check_link=True):
self.raise_os_error(errno.EEXIST, directory_path)
path_components = self._path_components(directory_path)
current_dir = self.root
new_dirs = []
for component in path_components:
directory = self._directory_content(current_dir, component)[1]
if not directory:
new_dir = FakeDirectory(component, filesystem=self)
new_dirs.append(new_dir)
current_dir.add_entry(new_dir)
current_dir = new_dir
else:
if S_ISLNK(directory.st_mode):
directory = self.resolve(directory.contents)
current_dir = directory
if directory.st_mode & S_IFDIR != S_IFDIR:
self.raise_os_error(errno.ENOTDIR, current_dir.path)
# set the permission after creating the directories
# to allow directory creation inside a read-only directory
for new_dir in new_dirs:
new_dir.st_mode = S_IFDIR | perm_bits
self._last_ino += 1
current_dir.st_ino = self._last_ino
return current_dir | [
"def",
"create_dir",
"(",
"self",
",",
"directory_path",
",",
"perm_bits",
"=",
"PERM_DEF",
")",
":",
"directory_path",
"=",
"self",
".",
"make_string_path",
"(",
"directory_path",
")",
"directory_path",
"=",
"self",
".",
"absnormpath",
"(",
"directory_path",
")... | Create `directory_path`, and all the parent directories.
Helper method to set up your test faster.
Args:
directory_path: The full directory path to create.
perm_bits: The permission bits as set by `chmod`.
Returns:
The newly created FakeDirectory object.
Raises:
OSError: if the directory already exists. | [
"Create",
"directory_path",
"and",
"all",
"the",
"parent",
"directories",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L2305-L2350 | train | 203,501 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFilesystem.create_file | def create_file(self, file_path, st_mode=S_IFREG | PERM_DEF_FILE,
contents='', st_size=None, create_missing_dirs=True,
apply_umask=False, encoding=None, errors=None,
side_effect=None):
"""Create `file_path`, including all the parent directories along
the way.
This helper method can be used to set up tests more easily.
Args:
file_path: The path to the file to create.
st_mode: The stat constant representing the file type.
contents: the contents of the file. If not given and st_size is
None, an empty file is assumed.
st_size: file size; only valid if contents not given. If given,
the file is considered to be in "large file mode" and trying
to read from or write to the file will result in an exception.
create_missing_dirs: If `True`, auto create missing directories.
apply_umask: `True` if the current umask must be applied
on `st_mode`.
encoding: If `contents` is a unicode string, the encoding used
for serialization.
errors: The error mode used for encoding/decoding errors.
side_effect: function handle that is executed when file is written,
must accept the file object as an argument.
Returns:
The newly created FakeFile object.
Raises:
IOError: if the file already exists.
IOError: if the containing directory is required and missing.
"""
return self.create_file_internally(
file_path, st_mode, contents, st_size, create_missing_dirs,
apply_umask, encoding, errors, side_effect=side_effect) | python | def create_file(self, file_path, st_mode=S_IFREG | PERM_DEF_FILE,
contents='', st_size=None, create_missing_dirs=True,
apply_umask=False, encoding=None, errors=None,
side_effect=None):
"""Create `file_path`, including all the parent directories along
the way.
This helper method can be used to set up tests more easily.
Args:
file_path: The path to the file to create.
st_mode: The stat constant representing the file type.
contents: the contents of the file. If not given and st_size is
None, an empty file is assumed.
st_size: file size; only valid if contents not given. If given,
the file is considered to be in "large file mode" and trying
to read from or write to the file will result in an exception.
create_missing_dirs: If `True`, auto create missing directories.
apply_umask: `True` if the current umask must be applied
on `st_mode`.
encoding: If `contents` is a unicode string, the encoding used
for serialization.
errors: The error mode used for encoding/decoding errors.
side_effect: function handle that is executed when file is written,
must accept the file object as an argument.
Returns:
The newly created FakeFile object.
Raises:
IOError: if the file already exists.
IOError: if the containing directory is required and missing.
"""
return self.create_file_internally(
file_path, st_mode, contents, st_size, create_missing_dirs,
apply_umask, encoding, errors, side_effect=side_effect) | [
"def",
"create_file",
"(",
"self",
",",
"file_path",
",",
"st_mode",
"=",
"S_IFREG",
"|",
"PERM_DEF_FILE",
",",
"contents",
"=",
"''",
",",
"st_size",
"=",
"None",
",",
"create_missing_dirs",
"=",
"True",
",",
"apply_umask",
"=",
"False",
",",
"encoding",
... | Create `file_path`, including all the parent directories along
the way.
This helper method can be used to set up tests more easily.
Args:
file_path: The path to the file to create.
st_mode: The stat constant representing the file type.
contents: the contents of the file. If not given and st_size is
None, an empty file is assumed.
st_size: file size; only valid if contents not given. If given,
the file is considered to be in "large file mode" and trying
to read from or write to the file will result in an exception.
create_missing_dirs: If `True`, auto create missing directories.
apply_umask: `True` if the current umask must be applied
on `st_mode`.
encoding: If `contents` is a unicode string, the encoding used
for serialization.
errors: The error mode used for encoding/decoding errors.
side_effect: function handle that is executed when file is written,
must accept the file object as an argument.
Returns:
The newly created FakeFile object.
Raises:
IOError: if the file already exists.
IOError: if the containing directory is required and missing. | [
"Create",
"file_path",
"including",
"all",
"the",
"parent",
"directories",
"along",
"the",
"way",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L2352-L2387 | train | 203,502 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFilesystem.add_real_file | def add_real_file(self, source_path, read_only=True, target_path=None):
"""Create `file_path`, including all the parent directories along the
way, for an existing real file. The contents of the real file are read
only on demand.
Args:
source_path: Path to an existing file in the real file system
read_only: If `True` (the default), writing to the fake file
raises an exception. Otherwise, writing to the file changes
the fake file only.
target_path: If given, the path of the target direction,
otherwise it is equal to `source_path`.
Returns:
the newly created FakeFile object.
Raises:
OSError: if the file does not exist in the real file system.
IOError: if the file already exists in the fake file system.
.. note:: On most systems, accessing the fake file's contents may
update both the real and fake files' `atime` (access time).
In this particular case, `add_real_file()` violates the rule
that `pyfakefs` must not modify the real file system.
"""
target_path = target_path or source_path
source_path = make_string_path(source_path)
target_path = self.make_string_path(target_path)
real_stat = os.stat(source_path)
fake_file = self.create_file_internally(target_path,
read_from_real_fs=True)
# for read-only mode, remove the write/executable permission bits
fake_file.stat_result.set_from_stat_result(real_stat)
if read_only:
fake_file.st_mode &= 0o777444
fake_file.file_path = source_path
self.change_disk_usage(fake_file.size, fake_file.name,
fake_file.st_dev)
return fake_file | python | def add_real_file(self, source_path, read_only=True, target_path=None):
"""Create `file_path`, including all the parent directories along the
way, for an existing real file. The contents of the real file are read
only on demand.
Args:
source_path: Path to an existing file in the real file system
read_only: If `True` (the default), writing to the fake file
raises an exception. Otherwise, writing to the file changes
the fake file only.
target_path: If given, the path of the target direction,
otherwise it is equal to `source_path`.
Returns:
the newly created FakeFile object.
Raises:
OSError: if the file does not exist in the real file system.
IOError: if the file already exists in the fake file system.
.. note:: On most systems, accessing the fake file's contents may
update both the real and fake files' `atime` (access time).
In this particular case, `add_real_file()` violates the rule
that `pyfakefs` must not modify the real file system.
"""
target_path = target_path or source_path
source_path = make_string_path(source_path)
target_path = self.make_string_path(target_path)
real_stat = os.stat(source_path)
fake_file = self.create_file_internally(target_path,
read_from_real_fs=True)
# for read-only mode, remove the write/executable permission bits
fake_file.stat_result.set_from_stat_result(real_stat)
if read_only:
fake_file.st_mode &= 0o777444
fake_file.file_path = source_path
self.change_disk_usage(fake_file.size, fake_file.name,
fake_file.st_dev)
return fake_file | [
"def",
"add_real_file",
"(",
"self",
",",
"source_path",
",",
"read_only",
"=",
"True",
",",
"target_path",
"=",
"None",
")",
":",
"target_path",
"=",
"target_path",
"or",
"source_path",
"source_path",
"=",
"make_string_path",
"(",
"source_path",
")",
"target_pa... | Create `file_path`, including all the parent directories along the
way, for an existing real file. The contents of the real file are read
only on demand.
Args:
source_path: Path to an existing file in the real file system
read_only: If `True` (the default), writing to the fake file
raises an exception. Otherwise, writing to the file changes
the fake file only.
target_path: If given, the path of the target direction,
otherwise it is equal to `source_path`.
Returns:
the newly created FakeFile object.
Raises:
OSError: if the file does not exist in the real file system.
IOError: if the file already exists in the fake file system.
.. note:: On most systems, accessing the fake file's contents may
update both the real and fake files' `atime` (access time).
In this particular case, `add_real_file()` violates the rule
that `pyfakefs` must not modify the real file system. | [
"Create",
"file_path",
"including",
"all",
"the",
"parent",
"directories",
"along",
"the",
"way",
"for",
"an",
"existing",
"real",
"file",
".",
"The",
"contents",
"of",
"the",
"real",
"file",
"are",
"read",
"only",
"on",
"demand",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L2389-L2428 | train | 203,503 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFilesystem.add_real_directory | def add_real_directory(self, source_path, read_only=True, lazy_read=True,
target_path=None):
"""Create a fake directory corresponding to the real directory at the
specified path. Add entries in the fake directory corresponding to
the entries in the real directory.
Args:
source_path: The path to the existing directory.
read_only: If set, all files under the directory are treated as
read-only, e.g. a write access raises an exception;
otherwise, writing to the files changes the fake files only
as usually.
lazy_read: If set (default), directory contents are only read when
accessed, and only until the needed subdirectory level.
.. note:: This means that the file system size is only updated
at the time the directory contents are read; set this to
`False` only if you are dependent on accurate file system
size in your test
target_path: If given, the target directory, otherwise,
the target directory is the same as `source_path`.
Returns:
the newly created FakeDirectory object.
Raises:
OSError: if the directory does not exist in the real file system.
IOError: if the directory already exists in the fake file system.
"""
source_path = self._path_without_trailing_separators(source_path)
if not os.path.exists(source_path):
self.raise_io_error(errno.ENOENT, source_path)
target_path = target_path or source_path
if lazy_read:
parent_path = os.path.split(target_path)[0]
if self.exists(parent_path):
parent_dir = self.get_object(parent_path)
else:
parent_dir = self.create_dir(parent_path)
new_dir = FakeDirectoryFromRealDirectory(
source_path, self, read_only, target_path)
parent_dir.add_entry(new_dir)
self._last_ino += 1
new_dir.st_ino = self._last_ino
else:
new_dir = self.create_dir(target_path)
for base, _, files in os.walk(source_path):
new_base = os.path.join(new_dir.path,
os.path.relpath(base, source_path))
for fileEntry in files:
self.add_real_file(os.path.join(base, fileEntry),
read_only,
os.path.join(new_base, fileEntry))
return new_dir | python | def add_real_directory(self, source_path, read_only=True, lazy_read=True,
target_path=None):
"""Create a fake directory corresponding to the real directory at the
specified path. Add entries in the fake directory corresponding to
the entries in the real directory.
Args:
source_path: The path to the existing directory.
read_only: If set, all files under the directory are treated as
read-only, e.g. a write access raises an exception;
otherwise, writing to the files changes the fake files only
as usually.
lazy_read: If set (default), directory contents are only read when
accessed, and only until the needed subdirectory level.
.. note:: This means that the file system size is only updated
at the time the directory contents are read; set this to
`False` only if you are dependent on accurate file system
size in your test
target_path: If given, the target directory, otherwise,
the target directory is the same as `source_path`.
Returns:
the newly created FakeDirectory object.
Raises:
OSError: if the directory does not exist in the real file system.
IOError: if the directory already exists in the fake file system.
"""
source_path = self._path_without_trailing_separators(source_path)
if not os.path.exists(source_path):
self.raise_io_error(errno.ENOENT, source_path)
target_path = target_path or source_path
if lazy_read:
parent_path = os.path.split(target_path)[0]
if self.exists(parent_path):
parent_dir = self.get_object(parent_path)
else:
parent_dir = self.create_dir(parent_path)
new_dir = FakeDirectoryFromRealDirectory(
source_path, self, read_only, target_path)
parent_dir.add_entry(new_dir)
self._last_ino += 1
new_dir.st_ino = self._last_ino
else:
new_dir = self.create_dir(target_path)
for base, _, files in os.walk(source_path):
new_base = os.path.join(new_dir.path,
os.path.relpath(base, source_path))
for fileEntry in files:
self.add_real_file(os.path.join(base, fileEntry),
read_only,
os.path.join(new_base, fileEntry))
return new_dir | [
"def",
"add_real_directory",
"(",
"self",
",",
"source_path",
",",
"read_only",
"=",
"True",
",",
"lazy_read",
"=",
"True",
",",
"target_path",
"=",
"None",
")",
":",
"source_path",
"=",
"self",
".",
"_path_without_trailing_separators",
"(",
"source_path",
")",
... | Create a fake directory corresponding to the real directory at the
specified path. Add entries in the fake directory corresponding to
the entries in the real directory.
Args:
source_path: The path to the existing directory.
read_only: If set, all files under the directory are treated as
read-only, e.g. a write access raises an exception;
otherwise, writing to the files changes the fake files only
as usually.
lazy_read: If set (default), directory contents are only read when
accessed, and only until the needed subdirectory level.
.. note:: This means that the file system size is only updated
at the time the directory contents are read; set this to
`False` only if you are dependent on accurate file system
size in your test
target_path: If given, the target directory, otherwise,
the target directory is the same as `source_path`.
Returns:
the newly created FakeDirectory object.
Raises:
OSError: if the directory does not exist in the real file system.
IOError: if the directory already exists in the fake file system. | [
"Create",
"a",
"fake",
"directory",
"corresponding",
"to",
"the",
"real",
"directory",
"at",
"the",
"specified",
"path",
".",
"Add",
"entries",
"in",
"the",
"fake",
"directory",
"corresponding",
"to",
"the",
"entries",
"in",
"the",
"real",
"directory",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L2430-L2483 | train | 203,504 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFilesystem.create_file_internally | def create_file_internally(self, file_path,
st_mode=S_IFREG | PERM_DEF_FILE,
contents='', st_size=None,
create_missing_dirs=True,
apply_umask=False, encoding=None, errors=None,
read_from_real_fs=False, raw_io=False,
side_effect=None):
"""Internal fake file creator that supports both normal fake files
and fake files based on real files.
Args:
file_path: path to the file to create.
st_mode: the stat.S_IF constant representing the file type.
contents: the contents of the file. If not given and st_size is
None, an empty file is assumed.
st_size: file size; only valid if contents not given. If given,
the file is considered to be in "large file mode" and trying
to read from or write to the file will result in an exception.
create_missing_dirs: if True, auto create missing directories.
apply_umask: whether or not the current umask must be applied
on st_mode.
encoding: if contents is a unicode string, the encoding used for
serialization.
errors: the error mode used for encoding/decoding errors
read_from_real_fs: if True, the contents are read from the real
file system on demand.
raw_io: `True` if called from low-level API (`os.open`)
side_effect: function handle that is executed when file is written,
must accept the file object as an argument.
"""
error_fct = self.raise_os_error if raw_io else self.raise_io_error
file_path = self.make_string_path(file_path)
file_path = self.absnormpath(file_path)
if not is_int_type(st_mode):
raise TypeError(
'st_mode must be of int type - did you mean to set contents?')
if self.exists(file_path, check_link=True):
self.raise_os_error(errno.EEXIST, file_path)
parent_directory, new_file = self.splitpath(file_path)
if not parent_directory:
parent_directory = self.cwd
self._auto_mount_drive_if_needed(parent_directory)
if not self.exists(parent_directory):
if not create_missing_dirs:
error_fct(errno.ENOENT, parent_directory)
self.create_dir(parent_directory)
else:
parent_directory = self._original_path(parent_directory)
if apply_umask:
st_mode &= ~self.umask
if read_from_real_fs:
file_object = FakeFileFromRealFile(file_path, filesystem=self,
side_effect=side_effect)
else:
file_object = FakeFile(new_file, st_mode, filesystem=self,
encoding=encoding, errors=errors,
side_effect=side_effect)
self._last_ino += 1
file_object.st_ino = self._last_ino
self.add_object(parent_directory, file_object, error_fct)
if st_size is None and contents is None:
contents = ''
if (not read_from_real_fs and
(contents is not None or st_size is not None)):
try:
if st_size is not None:
file_object.set_large_file_size(st_size)
else:
file_object._set_initial_contents(contents)
except IOError:
self.remove_object(file_path)
raise
return file_object | python | def create_file_internally(self, file_path,
st_mode=S_IFREG | PERM_DEF_FILE,
contents='', st_size=None,
create_missing_dirs=True,
apply_umask=False, encoding=None, errors=None,
read_from_real_fs=False, raw_io=False,
side_effect=None):
"""Internal fake file creator that supports both normal fake files
and fake files based on real files.
Args:
file_path: path to the file to create.
st_mode: the stat.S_IF constant representing the file type.
contents: the contents of the file. If not given and st_size is
None, an empty file is assumed.
st_size: file size; only valid if contents not given. If given,
the file is considered to be in "large file mode" and trying
to read from or write to the file will result in an exception.
create_missing_dirs: if True, auto create missing directories.
apply_umask: whether or not the current umask must be applied
on st_mode.
encoding: if contents is a unicode string, the encoding used for
serialization.
errors: the error mode used for encoding/decoding errors
read_from_real_fs: if True, the contents are read from the real
file system on demand.
raw_io: `True` if called from low-level API (`os.open`)
side_effect: function handle that is executed when file is written,
must accept the file object as an argument.
"""
error_fct = self.raise_os_error if raw_io else self.raise_io_error
file_path = self.make_string_path(file_path)
file_path = self.absnormpath(file_path)
if not is_int_type(st_mode):
raise TypeError(
'st_mode must be of int type - did you mean to set contents?')
if self.exists(file_path, check_link=True):
self.raise_os_error(errno.EEXIST, file_path)
parent_directory, new_file = self.splitpath(file_path)
if not parent_directory:
parent_directory = self.cwd
self._auto_mount_drive_if_needed(parent_directory)
if not self.exists(parent_directory):
if not create_missing_dirs:
error_fct(errno.ENOENT, parent_directory)
self.create_dir(parent_directory)
else:
parent_directory = self._original_path(parent_directory)
if apply_umask:
st_mode &= ~self.umask
if read_from_real_fs:
file_object = FakeFileFromRealFile(file_path, filesystem=self,
side_effect=side_effect)
else:
file_object = FakeFile(new_file, st_mode, filesystem=self,
encoding=encoding, errors=errors,
side_effect=side_effect)
self._last_ino += 1
file_object.st_ino = self._last_ino
self.add_object(parent_directory, file_object, error_fct)
if st_size is None and contents is None:
contents = ''
if (not read_from_real_fs and
(contents is not None or st_size is not None)):
try:
if st_size is not None:
file_object.set_large_file_size(st_size)
else:
file_object._set_initial_contents(contents)
except IOError:
self.remove_object(file_path)
raise
return file_object | [
"def",
"create_file_internally",
"(",
"self",
",",
"file_path",
",",
"st_mode",
"=",
"S_IFREG",
"|",
"PERM_DEF_FILE",
",",
"contents",
"=",
"''",
",",
"st_size",
"=",
"None",
",",
"create_missing_dirs",
"=",
"True",
",",
"apply_umask",
"=",
"False",
",",
"en... | Internal fake file creator that supports both normal fake files
and fake files based on real files.
Args:
file_path: path to the file to create.
st_mode: the stat.S_IF constant representing the file type.
contents: the contents of the file. If not given and st_size is
None, an empty file is assumed.
st_size: file size; only valid if contents not given. If given,
the file is considered to be in "large file mode" and trying
to read from or write to the file will result in an exception.
create_missing_dirs: if True, auto create missing directories.
apply_umask: whether or not the current umask must be applied
on st_mode.
encoding: if contents is a unicode string, the encoding used for
serialization.
errors: the error mode used for encoding/decoding errors
read_from_real_fs: if True, the contents are read from the real
file system on demand.
raw_io: `True` if called from low-level API (`os.open`)
side_effect: function handle that is executed when file is written,
must accept the file object as an argument. | [
"Internal",
"fake",
"file",
"creator",
"that",
"supports",
"both",
"normal",
"fake",
"files",
"and",
"fake",
"files",
"based",
"on",
"real",
"files",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L2512-L2588 | train | 203,505 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFilesystem.create_symlink | def create_symlink(self, file_path, link_target, create_missing_dirs=True):
"""Create the specified symlink, pointed at the specified link target.
Args:
file_path: path to the symlink to create
link_target: the target of the symlink
create_missing_dirs: If `True`, any missing parent directories of
file_path will be created
Returns:
The newly created FakeFile object.
Raises:
OSError: if the symlink could not be created
(see :py:meth:`create_file`).
OSError: if on Windows before Python 3.2.
"""
if not self._is_link_supported():
raise OSError("Symbolic links are not supported "
"on Windows before Python 3.2")
# the link path cannot end with a path separator
file_path = self.make_string_path(file_path)
link_target = self.make_string_path(link_target)
file_path = self.normcase(file_path)
if self.ends_with_path_separator(file_path):
if self.exists(file_path):
self.raise_os_error(errno.EEXIST, file_path)
if self.exists(link_target):
if not self.is_windows_fs:
self.raise_os_error(errno.ENOENT, file_path)
else:
if self.is_windows_fs:
self.raise_os_error(errno.EINVAL, link_target)
if not self.exists(
self._path_without_trailing_separators(file_path),
check_link=True):
self.raise_os_error(errno.ENOENT, link_target)
if self.is_macos:
# to avoid EEXIST exception, remove the link
# if it already exists
if self.exists(file_path, check_link=True):
self.remove_object(file_path)
else:
self.raise_os_error(errno.EEXIST, link_target)
# resolve the link path only if it is not a link itself
if not self.islink(file_path):
file_path = self.resolve_path(file_path)
link_target = make_string_path(link_target)
return self.create_file_internally(
file_path, st_mode=S_IFLNK | PERM_DEF,
contents=link_target,
create_missing_dirs=create_missing_dirs,
raw_io=True) | python | def create_symlink(self, file_path, link_target, create_missing_dirs=True):
"""Create the specified symlink, pointed at the specified link target.
Args:
file_path: path to the symlink to create
link_target: the target of the symlink
create_missing_dirs: If `True`, any missing parent directories of
file_path will be created
Returns:
The newly created FakeFile object.
Raises:
OSError: if the symlink could not be created
(see :py:meth:`create_file`).
OSError: if on Windows before Python 3.2.
"""
if not self._is_link_supported():
raise OSError("Symbolic links are not supported "
"on Windows before Python 3.2")
# the link path cannot end with a path separator
file_path = self.make_string_path(file_path)
link_target = self.make_string_path(link_target)
file_path = self.normcase(file_path)
if self.ends_with_path_separator(file_path):
if self.exists(file_path):
self.raise_os_error(errno.EEXIST, file_path)
if self.exists(link_target):
if not self.is_windows_fs:
self.raise_os_error(errno.ENOENT, file_path)
else:
if self.is_windows_fs:
self.raise_os_error(errno.EINVAL, link_target)
if not self.exists(
self._path_without_trailing_separators(file_path),
check_link=True):
self.raise_os_error(errno.ENOENT, link_target)
if self.is_macos:
# to avoid EEXIST exception, remove the link
# if it already exists
if self.exists(file_path, check_link=True):
self.remove_object(file_path)
else:
self.raise_os_error(errno.EEXIST, link_target)
# resolve the link path only if it is not a link itself
if not self.islink(file_path):
file_path = self.resolve_path(file_path)
link_target = make_string_path(link_target)
return self.create_file_internally(
file_path, st_mode=S_IFLNK | PERM_DEF,
contents=link_target,
create_missing_dirs=create_missing_dirs,
raw_io=True) | [
"def",
"create_symlink",
"(",
"self",
",",
"file_path",
",",
"link_target",
",",
"create_missing_dirs",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"_is_link_supported",
"(",
")",
":",
"raise",
"OSError",
"(",
"\"Symbolic links are not supported \"",
"\"on Wi... | Create the specified symlink, pointed at the specified link target.
Args:
file_path: path to the symlink to create
link_target: the target of the symlink
create_missing_dirs: If `True`, any missing parent directories of
file_path will be created
Returns:
The newly created FakeFile object.
Raises:
OSError: if the symlink could not be created
(see :py:meth:`create_file`).
OSError: if on Windows before Python 3.2. | [
"Create",
"the",
"specified",
"symlink",
"pointed",
"at",
"the",
"specified",
"link",
"target",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L2591-L2645 | train | 203,506 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFilesystem.makedirs | def makedirs(self, dir_name, mode=PERM_DEF, exist_ok=False):
"""Create a leaf Fake directory and create any non-existent
parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directories) with. This argument defaults to 0o777.
The umask is applied to this mode.
exist_ok: (boolean) If exist_ok is False (the default), an OSError is
raised if the target directory already exists.
New in Python 3.2.
Raises:
OSError: if the directory already exists and exist_ok=False,
or as per :py:meth:`create_dir`.
"""
ends_with_sep = self.ends_with_path_separator(dir_name)
dir_name = self.absnormpath(dir_name)
if (ends_with_sep and self.is_macos and
self.exists(dir_name, check_link=True) and
not self.exists(dir_name)):
# to avoid EEXIST exception, remove the link
self.remove_object(dir_name)
path_components = self._path_components(dir_name)
# Raise a permission denied error if the first existing directory
# is not writeable.
current_dir = self.root
for component in path_components:
if (component not in current_dir.contents
or not isinstance(current_dir.contents, dict)):
break
else:
current_dir = current_dir.contents[component]
try:
self.create_dir(dir_name, mode & ~self.umask)
except (IOError, OSError) as e:
if (not exist_ok or
not isinstance(self.resolve(dir_name), FakeDirectory)):
if self.is_windows_fs and e.errno == errno.ENOTDIR:
e.errno = errno.ENOENT
self.raise_os_error(e.errno, e.filename) | python | def makedirs(self, dir_name, mode=PERM_DEF, exist_ok=False):
"""Create a leaf Fake directory and create any non-existent
parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directories) with. This argument defaults to 0o777.
The umask is applied to this mode.
exist_ok: (boolean) If exist_ok is False (the default), an OSError is
raised if the target directory already exists.
New in Python 3.2.
Raises:
OSError: if the directory already exists and exist_ok=False,
or as per :py:meth:`create_dir`.
"""
ends_with_sep = self.ends_with_path_separator(dir_name)
dir_name = self.absnormpath(dir_name)
if (ends_with_sep and self.is_macos and
self.exists(dir_name, check_link=True) and
not self.exists(dir_name)):
# to avoid EEXIST exception, remove the link
self.remove_object(dir_name)
path_components = self._path_components(dir_name)
# Raise a permission denied error if the first existing directory
# is not writeable.
current_dir = self.root
for component in path_components:
if (component not in current_dir.contents
or not isinstance(current_dir.contents, dict)):
break
else:
current_dir = current_dir.contents[component]
try:
self.create_dir(dir_name, mode & ~self.umask)
except (IOError, OSError) as e:
if (not exist_ok or
not isinstance(self.resolve(dir_name), FakeDirectory)):
if self.is_windows_fs and e.errno == errno.ENOTDIR:
e.errno = errno.ENOENT
self.raise_os_error(e.errno, e.filename) | [
"def",
"makedirs",
"(",
"self",
",",
"dir_name",
",",
"mode",
"=",
"PERM_DEF",
",",
"exist_ok",
"=",
"False",
")",
":",
"ends_with_sep",
"=",
"self",
".",
"ends_with_path_separator",
"(",
"dir_name",
")",
"dir_name",
"=",
"self",
".",
"absnormpath",
"(",
"... | Create a leaf Fake directory and create any non-existent
parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directories) with. This argument defaults to 0o777.
The umask is applied to this mode.
exist_ok: (boolean) If exist_ok is False (the default), an OSError is
raised if the target directory already exists.
New in Python 3.2.
Raises:
OSError: if the directory already exists and exist_ok=False,
or as per :py:meth:`create_dir`. | [
"Create",
"a",
"leaf",
"Fake",
"directory",
"and",
"create",
"any",
"non",
"-",
"existent",
"parent",
"dirs",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L2800-L2843 | train | 203,507 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFilesystem.isdir | def isdir(self, path, follow_symlinks=True):
"""Determine if path identifies a directory.
Args:
path: Path to filesystem object.
Returns:
`True` if path points to a directory (following symlinks).
Raises:
TypeError: if path is None.
"""
return self._is_of_type(path, S_IFDIR, follow_symlinks) | python | def isdir(self, path, follow_symlinks=True):
"""Determine if path identifies a directory.
Args:
path: Path to filesystem object.
Returns:
`True` if path points to a directory (following symlinks).
Raises:
TypeError: if path is None.
"""
return self._is_of_type(path, S_IFDIR, follow_symlinks) | [
"def",
"isdir",
"(",
"self",
",",
"path",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"return",
"self",
".",
"_is_of_type",
"(",
"path",
",",
"S_IFDIR",
",",
"follow_symlinks",
")"
] | Determine if path identifies a directory.
Args:
path: Path to filesystem object.
Returns:
`True` if path points to a directory (following symlinks).
Raises:
TypeError: if path is None. | [
"Determine",
"if",
"path",
"identifies",
"a",
"directory",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L2873-L2885 | train | 203,508 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFilesystem.isfile | def isfile(self, path, follow_symlinks=True):
"""Determine if path identifies a regular file.
Args:
path: Path to filesystem object.
Returns:
`True` if path points to a regular file (following symlinks).
Raises:
TypeError: if path is None.
"""
return self._is_of_type(path, S_IFREG, follow_symlinks) | python | def isfile(self, path, follow_symlinks=True):
"""Determine if path identifies a regular file.
Args:
path: Path to filesystem object.
Returns:
`True` if path points to a regular file (following symlinks).
Raises:
TypeError: if path is None.
"""
return self._is_of_type(path, S_IFREG, follow_symlinks) | [
"def",
"isfile",
"(",
"self",
",",
"path",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"return",
"self",
".",
"_is_of_type",
"(",
"path",
",",
"S_IFREG",
",",
"follow_symlinks",
")"
] | Determine if path identifies a regular file.
Args:
path: Path to filesystem object.
Returns:
`True` if path points to a regular file (following symlinks).
Raises:
TypeError: if path is None. | [
"Determine",
"if",
"path",
"identifies",
"a",
"regular",
"file",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L2887-L2899 | train | 203,509 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFilesystem.confirmdir | def confirmdir(self, target_directory):
"""Test that the target is actually a directory, raising OSError
if not.
Args:
target_directory: Path to the target directory within the fake
filesystem.
Returns:
The FakeDirectory object corresponding to target_directory.
Raises:
OSError: if the target is not a directory.
"""
try:
directory = self.resolve(target_directory)
except IOError as exc:
self.raise_os_error(exc.errno, target_directory)
if not directory.st_mode & S_IFDIR:
if self.is_windows_fs and IS_PY2:
error_nr = errno.EINVAL
else:
error_nr = errno.ENOTDIR
self.raise_os_error(error_nr, target_directory, 267)
return directory | python | def confirmdir(self, target_directory):
"""Test that the target is actually a directory, raising OSError
if not.
Args:
target_directory: Path to the target directory within the fake
filesystem.
Returns:
The FakeDirectory object corresponding to target_directory.
Raises:
OSError: if the target is not a directory.
"""
try:
directory = self.resolve(target_directory)
except IOError as exc:
self.raise_os_error(exc.errno, target_directory)
if not directory.st_mode & S_IFDIR:
if self.is_windows_fs and IS_PY2:
error_nr = errno.EINVAL
else:
error_nr = errno.ENOTDIR
self.raise_os_error(error_nr, target_directory, 267)
return directory | [
"def",
"confirmdir",
"(",
"self",
",",
"target_directory",
")",
":",
"try",
":",
"directory",
"=",
"self",
".",
"resolve",
"(",
"target_directory",
")",
"except",
"IOError",
"as",
"exc",
":",
"self",
".",
"raise_os_error",
"(",
"exc",
".",
"errno",
",",
... | Test that the target is actually a directory, raising OSError
if not.
Args:
target_directory: Path to the target directory within the fake
filesystem.
Returns:
The FakeDirectory object corresponding to target_directory.
Raises:
OSError: if the target is not a directory. | [
"Test",
"that",
"the",
"target",
"is",
"actually",
"a",
"directory",
"raising",
"OSError",
"if",
"not",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L2915-L2939 | train | 203,510 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFilesystem.listdir | def listdir(self, target_directory):
"""Return a list of file names in target_directory.
Args:
target_directory: Path to the target directory within the
fake filesystem.
Returns:
A list of file names within the target directory in arbitrary
order.
Raises:
OSError: if the target is not a directory.
"""
target_directory = self.resolve_path(target_directory, allow_fd=True)
directory = self.confirmdir(target_directory)
directory_contents = directory.contents
return list(directory_contents.keys()) | python | def listdir(self, target_directory):
"""Return a list of file names in target_directory.
Args:
target_directory: Path to the target directory within the
fake filesystem.
Returns:
A list of file names within the target directory in arbitrary
order.
Raises:
OSError: if the target is not a directory.
"""
target_directory = self.resolve_path(target_directory, allow_fd=True)
directory = self.confirmdir(target_directory)
directory_contents = directory.contents
return list(directory_contents.keys()) | [
"def",
"listdir",
"(",
"self",
",",
"target_directory",
")",
":",
"target_directory",
"=",
"self",
".",
"resolve_path",
"(",
"target_directory",
",",
"allow_fd",
"=",
"True",
")",
"directory",
"=",
"self",
".",
"confirmdir",
"(",
"target_directory",
")",
"dire... | Return a list of file names in target_directory.
Args:
target_directory: Path to the target directory within the
fake filesystem.
Returns:
A list of file names within the target directory in arbitrary
order.
Raises:
OSError: if the target is not a directory. | [
"Return",
"a",
"list",
"of",
"file",
"names",
"in",
"target_directory",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3019-L3036 | train | 203,511 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakePathModule.getsize | def getsize(self, path):
"""Return the file object size in bytes.
Args:
path: path to the file object.
Returns:
file size in bytes.
"""
try:
file_obj = self.filesystem.resolve(path)
if (self.filesystem.ends_with_path_separator(path) and
S_IFMT(file_obj.st_mode) != S_IFDIR):
error_nr = (errno.EINVAL if self.filesystem.is_windows_fs
else errno.ENOTDIR)
self.filesystem.raise_os_error(error_nr, path)
return file_obj.st_size
except IOError as exc:
raise os.error(exc.errno, exc.strerror) | python | def getsize(self, path):
"""Return the file object size in bytes.
Args:
path: path to the file object.
Returns:
file size in bytes.
"""
try:
file_obj = self.filesystem.resolve(path)
if (self.filesystem.ends_with_path_separator(path) and
S_IFMT(file_obj.st_mode) != S_IFDIR):
error_nr = (errno.EINVAL if self.filesystem.is_windows_fs
else errno.ENOTDIR)
self.filesystem.raise_os_error(error_nr, path)
return file_obj.st_size
except IOError as exc:
raise os.error(exc.errno, exc.strerror) | [
"def",
"getsize",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"file_obj",
"=",
"self",
".",
"filesystem",
".",
"resolve",
"(",
"path",
")",
"if",
"(",
"self",
".",
"filesystem",
".",
"ends_with_path_separator",
"(",
"path",
")",
"and",
"S_IFMT",
"(... | Return the file object size in bytes.
Args:
path: path to the file object.
Returns:
file size in bytes. | [
"Return",
"the",
"file",
"object",
"size",
"in",
"bytes",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3161-L3179 | train | 203,512 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakePathModule.isabs | def isabs(self, path):
"""Return True if path is an absolute pathname."""
if self.filesystem.is_windows_fs:
path = self.splitdrive(path)[1]
path = make_string_path(path)
sep = self.filesystem._path_separator(path)
altsep = self.filesystem._alternative_path_separator(path)
if self.filesystem.is_windows_fs:
return len(path) > 0 and path[:1] in (sep, altsep)
else:
return (path.startswith(sep) or
altsep is not None and path.startswith(altsep)) | python | def isabs(self, path):
"""Return True if path is an absolute pathname."""
if self.filesystem.is_windows_fs:
path = self.splitdrive(path)[1]
path = make_string_path(path)
sep = self.filesystem._path_separator(path)
altsep = self.filesystem._alternative_path_separator(path)
if self.filesystem.is_windows_fs:
return len(path) > 0 and path[:1] in (sep, altsep)
else:
return (path.startswith(sep) or
altsep is not None and path.startswith(altsep)) | [
"def",
"isabs",
"(",
"self",
",",
"path",
")",
":",
"if",
"self",
".",
"filesystem",
".",
"is_windows_fs",
":",
"path",
"=",
"self",
".",
"splitdrive",
"(",
"path",
")",
"[",
"1",
"]",
"path",
"=",
"make_string_path",
"(",
"path",
")",
"sep",
"=",
... | Return True if path is an absolute pathname. | [
"Return",
"True",
"if",
"path",
"is",
"an",
"absolute",
"pathname",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3181-L3192 | train | 203,513 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakePathModule.getmtime | def getmtime(self, path):
"""Returns the modification time of the fake file.
Args:
path: the path to fake file.
Returns:
(int, float) the modification time of the fake file
in number of seconds since the epoch.
Raises:
OSError: if the file does not exist.
"""
try:
file_obj = self.filesystem.resolve(path)
return file_obj.st_mtime
except IOError:
self.filesystem.raise_os_error(errno.ENOENT, winerror=3) | python | def getmtime(self, path):
"""Returns the modification time of the fake file.
Args:
path: the path to fake file.
Returns:
(int, float) the modification time of the fake file
in number of seconds since the epoch.
Raises:
OSError: if the file does not exist.
"""
try:
file_obj = self.filesystem.resolve(path)
return file_obj.st_mtime
except IOError:
self.filesystem.raise_os_error(errno.ENOENT, winerror=3) | [
"def",
"getmtime",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"file_obj",
"=",
"self",
".",
"filesystem",
".",
"resolve",
"(",
"path",
")",
"return",
"file_obj",
".",
"st_mtime",
"except",
"IOError",
":",
"self",
".",
"filesystem",
".",
"raise_os_er... | Returns the modification time of the fake file.
Args:
path: the path to fake file.
Returns:
(int, float) the modification time of the fake file
in number of seconds since the epoch.
Raises:
OSError: if the file does not exist. | [
"Returns",
"the",
"modification",
"time",
"of",
"the",
"fake",
"file",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3216-L3233 | train | 203,514 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakePathModule.getatime | def getatime(self, path):
"""Returns the last access time of the fake file.
Note: Access time is not set automatically in fake filesystem
on access.
Args:
path: the path to fake file.
Returns:
(int, float) the access time of the fake file in number of seconds
since the epoch.
Raises:
OSError: if the file does not exist.
"""
try:
file_obj = self.filesystem.resolve(path)
except IOError:
self.filesystem.raise_os_error(errno.ENOENT)
return file_obj.st_atime | python | def getatime(self, path):
"""Returns the last access time of the fake file.
Note: Access time is not set automatically in fake filesystem
on access.
Args:
path: the path to fake file.
Returns:
(int, float) the access time of the fake file in number of seconds
since the epoch.
Raises:
OSError: if the file does not exist.
"""
try:
file_obj = self.filesystem.resolve(path)
except IOError:
self.filesystem.raise_os_error(errno.ENOENT)
return file_obj.st_atime | [
"def",
"getatime",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"file_obj",
"=",
"self",
".",
"filesystem",
".",
"resolve",
"(",
"path",
")",
"except",
"IOError",
":",
"self",
".",
"filesystem",
".",
"raise_os_error",
"(",
"errno",
".",
"ENOENT",
")... | Returns the last access time of the fake file.
Note: Access time is not set automatically in fake filesystem
on access.
Args:
path: the path to fake file.
Returns:
(int, float) the access time of the fake file in number of seconds
since the epoch.
Raises:
OSError: if the file does not exist. | [
"Returns",
"the",
"last",
"access",
"time",
"of",
"the",
"fake",
"file",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3235-L3255 | train | 203,515 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakePathModule.getctime | def getctime(self, path):
"""Returns the creation time of the fake file.
Args:
path: the path to fake file.
Returns:
(int, float) the creation time of the fake file in number of
seconds since the epoch.
Raises:
OSError: if the file does not exist.
"""
try:
file_obj = self.filesystem.resolve(path)
except IOError:
self.filesystem.raise_os_error(errno.ENOENT)
return file_obj.st_ctime | python | def getctime(self, path):
"""Returns the creation time of the fake file.
Args:
path: the path to fake file.
Returns:
(int, float) the creation time of the fake file in number of
seconds since the epoch.
Raises:
OSError: if the file does not exist.
"""
try:
file_obj = self.filesystem.resolve(path)
except IOError:
self.filesystem.raise_os_error(errno.ENOENT)
return file_obj.st_ctime | [
"def",
"getctime",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"file_obj",
"=",
"self",
".",
"filesystem",
".",
"resolve",
"(",
"path",
")",
"except",
"IOError",
":",
"self",
".",
"filesystem",
".",
"raise_os_error",
"(",
"errno",
".",
"ENOENT",
")... | Returns the creation time of the fake file.
Args:
path: the path to fake file.
Returns:
(int, float) the creation time of the fake file in number of
seconds since the epoch.
Raises:
OSError: if the file does not exist. | [
"Returns",
"the",
"creation",
"time",
"of",
"the",
"fake",
"file",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3257-L3274 | train | 203,516 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakePathModule.abspath | def abspath(self, path):
"""Return the absolute version of a path."""
def getcwd():
"""Return the current working directory."""
# pylint: disable=undefined-variable
if IS_PY2 and isinstance(path, text_type):
return self.os.getcwdu()
elif not IS_PY2 and isinstance(path, bytes):
return self.os.getcwdb()
else:
return self.os.getcwd()
path = make_string_path(path)
sep = self.filesystem._path_separator(path)
altsep = self.filesystem._alternative_path_separator(path)
if not self.isabs(path):
path = self.join(getcwd(), path)
elif (self.filesystem.is_windows_fs and
path.startswith(sep) or altsep is not None and
path.startswith(altsep)):
cwd = getcwd()
if self.filesystem._starts_with_drive_letter(cwd):
path = self.join(cwd[:2], path)
return self.normpath(path) | python | def abspath(self, path):
"""Return the absolute version of a path."""
def getcwd():
"""Return the current working directory."""
# pylint: disable=undefined-variable
if IS_PY2 and isinstance(path, text_type):
return self.os.getcwdu()
elif not IS_PY2 and isinstance(path, bytes):
return self.os.getcwdb()
else:
return self.os.getcwd()
path = make_string_path(path)
sep = self.filesystem._path_separator(path)
altsep = self.filesystem._alternative_path_separator(path)
if not self.isabs(path):
path = self.join(getcwd(), path)
elif (self.filesystem.is_windows_fs and
path.startswith(sep) or altsep is not None and
path.startswith(altsep)):
cwd = getcwd()
if self.filesystem._starts_with_drive_letter(cwd):
path = self.join(cwd[:2], path)
return self.normpath(path) | [
"def",
"abspath",
"(",
"self",
",",
"path",
")",
":",
"def",
"getcwd",
"(",
")",
":",
"\"\"\"Return the current working directory.\"\"\"",
"# pylint: disable=undefined-variable",
"if",
"IS_PY2",
"and",
"isinstance",
"(",
"path",
",",
"text_type",
")",
":",
"return",... | Return the absolute version of a path. | [
"Return",
"the",
"absolute",
"version",
"of",
"a",
"path",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3276-L3300 | train | 203,517 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakePathModule.normcase | def normcase(self, path):
"""Convert to lower case under windows, replaces additional path
separator."""
path = self.filesystem.normcase(path)
if self.filesystem.is_windows_fs:
path = path.lower()
return path | python | def normcase(self, path):
"""Convert to lower case under windows, replaces additional path
separator."""
path = self.filesystem.normcase(path)
if self.filesystem.is_windows_fs:
path = path.lower()
return path | [
"def",
"normcase",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"self",
".",
"filesystem",
".",
"normcase",
"(",
"path",
")",
"if",
"self",
".",
"filesystem",
".",
"is_windows_fs",
":",
"path",
"=",
"path",
".",
"lower",
"(",
")",
"return",
"path... | Convert to lower case under windows, replaces additional path
separator. | [
"Convert",
"to",
"lower",
"case",
"under",
"windows",
"replaces",
"additional",
"path",
"separator",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3320-L3326 | train | 203,518 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakePathModule.relpath | def relpath(self, path, start=None):
"""We mostly rely on the native implementation and adapt the
path separator."""
if not path:
raise ValueError("no path specified")
path = make_string_path(path)
if start is not None:
start = make_string_path(start)
else:
start = self.filesystem.cwd
if self.filesystem.alternative_path_separator is not None:
path = path.replace(self.filesystem.alternative_path_separator,
self._os_path.sep)
start = start.replace(self.filesystem.alternative_path_separator,
self._os_path.sep)
path = path.replace(self.filesystem.path_separator, self._os_path.sep)
start = start.replace(
self.filesystem.path_separator, self._os_path.sep)
path = self._os_path.relpath(path, start)
return path.replace(self._os_path.sep, self.filesystem.path_separator) | python | def relpath(self, path, start=None):
"""We mostly rely on the native implementation and adapt the
path separator."""
if not path:
raise ValueError("no path specified")
path = make_string_path(path)
if start is not None:
start = make_string_path(start)
else:
start = self.filesystem.cwd
if self.filesystem.alternative_path_separator is not None:
path = path.replace(self.filesystem.alternative_path_separator,
self._os_path.sep)
start = start.replace(self.filesystem.alternative_path_separator,
self._os_path.sep)
path = path.replace(self.filesystem.path_separator, self._os_path.sep)
start = start.replace(
self.filesystem.path_separator, self._os_path.sep)
path = self._os_path.relpath(path, start)
return path.replace(self._os_path.sep, self.filesystem.path_separator) | [
"def",
"relpath",
"(",
"self",
",",
"path",
",",
"start",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"\"no path specified\"",
")",
"path",
"=",
"make_string_path",
"(",
"path",
")",
"if",
"start",
"is",
"not",
"None",
... | We mostly rely on the native implementation and adapt the
path separator. | [
"We",
"mostly",
"rely",
"on",
"the",
"native",
"implementation",
"and",
"adapt",
"the",
"path",
"separator",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3328-L3347 | train | 203,519 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakePathModule.realpath | def realpath(self, filename):
"""Return the canonical path of the specified filename, eliminating any
symbolic links encountered in the path.
"""
if self.filesystem.is_windows_fs:
return self.abspath(filename)
filename = make_string_path(filename)
path, ok = self._joinrealpath(filename[:0], filename, {})
return self.abspath(path) | python | def realpath(self, filename):
"""Return the canonical path of the specified filename, eliminating any
symbolic links encountered in the path.
"""
if self.filesystem.is_windows_fs:
return self.abspath(filename)
filename = make_string_path(filename)
path, ok = self._joinrealpath(filename[:0], filename, {})
return self.abspath(path) | [
"def",
"realpath",
"(",
"self",
",",
"filename",
")",
":",
"if",
"self",
".",
"filesystem",
".",
"is_windows_fs",
":",
"return",
"self",
".",
"abspath",
"(",
"filename",
")",
"filename",
"=",
"make_string_path",
"(",
"filename",
")",
"path",
",",
"ok",
"... | Return the canonical path of the specified filename, eliminating any
symbolic links encountered in the path. | [
"Return",
"the",
"canonical",
"path",
"of",
"the",
"specified",
"filename",
"eliminating",
"any",
"symbolic",
"links",
"encountered",
"in",
"the",
"path",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3349-L3357 | train | 203,520 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakePathModule._joinrealpath | def _joinrealpath(self, path, rest, seen):
"""Join two paths, normalizing and eliminating any symbolic links
encountered in the second path.
Taken from Python source and adapted.
"""
curdir = self.filesystem._matching_string(path, '.')
pardir = self.filesystem._matching_string(path, '..')
sep = self.filesystem._path_separator(path)
if self.isabs(rest):
rest = rest[1:]
path = sep
while rest:
name, _, rest = rest.partition(sep)
if not name or name == curdir:
# current dir
continue
if name == pardir:
# parent dir
if path:
path, name = self.filesystem.splitpath(path)
if name == pardir:
path = self.filesystem.joinpaths(path, pardir, pardir)
else:
path = pardir
continue
newpath = self.filesystem.joinpaths(path, name)
if not self.filesystem.islink(newpath):
path = newpath
continue
# Resolve the symbolic link
if newpath in seen:
# Already seen this path
path = seen[newpath]
if path is not None:
# use cached value
continue
# The symlink is not resolved, so we must have a symlink loop.
# Return already resolved part + rest of the path unchanged.
return self.filesystem.joinpaths(newpath, rest), False
seen[newpath] = None # not resolved symlink
path, ok = self._joinrealpath(
path, self.filesystem.readlink(newpath), seen)
if not ok:
return self.filesystem.joinpaths(path, rest), False
seen[newpath] = path # resolved symlink
return path, True | python | def _joinrealpath(self, path, rest, seen):
"""Join two paths, normalizing and eliminating any symbolic links
encountered in the second path.
Taken from Python source and adapted.
"""
curdir = self.filesystem._matching_string(path, '.')
pardir = self.filesystem._matching_string(path, '..')
sep = self.filesystem._path_separator(path)
if self.isabs(rest):
rest = rest[1:]
path = sep
while rest:
name, _, rest = rest.partition(sep)
if not name or name == curdir:
# current dir
continue
if name == pardir:
# parent dir
if path:
path, name = self.filesystem.splitpath(path)
if name == pardir:
path = self.filesystem.joinpaths(path, pardir, pardir)
else:
path = pardir
continue
newpath = self.filesystem.joinpaths(path, name)
if not self.filesystem.islink(newpath):
path = newpath
continue
# Resolve the symbolic link
if newpath in seen:
# Already seen this path
path = seen[newpath]
if path is not None:
# use cached value
continue
# The symlink is not resolved, so we must have a symlink loop.
# Return already resolved part + rest of the path unchanged.
return self.filesystem.joinpaths(newpath, rest), False
seen[newpath] = None # not resolved symlink
path, ok = self._joinrealpath(
path, self.filesystem.readlink(newpath), seen)
if not ok:
return self.filesystem.joinpaths(path, rest), False
seen[newpath] = path # resolved symlink
return path, True | [
"def",
"_joinrealpath",
"(",
"self",
",",
"path",
",",
"rest",
",",
"seen",
")",
":",
"curdir",
"=",
"self",
".",
"filesystem",
".",
"_matching_string",
"(",
"path",
",",
"'.'",
")",
"pardir",
"=",
"self",
".",
"filesystem",
".",
"_matching_string",
"(",... | Join two paths, normalizing and eliminating any symbolic links
encountered in the second path.
Taken from Python source and adapted. | [
"Join",
"two",
"paths",
"normalizing",
"and",
"eliminating",
"any",
"symbolic",
"links",
"encountered",
"in",
"the",
"second",
"path",
".",
"Taken",
"from",
"Python",
"source",
"and",
"adapted",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3377-L3424 | train | 203,521 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakePathModule.ismount | def ismount(self, path):
"""Return true if the given path is a mount point.
Args:
path: Path to filesystem object to be checked
Returns:
`True` if path is a mount point added to the fake file system.
Under Windows also returns True for drive and UNC roots
(independent of their existence).
"""
path = make_string_path(path)
if not path:
return False
normed_path = self.filesystem.absnormpath(path)
sep = self.filesystem._path_separator(path)
if self.filesystem.is_windows_fs:
if self.filesystem.alternative_path_separator is not None:
path_seps = (
sep, self.filesystem._alternative_path_separator(path)
)
else:
path_seps = (sep, )
drive, rest = self.filesystem.splitdrive(normed_path)
if drive and drive[:1] in path_seps:
return (not rest) or (rest in path_seps)
if rest in path_seps:
return True
for mount_point in self.filesystem.mount_points:
if normed_path.rstrip(sep) == mount_point.rstrip(sep):
return True
return False | python | def ismount(self, path):
"""Return true if the given path is a mount point.
Args:
path: Path to filesystem object to be checked
Returns:
`True` if path is a mount point added to the fake file system.
Under Windows also returns True for drive and UNC roots
(independent of their existence).
"""
path = make_string_path(path)
if not path:
return False
normed_path = self.filesystem.absnormpath(path)
sep = self.filesystem._path_separator(path)
if self.filesystem.is_windows_fs:
if self.filesystem.alternative_path_separator is not None:
path_seps = (
sep, self.filesystem._alternative_path_separator(path)
)
else:
path_seps = (sep, )
drive, rest = self.filesystem.splitdrive(normed_path)
if drive and drive[:1] in path_seps:
return (not rest) or (rest in path_seps)
if rest in path_seps:
return True
for mount_point in self.filesystem.mount_points:
if normed_path.rstrip(sep) == mount_point.rstrip(sep):
return True
return False | [
"def",
"ismount",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"make_string_path",
"(",
"path",
")",
"if",
"not",
"path",
":",
"return",
"False",
"normed_path",
"=",
"self",
".",
"filesystem",
".",
"absnormpath",
"(",
"path",
")",
"sep",
"=",
"self... | Return true if the given path is a mount point.
Args:
path: Path to filesystem object to be checked
Returns:
`True` if path is a mount point added to the fake file system.
Under Windows also returns True for drive and UNC roots
(independent of their existence). | [
"Return",
"true",
"if",
"the",
"given",
"path",
"is",
"a",
"mount",
"point",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3437-L3468 | train | 203,522 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule._fdopen_ver2 | def _fdopen_ver2(self, file_des, mode='r',
bufsize=None): # pylint: disable=unused-argument
"""Returns an open file object connected to the file descriptor
file_des.
Args:
file_des: An integer file descriptor for the file object requested.
mode: Additional file flags. Currently checks to see if the mode
matches the mode of the requested file object.
bufsize: ignored. (Used for signature compliance with
__builtin__.fdopen)
Returns:
File object corresponding to file_des.
Raises:
OSError: if bad file descriptor or incompatible mode is given.
TypeError: if file descriptor is not an integer.
"""
if not is_int_type(file_des):
raise TypeError('an integer is required')
try:
return FakeFileOpen(self.filesystem).call(file_des, mode=mode)
except IOError as exc:
self.filesystem.raise_os_error(exc.errno, exc.filename) | python | def _fdopen_ver2(self, file_des, mode='r',
bufsize=None): # pylint: disable=unused-argument
"""Returns an open file object connected to the file descriptor
file_des.
Args:
file_des: An integer file descriptor for the file object requested.
mode: Additional file flags. Currently checks to see if the mode
matches the mode of the requested file object.
bufsize: ignored. (Used for signature compliance with
__builtin__.fdopen)
Returns:
File object corresponding to file_des.
Raises:
OSError: if bad file descriptor or incompatible mode is given.
TypeError: if file descriptor is not an integer.
"""
if not is_int_type(file_des):
raise TypeError('an integer is required')
try:
return FakeFileOpen(self.filesystem).call(file_des, mode=mode)
except IOError as exc:
self.filesystem.raise_os_error(exc.errno, exc.filename) | [
"def",
"_fdopen_ver2",
"(",
"self",
",",
"file_des",
",",
"mode",
"=",
"'r'",
",",
"bufsize",
"=",
"None",
")",
":",
"# pylint: disable=unused-argument",
"if",
"not",
"is_int_type",
"(",
"file_des",
")",
":",
"raise",
"TypeError",
"(",
"'an integer is required'"... | Returns an open file object connected to the file descriptor
file_des.
Args:
file_des: An integer file descriptor for the file object requested.
mode: Additional file flags. Currently checks to see if the mode
matches the mode of the requested file object.
bufsize: ignored. (Used for signature compliance with
__builtin__.fdopen)
Returns:
File object corresponding to file_des.
Raises:
OSError: if bad file descriptor or incompatible mode is given.
TypeError: if file descriptor is not an integer. | [
"Returns",
"an",
"open",
"file",
"object",
"connected",
"to",
"the",
"file",
"descriptor",
"file_des",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3586-L3611 | train | 203,523 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule._umask | def _umask(self):
"""Return the current umask."""
if self.filesystem.is_windows_fs:
# windows always returns 0 - it has no real notion of umask
return 0
if sys.platform == 'win32':
# if we are testing Unix under Windows we assume a default mask
return 0o002
else:
# under Unix, we return the real umask;
# as there is no pure getter for umask, so we have to first
# set a mode to get the previous one and then re-set that
mask = os.umask(0)
os.umask(mask)
return mask | python | def _umask(self):
"""Return the current umask."""
if self.filesystem.is_windows_fs:
# windows always returns 0 - it has no real notion of umask
return 0
if sys.platform == 'win32':
# if we are testing Unix under Windows we assume a default mask
return 0o002
else:
# under Unix, we return the real umask;
# as there is no pure getter for umask, so we have to first
# set a mode to get the previous one and then re-set that
mask = os.umask(0)
os.umask(mask)
return mask | [
"def",
"_umask",
"(",
"self",
")",
":",
"if",
"self",
".",
"filesystem",
".",
"is_windows_fs",
":",
"# windows always returns 0 - it has no real notion of umask",
"return",
"0",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"# if we are testing Unix under Windows ... | Return the current umask. | [
"Return",
"the",
"current",
"umask",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3613-L3627 | train | 203,524 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.open | def open(self, file_path, flags, mode=None, dir_fd=None):
"""Return the file descriptor for a FakeFile.
Args:
file_path: the path to the file
flags: low-level bits to indicate io operation
mode: bits to define default permissions
Note: only basic modes are supported, OS-specific modes are
ignored
dir_fd: If not `None`, the file descriptor of a directory,
with `file_path` being relative to this directory.
New in Python 3.3.
Returns:
A file descriptor.
Raises:
IOError: if the path cannot be found
ValueError: if invalid mode is given
NotImplementedError: if `os.O_EXCL` is used without `os.O_CREAT`
"""
file_path = self._path_with_dir_fd(file_path, self.open, dir_fd)
if mode is None:
if self.filesystem.is_windows_fs:
mode = 0o666
else:
mode = 0o777 & ~self._umask()
open_modes = _OpenModes(
must_exist=not flags & os.O_CREAT,
can_read=not flags & os.O_WRONLY,
can_write=flags & (os.O_RDWR | os.O_WRONLY),
truncate=flags & os.O_TRUNC,
append=flags & os.O_APPEND,
must_not_exist=flags & os.O_EXCL
)
if open_modes.must_not_exist and open_modes.must_exist:
raise NotImplementedError(
'O_EXCL without O_CREAT mode is not supported')
if (not self.filesystem.is_windows_fs and
self.filesystem.exists(file_path)):
# handle opening directory - only allowed under Posix
# with read-only mode
obj = self.filesystem.resolve(file_path)
if isinstance(obj, FakeDirectory):
if ((not open_modes.must_exist and
not self.filesystem.is_macos)
or open_modes.can_write):
self.filesystem.raise_os_error(errno.EISDIR, file_path)
dir_wrapper = FakeDirWrapper(obj, file_path, self.filesystem)
file_des = self.filesystem._add_open_file(dir_wrapper)
dir_wrapper.filedes = file_des
return file_des
# low level open is always binary
str_flags = 'b'
delete_on_close = False
if hasattr(os, 'O_TEMPORARY'):
delete_on_close = flags & os.O_TEMPORARY == os.O_TEMPORARY
fake_file = FakeFileOpen(
self.filesystem, delete_on_close=delete_on_close, raw_io=True)(
file_path, str_flags, open_modes=open_modes)
if fake_file.file_object != self.filesystem.dev_null:
self.chmod(file_path, mode)
return fake_file.fileno() | python | def open(self, file_path, flags, mode=None, dir_fd=None):
"""Return the file descriptor for a FakeFile.
Args:
file_path: the path to the file
flags: low-level bits to indicate io operation
mode: bits to define default permissions
Note: only basic modes are supported, OS-specific modes are
ignored
dir_fd: If not `None`, the file descriptor of a directory,
with `file_path` being relative to this directory.
New in Python 3.3.
Returns:
A file descriptor.
Raises:
IOError: if the path cannot be found
ValueError: if invalid mode is given
NotImplementedError: if `os.O_EXCL` is used without `os.O_CREAT`
"""
file_path = self._path_with_dir_fd(file_path, self.open, dir_fd)
if mode is None:
if self.filesystem.is_windows_fs:
mode = 0o666
else:
mode = 0o777 & ~self._umask()
open_modes = _OpenModes(
must_exist=not flags & os.O_CREAT,
can_read=not flags & os.O_WRONLY,
can_write=flags & (os.O_RDWR | os.O_WRONLY),
truncate=flags & os.O_TRUNC,
append=flags & os.O_APPEND,
must_not_exist=flags & os.O_EXCL
)
if open_modes.must_not_exist and open_modes.must_exist:
raise NotImplementedError(
'O_EXCL without O_CREAT mode is not supported')
if (not self.filesystem.is_windows_fs and
self.filesystem.exists(file_path)):
# handle opening directory - only allowed under Posix
# with read-only mode
obj = self.filesystem.resolve(file_path)
if isinstance(obj, FakeDirectory):
if ((not open_modes.must_exist and
not self.filesystem.is_macos)
or open_modes.can_write):
self.filesystem.raise_os_error(errno.EISDIR, file_path)
dir_wrapper = FakeDirWrapper(obj, file_path, self.filesystem)
file_des = self.filesystem._add_open_file(dir_wrapper)
dir_wrapper.filedes = file_des
return file_des
# low level open is always binary
str_flags = 'b'
delete_on_close = False
if hasattr(os, 'O_TEMPORARY'):
delete_on_close = flags & os.O_TEMPORARY == os.O_TEMPORARY
fake_file = FakeFileOpen(
self.filesystem, delete_on_close=delete_on_close, raw_io=True)(
file_path, str_flags, open_modes=open_modes)
if fake_file.file_object != self.filesystem.dev_null:
self.chmod(file_path, mode)
return fake_file.fileno() | [
"def",
"open",
"(",
"self",
",",
"file_path",
",",
"flags",
",",
"mode",
"=",
"None",
",",
"dir_fd",
"=",
"None",
")",
":",
"file_path",
"=",
"self",
".",
"_path_with_dir_fd",
"(",
"file_path",
",",
"self",
".",
"open",
",",
"dir_fd",
")",
"if",
"mod... | Return the file descriptor for a FakeFile.
Args:
file_path: the path to the file
flags: low-level bits to indicate io operation
mode: bits to define default permissions
Note: only basic modes are supported, OS-specific modes are
ignored
dir_fd: If not `None`, the file descriptor of a directory,
with `file_path` being relative to this directory.
New in Python 3.3.
Returns:
A file descriptor.
Raises:
IOError: if the path cannot be found
ValueError: if invalid mode is given
NotImplementedError: if `os.O_EXCL` is used without `os.O_CREAT` | [
"Return",
"the",
"file",
"descriptor",
"for",
"a",
"FakeFile",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3629-L3694 | train | 203,525 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.close | def close(self, file_des):
"""Close a file descriptor.
Args:
file_des: An integer file descriptor for the file object requested.
Raises:
OSError: bad file descriptor.
TypeError: if file descriptor is not an integer.
"""
file_handle = self.filesystem.get_open_file(file_des)
file_handle.close() | python | def close(self, file_des):
"""Close a file descriptor.
Args:
file_des: An integer file descriptor for the file object requested.
Raises:
OSError: bad file descriptor.
TypeError: if file descriptor is not an integer.
"""
file_handle = self.filesystem.get_open_file(file_des)
file_handle.close() | [
"def",
"close",
"(",
"self",
",",
"file_des",
")",
":",
"file_handle",
"=",
"self",
".",
"filesystem",
".",
"get_open_file",
"(",
"file_des",
")",
"file_handle",
".",
"close",
"(",
")"
] | Close a file descriptor.
Args:
file_des: An integer file descriptor for the file object requested.
Raises:
OSError: bad file descriptor.
TypeError: if file descriptor is not an integer. | [
"Close",
"a",
"file",
"descriptor",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3696-L3707 | train | 203,526 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.read | def read(self, file_des, num_bytes):
"""Read number of bytes from a file descriptor, returns bytes read.
Args:
file_des: An integer file descriptor for the file object requested.
num_bytes: Number of bytes to read from file.
Returns:
Bytes read from file.
Raises:
OSError: bad file descriptor.
TypeError: if file descriptor is not an integer.
"""
file_handle = self.filesystem.get_open_file(file_des)
file_handle.raw_io = True
return file_handle.read(num_bytes) | python | def read(self, file_des, num_bytes):
"""Read number of bytes from a file descriptor, returns bytes read.
Args:
file_des: An integer file descriptor for the file object requested.
num_bytes: Number of bytes to read from file.
Returns:
Bytes read from file.
Raises:
OSError: bad file descriptor.
TypeError: if file descriptor is not an integer.
"""
file_handle = self.filesystem.get_open_file(file_des)
file_handle.raw_io = True
return file_handle.read(num_bytes) | [
"def",
"read",
"(",
"self",
",",
"file_des",
",",
"num_bytes",
")",
":",
"file_handle",
"=",
"self",
".",
"filesystem",
".",
"get_open_file",
"(",
"file_des",
")",
"file_handle",
".",
"raw_io",
"=",
"True",
"return",
"file_handle",
".",
"read",
"(",
"num_b... | Read number of bytes from a file descriptor, returns bytes read.
Args:
file_des: An integer file descriptor for the file object requested.
num_bytes: Number of bytes to read from file.
Returns:
Bytes read from file.
Raises:
OSError: bad file descriptor.
TypeError: if file descriptor is not an integer. | [
"Read",
"number",
"of",
"bytes",
"from",
"a",
"file",
"descriptor",
"returns",
"bytes",
"read",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3709-L3725 | train | 203,527 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.write | def write(self, file_des, contents):
"""Write string to file descriptor, returns number of bytes written.
Args:
file_des: An integer file descriptor for the file object requested.
contents: String of bytes to write to file.
Returns:
Number of bytes written.
Raises:
OSError: bad file descriptor.
TypeError: if file descriptor is not an integer.
"""
file_handle = self.filesystem.get_open_file(file_des)
if isinstance(file_handle, FakeDirWrapper):
self.filesystem.raise_os_error(errno.EBADF, file_handle.file_path)
if isinstance(file_handle, FakePipeWrapper):
return file_handle.write(contents)
file_handle.raw_io = True
file_handle._sync_io()
file_handle.update_flush_pos()
file_handle.write(contents)
file_handle.flush()
return len(contents) | python | def write(self, file_des, contents):
"""Write string to file descriptor, returns number of bytes written.
Args:
file_des: An integer file descriptor for the file object requested.
contents: String of bytes to write to file.
Returns:
Number of bytes written.
Raises:
OSError: bad file descriptor.
TypeError: if file descriptor is not an integer.
"""
file_handle = self.filesystem.get_open_file(file_des)
if isinstance(file_handle, FakeDirWrapper):
self.filesystem.raise_os_error(errno.EBADF, file_handle.file_path)
if isinstance(file_handle, FakePipeWrapper):
return file_handle.write(contents)
file_handle.raw_io = True
file_handle._sync_io()
file_handle.update_flush_pos()
file_handle.write(contents)
file_handle.flush()
return len(contents) | [
"def",
"write",
"(",
"self",
",",
"file_des",
",",
"contents",
")",
":",
"file_handle",
"=",
"self",
".",
"filesystem",
".",
"get_open_file",
"(",
"file_des",
")",
"if",
"isinstance",
"(",
"file_handle",
",",
"FakeDirWrapper",
")",
":",
"self",
".",
"files... | Write string to file descriptor, returns number of bytes written.
Args:
file_des: An integer file descriptor for the file object requested.
contents: String of bytes to write to file.
Returns:
Number of bytes written.
Raises:
OSError: bad file descriptor.
TypeError: if file descriptor is not an integer. | [
"Write",
"string",
"to",
"file",
"descriptor",
"returns",
"number",
"of",
"bytes",
"written",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3727-L3753 | train | 203,528 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.fstat | def fstat(self, file_des):
"""Return the os.stat-like tuple for the FakeFile object of file_des.
Args:
file_des: The file descriptor of filesystem object to retrieve.
Returns:
The FakeStatResult object corresponding to entry_path.
Raises:
OSError: if the filesystem object doesn't exist.
"""
# stat should return the tuple representing return value of os.stat
file_object = self.filesystem.get_open_file(file_des).get_object()
return file_object.stat_result.copy() | python | def fstat(self, file_des):
"""Return the os.stat-like tuple for the FakeFile object of file_des.
Args:
file_des: The file descriptor of filesystem object to retrieve.
Returns:
The FakeStatResult object corresponding to entry_path.
Raises:
OSError: if the filesystem object doesn't exist.
"""
# stat should return the tuple representing return value of os.stat
file_object = self.filesystem.get_open_file(file_des).get_object()
return file_object.stat_result.copy() | [
"def",
"fstat",
"(",
"self",
",",
"file_des",
")",
":",
"# stat should return the tuple representing return value of os.stat",
"file_object",
"=",
"self",
".",
"filesystem",
".",
"get_open_file",
"(",
"file_des",
")",
".",
"get_object",
"(",
")",
"return",
"file_objec... | Return the os.stat-like tuple for the FakeFile object of file_des.
Args:
file_des: The file descriptor of filesystem object to retrieve.
Returns:
The FakeStatResult object corresponding to entry_path.
Raises:
OSError: if the filesystem object doesn't exist. | [
"Return",
"the",
"os",
".",
"stat",
"-",
"like",
"tuple",
"for",
"the",
"FakeFile",
"object",
"of",
"file_des",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3779-L3793 | train | 203,529 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.umask | def umask(self, new_mask):
"""Change the current umask.
Args:
new_mask: (int) The new umask value.
Returns:
The old umask.
Raises:
TypeError: if new_mask is of an invalid type.
"""
if not is_int_type(new_mask):
raise TypeError('an integer is required')
old_umask = self.filesystem.umask
self.filesystem.umask = new_mask
return old_umask | python | def umask(self, new_mask):
"""Change the current umask.
Args:
new_mask: (int) The new umask value.
Returns:
The old umask.
Raises:
TypeError: if new_mask is of an invalid type.
"""
if not is_int_type(new_mask):
raise TypeError('an integer is required')
old_umask = self.filesystem.umask
self.filesystem.umask = new_mask
return old_umask | [
"def",
"umask",
"(",
"self",
",",
"new_mask",
")",
":",
"if",
"not",
"is_int_type",
"(",
"new_mask",
")",
":",
"raise",
"TypeError",
"(",
"'an integer is required'",
")",
"old_umask",
"=",
"self",
".",
"filesystem",
".",
"umask",
"self",
".",
"filesystem",
... | Change the current umask.
Args:
new_mask: (int) The new umask value.
Returns:
The old umask.
Raises:
TypeError: if new_mask is of an invalid type. | [
"Change",
"the",
"current",
"umask",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3795-L3811 | train | 203,530 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.chdir | def chdir(self, target_directory):
"""Change current working directory to target directory.
Args:
target_directory: The path to new current working directory.
Raises:
OSError: if user lacks permission to enter the argument directory
or if the target is not a directory.
"""
target_directory = self.filesystem.resolve_path(
target_directory, allow_fd=True)
self.filesystem.confirmdir(target_directory)
directory = self.filesystem.resolve(target_directory)
# A full implementation would check permissions all the way
# up the tree.
if not is_root() and not directory.st_mode | PERM_EXE:
self.filesystem.raise_os_error(errno.EACCES, directory)
self.filesystem.cwd = target_directory | python | def chdir(self, target_directory):
"""Change current working directory to target directory.
Args:
target_directory: The path to new current working directory.
Raises:
OSError: if user lacks permission to enter the argument directory
or if the target is not a directory.
"""
target_directory = self.filesystem.resolve_path(
target_directory, allow_fd=True)
self.filesystem.confirmdir(target_directory)
directory = self.filesystem.resolve(target_directory)
# A full implementation would check permissions all the way
# up the tree.
if not is_root() and not directory.st_mode | PERM_EXE:
self.filesystem.raise_os_error(errno.EACCES, directory)
self.filesystem.cwd = target_directory | [
"def",
"chdir",
"(",
"self",
",",
"target_directory",
")",
":",
"target_directory",
"=",
"self",
".",
"filesystem",
".",
"resolve_path",
"(",
"target_directory",
",",
"allow_fd",
"=",
"True",
")",
"self",
".",
"filesystem",
".",
"confirmdir",
"(",
"target_dire... | Change current working directory to target directory.
Args:
target_directory: The path to new current working directory.
Raises:
OSError: if user lacks permission to enter the argument directory
or if the target is not a directory. | [
"Change",
"current",
"working",
"directory",
"to",
"target",
"directory",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L3813-L3831 | train | 203,531 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.lstat | def lstat(self, entry_path, dir_fd=None):
"""Return the os.stat-like tuple for entry_path, not following symlinks.
Args:
entry_path: path to filesystem object to retrieve.
dir_fd: If not `None`, the file descriptor of a directory, with
`entry_path` being relative to this directory.
New in Python 3.3.
Returns:
the FakeStatResult object corresponding to `entry_path`.
Raises:
OSError: if the filesystem object doesn't exist.
"""
# stat should return the tuple representing return value of os.stat
entry_path = self._path_with_dir_fd(entry_path, self.lstat, dir_fd)
return self.filesystem.stat(entry_path, follow_symlinks=False) | python | def lstat(self, entry_path, dir_fd=None):
"""Return the os.stat-like tuple for entry_path, not following symlinks.
Args:
entry_path: path to filesystem object to retrieve.
dir_fd: If not `None`, the file descriptor of a directory, with
`entry_path` being relative to this directory.
New in Python 3.3.
Returns:
the FakeStatResult object corresponding to `entry_path`.
Raises:
OSError: if the filesystem object doesn't exist.
"""
# stat should return the tuple representing return value of os.stat
entry_path = self._path_with_dir_fd(entry_path, self.lstat, dir_fd)
return self.filesystem.stat(entry_path, follow_symlinks=False) | [
"def",
"lstat",
"(",
"self",
",",
"entry_path",
",",
"dir_fd",
"=",
"None",
")",
":",
"# stat should return the tuple representing return value of os.stat",
"entry_path",
"=",
"self",
".",
"_path_with_dir_fd",
"(",
"entry_path",
",",
"self",
".",
"lstat",
",",
"dir_... | Return the os.stat-like tuple for entry_path, not following symlinks.
Args:
entry_path: path to filesystem object to retrieve.
dir_fd: If not `None`, the file descriptor of a directory, with
`entry_path` being relative to this directory.
New in Python 3.3.
Returns:
the FakeStatResult object corresponding to `entry_path`.
Raises:
OSError: if the filesystem object doesn't exist. | [
"Return",
"the",
"os",
".",
"stat",
"-",
"like",
"tuple",
"for",
"entry_path",
"not",
"following",
"symlinks",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4062-L4079 | train | 203,532 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.removedirs | def removedirs(self, target_directory):
"""Remove a leaf fake directory and all empty intermediate ones.
Args:
target_directory: the directory to be removed.
Raises:
OSError: if target_directory does not exist or is not a directory.
OSError: if target_directory is not empty.
"""
target_directory = self.filesystem.absnormpath(target_directory)
directory = self.filesystem.confirmdir(target_directory)
if directory.contents:
self.filesystem.raise_os_error(
errno.ENOTEMPTY, self.path.basename(target_directory))
else:
self.rmdir(target_directory)
head, tail = self.path.split(target_directory)
if not tail:
head, tail = self.path.split(head)
while head and tail:
head_dir = self.filesystem.confirmdir(head)
if head_dir.contents:
break
# only the top-level dir may not be a symlink
self.filesystem.rmdir(head, allow_symlink=True)
head, tail = self.path.split(head) | python | def removedirs(self, target_directory):
"""Remove a leaf fake directory and all empty intermediate ones.
Args:
target_directory: the directory to be removed.
Raises:
OSError: if target_directory does not exist or is not a directory.
OSError: if target_directory is not empty.
"""
target_directory = self.filesystem.absnormpath(target_directory)
directory = self.filesystem.confirmdir(target_directory)
if directory.contents:
self.filesystem.raise_os_error(
errno.ENOTEMPTY, self.path.basename(target_directory))
else:
self.rmdir(target_directory)
head, tail = self.path.split(target_directory)
if not tail:
head, tail = self.path.split(head)
while head and tail:
head_dir = self.filesystem.confirmdir(head)
if head_dir.contents:
break
# only the top-level dir may not be a symlink
self.filesystem.rmdir(head, allow_symlink=True)
head, tail = self.path.split(head) | [
"def",
"removedirs",
"(",
"self",
",",
"target_directory",
")",
":",
"target_directory",
"=",
"self",
".",
"filesystem",
".",
"absnormpath",
"(",
"target_directory",
")",
"directory",
"=",
"self",
".",
"filesystem",
".",
"confirmdir",
"(",
"target_directory",
")... | Remove a leaf fake directory and all empty intermediate ones.
Args:
target_directory: the directory to be removed.
Raises:
OSError: if target_directory does not exist or is not a directory.
OSError: if target_directory is not empty. | [
"Remove",
"a",
"leaf",
"fake",
"directory",
"and",
"all",
"empty",
"intermediate",
"ones",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4183-L4209 | train | 203,533 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.makedirs | def makedirs(self, dir_name, mode=PERM_DEF, exist_ok=None):
"""Create a leaf Fake directory + create any non-existent parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directories) with. This argument defaults to 0o777.
The umask is applied to this mode.
exist_ok: (boolean) If exist_ok is False (the default), an OSError
is raised if the target directory already exists.
New in Python 3.2.
Raises:
OSError: if the directory already exists and exist_ok=False, or as
per :py:meth:`FakeFilesystem.create_dir`.
"""
if exist_ok is None:
exist_ok = False
elif sys.version_info < (3, 2):
raise TypeError("makedir() got an unexpected "
"keyword argument 'exist_ok'")
self.filesystem.makedirs(dir_name, mode, exist_ok) | python | def makedirs(self, dir_name, mode=PERM_DEF, exist_ok=None):
"""Create a leaf Fake directory + create any non-existent parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directories) with. This argument defaults to 0o777.
The umask is applied to this mode.
exist_ok: (boolean) If exist_ok is False (the default), an OSError
is raised if the target directory already exists.
New in Python 3.2.
Raises:
OSError: if the directory already exists and exist_ok=False, or as
per :py:meth:`FakeFilesystem.create_dir`.
"""
if exist_ok is None:
exist_ok = False
elif sys.version_info < (3, 2):
raise TypeError("makedir() got an unexpected "
"keyword argument 'exist_ok'")
self.filesystem.makedirs(dir_name, mode, exist_ok) | [
"def",
"makedirs",
"(",
"self",
",",
"dir_name",
",",
"mode",
"=",
"PERM_DEF",
",",
"exist_ok",
"=",
"None",
")",
":",
"if",
"exist_ok",
"is",
"None",
":",
"exist_ok",
"=",
"False",
"elif",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"2",
")",
... | Create a leaf Fake directory + create any non-existent parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directories) with. This argument defaults to 0o777.
The umask is applied to this mode.
exist_ok: (boolean) If exist_ok is False (the default), an OSError
is raised if the target directory already exists.
New in Python 3.2.
Raises:
OSError: if the directory already exists and exist_ok=False, or as
per :py:meth:`FakeFilesystem.create_dir`. | [
"Create",
"a",
"leaf",
"Fake",
"directory",
"+",
"create",
"any",
"non",
"-",
"existent",
"parent",
"dirs",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4235-L4256 | train | 203,534 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule._path_with_dir_fd | def _path_with_dir_fd(self, path, fct, dir_fd):
"""Return the path considering dir_fd. Raise on nmvalid parameters."""
if dir_fd is not None:
if sys.version_info < (3, 3):
raise TypeError("%s() got an unexpected keyword "
"argument 'dir_fd'" % fct.__name__)
# check if fd is supported for the built-in real function
real_fct = getattr(os, fct.__name__)
if real_fct not in self.supports_dir_fd:
raise NotImplementedError(
'dir_fd unavailable on this platform')
if isinstance(path, int):
raise ValueError("%s: Can't specify dir_fd without "
"matching path" % fct.__name__)
if not self.path.isabs(path):
return self.path.join(
self.filesystem.get_open_file(
dir_fd).get_object().path, path)
return path | python | def _path_with_dir_fd(self, path, fct, dir_fd):
"""Return the path considering dir_fd. Raise on nmvalid parameters."""
if dir_fd is not None:
if sys.version_info < (3, 3):
raise TypeError("%s() got an unexpected keyword "
"argument 'dir_fd'" % fct.__name__)
# check if fd is supported for the built-in real function
real_fct = getattr(os, fct.__name__)
if real_fct not in self.supports_dir_fd:
raise NotImplementedError(
'dir_fd unavailable on this platform')
if isinstance(path, int):
raise ValueError("%s: Can't specify dir_fd without "
"matching path" % fct.__name__)
if not self.path.isabs(path):
return self.path.join(
self.filesystem.get_open_file(
dir_fd).get_object().path, path)
return path | [
"def",
"_path_with_dir_fd",
"(",
"self",
",",
"path",
",",
"fct",
",",
"dir_fd",
")",
":",
"if",
"dir_fd",
"is",
"not",
"None",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"3",
")",
":",
"raise",
"TypeError",
"(",
"\"%s() got an unexpect... | Return the path considering dir_fd. Raise on nmvalid parameters. | [
"Return",
"the",
"path",
"considering",
"dir_fd",
".",
"Raise",
"on",
"nmvalid",
"parameters",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4258-L4276 | train | 203,535 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.access | def access(self, path, mode, dir_fd=None, follow_symlinks=None):
"""Check if a file exists and has the specified permissions.
Args:
path: (str) Path to the file.
mode: (int) Permissions represented as a bitwise-OR combination of
os.F_OK, os.R_OK, os.W_OK, and os.X_OK.
dir_fd: If not `None`, the file descriptor of a directory, with
`path` being relative to this directory.
New in Python 3.3.
follow_symlinks: (bool) If `False` and `path` points to a symlink,
the link itself is queried instead of the linked object.
New in Python 3.3.
Returns:
bool, `True` if file is accessible, `False` otherwise.
"""
if follow_symlinks is not None and sys.version_info < (3, 3):
raise TypeError("access() got an unexpected "
"keyword argument 'follow_symlinks'")
path = self._path_with_dir_fd(path, self.access, dir_fd)
try:
stat_result = self.stat(path, follow_symlinks=follow_symlinks)
except OSError as os_error:
if os_error.errno == errno.ENOENT:
return False
raise
if is_root():
mode &= ~os.W_OK
return (mode & ((stat_result.st_mode >> 6) & 7)) == mode | python | def access(self, path, mode, dir_fd=None, follow_symlinks=None):
"""Check if a file exists and has the specified permissions.
Args:
path: (str) Path to the file.
mode: (int) Permissions represented as a bitwise-OR combination of
os.F_OK, os.R_OK, os.W_OK, and os.X_OK.
dir_fd: If not `None`, the file descriptor of a directory, with
`path` being relative to this directory.
New in Python 3.3.
follow_symlinks: (bool) If `False` and `path` points to a symlink,
the link itself is queried instead of the linked object.
New in Python 3.3.
Returns:
bool, `True` if file is accessible, `False` otherwise.
"""
if follow_symlinks is not None and sys.version_info < (3, 3):
raise TypeError("access() got an unexpected "
"keyword argument 'follow_symlinks'")
path = self._path_with_dir_fd(path, self.access, dir_fd)
try:
stat_result = self.stat(path, follow_symlinks=follow_symlinks)
except OSError as os_error:
if os_error.errno == errno.ENOENT:
return False
raise
if is_root():
mode &= ~os.W_OK
return (mode & ((stat_result.st_mode >> 6) & 7)) == mode | [
"def",
"access",
"(",
"self",
",",
"path",
",",
"mode",
",",
"dir_fd",
"=",
"None",
",",
"follow_symlinks",
"=",
"None",
")",
":",
"if",
"follow_symlinks",
"is",
"not",
"None",
"and",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"3",
")",
":",
"... | Check if a file exists and has the specified permissions.
Args:
path: (str) Path to the file.
mode: (int) Permissions represented as a bitwise-OR combination of
os.F_OK, os.R_OK, os.W_OK, and os.X_OK.
dir_fd: If not `None`, the file descriptor of a directory, with
`path` being relative to this directory.
New in Python 3.3.
follow_symlinks: (bool) If `False` and `path` points to a symlink,
the link itself is queried instead of the linked object.
New in Python 3.3.
Returns:
bool, `True` if file is accessible, `False` otherwise. | [
"Check",
"if",
"a",
"file",
"exists",
"and",
"has",
"the",
"specified",
"permissions",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4278-L4307 | train | 203,536 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.lchmod | def lchmod(self, path, mode):
"""Change the permissions of a file as encoded in integer mode.
If the file is a link, the permissions of the link are changed.
Args:
path: (str) Path to the file.
mode: (int) Permissions.
"""
if self.filesystem.is_windows_fs:
raise (NameError, "name 'lchmod' is not defined")
self.filesystem.chmod(path, mode, follow_symlinks=False) | python | def lchmod(self, path, mode):
"""Change the permissions of a file as encoded in integer mode.
If the file is a link, the permissions of the link are changed.
Args:
path: (str) Path to the file.
mode: (int) Permissions.
"""
if self.filesystem.is_windows_fs:
raise (NameError, "name 'lchmod' is not defined")
self.filesystem.chmod(path, mode, follow_symlinks=False) | [
"def",
"lchmod",
"(",
"self",
",",
"path",
",",
"mode",
")",
":",
"if",
"self",
".",
"filesystem",
".",
"is_windows_fs",
":",
"raise",
"(",
"NameError",
",",
"\"name 'lchmod' is not defined\"",
")",
"self",
".",
"filesystem",
".",
"chmod",
"(",
"path",
","... | Change the permissions of a file as encoded in integer mode.
If the file is a link, the permissions of the link are changed.
Args:
path: (str) Path to the file.
mode: (int) Permissions. | [
"Change",
"the",
"permissions",
"of",
"a",
"file",
"as",
"encoded",
"in",
"integer",
"mode",
".",
"If",
"the",
"file",
"is",
"a",
"link",
"the",
"permissions",
"of",
"the",
"link",
"are",
"changed",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4330-L4340 | train | 203,537 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.chown | def chown(self, path, uid, gid, dir_fd=None, follow_symlinks=None):
"""Set ownership of a faked file.
Args:
path: (str) Path to the file or directory.
uid: (int) Numeric uid to set the file or directory to.
gid: (int) Numeric gid to set the file or directory to.
dir_fd: (int) If not `None`, the file descriptor of a directory,
with `path` being relative to this directory.
New in Python 3.3.
follow_symlinks: (bool) If `False` and path points to a symlink,
the link itself is changed instead of the linked object.
New in Python 3.3.
Raises:
OSError: if path does not exist.
`None` is also allowed for `uid` and `gid`. This permits `os.rename`
to use `os.chown` even when the source file `uid` and `gid` are
`None` (unset).
"""
if follow_symlinks is None:
follow_symlinks = True
elif sys.version_info < (3, 3):
raise TypeError(
"chown() got an unexpected keyword argument 'follow_symlinks'")
path = self._path_with_dir_fd(path, self.chown, dir_fd)
try:
file_object = self.filesystem.resolve(
path, follow_symlinks, allow_fd=True)
except IOError as io_error:
if io_error.errno == errno.ENOENT:
self.filesystem.raise_os_error(errno.ENOENT, path)
raise
if not ((is_int_type(uid) or uid is None) and
(is_int_type(gid) or gid is None)):
raise TypeError("An integer is required")
if uid != -1:
file_object.st_uid = uid
if gid != -1:
file_object.st_gid = gid | python | def chown(self, path, uid, gid, dir_fd=None, follow_symlinks=None):
"""Set ownership of a faked file.
Args:
path: (str) Path to the file or directory.
uid: (int) Numeric uid to set the file or directory to.
gid: (int) Numeric gid to set the file or directory to.
dir_fd: (int) If not `None`, the file descriptor of a directory,
with `path` being relative to this directory.
New in Python 3.3.
follow_symlinks: (bool) If `False` and path points to a symlink,
the link itself is changed instead of the linked object.
New in Python 3.3.
Raises:
OSError: if path does not exist.
`None` is also allowed for `uid` and `gid`. This permits `os.rename`
to use `os.chown` even when the source file `uid` and `gid` are
`None` (unset).
"""
if follow_symlinks is None:
follow_symlinks = True
elif sys.version_info < (3, 3):
raise TypeError(
"chown() got an unexpected keyword argument 'follow_symlinks'")
path = self._path_with_dir_fd(path, self.chown, dir_fd)
try:
file_object = self.filesystem.resolve(
path, follow_symlinks, allow_fd=True)
except IOError as io_error:
if io_error.errno == errno.ENOENT:
self.filesystem.raise_os_error(errno.ENOENT, path)
raise
if not ((is_int_type(uid) or uid is None) and
(is_int_type(gid) or gid is None)):
raise TypeError("An integer is required")
if uid != -1:
file_object.st_uid = uid
if gid != -1:
file_object.st_gid = gid | [
"def",
"chown",
"(",
"self",
",",
"path",
",",
"uid",
",",
"gid",
",",
"dir_fd",
"=",
"None",
",",
"follow_symlinks",
"=",
"None",
")",
":",
"if",
"follow_symlinks",
"is",
"None",
":",
"follow_symlinks",
"=",
"True",
"elif",
"sys",
".",
"version_info",
... | Set ownership of a faked file.
Args:
path: (str) Path to the file or directory.
uid: (int) Numeric uid to set the file or directory to.
gid: (int) Numeric gid to set the file or directory to.
dir_fd: (int) If not `None`, the file descriptor of a directory,
with `path` being relative to this directory.
New in Python 3.3.
follow_symlinks: (bool) If `False` and path points to a symlink,
the link itself is changed instead of the linked object.
New in Python 3.3.
Raises:
OSError: if path does not exist.
`None` is also allowed for `uid` and `gid`. This permits `os.rename`
to use `os.chown` even when the source file `uid` and `gid` are
`None` (unset). | [
"Set",
"ownership",
"of",
"a",
"faked",
"file",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4379-L4419 | train | 203,538 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.mknod | def mknod(self, filename, mode=None, device=None, dir_fd=None):
"""Create a filesystem node named 'filename'.
Does not support device special files or named pipes as the real os
module does.
Args:
filename: (str) Name of the file to create
mode: (int) Permissions to use and type of file to be created.
Default permissions are 0o666. Only the stat.S_IFREG file type
is supported by the fake implementation. The umask is applied
to this mode.
device: not supported in fake implementation
dir_fd: If not `None`, the file descriptor of a directory,
with `filename` being relative to this directory.
New in Python 3.3.
Raises:
OSError: if called with unsupported options or the file can not be
created.
"""
if self.filesystem.is_windows_fs:
raise(AttributeError, "module 'os' has no attribute 'mknode'")
if mode is None:
# note that a default value of 0o600 without a device type is
# documented - this is not how it seems to work
mode = S_IFREG | 0o600
if device or not mode & S_IFREG and not is_root():
self.filesystem.raise_os_error(errno.EPERM)
filename = self._path_with_dir_fd(filename, self.mknod, dir_fd)
head, tail = self.path.split(filename)
if not tail:
if self.filesystem.exists(head, check_link=True):
self.filesystem.raise_os_error(errno.EEXIST, filename)
self.filesystem.raise_os_error(errno.ENOENT, filename)
if tail in (b'.', u'.', b'..', u'..'):
self.filesystem.raise_os_error(errno.ENOENT, filename)
if self.filesystem.exists(filename, check_link=True):
self.filesystem.raise_os_error(errno.EEXIST, filename)
try:
self.filesystem.add_object(head, FakeFile(
tail, mode & ~self.filesystem.umask,
filesystem=self.filesystem))
except IOError as e:
self.filesystem.raise_os_error(e.errno, filename) | python | def mknod(self, filename, mode=None, device=None, dir_fd=None):
"""Create a filesystem node named 'filename'.
Does not support device special files or named pipes as the real os
module does.
Args:
filename: (str) Name of the file to create
mode: (int) Permissions to use and type of file to be created.
Default permissions are 0o666. Only the stat.S_IFREG file type
is supported by the fake implementation. The umask is applied
to this mode.
device: not supported in fake implementation
dir_fd: If not `None`, the file descriptor of a directory,
with `filename` being relative to this directory.
New in Python 3.3.
Raises:
OSError: if called with unsupported options or the file can not be
created.
"""
if self.filesystem.is_windows_fs:
raise(AttributeError, "module 'os' has no attribute 'mknode'")
if mode is None:
# note that a default value of 0o600 without a device type is
# documented - this is not how it seems to work
mode = S_IFREG | 0o600
if device or not mode & S_IFREG and not is_root():
self.filesystem.raise_os_error(errno.EPERM)
filename = self._path_with_dir_fd(filename, self.mknod, dir_fd)
head, tail = self.path.split(filename)
if not tail:
if self.filesystem.exists(head, check_link=True):
self.filesystem.raise_os_error(errno.EEXIST, filename)
self.filesystem.raise_os_error(errno.ENOENT, filename)
if tail in (b'.', u'.', b'..', u'..'):
self.filesystem.raise_os_error(errno.ENOENT, filename)
if self.filesystem.exists(filename, check_link=True):
self.filesystem.raise_os_error(errno.EEXIST, filename)
try:
self.filesystem.add_object(head, FakeFile(
tail, mode & ~self.filesystem.umask,
filesystem=self.filesystem))
except IOError as e:
self.filesystem.raise_os_error(e.errno, filename) | [
"def",
"mknod",
"(",
"self",
",",
"filename",
",",
"mode",
"=",
"None",
",",
"device",
"=",
"None",
",",
"dir_fd",
"=",
"None",
")",
":",
"if",
"self",
".",
"filesystem",
".",
"is_windows_fs",
":",
"raise",
"(",
"AttributeError",
",",
"\"module 'os' has ... | Create a filesystem node named 'filename'.
Does not support device special files or named pipes as the real os
module does.
Args:
filename: (str) Name of the file to create
mode: (int) Permissions to use and type of file to be created.
Default permissions are 0o666. Only the stat.S_IFREG file type
is supported by the fake implementation. The umask is applied
to this mode.
device: not supported in fake implementation
dir_fd: If not `None`, the file descriptor of a directory,
with `filename` being relative to this directory.
New in Python 3.3.
Raises:
OSError: if called with unsupported options or the file can not be
created. | [
"Create",
"a",
"filesystem",
"node",
"named",
"filename",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4421-L4466 | train | 203,539 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeOsModule.symlink | def symlink(self, link_target, path, dir_fd=None):
"""Creates the specified symlink, pointed at the specified link target.
Args:
link_target: The target of the symlink.
path: Path to the symlink to create.
dir_fd: If not `None`, the file descriptor of a directory,
with `link_target` being relative to this directory.
New in Python 3.3.
Raises:
OSError: if the file already exists.
"""
link_target = self._path_with_dir_fd(link_target, self.symlink, dir_fd)
self.filesystem.create_symlink(
path, link_target, create_missing_dirs=False) | python | def symlink(self, link_target, path, dir_fd=None):
"""Creates the specified symlink, pointed at the specified link target.
Args:
link_target: The target of the symlink.
path: Path to the symlink to create.
dir_fd: If not `None`, the file descriptor of a directory,
with `link_target` being relative to this directory.
New in Python 3.3.
Raises:
OSError: if the file already exists.
"""
link_target = self._path_with_dir_fd(link_target, self.symlink, dir_fd)
self.filesystem.create_symlink(
path, link_target, create_missing_dirs=False) | [
"def",
"symlink",
"(",
"self",
",",
"link_target",
",",
"path",
",",
"dir_fd",
"=",
"None",
")",
":",
"link_target",
"=",
"self",
".",
"_path_with_dir_fd",
"(",
"link_target",
",",
"self",
".",
"symlink",
",",
"dir_fd",
")",
"self",
".",
"filesystem",
".... | Creates the specified symlink, pointed at the specified link target.
Args:
link_target: The target of the symlink.
path: Path to the symlink to create.
dir_fd: If not `None`, the file descriptor of a directory,
with `link_target` being relative to this directory.
New in Python 3.3.
Raises:
OSError: if the file already exists. | [
"Creates",
"the",
"specified",
"symlink",
"pointed",
"at",
"the",
"specified",
"link",
"target",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4468-L4483 | train | 203,540 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFileWrapper.flush | def flush(self):
"""Flush file contents to 'disk'."""
self._check_open_file()
if self.allow_update and not self.is_stream:
contents = self._io.getvalue()
if self._append:
self._sync_io()
old_contents = (self.file_object.byte_contents
if is_byte_string(contents) else
self.file_object.contents)
contents = old_contents + contents[self._flush_pos:]
self._set_stream_contents(contents)
self.update_flush_pos()
else:
self._io.flush()
if self.file_object.set_contents(contents, self._encoding):
if self._filesystem.is_windows_fs:
self._changed = True
else:
current_time = time.time()
self.file_object.st_ctime = current_time
self.file_object.st_mtime = current_time
self._file_epoch = self.file_object.epoch
if not self.is_stream:
self._flush_related_files() | python | def flush(self):
"""Flush file contents to 'disk'."""
self._check_open_file()
if self.allow_update and not self.is_stream:
contents = self._io.getvalue()
if self._append:
self._sync_io()
old_contents = (self.file_object.byte_contents
if is_byte_string(contents) else
self.file_object.contents)
contents = old_contents + contents[self._flush_pos:]
self._set_stream_contents(contents)
self.update_flush_pos()
else:
self._io.flush()
if self.file_object.set_contents(contents, self._encoding):
if self._filesystem.is_windows_fs:
self._changed = True
else:
current_time = time.time()
self.file_object.st_ctime = current_time
self.file_object.st_mtime = current_time
self._file_epoch = self.file_object.epoch
if not self.is_stream:
self._flush_related_files() | [
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"_check_open_file",
"(",
")",
"if",
"self",
".",
"allow_update",
"and",
"not",
"self",
".",
"is_stream",
":",
"contents",
"=",
"self",
".",
"_io",
".",
"getvalue",
"(",
")",
"if",
"self",
".",
"_app... | Flush file contents to 'disk'. | [
"Flush",
"file",
"contents",
"to",
"disk",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4690-L4715 | train | 203,541 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFileWrapper.tell | def tell(self):
"""Return the file's current position.
Returns:
int, file's current position in bytes.
"""
self._check_open_file()
if self._flushes_after_tell():
self.flush()
if not self._append:
return self._io.tell()
if self._read_whence:
write_seek = self._io.tell()
self._io.seek(self._read_seek, self._read_whence)
self._read_seek = self._io.tell()
self._read_whence = 0
self._io.seek(write_seek)
return self._read_seek | python | def tell(self):
"""Return the file's current position.
Returns:
int, file's current position in bytes.
"""
self._check_open_file()
if self._flushes_after_tell():
self.flush()
if not self._append:
return self._io.tell()
if self._read_whence:
write_seek = self._io.tell()
self._io.seek(self._read_seek, self._read_whence)
self._read_seek = self._io.tell()
self._read_whence = 0
self._io.seek(write_seek)
return self._read_seek | [
"def",
"tell",
"(",
"self",
")",
":",
"self",
".",
"_check_open_file",
"(",
")",
"if",
"self",
".",
"_flushes_after_tell",
"(",
")",
":",
"self",
".",
"flush",
"(",
")",
"if",
"not",
"self",
".",
"_append",
":",
"return",
"self",
".",
"_io",
".",
"... | Return the file's current position.
Returns:
int, file's current position in bytes. | [
"Return",
"the",
"file",
"s",
"current",
"position",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4740-L4758 | train | 203,542 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFileWrapper._sync_io | def _sync_io(self):
"""Update the stream with changes to the file object contents."""
if self._file_epoch == self.file_object.epoch:
return
if self._io.binary:
contents = self.file_object.byte_contents
else:
contents = self.file_object.contents
self._set_stream_contents(contents)
self._file_epoch = self.file_object.epoch | python | def _sync_io(self):
"""Update the stream with changes to the file object contents."""
if self._file_epoch == self.file_object.epoch:
return
if self._io.binary:
contents = self.file_object.byte_contents
else:
contents = self.file_object.contents
self._set_stream_contents(contents)
self._file_epoch = self.file_object.epoch | [
"def",
"_sync_io",
"(",
"self",
")",
":",
"if",
"self",
".",
"_file_epoch",
"==",
"self",
".",
"file_object",
".",
"epoch",
":",
"return",
"if",
"self",
".",
"_io",
".",
"binary",
":",
"contents",
"=",
"self",
".",
"file_object",
".",
"byte_contents",
... | Update the stream with changes to the file object contents. | [
"Update",
"the",
"stream",
"with",
"changes",
"to",
"the",
"file",
"object",
"contents",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4768-L4779 | train | 203,543 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFileWrapper._read_wrappers | def _read_wrappers(self, name):
"""Wrap a stream attribute in a read wrapper.
Returns a read_wrapper which tracks our own read pointer since the
stream object has no concept of a different read and write pointer.
Args:
name: The name of the attribute to wrap. Should be a read call.
Returns:
The read_wrapper function.
"""
io_attr = getattr(self._io, name)
def read_wrapper(*args, **kwargs):
"""Wrap all read calls to the stream object.
We do this to track the read pointer separate from the write
pointer. Anything that wants to read from the stream object
while we're in append mode goes through this.
Args:
*args: pass through args
**kwargs: pass through kwargs
Returns:
Wrapped stream object method
"""
self._io.seek(self._read_seek, self._read_whence)
ret_value = io_attr(*args, **kwargs)
self._read_seek = self._io.tell()
self._read_whence = 0
self._io.seek(0, 2)
return ret_value
return read_wrapper | python | def _read_wrappers(self, name):
"""Wrap a stream attribute in a read wrapper.
Returns a read_wrapper which tracks our own read pointer since the
stream object has no concept of a different read and write pointer.
Args:
name: The name of the attribute to wrap. Should be a read call.
Returns:
The read_wrapper function.
"""
io_attr = getattr(self._io, name)
def read_wrapper(*args, **kwargs):
"""Wrap all read calls to the stream object.
We do this to track the read pointer separate from the write
pointer. Anything that wants to read from the stream object
while we're in append mode goes through this.
Args:
*args: pass through args
**kwargs: pass through kwargs
Returns:
Wrapped stream object method
"""
self._io.seek(self._read_seek, self._read_whence)
ret_value = io_attr(*args, **kwargs)
self._read_seek = self._io.tell()
self._read_whence = 0
self._io.seek(0, 2)
return ret_value
return read_wrapper | [
"def",
"_read_wrappers",
"(",
"self",
",",
"name",
")",
":",
"io_attr",
"=",
"getattr",
"(",
"self",
".",
"_io",
",",
"name",
")",
"def",
"read_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrap all read calls to the stream object.\n\... | Wrap a stream attribute in a read wrapper.
Returns a read_wrapper which tracks our own read pointer since the
stream object has no concept of a different read and write pointer.
Args:
name: The name of the attribute to wrap. Should be a read call.
Returns:
The read_wrapper function. | [
"Wrap",
"a",
"stream",
"attribute",
"in",
"a",
"read",
"wrapper",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4791-L4825 | train | 203,544 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFileWrapper._other_wrapper | def _other_wrapper(self, name, writing):
"""Wrap a stream attribute in an other_wrapper.
Args:
name: the name of the stream attribute to wrap.
Returns:
other_wrapper which is described below.
"""
io_attr = getattr(self._io, name)
def other_wrapper(*args, **kwargs):
"""Wrap all other calls to the stream Object.
We do this to track changes to the write pointer. Anything that
moves the write pointer in a file open for appending should move
the read pointer as well.
Args:
*args: Pass through args.
**kwargs: Pass through kwargs.
Returns:
Wrapped stream object method.
"""
write_seek = self._io.tell()
ret_value = io_attr(*args, **kwargs)
if write_seek != self._io.tell():
self._read_seek = self._io.tell()
self._read_whence = 0
if not writing or not IS_PY2:
return ret_value
return other_wrapper | python | def _other_wrapper(self, name, writing):
"""Wrap a stream attribute in an other_wrapper.
Args:
name: the name of the stream attribute to wrap.
Returns:
other_wrapper which is described below.
"""
io_attr = getattr(self._io, name)
def other_wrapper(*args, **kwargs):
"""Wrap all other calls to the stream Object.
We do this to track changes to the write pointer. Anything that
moves the write pointer in a file open for appending should move
the read pointer as well.
Args:
*args: Pass through args.
**kwargs: Pass through kwargs.
Returns:
Wrapped stream object method.
"""
write_seek = self._io.tell()
ret_value = io_attr(*args, **kwargs)
if write_seek != self._io.tell():
self._read_seek = self._io.tell()
self._read_whence = 0
if not writing or not IS_PY2:
return ret_value
return other_wrapper | [
"def",
"_other_wrapper",
"(",
"self",
",",
"name",
",",
"writing",
")",
":",
"io_attr",
"=",
"getattr",
"(",
"self",
".",
"_io",
",",
"name",
")",
"def",
"other_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrap all other calls to... | Wrap a stream attribute in an other_wrapper.
Args:
name: the name of the stream attribute to wrap.
Returns:
other_wrapper which is described below. | [
"Wrap",
"a",
"stream",
"attribute",
"in",
"an",
"other_wrapper",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L4827-L4860 | train | 203,545 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakePipeWrapper.close | def close(self):
"""Close the pipe descriptor."""
self._filesystem.open_files[self.filedes].remove(self)
os.close(self.fd) | python | def close(self):
"""Close the pipe descriptor."""
self._filesystem.open_files[self.filedes].remove(self)
os.close(self.fd) | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_filesystem",
".",
"open_files",
"[",
"self",
".",
"filedes",
"]",
".",
"remove",
"(",
"self",
")",
"os",
".",
"close",
"(",
"self",
".",
"fd",
")"
] | Close the pipe descriptor. | [
"Close",
"the",
"pipe",
"descriptor",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L5065-L5068 | train | 203,546 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | FakeFileOpen.call | def call(self, file_, mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True, opener=None,
open_modes=None):
"""Return a file-like object with the contents of the target
file object.
Args:
file_: Path to target file or a file descriptor.
mode: Additional file modes (all modes in `open()` are supported).
buffering: ignored. (Used for signature compliance with
__builtin__.open)
encoding: The encoding used to encode unicode strings / decode
bytes.
errors: (str) Defines how encoding errors are handled.
newline: Controls universal newlines, passed to stream object.
closefd: If a file descriptor rather than file name is passed,
and this is set to `False`, then the file descriptor is kept
open when file is closed.
opener: not supported.
open_modes: Modes for opening files if called from low-level API.
Returns:
A file-like object containing the contents of the target file.
Raises:
IOError, OSError depending on Python version / call mode:
- if the target object is a directory
- on an invalid path
- if the file does not exist when it should
- if the file exists but should not
- if permission is denied
ValueError: for an invalid mode or mode combination
"""
binary = 'b' in mode
newline, open_modes = self._handle_file_mode(mode, newline, open_modes)
file_object, file_path, filedes, real_path = self._handle_file_arg(
file_)
if not filedes:
closefd = True
error_fct = (self.filesystem.raise_os_error if self.raw_io
else self.filesystem.raise_io_error)
if (open_modes.must_not_exist and
(file_object or self.filesystem.islink(file_path) and
not self.filesystem.is_windows_fs)):
error_fct(errno.EEXIST, file_path)
if file_object:
if (not is_root() and
((open_modes.can_read and
not file_object.st_mode & PERM_READ)
or (open_modes.can_write and
not file_object.st_mode & PERM_WRITE))):
error_fct(errno.EACCES, file_path)
if open_modes.can_write:
if open_modes.truncate:
file_object.set_contents('')
else:
if open_modes.must_exist:
error_fct(errno.ENOENT, file_path)
if self.filesystem.islink(file_path):
link_object = self.filesystem.resolve(file_path,
follow_symlinks=False)
target_path = link_object.contents
else:
target_path = file_path
if self.filesystem.ends_with_path_separator(target_path):
error = (errno.EINVAL if self.filesystem.is_windows_fs
else errno.ENOENT if self.filesystem.is_macos
else errno.EISDIR)
error_fct(error, file_path)
file_object = self.filesystem.create_file_internally(
real_path, create_missing_dirs=False,
apply_umask=True, raw_io=self.raw_io)
if S_ISDIR(file_object.st_mode):
if self.filesystem.is_windows_fs:
error_fct(errno.EACCES, file_path)
else:
error_fct(errno.EISDIR, file_path)
# If you print obj.name, the argument to open() must be printed.
# Not the abspath, not the filename, but the actual argument.
file_object.opened_as = file_path
if open_modes.truncate:
current_time = time.time()
file_object.st_mtime = current_time
if not self.filesystem.is_windows_fs:
file_object.st_ctime = current_time
fakefile = FakeFileWrapper(file_object,
file_path,
update=open_modes.can_write,
read=open_modes.can_read,
append=open_modes.append,
delete_on_close=self._delete_on_close,
filesystem=self.filesystem,
newline=newline,
binary=binary,
closefd=closefd,
encoding=encoding,
errors=errors,
raw_io=self.raw_io,
use_io=self._use_io)
if filedes is not None:
fakefile.filedes = filedes
# replace the file wrapper
self.filesystem.open_files[filedes].append(fakefile)
else:
fakefile.filedes = self.filesystem._add_open_file(fakefile)
return fakefile | python | def call(self, file_, mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True, opener=None,
open_modes=None):
"""Return a file-like object with the contents of the target
file object.
Args:
file_: Path to target file or a file descriptor.
mode: Additional file modes (all modes in `open()` are supported).
buffering: ignored. (Used for signature compliance with
__builtin__.open)
encoding: The encoding used to encode unicode strings / decode
bytes.
errors: (str) Defines how encoding errors are handled.
newline: Controls universal newlines, passed to stream object.
closefd: If a file descriptor rather than file name is passed,
and this is set to `False`, then the file descriptor is kept
open when file is closed.
opener: not supported.
open_modes: Modes for opening files if called from low-level API.
Returns:
A file-like object containing the contents of the target file.
Raises:
IOError, OSError depending on Python version / call mode:
- if the target object is a directory
- on an invalid path
- if the file does not exist when it should
- if the file exists but should not
- if permission is denied
ValueError: for an invalid mode or mode combination
"""
binary = 'b' in mode
newline, open_modes = self._handle_file_mode(mode, newline, open_modes)
file_object, file_path, filedes, real_path = self._handle_file_arg(
file_)
if not filedes:
closefd = True
error_fct = (self.filesystem.raise_os_error if self.raw_io
else self.filesystem.raise_io_error)
if (open_modes.must_not_exist and
(file_object or self.filesystem.islink(file_path) and
not self.filesystem.is_windows_fs)):
error_fct(errno.EEXIST, file_path)
if file_object:
if (not is_root() and
((open_modes.can_read and
not file_object.st_mode & PERM_READ)
or (open_modes.can_write and
not file_object.st_mode & PERM_WRITE))):
error_fct(errno.EACCES, file_path)
if open_modes.can_write:
if open_modes.truncate:
file_object.set_contents('')
else:
if open_modes.must_exist:
error_fct(errno.ENOENT, file_path)
if self.filesystem.islink(file_path):
link_object = self.filesystem.resolve(file_path,
follow_symlinks=False)
target_path = link_object.contents
else:
target_path = file_path
if self.filesystem.ends_with_path_separator(target_path):
error = (errno.EINVAL if self.filesystem.is_windows_fs
else errno.ENOENT if self.filesystem.is_macos
else errno.EISDIR)
error_fct(error, file_path)
file_object = self.filesystem.create_file_internally(
real_path, create_missing_dirs=False,
apply_umask=True, raw_io=self.raw_io)
if S_ISDIR(file_object.st_mode):
if self.filesystem.is_windows_fs:
error_fct(errno.EACCES, file_path)
else:
error_fct(errno.EISDIR, file_path)
# If you print obj.name, the argument to open() must be printed.
# Not the abspath, not the filename, but the actual argument.
file_object.opened_as = file_path
if open_modes.truncate:
current_time = time.time()
file_object.st_mtime = current_time
if not self.filesystem.is_windows_fs:
file_object.st_ctime = current_time
fakefile = FakeFileWrapper(file_object,
file_path,
update=open_modes.can_write,
read=open_modes.can_read,
append=open_modes.append,
delete_on_close=self._delete_on_close,
filesystem=self.filesystem,
newline=newline,
binary=binary,
closefd=closefd,
encoding=encoding,
errors=errors,
raw_io=self.raw_io,
use_io=self._use_io)
if filedes is not None:
fakefile.filedes = filedes
# replace the file wrapper
self.filesystem.open_files[filedes].append(fakefile)
else:
fakefile.filedes = self.filesystem._add_open_file(fakefile)
return fakefile | [
"def",
"call",
"(",
"self",
",",
"file_",
",",
"mode",
"=",
"'r'",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
"newline",
"=",
"None",
",",
"closefd",
"=",
"True",
",",
"opener",
"=",
"None",
",... | Return a file-like object with the contents of the target
file object.
Args:
file_: Path to target file or a file descriptor.
mode: Additional file modes (all modes in `open()` are supported).
buffering: ignored. (Used for signature compliance with
__builtin__.open)
encoding: The encoding used to encode unicode strings / decode
bytes.
errors: (str) Defines how encoding errors are handled.
newline: Controls universal newlines, passed to stream object.
closefd: If a file descriptor rather than file name is passed,
and this is set to `False`, then the file descriptor is kept
open when file is closed.
opener: not supported.
open_modes: Modes for opening files if called from low-level API.
Returns:
A file-like object containing the contents of the target file.
Raises:
IOError, OSError depending on Python version / call mode:
- if the target object is a directory
- on an invalid path
- if the file does not exist when it should
- if the file exists but should not
- if permission is denied
ValueError: for an invalid mode or mode combination | [
"Return",
"a",
"file",
"-",
"like",
"object",
"with",
"the",
"contents",
"of",
"the",
"target",
"file",
"object",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L5114-L5224 | train | 203,547 |
jmcgeheeiv/pyfakefs | pyfakefs/helpers.py | is_int_type | def is_int_type(val):
"""Return True if `val` is of integer type."""
try: # Python 2
return isinstance(val, (int, long))
except NameError: # Python 3
return isinstance(val, int) | python | def is_int_type(val):
"""Return True if `val` is of integer type."""
try: # Python 2
return isinstance(val, (int, long))
except NameError: # Python 3
return isinstance(val, int) | [
"def",
"is_int_type",
"(",
"val",
")",
":",
"try",
":",
"# Python 2",
"return",
"isinstance",
"(",
"val",
",",
"(",
"int",
",",
"long",
")",
")",
"except",
"NameError",
":",
"# Python 3",
"return",
"isinstance",
"(",
"val",
",",
"int",
")"
] | Return True if `val` is of integer type. | [
"Return",
"True",
"if",
"val",
"is",
"of",
"integer",
"type",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/helpers.py#L33-L38 | train | 203,548 |
jmcgeheeiv/pyfakefs | pyfakefs/helpers.py | FakeStatResult.copy | def copy(self):
"""Return a copy where the float usage is hard-coded to mimic the
behavior of the real os.stat_result.
"""
stat_result = copy(self)
stat_result.use_float = self.use_float
return stat_result | python | def copy(self):
"""Return a copy where the float usage is hard-coded to mimic the
behavior of the real os.stat_result.
"""
stat_result = copy(self)
stat_result.use_float = self.use_float
return stat_result | [
"def",
"copy",
"(",
"self",
")",
":",
"stat_result",
"=",
"copy",
"(",
"self",
")",
"stat_result",
".",
"use_float",
"=",
"self",
".",
"use_float",
"return",
"stat_result"
] | Return a copy where the float usage is hard-coded to mimic the
behavior of the real os.stat_result. | [
"Return",
"a",
"copy",
"where",
"the",
"float",
"usage",
"is",
"hard",
"-",
"coded",
"to",
"mimic",
"the",
"behavior",
"of",
"the",
"real",
"os",
".",
"stat_result",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/helpers.py#L120-L126 | train | 203,549 |
jmcgeheeiv/pyfakefs | pyfakefs/helpers.py | FakeStatResult.stat_float_times | def stat_float_times(cls, newvalue=None):
"""Determine whether a file's time stamps are reported as floats
or ints.
Calling without arguments returns the current value.
The value is shared by all instances of FakeOsModule.
Args:
newvalue: If `True`, mtime, ctime, atime are reported as floats.
Otherwise, they are returned as ints (rounding down).
"""
if newvalue is not None:
cls._stat_float_times = bool(newvalue)
return cls._stat_float_times | python | def stat_float_times(cls, newvalue=None):
"""Determine whether a file's time stamps are reported as floats
or ints.
Calling without arguments returns the current value.
The value is shared by all instances of FakeOsModule.
Args:
newvalue: If `True`, mtime, ctime, atime are reported as floats.
Otherwise, they are returned as ints (rounding down).
"""
if newvalue is not None:
cls._stat_float_times = bool(newvalue)
return cls._stat_float_times | [
"def",
"stat_float_times",
"(",
"cls",
",",
"newvalue",
"=",
"None",
")",
":",
"if",
"newvalue",
"is",
"not",
"None",
":",
"cls",
".",
"_stat_float_times",
"=",
"bool",
"(",
"newvalue",
")",
"return",
"cls",
".",
"_stat_float_times"
] | Determine whether a file's time stamps are reported as floats
or ints.
Calling without arguments returns the current value.
The value is shared by all instances of FakeOsModule.
Args:
newvalue: If `True`, mtime, ctime, atime are reported as floats.
Otherwise, they are returned as ints (rounding down). | [
"Determine",
"whether",
"a",
"file",
"s",
"time",
"stamps",
"are",
"reported",
"as",
"floats",
"or",
"ints",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/helpers.py#L147-L160 | train | 203,550 |
jmcgeheeiv/pyfakefs | pyfakefs/helpers.py | FakeStatResult.st_ctime | def st_ctime(self):
"""Return the creation time in seconds."""
ctime = self._st_ctime_ns / 1e9
return ctime if self.use_float else int(ctime) | python | def st_ctime(self):
"""Return the creation time in seconds."""
ctime = self._st_ctime_ns / 1e9
return ctime if self.use_float else int(ctime) | [
"def",
"st_ctime",
"(",
"self",
")",
":",
"ctime",
"=",
"self",
".",
"_st_ctime_ns",
"/",
"1e9",
"return",
"ctime",
"if",
"self",
".",
"use_float",
"else",
"int",
"(",
"ctime",
")"
] | Return the creation time in seconds. | [
"Return",
"the",
"creation",
"time",
"in",
"seconds",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/helpers.py#L163-L166 | train | 203,551 |
jmcgeheeiv/pyfakefs | pyfakefs/helpers.py | FakeStatResult.st_atime | def st_atime(self):
"""Return the access time in seconds."""
atime = self._st_atime_ns / 1e9
return atime if self.use_float else int(atime) | python | def st_atime(self):
"""Return the access time in seconds."""
atime = self._st_atime_ns / 1e9
return atime if self.use_float else int(atime) | [
"def",
"st_atime",
"(",
"self",
")",
":",
"atime",
"=",
"self",
".",
"_st_atime_ns",
"/",
"1e9",
"return",
"atime",
"if",
"self",
".",
"use_float",
"else",
"int",
"(",
"atime",
")"
] | Return the access time in seconds. | [
"Return",
"the",
"access",
"time",
"in",
"seconds",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/helpers.py#L169-L172 | train | 203,552 |
jmcgeheeiv/pyfakefs | pyfakefs/helpers.py | FakeStatResult.st_mtime | def st_mtime(self):
"""Return the modification time in seconds."""
mtime = self._st_mtime_ns / 1e9
return mtime if self.use_float else int(mtime) | python | def st_mtime(self):
"""Return the modification time in seconds."""
mtime = self._st_mtime_ns / 1e9
return mtime if self.use_float else int(mtime) | [
"def",
"st_mtime",
"(",
"self",
")",
":",
"mtime",
"=",
"self",
".",
"_st_mtime_ns",
"/",
"1e9",
"return",
"mtime",
"if",
"self",
".",
"use_float",
"else",
"int",
"(",
"mtime",
")"
] | Return the modification time in seconds. | [
"Return",
"the",
"modification",
"time",
"in",
"seconds",
"."
] | 6c36fb8987108107fc861fc3013620d46c7d2f9c | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/helpers.py#L175-L178 | train | 203,553 |
scopus-api/scopus | scopus/utils/get_content.py | detect_id_type | def detect_id_type(sid):
"""Method that tries to infer the type of abstract ID.
Parameters
----------
sid : str
The ID of an abstract on Scopus.
Raises
------
ValueError
If the ID type cannot be inferred.
Notes
-----
PII usually has 17 chars, but in Scopus there are valid cases with only
16 for old converted articles.
Scopus ID contains only digits, but it can have leading zeros. If ID
with leading zeros is treated as a number, SyntaxError can occur, or the
ID will be rendered invalid and the type will be misinterpreted.
"""
sid = str(sid)
if not sid.isnumeric():
if sid.startswith('2-s2.0-'):
id_type = 'eid'
elif '/' in sid:
id_type = 'doi'
elif 16 <= len(sid) <= 17:
id_type = 'pii'
elif sid.isnumeric():
if len(sid) < 10:
id_type = 'pubmed_id'
else:
id_type = 'scopus_id'
else:
raise ValueError('ID type detection failed for \'{}\'.'.format(sid))
return id_type | python | def detect_id_type(sid):
"""Method that tries to infer the type of abstract ID.
Parameters
----------
sid : str
The ID of an abstract on Scopus.
Raises
------
ValueError
If the ID type cannot be inferred.
Notes
-----
PII usually has 17 chars, but in Scopus there are valid cases with only
16 for old converted articles.
Scopus ID contains only digits, but it can have leading zeros. If ID
with leading zeros is treated as a number, SyntaxError can occur, or the
ID will be rendered invalid and the type will be misinterpreted.
"""
sid = str(sid)
if not sid.isnumeric():
if sid.startswith('2-s2.0-'):
id_type = 'eid'
elif '/' in sid:
id_type = 'doi'
elif 16 <= len(sid) <= 17:
id_type = 'pii'
elif sid.isnumeric():
if len(sid) < 10:
id_type = 'pubmed_id'
else:
id_type = 'scopus_id'
else:
raise ValueError('ID type detection failed for \'{}\'.'.format(sid))
return id_type | [
"def",
"detect_id_type",
"(",
"sid",
")",
":",
"sid",
"=",
"str",
"(",
"sid",
")",
"if",
"not",
"sid",
".",
"isnumeric",
"(",
")",
":",
"if",
"sid",
".",
"startswith",
"(",
"'2-s2.0-'",
")",
":",
"id_type",
"=",
"'eid'",
"elif",
"'/'",
"in",
"sid",... | Method that tries to infer the type of abstract ID.
Parameters
----------
sid : str
The ID of an abstract on Scopus.
Raises
------
ValueError
If the ID type cannot be inferred.
Notes
-----
PII usually has 17 chars, but in Scopus there are valid cases with only
16 for old converted articles.
Scopus ID contains only digits, but it can have leading zeros. If ID
with leading zeros is treated as a number, SyntaxError can occur, or the
ID will be rendered invalid and the type will be misinterpreted. | [
"Method",
"that",
"tries",
"to",
"infer",
"the",
"type",
"of",
"abstract",
"ID",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/utils/get_content.py#L12-L49 | train | 203,554 |
scopus-api/scopus | scopus/utils/get_content.py | download | def download(url, params=None, accept="xml", **kwds):
"""Helper function to download a file and return its content.
Parameters
----------
url : string
The URL to be parsed.
params : dict (optional)
Dictionary containing query parameters. For required keys
and accepted values see e.g.
https://api.elsevier.com/documentation/AuthorRetrievalAPI.wadl
accept : str (optional, default=xml)
mime type of the file to be downloaded. Accepted values are json,
atom+xml, xml.
kwds : key-value parings, optional
Keywords passed on to as query parameters. Must contain fields
and values specified in the respective API specification.
Raises
------
ScopusHtmlError
If the status of the response is not ok.
ValueError
If the accept parameter is not one of the accepted values.
Returns
-------
resp : byte-like object
The content of the file, which needs to be serialized.
"""
# Value check
accepted = ("json", "xml", "atom+xml")
if accept.lower() not in accepted:
raise ValueError('accept parameter must be one of ' +
', '.join(accepted))
# Get credentials
key = config.get('Authentication', 'APIKey')
header = {'X-ELS-APIKey': key}
if config.has_option('Authentication', 'InstToken'):
token = config.get('Authentication', 'InstToken')
header.update({'X-ELS-APIKey': key, 'X-ELS-Insttoken': token})
header.update({'Accept': 'application/{}'.format(accept)})
# Perform request
params.update(**kwds)
resp = requests.get(url, headers=header, params=params)
# Raise error if necessary
try:
reason = resp.reason.upper() + " for url: " + url
raise errors[resp.status_code](reason)
except KeyError: # Exception not specified in scopus
resp.raise_for_status() # Will pass when everything is ok
return resp | python | def download(url, params=None, accept="xml", **kwds):
"""Helper function to download a file and return its content.
Parameters
----------
url : string
The URL to be parsed.
params : dict (optional)
Dictionary containing query parameters. For required keys
and accepted values see e.g.
https://api.elsevier.com/documentation/AuthorRetrievalAPI.wadl
accept : str (optional, default=xml)
mime type of the file to be downloaded. Accepted values are json,
atom+xml, xml.
kwds : key-value parings, optional
Keywords passed on to as query parameters. Must contain fields
and values specified in the respective API specification.
Raises
------
ScopusHtmlError
If the status of the response is not ok.
ValueError
If the accept parameter is not one of the accepted values.
Returns
-------
resp : byte-like object
The content of the file, which needs to be serialized.
"""
# Value check
accepted = ("json", "xml", "atom+xml")
if accept.lower() not in accepted:
raise ValueError('accept parameter must be one of ' +
', '.join(accepted))
# Get credentials
key = config.get('Authentication', 'APIKey')
header = {'X-ELS-APIKey': key}
if config.has_option('Authentication', 'InstToken'):
token = config.get('Authentication', 'InstToken')
header.update({'X-ELS-APIKey': key, 'X-ELS-Insttoken': token})
header.update({'Accept': 'application/{}'.format(accept)})
# Perform request
params.update(**kwds)
resp = requests.get(url, headers=header, params=params)
# Raise error if necessary
try:
reason = resp.reason.upper() + " for url: " + url
raise errors[resp.status_code](reason)
except KeyError: # Exception not specified in scopus
resp.raise_for_status() # Will pass when everything is ok
return resp | [
"def",
"download",
"(",
"url",
",",
"params",
"=",
"None",
",",
"accept",
"=",
"\"xml\"",
",",
"*",
"*",
"kwds",
")",
":",
"# Value check",
"accepted",
"=",
"(",
"\"json\"",
",",
"\"xml\"",
",",
"\"atom+xml\"",
")",
"if",
"accept",
".",
"lower",
"(",
... | Helper function to download a file and return its content.
Parameters
----------
url : string
The URL to be parsed.
params : dict (optional)
Dictionary containing query parameters. For required keys
and accepted values see e.g.
https://api.elsevier.com/documentation/AuthorRetrievalAPI.wadl
accept : str (optional, default=xml)
mime type of the file to be downloaded. Accepted values are json,
atom+xml, xml.
kwds : key-value parings, optional
Keywords passed on to as query parameters. Must contain fields
and values specified in the respective API specification.
Raises
------
ScopusHtmlError
If the status of the response is not ok.
ValueError
If the accept parameter is not one of the accepted values.
Returns
-------
resp : byte-like object
The content of the file, which needs to be serialized. | [
"Helper",
"function",
"to",
"download",
"a",
"file",
"and",
"return",
"its",
"content",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/utils/get_content.py#L52-L107 | train | 203,555 |
scopus-api/scopus | scopus/affiliation_retrieval.py | ContentAffiliationRetrieval.name_variants | def name_variants(self):
"""A list of namedtuples representing variants of the affiliation name
with number of documents referring to this variant.
"""
out = []
variant = namedtuple('Variant', 'name doc_count')
for var in chained_get(self._json, ['name-variants', 'name-variant'], []):
new = variant(name=var['$'], doc_count=var.get('@doc-count'))
out.append(new)
return out | python | def name_variants(self):
"""A list of namedtuples representing variants of the affiliation name
with number of documents referring to this variant.
"""
out = []
variant = namedtuple('Variant', 'name doc_count')
for var in chained_get(self._json, ['name-variants', 'name-variant'], []):
new = variant(name=var['$'], doc_count=var.get('@doc-count'))
out.append(new)
return out | [
"def",
"name_variants",
"(",
"self",
")",
":",
"out",
"=",
"[",
"]",
"variant",
"=",
"namedtuple",
"(",
"'Variant'",
",",
"'name doc_count'",
")",
"for",
"var",
"in",
"chained_get",
"(",
"self",
".",
"_json",
",",
"[",
"'name-variants'",
",",
"'name-varian... | A list of namedtuples representing variants of the affiliation name
with number of documents referring to this variant. | [
"A",
"list",
"of",
"namedtuples",
"representing",
"variants",
"of",
"the",
"affiliation",
"name",
"with",
"number",
"of",
"documents",
"referring",
"to",
"this",
"variant",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/affiliation_retrieval.py#L54-L63 | train | 203,556 |
scopus-api/scopus | scopus/deprecated_/scopus_affiliation.py | ScopusAffiliation.url | def url(self):
"""URL to the affiliation's profile page."""
url = self.xml.find('coredata/link[@rel="scopus-affiliation"]')
if url is not None:
url = url.get('href')
return url | python | def url(self):
"""URL to the affiliation's profile page."""
url = self.xml.find('coredata/link[@rel="scopus-affiliation"]')
if url is not None:
url = url.get('href')
return url | [
"def",
"url",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"xml",
".",
"find",
"(",
"'coredata/link[@rel=\"scopus-affiliation\"]'",
")",
"if",
"url",
"is",
"not",
"None",
":",
"url",
"=",
"url",
".",
"get",
"(",
"'href'",
")",
"return",
"url"
] | URL to the affiliation's profile page. | [
"URL",
"to",
"the",
"affiliation",
"s",
"profile",
"page",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_affiliation.py#L43-L48 | train | 203,557 |
scopus-api/scopus | scopus/utils/parse_content.py | parse_date_created | def parse_date_created(dct):
"""Helper function to parse date-created from profile."""
date = dct['date-created']
if date:
return (int(date['@year']), int(date['@month']), int(date['@day']))
else:
return (None, None, None) | python | def parse_date_created(dct):
"""Helper function to parse date-created from profile."""
date = dct['date-created']
if date:
return (int(date['@year']), int(date['@month']), int(date['@day']))
else:
return (None, None, None) | [
"def",
"parse_date_created",
"(",
"dct",
")",
":",
"date",
"=",
"dct",
"[",
"'date-created'",
"]",
"if",
"date",
":",
"return",
"(",
"int",
"(",
"date",
"[",
"'@year'",
"]",
")",
",",
"int",
"(",
"date",
"[",
"'@month'",
"]",
")",
",",
"int",
"(",
... | Helper function to parse date-created from profile. | [
"Helper",
"function",
"to",
"parse",
"date",
"-",
"created",
"from",
"profile",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/utils/parse_content.py#L43-L49 | train | 203,558 |
scopus-api/scopus | scopus/author_retrieval.py | AuthorRetrieval.affiliation_history | def affiliation_history(self):
"""Unordered list of IDs of all affiliations the author was
affiliated with acccording to Scopus.
"""
affs = self._json.get('affiliation-history', {}).get('affiliation')
try:
return [d['@id'] for d in affs]
except TypeError: # No affiliation history
return None | python | def affiliation_history(self):
"""Unordered list of IDs of all affiliations the author was
affiliated with acccording to Scopus.
"""
affs = self._json.get('affiliation-history', {}).get('affiliation')
try:
return [d['@id'] for d in affs]
except TypeError: # No affiliation history
return None | [
"def",
"affiliation_history",
"(",
"self",
")",
":",
"affs",
"=",
"self",
".",
"_json",
".",
"get",
"(",
"'affiliation-history'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'affiliation'",
")",
"try",
":",
"return",
"[",
"d",
"[",
"'@id'",
"]",
"for",
"d"... | Unordered list of IDs of all affiliations the author was
affiliated with acccording to Scopus. | [
"Unordered",
"list",
"of",
"IDs",
"of",
"all",
"affiliations",
"the",
"author",
"was",
"affiliated",
"with",
"acccording",
"to",
"Scopus",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/author_retrieval.py#L19-L27 | train | 203,559 |
scopus-api/scopus | scopus/author_retrieval.py | AuthorRetrieval.historical_identifier | def historical_identifier(self):
"""Scopus IDs of previous profiles now compromising this profile."""
hist = chained_get(self._json, ["coredata", 'historical-identifier'], [])
return [d['$'].split(":")[-1] for d in hist] or None | python | def historical_identifier(self):
"""Scopus IDs of previous profiles now compromising this profile."""
hist = chained_get(self._json, ["coredata", 'historical-identifier'], [])
return [d['$'].split(":")[-1] for d in hist] or None | [
"def",
"historical_identifier",
"(",
"self",
")",
":",
"hist",
"=",
"chained_get",
"(",
"self",
".",
"_json",
",",
"[",
"\"coredata\"",
",",
"'historical-identifier'",
"]",
",",
"[",
"]",
")",
"return",
"[",
"d",
"[",
"'$'",
"]",
".",
"split",
"(",
"\"... | Scopus IDs of previous profiles now compromising this profile. | [
"Scopus",
"IDs",
"of",
"previous",
"profiles",
"now",
"compromising",
"this",
"profile",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/author_retrieval.py#L85-L88 | train | 203,560 |
scopus-api/scopus | scopus/author_retrieval.py | AuthorRetrieval.identifier | def identifier(self):
"""The author's ID. Might differ from the one provided."""
ident = self._json['coredata']['dc:identifier'].split(":")[-1]
if ident != self._id:
text = "Profile with ID {} has been merged and the new ID is "\
"{}. Please update your records manually. Files have "\
"been cached with the old ID.".format(self._id, ident)
warn(text, UserWarning)
return ident | python | def identifier(self):
"""The author's ID. Might differ from the one provided."""
ident = self._json['coredata']['dc:identifier'].split(":")[-1]
if ident != self._id:
text = "Profile with ID {} has been merged and the new ID is "\
"{}. Please update your records manually. Files have "\
"been cached with the old ID.".format(self._id, ident)
warn(text, UserWarning)
return ident | [
"def",
"identifier",
"(",
"self",
")",
":",
"ident",
"=",
"self",
".",
"_json",
"[",
"'coredata'",
"]",
"[",
"'dc:identifier'",
"]",
".",
"split",
"(",
"\":\"",
")",
"[",
"-",
"1",
"]",
"if",
"ident",
"!=",
"self",
".",
"_id",
":",
"text",
"=",
"... | The author's ID. Might differ from the one provided. | [
"The",
"author",
"s",
"ID",
".",
"Might",
"differ",
"from",
"the",
"one",
"provided",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/author_retrieval.py#L91-L99 | train | 203,561 |
scopus-api/scopus | scopus/author_retrieval.py | AuthorRetrieval.name_variants | def name_variants(self):
"""List of named tuples containing variants of the author name with
number of documents published with that variant.
"""
fields = 'indexed_name initials surname given_name doc_count'
variant = namedtuple('Variant', fields)
path = ['author-profile', 'name-variant']
out = [variant(indexed_name=var['indexed-name'], surname=var['surname'],
doc_count=var.get('@doc-count'), initials=var['initials'],
given_name=var.get('given-name'))
for var in listify(chained_get(self._json, path, []))]
return out or None | python | def name_variants(self):
"""List of named tuples containing variants of the author name with
number of documents published with that variant.
"""
fields = 'indexed_name initials surname given_name doc_count'
variant = namedtuple('Variant', fields)
path = ['author-profile', 'name-variant']
out = [variant(indexed_name=var['indexed-name'], surname=var['surname'],
doc_count=var.get('@doc-count'), initials=var['initials'],
given_name=var.get('given-name'))
for var in listify(chained_get(self._json, path, []))]
return out or None | [
"def",
"name_variants",
"(",
"self",
")",
":",
"fields",
"=",
"'indexed_name initials surname given_name doc_count'",
"variant",
"=",
"namedtuple",
"(",
"'Variant'",
",",
"fields",
")",
"path",
"=",
"[",
"'author-profile'",
",",
"'name-variant'",
"]",
"out",
"=",
... | List of named tuples containing variants of the author name with
number of documents published with that variant. | [
"List",
"of",
"named",
"tuples",
"containing",
"variants",
"of",
"the",
"author",
"name",
"with",
"number",
"of",
"documents",
"published",
"with",
"that",
"variant",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/author_retrieval.py#L128-L139 | train | 203,562 |
scopus-api/scopus | scopus/author_retrieval.py | AuthorRetrieval.publication_range | def publication_range(self):
"""Tuple containing years of first and last publication."""
r = self._json['author-profile']['publication-range']
return (r['@start'], r['@end'])
return self._json['coredata'].get('orcid') | python | def publication_range(self):
"""Tuple containing years of first and last publication."""
r = self._json['author-profile']['publication-range']
return (r['@start'], r['@end'])
return self._json['coredata'].get('orcid') | [
"def",
"publication_range",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"_json",
"[",
"'author-profile'",
"]",
"[",
"'publication-range'",
"]",
"return",
"(",
"r",
"[",
"'@start'",
"]",
",",
"r",
"[",
"'@end'",
"]",
")",
"return",
"self",
".",
"_json... | Tuple containing years of first and last publication. | [
"Tuple",
"containing",
"years",
"of",
"first",
"and",
"last",
"publication",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/author_retrieval.py#L147-L151 | train | 203,563 |
scopus-api/scopus | scopus/author_retrieval.py | AuthorRetrieval.get_documents | def get_documents(self, subtypes=None, refresh=False):
"""Return list of author's publications using ScopusSearch, which
fit a specified set of document subtypes.
"""
search = ScopusSearch('au-id({})'.format(self.identifier), refresh)
if subtypes:
return [p for p in search.results if p.subtype in subtypes]
else:
return search.results | python | def get_documents(self, subtypes=None, refresh=False):
"""Return list of author's publications using ScopusSearch, which
fit a specified set of document subtypes.
"""
search = ScopusSearch('au-id({})'.format(self.identifier), refresh)
if subtypes:
return [p for p in search.results if p.subtype in subtypes]
else:
return search.results | [
"def",
"get_documents",
"(",
"self",
",",
"subtypes",
"=",
"None",
",",
"refresh",
"=",
"False",
")",
":",
"search",
"=",
"ScopusSearch",
"(",
"'au-id({})'",
".",
"format",
"(",
"self",
".",
"identifier",
")",
",",
"refresh",
")",
"if",
"subtypes",
":",
... | Return list of author's publications using ScopusSearch, which
fit a specified set of document subtypes. | [
"Return",
"list",
"of",
"author",
"s",
"publications",
"using",
"ScopusSearch",
"which",
"fit",
"a",
"specified",
"set",
"of",
"document",
"subtypes",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/author_retrieval.py#L280-L288 | train | 203,564 |
scopus-api/scopus | scopus/scopus_search.py | _deduplicate | def _deduplicate(lst):
"""Auxiliary function to deduplicate lst."""
out = []
for i in lst:
if i not in out:
out.append(i)
return out | python | def _deduplicate(lst):
"""Auxiliary function to deduplicate lst."""
out = []
for i in lst:
if i not in out:
out.append(i)
return out | [
"def",
"_deduplicate",
"(",
"lst",
")",
":",
"out",
"=",
"[",
"]",
"for",
"i",
"in",
"lst",
":",
"if",
"i",
"not",
"in",
"out",
":",
"out",
".",
"append",
"(",
"i",
")",
"return",
"out"
] | Auxiliary function to deduplicate lst. | [
"Auxiliary",
"function",
"to",
"deduplicate",
"lst",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/scopus_search.py#L187-L193 | train | 203,565 |
scopus-api/scopus | scopus/scopus_search.py | _join | def _join(lst, key, sep=";"):
"""Auxiliary function to join same elements of a list of dictionaries if
the elements are not None.
"""
return sep.join([d[key] for d in lst if d[key]]) | python | def _join(lst, key, sep=";"):
"""Auxiliary function to join same elements of a list of dictionaries if
the elements are not None.
"""
return sep.join([d[key] for d in lst if d[key]]) | [
"def",
"_join",
"(",
"lst",
",",
"key",
",",
"sep",
"=",
"\";\"",
")",
":",
"return",
"sep",
".",
"join",
"(",
"[",
"d",
"[",
"key",
"]",
"for",
"d",
"in",
"lst",
"if",
"d",
"[",
"key",
"]",
"]",
")"
] | Auxiliary function to join same elements of a list of dictionaries if
the elements are not None. | [
"Auxiliary",
"function",
"to",
"join",
"same",
"elements",
"of",
"a",
"list",
"of",
"dictionaries",
"if",
"the",
"elements",
"are",
"not",
"None",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/scopus_search.py#L196-L200 | train | 203,566 |
scopus-api/scopus | scopus/deprecated_/scopus_api.py | ScopusAbstract.authors | def authors(self):
"""A list of scopus_api._ScopusAuthor objects."""
authors = self.xml.find('authors', ns)
try:
return [_ScopusAuthor(author) for author in authors]
except TypeError:
return None | python | def authors(self):
"""A list of scopus_api._ScopusAuthor objects."""
authors = self.xml.find('authors', ns)
try:
return [_ScopusAuthor(author) for author in authors]
except TypeError:
return None | [
"def",
"authors",
"(",
"self",
")",
":",
"authors",
"=",
"self",
".",
"xml",
".",
"find",
"(",
"'authors'",
",",
"ns",
")",
"try",
":",
"return",
"[",
"_ScopusAuthor",
"(",
"author",
")",
"for",
"author",
"in",
"authors",
"]",
"except",
"TypeError",
... | A list of scopus_api._ScopusAuthor objects. | [
"A",
"list",
"of",
"scopus_api",
".",
"_ScopusAuthor",
"objects",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_api.py#L52-L58 | train | 203,567 |
scopus-api/scopus | scopus/deprecated_/scopus_api.py | ScopusAbstract.citedby_url | def citedby_url(self):
"""URL to Scopus page listing citing papers."""
cite_link = self.coredata.find('link[@rel="scopus-citedby"]', ns)
try:
return cite_link.get('href')
except AttributeError: # cite_link is None
return None | python | def citedby_url(self):
"""URL to Scopus page listing citing papers."""
cite_link = self.coredata.find('link[@rel="scopus-citedby"]', ns)
try:
return cite_link.get('href')
except AttributeError: # cite_link is None
return None | [
"def",
"citedby_url",
"(",
"self",
")",
":",
"cite_link",
"=",
"self",
".",
"coredata",
".",
"find",
"(",
"'link[@rel=\"scopus-citedby\"]'",
",",
"ns",
")",
"try",
":",
"return",
"cite_link",
".",
"get",
"(",
"'href'",
")",
"except",
"AttributeError",
":",
... | URL to Scopus page listing citing papers. | [
"URL",
"to",
"Scopus",
"page",
"listing",
"citing",
"papers",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_api.py#L84-L90 | train | 203,568 |
scopus-api/scopus | scopus/deprecated_/scopus_api.py | ScopusAbstract.scopus_url | def scopus_url(self):
"""URL to the abstract page on Scopus."""
scopus_url = self.coredata.find('link[@rel="scopus"]', ns)
try:
return scopus_url.get('href')
except AttributeError: # scopus_url is None
return None | python | def scopus_url(self):
"""URL to the abstract page on Scopus."""
scopus_url = self.coredata.find('link[@rel="scopus"]', ns)
try:
return scopus_url.get('href')
except AttributeError: # scopus_url is None
return None | [
"def",
"scopus_url",
"(",
"self",
")",
":",
"scopus_url",
"=",
"self",
".",
"coredata",
".",
"find",
"(",
"'link[@rel=\"scopus\"]'",
",",
"ns",
")",
"try",
":",
"return",
"scopus_url",
".",
"get",
"(",
"'href'",
")",
"except",
"AttributeError",
":",
"# sco... | URL to the abstract page on Scopus. | [
"URL",
"to",
"the",
"abstract",
"page",
"on",
"Scopus",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_api.py#L203-L209 | train | 203,569 |
scopus-api/scopus | scopus/deprecated_/scopus_api.py | ScopusAbstract.get_corresponding_author_info | def get_corresponding_author_info(self):
"""Try to get corresponding author information.
Returns (scopus-id, name, email).
"""
resp = requests.get(self.scopus_url)
from lxml import html
parsed_doc = html.fromstring(resp.content)
for div in parsed_doc.body.xpath('.//div'):
for a in div.xpath('a'):
if '/cdn-cgi/l/email-protection' not in a.get('href', ''):
continue
encoded_text = a.attrib['href'].replace('/cdn-cgi/l/email-protection#', '')
key = int(encoded_text[0:2], 16)
email = ''.join([chr(int('0x{}'.format(x), 16) ^ key)
for x in
map(''.join, zip(*[iter(encoded_text[2:])]*2))])
for aa in div.xpath('a'):
if 'http://www.scopus.com/authid/detail.url' in aa.get('href', ''):
scopus_url = aa.attrib['href']
name = aa.text
else:
scopus_url, name = None, None
return (scopus_url, name, email) | python | def get_corresponding_author_info(self):
"""Try to get corresponding author information.
Returns (scopus-id, name, email).
"""
resp = requests.get(self.scopus_url)
from lxml import html
parsed_doc = html.fromstring(resp.content)
for div in parsed_doc.body.xpath('.//div'):
for a in div.xpath('a'):
if '/cdn-cgi/l/email-protection' not in a.get('href', ''):
continue
encoded_text = a.attrib['href'].replace('/cdn-cgi/l/email-protection#', '')
key = int(encoded_text[0:2], 16)
email = ''.join([chr(int('0x{}'.format(x), 16) ^ key)
for x in
map(''.join, zip(*[iter(encoded_text[2:])]*2))])
for aa in div.xpath('a'):
if 'http://www.scopus.com/authid/detail.url' in aa.get('href', ''):
scopus_url = aa.attrib['href']
name = aa.text
else:
scopus_url, name = None, None
return (scopus_url, name, email) | [
"def",
"get_corresponding_author_info",
"(",
"self",
")",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"scopus_url",
")",
"from",
"lxml",
"import",
"html",
"parsed_doc",
"=",
"html",
".",
"fromstring",
"(",
"resp",
".",
"content",
")",
"for"... | Try to get corresponding author information.
Returns (scopus-id, name, email). | [
"Try",
"to",
"get",
"corresponding",
"author",
"information",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_api.py#L283-L308 | train | 203,570 |
scopus-api/scopus | scopus/deprecated_/scopus_api.py | ScopusAbstract.latex | def latex(self):
"""Return LaTeX representation of the abstract."""
s = ('{authors}, \\textit{{{title}}}, {journal}, {volissue}, '
'{pages}, ({date}). {doi}, {scopus_url}.')
if len(self.authors) > 1:
authors = ', '.join([str(a.given_name) +
' ' + str(a.surname)
for a in self.authors[0:-1]])
authors += (' and ' +
str(self.authors[-1].given_name) +
' ' + str(self.authors[-1].surname))
else:
a = self.authors[0]
authors = str(a.given_name) + ' ' + str(a.surname)
title = self.title
journal = self.publicationName
volume = self.volume
issue = self.issueIdentifier
if volume and issue:
volissue = '\\textbf{{{0}({1})}}'.format(volume, issue)
elif volume:
volissue = '\\textbf{{0}}'.format(volume)
else:
volissue = 'no volume'
date = self.coverDate
if self.pageRange:
pages = 'p. {0}'.format(self.pageRange)
elif self.startingPage:
pages = 'p. {self.startingPage}'.format(self)
elif self.article_number:
pages = 'Art. No. {self.article_number}, '.format(self)
else:
pages = '(no pages found)'
doi = '\\href{{https://doi.org/{0}}}{{doi:{0}}}'.format(self.doi)
scopus_url = '\\href{{{0}}}{{scopus:{1}}}'.format(self.scopus_url,
self.eid)
return s.format(**locals()) | python | def latex(self):
"""Return LaTeX representation of the abstract."""
s = ('{authors}, \\textit{{{title}}}, {journal}, {volissue}, '
'{pages}, ({date}). {doi}, {scopus_url}.')
if len(self.authors) > 1:
authors = ', '.join([str(a.given_name) +
' ' + str(a.surname)
for a in self.authors[0:-1]])
authors += (' and ' +
str(self.authors[-1].given_name) +
' ' + str(self.authors[-1].surname))
else:
a = self.authors[0]
authors = str(a.given_name) + ' ' + str(a.surname)
title = self.title
journal = self.publicationName
volume = self.volume
issue = self.issueIdentifier
if volume and issue:
volissue = '\\textbf{{{0}({1})}}'.format(volume, issue)
elif volume:
volissue = '\\textbf{{0}}'.format(volume)
else:
volissue = 'no volume'
date = self.coverDate
if self.pageRange:
pages = 'p. {0}'.format(self.pageRange)
elif self.startingPage:
pages = 'p. {self.startingPage}'.format(self)
elif self.article_number:
pages = 'Art. No. {self.article_number}, '.format(self)
else:
pages = '(no pages found)'
doi = '\\href{{https://doi.org/{0}}}{{doi:{0}}}'.format(self.doi)
scopus_url = '\\href{{{0}}}{{scopus:{1}}}'.format(self.scopus_url,
self.eid)
return s.format(**locals()) | [
"def",
"latex",
"(",
"self",
")",
":",
"s",
"=",
"(",
"'{authors}, \\\\textit{{{title}}}, {journal}, {volissue}, '",
"'{pages}, ({date}). {doi}, {scopus_url}.'",
")",
"if",
"len",
"(",
"self",
".",
"authors",
")",
">",
"1",
":",
"authors",
"=",
"', '",
".",
"join"... | Return LaTeX representation of the abstract. | [
"Return",
"LaTeX",
"representation",
"of",
"the",
"abstract",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_api.py#L359-L396 | train | 203,571 |
scopus-api/scopus | scopus/deprecated_/scopus_api.py | ScopusAbstract.html | def html(self):
"""Returns an HTML citation."""
s = (u'{authors}, {title}, {journal}, {volissue}, {pages}, '
'({date}). {doi}.')
au_link = ('<a href="https://www.scopus.com/authid/detail.url'
'?origin=AuthorProfile&authorId={0}">{1}</a>')
if len(self.authors) > 1:
authors = u', '.join([au_link.format(a.auid,
(str(a.given_name) +
' ' + str(a.surname)))
for a in self.authors[0:-1]])
authors += (u' and ' +
au_link.format(self.authors[-1].auid,
(str(self.authors[-1].given_name) +
' ' +
str(self.authors[-1].surname))))
else:
a = self.authors[0]
authors = au_link.format(a.auid,
str(a.given_name) + ' ' + str(a.surname))
title = u'<a href="{link}">{title}</a>'.format(link=self.scopus_url,
title=self.title)
jname = self.publicationName
sid = self.source_id
jlink = ('<a href="https://www.scopus.com/source/sourceInfo.url'
'?sourceId={sid}">{journal}</a>')
journal = jlink.format(sid=sid, journal=jname)
volume = self.volume
issue = self.issueIdentifier
if volume and issue:
volissue = u'<b>{0}({1})</b>'.format(volume, issue)
elif volume:
volissue = u'<b>{0}</b>'.format(volume)
else:
volissue = 'no volume'
date = self.coverDate
if self.pageRange:
pages = u'p. {0}'.format(self.pageRange)
elif self.startingPage:
pages = u'p. {self.startingPage}'.format(self=self)
elif self.article_number:
pages = u'Art. No. {self.article_number}, '.format(self=self)
else:
pages = '(no pages found)'
doi = '<a href="https://doi.org/{0}">doi:{0}</a>'.format(self.doi)
html = s.format(**locals())
return html.replace('None', '') | python | def html(self):
"""Returns an HTML citation."""
s = (u'{authors}, {title}, {journal}, {volissue}, {pages}, '
'({date}). {doi}.')
au_link = ('<a href="https://www.scopus.com/authid/detail.url'
'?origin=AuthorProfile&authorId={0}">{1}</a>')
if len(self.authors) > 1:
authors = u', '.join([au_link.format(a.auid,
(str(a.given_name) +
' ' + str(a.surname)))
for a in self.authors[0:-1]])
authors += (u' and ' +
au_link.format(self.authors[-1].auid,
(str(self.authors[-1].given_name) +
' ' +
str(self.authors[-1].surname))))
else:
a = self.authors[0]
authors = au_link.format(a.auid,
str(a.given_name) + ' ' + str(a.surname))
title = u'<a href="{link}">{title}</a>'.format(link=self.scopus_url,
title=self.title)
jname = self.publicationName
sid = self.source_id
jlink = ('<a href="https://www.scopus.com/source/sourceInfo.url'
'?sourceId={sid}">{journal}</a>')
journal = jlink.format(sid=sid, journal=jname)
volume = self.volume
issue = self.issueIdentifier
if volume and issue:
volissue = u'<b>{0}({1})</b>'.format(volume, issue)
elif volume:
volissue = u'<b>{0}</b>'.format(volume)
else:
volissue = 'no volume'
date = self.coverDate
if self.pageRange:
pages = u'p. {0}'.format(self.pageRange)
elif self.startingPage:
pages = u'p. {self.startingPage}'.format(self=self)
elif self.article_number:
pages = u'Art. No. {self.article_number}, '.format(self=self)
else:
pages = '(no pages found)'
doi = '<a href="https://doi.org/{0}">doi:{0}</a>'.format(self.doi)
html = s.format(**locals())
return html.replace('None', '') | [
"def",
"html",
"(",
"self",
")",
":",
"s",
"=",
"(",
"u'{authors}, {title}, {journal}, {volissue}, {pages}, '",
"'({date}). {doi}.'",
")",
"au_link",
"=",
"(",
"'<a href=\"https://www.scopus.com/authid/detail.url'",
"'?origin=AuthorProfile&authorId={0}\">{1}</a>'",
")",
"if",
"... | Returns an HTML citation. | [
"Returns",
"an",
"HTML",
"citation",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_api.py#L399-L451 | train | 203,572 |
scopus-api/scopus | scopus/abstract_citations.py | CitationOverview.cc | def cc(self):
"""List of tuples of yearly number of citations
for specified years."""
_years = range(self._start, self._end+1)
try:
return list(zip(_years, [d.get('$') for d in self._citeInfoMatrix['cc']]))
except AttributeError: # No citations
return list(zip(_years, [0]*len(_years))) | python | def cc(self):
"""List of tuples of yearly number of citations
for specified years."""
_years = range(self._start, self._end+1)
try:
return list(zip(_years, [d.get('$') for d in self._citeInfoMatrix['cc']]))
except AttributeError: # No citations
return list(zip(_years, [0]*len(_years))) | [
"def",
"cc",
"(",
"self",
")",
":",
"_years",
"=",
"range",
"(",
"self",
".",
"_start",
",",
"self",
".",
"_end",
"+",
"1",
")",
"try",
":",
"return",
"list",
"(",
"zip",
"(",
"_years",
",",
"[",
"d",
".",
"get",
"(",
"'$'",
")",
"for",
"d",
... | List of tuples of yearly number of citations
for specified years. | [
"List",
"of",
"tuples",
"of",
"yearly",
"number",
"of",
"citations",
"for",
"specified",
"years",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/abstract_citations.py#L28-L35 | train | 203,573 |
scopus-api/scopus | scopus/deprecated_/scopus_author.py | ScopusAuthor.affiliation_history | def affiliation_history(self):
"""List of ScopusAffiliation objects representing former
affiliations of the author. Only affiliations with more than one
publication are considered.
"""
aff_ids = [e.attrib.get('affiliation-id') for e in
self.xml.findall('author-profile/affiliation-history/affiliation')
if e is not None and len(list(e.find("ip-doc").iter())) > 1]
return [ScopusAffiliation(aff_id) for aff_id in aff_ids] | python | def affiliation_history(self):
"""List of ScopusAffiliation objects representing former
affiliations of the author. Only affiliations with more than one
publication are considered.
"""
aff_ids = [e.attrib.get('affiliation-id') for e in
self.xml.findall('author-profile/affiliation-history/affiliation')
if e is not None and len(list(e.find("ip-doc").iter())) > 1]
return [ScopusAffiliation(aff_id) for aff_id in aff_ids] | [
"def",
"affiliation_history",
"(",
"self",
")",
":",
"aff_ids",
"=",
"[",
"e",
".",
"attrib",
".",
"get",
"(",
"'affiliation-id'",
")",
"for",
"e",
"in",
"self",
".",
"xml",
".",
"findall",
"(",
"'author-profile/affiliation-history/affiliation'",
")",
"if",
... | List of ScopusAffiliation objects representing former
affiliations of the author. Only affiliations with more than one
publication are considered. | [
"List",
"of",
"ScopusAffiliation",
"objects",
"representing",
"former",
"affiliations",
"of",
"the",
"author",
".",
"Only",
"affiliations",
"with",
"more",
"than",
"one",
"publication",
"are",
"considered",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_author.py#L71-L79 | train | 203,574 |
scopus-api/scopus | scopus/deprecated_/scopus_author.py | ScopusAuthor.get_coauthors | def get_coauthors(self):
"""Return list of coauthors, their scopus-id and research areas."""
url = self.xml.find('coredata/link[@rel="coauthor-search"]').get('href')
xml = download(url=url).text.encode('utf-8')
xml = ET.fromstring(xml)
coauthors = []
N = int(get_encoded_text(xml, 'opensearch:totalResults') or 0)
AUTHOR = namedtuple('Author',
['name', 'scopus_id', 'affiliation', 'categories'])
count = 0
while count < N:
params = {'start': count, 'count': 25}
xml = download(url=url, params=params).text.encode('utf-8')
xml = ET.fromstring(xml)
for entry in xml.findall('atom:entry', ns):
given_name = get_encoded_text(entry,
'atom:preferred-name/atom:given-name')
surname = get_encoded_text(entry,
'atom:preferred-name/atom:surname')
coauthor_name = u'{0} {1}'.format(given_name, surname)
scopus_id = get_encoded_text(entry,
'dc:identifier').replace('AUTHOR_ID:', '')
affiliation = get_encoded_text(entry,
'atom:affiliation-current/atom:affiliation-name')
# get categories for this author
s = u', '.join(['{0} ({1})'.format(subject.text,
subject.attrib['frequency'])
for subject in
entry.findall('atom:subject-area', ns)])
coauthors += [AUTHOR(coauthor_name, scopus_id, affiliation, s)]
count += 25
return coauthors | python | def get_coauthors(self):
"""Return list of coauthors, their scopus-id and research areas."""
url = self.xml.find('coredata/link[@rel="coauthor-search"]').get('href')
xml = download(url=url).text.encode('utf-8')
xml = ET.fromstring(xml)
coauthors = []
N = int(get_encoded_text(xml, 'opensearch:totalResults') or 0)
AUTHOR = namedtuple('Author',
['name', 'scopus_id', 'affiliation', 'categories'])
count = 0
while count < N:
params = {'start': count, 'count': 25}
xml = download(url=url, params=params).text.encode('utf-8')
xml = ET.fromstring(xml)
for entry in xml.findall('atom:entry', ns):
given_name = get_encoded_text(entry,
'atom:preferred-name/atom:given-name')
surname = get_encoded_text(entry,
'atom:preferred-name/atom:surname')
coauthor_name = u'{0} {1}'.format(given_name, surname)
scopus_id = get_encoded_text(entry,
'dc:identifier').replace('AUTHOR_ID:', '')
affiliation = get_encoded_text(entry,
'atom:affiliation-current/atom:affiliation-name')
# get categories for this author
s = u', '.join(['{0} ({1})'.format(subject.text,
subject.attrib['frequency'])
for subject in
entry.findall('atom:subject-area', ns)])
coauthors += [AUTHOR(coauthor_name, scopus_id, affiliation, s)]
count += 25
return coauthors | [
"def",
"get_coauthors",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"xml",
".",
"find",
"(",
"'coredata/link[@rel=\"coauthor-search\"]'",
")",
".",
"get",
"(",
"'href'",
")",
"xml",
"=",
"download",
"(",
"url",
"=",
"url",
")",
".",
"text",
".",
"e... | Return list of coauthors, their scopus-id and research areas. | [
"Return",
"list",
"of",
"coauthors",
"their",
"scopus",
"-",
"id",
"and",
"research",
"areas",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_author.py#L214-L254 | train | 203,575 |
scopus-api/scopus | scopus/deprecated_/scopus_author.py | ScopusAuthor.get_document_eids | def get_document_eids(self, *args, **kwds):
"""Return list of EIDs for the author using ScopusSearch."""
search = ScopusSearch('au-id({})'.format(self.author_id),
*args, **kwds)
return search.get_eids() | python | def get_document_eids(self, *args, **kwds):
"""Return list of EIDs for the author using ScopusSearch."""
search = ScopusSearch('au-id({})'.format(self.author_id),
*args, **kwds)
return search.get_eids() | [
"def",
"get_document_eids",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"search",
"=",
"ScopusSearch",
"(",
"'au-id({})'",
".",
"format",
"(",
"self",
".",
"author_id",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"return",
... | Return list of EIDs for the author using ScopusSearch. | [
"Return",
"list",
"of",
"EIDs",
"for",
"the",
"author",
"using",
"ScopusSearch",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_author.py#L256-L260 | train | 203,576 |
scopus-api/scopus | scopus/deprecated_/scopus_author.py | ScopusAuthor.get_abstracts | def get_abstracts(self, refresh=True):
"""Return a list of ScopusAbstract objects using ScopusSearch."""
return [ScopusAbstract(eid, refresh=refresh)
for eid in self.get_document_eids(refresh=refresh)] | python | def get_abstracts(self, refresh=True):
"""Return a list of ScopusAbstract objects using ScopusSearch."""
return [ScopusAbstract(eid, refresh=refresh)
for eid in self.get_document_eids(refresh=refresh)] | [
"def",
"get_abstracts",
"(",
"self",
",",
"refresh",
"=",
"True",
")",
":",
"return",
"[",
"ScopusAbstract",
"(",
"eid",
",",
"refresh",
"=",
"refresh",
")",
"for",
"eid",
"in",
"self",
".",
"get_document_eids",
"(",
"refresh",
"=",
"refresh",
")",
"]"
] | Return a list of ScopusAbstract objects using ScopusSearch. | [
"Return",
"a",
"list",
"of",
"ScopusAbstract",
"objects",
"using",
"ScopusSearch",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_author.py#L262-L265 | train | 203,577 |
scopus-api/scopus | scopus/deprecated_/scopus_author.py | ScopusAuthor.get_journal_abstracts | def get_journal_abstracts(self, refresh=True):
"""Return a list of ScopusAbstract objects using ScopusSearch,
but only if belonging to a Journal."""
return [abstract for abstract in self.get_abstracts(refresh=refresh) if
abstract.aggregationType == 'Journal'] | python | def get_journal_abstracts(self, refresh=True):
"""Return a list of ScopusAbstract objects using ScopusSearch,
but only if belonging to a Journal."""
return [abstract for abstract in self.get_abstracts(refresh=refresh) if
abstract.aggregationType == 'Journal'] | [
"def",
"get_journal_abstracts",
"(",
"self",
",",
"refresh",
"=",
"True",
")",
":",
"return",
"[",
"abstract",
"for",
"abstract",
"in",
"self",
".",
"get_abstracts",
"(",
"refresh",
"=",
"refresh",
")",
"if",
"abstract",
".",
"aggregationType",
"==",
"'Journ... | Return a list of ScopusAbstract objects using ScopusSearch,
but only if belonging to a Journal. | [
"Return",
"a",
"list",
"of",
"ScopusAbstract",
"objects",
"using",
"ScopusSearch",
"but",
"only",
"if",
"belonging",
"to",
"a",
"Journal",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_author.py#L267-L271 | train | 203,578 |
scopus-api/scopus | scopus/deprecated_/scopus_author.py | ScopusAuthor.get_document_summary | def get_document_summary(self, N=None, cite_sort=True, refresh=True):
"""Return a summary string of documents.
Parameters
----------
N : int or None (optional, default=None)
Maximum number of documents to include in the summary.
If None, return all documents.
cite_sort : bool (optional, default=True)
Whether to sort xml by number of citations, in decreasing order,
or not.
refresh : bool (optional, default=True)
Whether to refresh the cached abstract file (if it exists) or not.
Returns
-------
s : str
Text summarizing an author's documents.
"""
abstracts = self.get_abstracts(refresh=refresh)
if cite_sort:
counts = [(a, int(a.citedby_count)) for a in abstracts]
counts.sort(reverse=True, key=itemgetter(1))
abstracts = [a[0] for a in counts]
if N is None:
N = len(abstracts)
s = [u'{0} of {1} documents'.format(N, len(abstracts))]
for i in range(N):
s += ['{0:2d}. {1}\n'.format(i + 1, str(abstracts[i]))]
return '\n'.join(s) | python | def get_document_summary(self, N=None, cite_sort=True, refresh=True):
"""Return a summary string of documents.
Parameters
----------
N : int or None (optional, default=None)
Maximum number of documents to include in the summary.
If None, return all documents.
cite_sort : bool (optional, default=True)
Whether to sort xml by number of citations, in decreasing order,
or not.
refresh : bool (optional, default=True)
Whether to refresh the cached abstract file (if it exists) or not.
Returns
-------
s : str
Text summarizing an author's documents.
"""
abstracts = self.get_abstracts(refresh=refresh)
if cite_sort:
counts = [(a, int(a.citedby_count)) for a in abstracts]
counts.sort(reverse=True, key=itemgetter(1))
abstracts = [a[0] for a in counts]
if N is None:
N = len(abstracts)
s = [u'{0} of {1} documents'.format(N, len(abstracts))]
for i in range(N):
s += ['{0:2d}. {1}\n'.format(i + 1, str(abstracts[i]))]
return '\n'.join(s) | [
"def",
"get_document_summary",
"(",
"self",
",",
"N",
"=",
"None",
",",
"cite_sort",
"=",
"True",
",",
"refresh",
"=",
"True",
")",
":",
"abstracts",
"=",
"self",
".",
"get_abstracts",
"(",
"refresh",
"=",
"refresh",
")",
"if",
"cite_sort",
":",
"counts"... | Return a summary string of documents.
Parameters
----------
N : int or None (optional, default=None)
Maximum number of documents to include in the summary.
If None, return all documents.
cite_sort : bool (optional, default=True)
Whether to sort xml by number of citations, in decreasing order,
or not.
refresh : bool (optional, default=True)
Whether to refresh the cached abstract file (if it exists) or not.
Returns
-------
s : str
Text summarizing an author's documents. | [
"Return",
"a",
"summary",
"string",
"of",
"documents",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_author.py#L273-L309 | train | 203,579 |
scopus-api/scopus | scopus/deprecated_/scopus_author.py | ScopusAuthor.author_impact_factor | def author_impact_factor(self, year=2014, refresh=True):
"""Get author_impact_factor for the .
Parameters
----------
year : int (optional, default=2014)
The year based for which the impact factor is to be calculated.
refresh : bool (optional, default=True)
Whether to refresh the cached search file (if it exists) or not.
Returns
-------
(ncites, npapers, aif) : tuple of integers
The citations count, publication count, and author impact factor.
"""
scopus_abstracts = self.get_journal_abstracts(refresh=refresh)
cites = [int(ab.citedby_count) for ab in scopus_abstracts]
years = [int(ab.coverDate.split('-')[0]) for ab in scopus_abstracts]
data = zip(years, cites, scopus_abstracts)
data = sorted(data, key=itemgetter(1), reverse=True)
# now get aif papers for year-1 and year-2
aif_data = [tup for tup in data if tup[0] in (year - 1, year - 2)]
Ncites = sum([tup[1] for tup in aif_data])
if len(aif_data) > 0:
return (Ncites, len(aif_data), Ncites / float(len(aif_data)))
else:
return (Ncites, len(aif_data), 0) | python | def author_impact_factor(self, year=2014, refresh=True):
"""Get author_impact_factor for the .
Parameters
----------
year : int (optional, default=2014)
The year based for which the impact factor is to be calculated.
refresh : bool (optional, default=True)
Whether to refresh the cached search file (if it exists) or not.
Returns
-------
(ncites, npapers, aif) : tuple of integers
The citations count, publication count, and author impact factor.
"""
scopus_abstracts = self.get_journal_abstracts(refresh=refresh)
cites = [int(ab.citedby_count) for ab in scopus_abstracts]
years = [int(ab.coverDate.split('-')[0]) for ab in scopus_abstracts]
data = zip(years, cites, scopus_abstracts)
data = sorted(data, key=itemgetter(1), reverse=True)
# now get aif papers for year-1 and year-2
aif_data = [tup for tup in data if tup[0] in (year - 1, year - 2)]
Ncites = sum([tup[1] for tup in aif_data])
if len(aif_data) > 0:
return (Ncites, len(aif_data), Ncites / float(len(aif_data)))
else:
return (Ncites, len(aif_data), 0) | [
"def",
"author_impact_factor",
"(",
"self",
",",
"year",
"=",
"2014",
",",
"refresh",
"=",
"True",
")",
":",
"scopus_abstracts",
"=",
"self",
".",
"get_journal_abstracts",
"(",
"refresh",
"=",
"refresh",
")",
"cites",
"=",
"[",
"int",
"(",
"ab",
".",
"ci... | Get author_impact_factor for the .
Parameters
----------
year : int (optional, default=2014)
The year based for which the impact factor is to be calculated.
refresh : bool (optional, default=True)
Whether to refresh the cached search file (if it exists) or not.
Returns
-------
(ncites, npapers, aif) : tuple of integers
The citations count, publication count, and author impact factor. | [
"Get",
"author_impact_factor",
"for",
"the",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_author.py#L350-L380 | train | 203,580 |
scopus-api/scopus | scopus/deprecated_/scopus_author.py | ScopusAuthor.n_first_author_papers | def n_first_author_papers(self, refresh=True):
"""Return number of papers with author as the first author."""
first_authors = [1 for ab in self.get_journal_abstracts(refresh=refresh)
if ab.authors[0].scopusid == self.author_id]
return sum(first_authors) | python | def n_first_author_papers(self, refresh=True):
"""Return number of papers with author as the first author."""
first_authors = [1 for ab in self.get_journal_abstracts(refresh=refresh)
if ab.authors[0].scopusid == self.author_id]
return sum(first_authors) | [
"def",
"n_first_author_papers",
"(",
"self",
",",
"refresh",
"=",
"True",
")",
":",
"first_authors",
"=",
"[",
"1",
"for",
"ab",
"in",
"self",
".",
"get_journal_abstracts",
"(",
"refresh",
"=",
"refresh",
")",
"if",
"ab",
".",
"authors",
"[",
"0",
"]",
... | Return number of papers with author as the first author. | [
"Return",
"number",
"of",
"papers",
"with",
"author",
"as",
"the",
"first",
"author",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_author.py#L382-L386 | train | 203,581 |
scopus-api/scopus | scopus/deprecated_/scopus_author.py | ScopusAuthor.n_yearly_publications | def n_yearly_publications(self, refresh=True):
"""Number of journal publications in a given year."""
pub_years = [int(ab.coverDate.split('-')[0])
for ab in self.get_journal_abstracts(refresh=refresh)]
return Counter(pub_years) | python | def n_yearly_publications(self, refresh=True):
"""Number of journal publications in a given year."""
pub_years = [int(ab.coverDate.split('-')[0])
for ab in self.get_journal_abstracts(refresh=refresh)]
return Counter(pub_years) | [
"def",
"n_yearly_publications",
"(",
"self",
",",
"refresh",
"=",
"True",
")",
":",
"pub_years",
"=",
"[",
"int",
"(",
"ab",
".",
"coverDate",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]",
")",
"for",
"ab",
"in",
"self",
".",
"get_journal_abstracts",
... | Number of journal publications in a given year. | [
"Number",
"of",
"journal",
"publications",
"in",
"a",
"given",
"year",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/deprecated_/scopus_author.py#L398-L402 | train | 203,582 |
scopus-api/scopus | scopus/abstract_retrieval.py | _get_org | def _get_org(aff):
"""Auxiliary function to extract org information from affiliation
for authorgroup.
"""
try:
org = aff['organization']
if not isinstance(org, str):
try:
org = org['$']
except TypeError: # Multiple names given
org = ', '.join([d['$'] for d in org if d])
except KeyError: # Author group w/o affiliation
org = None
return org | python | def _get_org(aff):
"""Auxiliary function to extract org information from affiliation
for authorgroup.
"""
try:
org = aff['organization']
if not isinstance(org, str):
try:
org = org['$']
except TypeError: # Multiple names given
org = ', '.join([d['$'] for d in org if d])
except KeyError: # Author group w/o affiliation
org = None
return org | [
"def",
"_get_org",
"(",
"aff",
")",
":",
"try",
":",
"org",
"=",
"aff",
"[",
"'organization'",
"]",
"if",
"not",
"isinstance",
"(",
"org",
",",
"str",
")",
":",
"try",
":",
"org",
"=",
"org",
"[",
"'$'",
"]",
"except",
"TypeError",
":",
"# Multiple... | Auxiliary function to extract org information from affiliation
for authorgroup. | [
"Auxiliary",
"function",
"to",
"extract",
"org",
"information",
"from",
"affiliation",
"for",
"authorgroup",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/abstract_retrieval.py#L765-L778 | train | 203,583 |
scopus-api/scopus | scopus/abstract_retrieval.py | _parse_pages | def _parse_pages(self, unicode=False):
"""Auxiliary function to parse and format page range of a document."""
if self.pageRange:
pages = 'pp. {}'.format(self.pageRange)
elif self.startingPage:
pages = 'pp. {}-{}'.format(self.startingPage, self.endingPage)
else:
pages = '(no pages found)'
if unicode:
pages = u'{}'.format(pages)
return pages | python | def _parse_pages(self, unicode=False):
"""Auxiliary function to parse and format page range of a document."""
if self.pageRange:
pages = 'pp. {}'.format(self.pageRange)
elif self.startingPage:
pages = 'pp. {}-{}'.format(self.startingPage, self.endingPage)
else:
pages = '(no pages found)'
if unicode:
pages = u'{}'.format(pages)
return pages | [
"def",
"_parse_pages",
"(",
"self",
",",
"unicode",
"=",
"False",
")",
":",
"if",
"self",
".",
"pageRange",
":",
"pages",
"=",
"'pp. {}'",
".",
"format",
"(",
"self",
".",
"pageRange",
")",
"elif",
"self",
".",
"startingPage",
":",
"pages",
"=",
"'pp. ... | Auxiliary function to parse and format page range of a document. | [
"Auxiliary",
"function",
"to",
"parse",
"and",
"format",
"page",
"range",
"of",
"a",
"document",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/abstract_retrieval.py#L788-L798 | train | 203,584 |
scopus-api/scopus | scopus/abstract_retrieval.py | AbstractRetrieval.authkeywords | def authkeywords(self):
"""List of author-provided keywords of the abstract."""
keywords = self._json['authkeywords']
if keywords is None:
return None
else:
try:
return [d['$'] for d in keywords['author-keyword']]
except TypeError: # Singleton keyword
return [keywords['author-keyword']['$']] | python | def authkeywords(self):
"""List of author-provided keywords of the abstract."""
keywords = self._json['authkeywords']
if keywords is None:
return None
else:
try:
return [d['$'] for d in keywords['author-keyword']]
except TypeError: # Singleton keyword
return [keywords['author-keyword']['$']] | [
"def",
"authkeywords",
"(",
"self",
")",
":",
"keywords",
"=",
"self",
".",
"_json",
"[",
"'authkeywords'",
"]",
"if",
"keywords",
"is",
"None",
":",
"return",
"None",
"else",
":",
"try",
":",
"return",
"[",
"d",
"[",
"'$'",
"]",
"for",
"d",
"in",
... | List of author-provided keywords of the abstract. | [
"List",
"of",
"author",
"-",
"provided",
"keywords",
"of",
"the",
"abstract",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/abstract_retrieval.py#L38-L47 | train | 203,585 |
scopus-api/scopus | scopus/abstract_retrieval.py | AbstractRetrieval.idxterms | def idxterms(self):
"""List of index terms."""
try:
terms = listify(self._json.get("idxterms", {}).get('mainterm', []))
except AttributeError: # idxterms is empty
return None
try:
return [d['$'] for d in terms]
except AttributeError:
return None | python | def idxterms(self):
"""List of index terms."""
try:
terms = listify(self._json.get("idxterms", {}).get('mainterm', []))
except AttributeError: # idxterms is empty
return None
try:
return [d['$'] for d in terms]
except AttributeError:
return None | [
"def",
"idxterms",
"(",
"self",
")",
":",
"try",
":",
"terms",
"=",
"listify",
"(",
"self",
".",
"_json",
".",
"get",
"(",
"\"idxterms\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"'mainterm'",
",",
"[",
"]",
")",
")",
"except",
"AttributeError",
":",
... | List of index terms. | [
"List",
"of",
"index",
"terms",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/abstract_retrieval.py#L305-L314 | train | 203,586 |
scopus-api/scopus | scopus/abstract_retrieval.py | AbstractRetrieval.get_html | def get_html(self):
"""Bibliographic entry in html format."""
# Author links
au_link = ('<a href="https://www.scopus.com/authid/detail.url'
'?origin=AuthorProfile&authorId={0}">{1}</a>')
if len(self.authors) > 1:
authors = u', '.join([au_link.format(a.auid, a.given_name +
' ' + a.surname)
for a in self.authors[0:-1]])
authors += (u' and ' +
au_link.format(self.authors[-1].auid,
(str(self.authors[-1].given_name) +
' ' +
str(self.authors[-1].surname))))
else:
a = self.authors[0]
authors = au_link.format(a.auid, a.given_name + ' ' + a.surname)
title = u'<a href="{}">{}</a>'.format(self.scopus_link, self.title)
if self.volume and self.issueIdentifier:
volissue = u'<b>{}({})</b>'.format(self.volume, self.issueIdentifier)
elif self.volume:
volissue = u'<b>{}</b>'.format(self.volume)
else:
volissue = 'no volume'
jlink = '<a href="https://www.scopus.com/source/sourceInfo.url'\
'?sourceId={}">{}</a>'.format(
self.source_id, self.publicationName)
pages = _parse_pages(self, unicode=True)
s = "{auth}, {title}, {jour}, {volissue}, {pages}, ({year}).".format(
auth=authors, title=title, jour=jlink, volissue=volissue,
pages=pages, year=self.coverDate[:4])
if self.doi:
s += ' <a href="https://doi.org/{0}">doi:{0}</a>.'.format(self.doi)
return s | python | def get_html(self):
"""Bibliographic entry in html format."""
# Author links
au_link = ('<a href="https://www.scopus.com/authid/detail.url'
'?origin=AuthorProfile&authorId={0}">{1}</a>')
if len(self.authors) > 1:
authors = u', '.join([au_link.format(a.auid, a.given_name +
' ' + a.surname)
for a in self.authors[0:-1]])
authors += (u' and ' +
au_link.format(self.authors[-1].auid,
(str(self.authors[-1].given_name) +
' ' +
str(self.authors[-1].surname))))
else:
a = self.authors[0]
authors = au_link.format(a.auid, a.given_name + ' ' + a.surname)
title = u'<a href="{}">{}</a>'.format(self.scopus_link, self.title)
if self.volume and self.issueIdentifier:
volissue = u'<b>{}({})</b>'.format(self.volume, self.issueIdentifier)
elif self.volume:
volissue = u'<b>{}</b>'.format(self.volume)
else:
volissue = 'no volume'
jlink = '<a href="https://www.scopus.com/source/sourceInfo.url'\
'?sourceId={}">{}</a>'.format(
self.source_id, self.publicationName)
pages = _parse_pages(self, unicode=True)
s = "{auth}, {title}, {jour}, {volissue}, {pages}, ({year}).".format(
auth=authors, title=title, jour=jlink, volissue=volissue,
pages=pages, year=self.coverDate[:4])
if self.doi:
s += ' <a href="https://doi.org/{0}">doi:{0}</a>.'.format(self.doi)
return s | [
"def",
"get_html",
"(",
"self",
")",
":",
"# Author links",
"au_link",
"=",
"(",
"'<a href=\"https://www.scopus.com/authid/detail.url'",
"'?origin=AuthorProfile&authorId={0}\">{1}</a>'",
")",
"if",
"len",
"(",
"self",
".",
"authors",
")",
">",
"1",
":",
"authors",
"="... | Bibliographic entry in html format. | [
"Bibliographic",
"entry",
"in",
"html",
"format",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/abstract_retrieval.py#L678-L711 | train | 203,587 |
scopus-api/scopus | scopus/abstract_retrieval.py | AbstractRetrieval.get_latex | def get_latex(self):
"""Bibliographic entry in LaTeX format."""
if len(self.authors) > 1:
authors = _list_authors(self.authors)
else:
a = self.authors
authors = ' '.join([a.given_name, a.surname])
if self.volume and self.issueIdentifier:
volissue = '\\textbf{{{}({})}}'.format(self.volume, self.issueIdentifier)
elif self.volume:
volissue = '\\textbf{{{}}}'.format(self.volume)
else:
volissue = 'no volume'
pages = _parse_pages(self)
s = '{auth}, \\textit{{{title}}}, {jour}, {vol}, {pages} ({year}).'.format(
auth=authors, title=self.title, jour=self.publicationName,
vol=volissue, pages=pages, year=self.coverDate[:4])
if self.doi is not None:
s += ' \\href{{https://doi.org/{0}}}{{doi:{0}}}, '.format(self.doi)
s += '\\href{{{0}}}{{scopus:{1}}}.'.format(self.scopus_link, self.eid)
return s | python | def get_latex(self):
"""Bibliographic entry in LaTeX format."""
if len(self.authors) > 1:
authors = _list_authors(self.authors)
else:
a = self.authors
authors = ' '.join([a.given_name, a.surname])
if self.volume and self.issueIdentifier:
volissue = '\\textbf{{{}({})}}'.format(self.volume, self.issueIdentifier)
elif self.volume:
volissue = '\\textbf{{{}}}'.format(self.volume)
else:
volissue = 'no volume'
pages = _parse_pages(self)
s = '{auth}, \\textit{{{title}}}, {jour}, {vol}, {pages} ({year}).'.format(
auth=authors, title=self.title, jour=self.publicationName,
vol=volissue, pages=pages, year=self.coverDate[:4])
if self.doi is not None:
s += ' \\href{{https://doi.org/{0}}}{{doi:{0}}}, '.format(self.doi)
s += '\\href{{{0}}}{{scopus:{1}}}.'.format(self.scopus_link, self.eid)
return s | [
"def",
"get_latex",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"authors",
")",
">",
"1",
":",
"authors",
"=",
"_list_authors",
"(",
"self",
".",
"authors",
")",
"else",
":",
"a",
"=",
"self",
".",
"authors",
"authors",
"=",
"' '",
".",
... | Bibliographic entry in LaTeX format. | [
"Bibliographic",
"entry",
"in",
"LaTeX",
"format",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/abstract_retrieval.py#L713-L733 | train | 203,588 |
scopus-api/scopus | scopus/classes/search.py | _parse | def _parse(res, params, n, api, **kwds):
"""Auxiliary function to download results and parse json."""
cursor = "cursor" in params
if not cursor:
start = params["start"]
if n == 0:
return ""
_json = res.get('search-results', {}).get('entry', [])
# Download the remaining information in chunks
while n > 0:
n -= params["count"]
if cursor:
pointer = res['search-results']['cursor'].get('@next')
params.update({'cursor': pointer})
else:
start += params["count"]
params.update({'start': start})
res = download(url=URL[api], params=params, accept="json", **kwds).json()
_json.extend(res.get('search-results', {}).get('entry', []))
return _json | python | def _parse(res, params, n, api, **kwds):
"""Auxiliary function to download results and parse json."""
cursor = "cursor" in params
if not cursor:
start = params["start"]
if n == 0:
return ""
_json = res.get('search-results', {}).get('entry', [])
# Download the remaining information in chunks
while n > 0:
n -= params["count"]
if cursor:
pointer = res['search-results']['cursor'].get('@next')
params.update({'cursor': pointer})
else:
start += params["count"]
params.update({'start': start})
res = download(url=URL[api], params=params, accept="json", **kwds).json()
_json.extend(res.get('search-results', {}).get('entry', []))
return _json | [
"def",
"_parse",
"(",
"res",
",",
"params",
",",
"n",
",",
"api",
",",
"*",
"*",
"kwds",
")",
":",
"cursor",
"=",
"\"cursor\"",
"in",
"params",
"if",
"not",
"cursor",
":",
"start",
"=",
"params",
"[",
"\"start\"",
"]",
"if",
"n",
"==",
"0",
":",
... | Auxiliary function to download results and parse json. | [
"Auxiliary",
"function",
"to",
"download",
"results",
"and",
"parse",
"json",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/classes/search.py#L120-L139 | train | 203,589 |
scopus-api/scopus | scopus/utils/create_config.py | create_config | def create_config():
"""Initiates process to generate configuration file."""
file_exists = exists(CONFIG_FILE)
if not file_exists:
# Set directories
config.add_section('Directories')
defaults = [
('AbstractRetrieval', expanduser('~/.scopus/abstract_retrieval')),
('AffiliationSearch', expanduser('~/.scopus/affiliation_search')),
('AuthorRetrieval', expanduser('~/.scopus/author_retrieval')),
('AuthorSearch', expanduser('~/.scopus/author_search')),
('CitationOverview', expanduser('~/.scopus/citation_overview')),
('ContentAffiliationRetrieval', expanduser('~/.scopus/affiliation_retrieval')),
('ScopusSearch', expanduser('~/.scopus/scopus_search'))
]
for key, value in defaults:
config.set('Directories', key, value)
if not exists(value):
makedirs(value)
# Set authentication
config.add_section('Authentication')
prompt_key = "Please enter your API Key, obtained from "\
"http://dev.elsevier.com/myapikey.html: \n"
if py3:
key = input(prompt_key)
else:
key = raw_input(prompt_key)
config.set('Authentication', 'APIKey', key)
prompt_token = "API Keys are sufficient for most users. If you "\
"have to use Authtoken authentication, please enter "\
"the token, otherwise press Enter: \n"
if py3:
token = input(prompt_token)
else:
token = raw_input(prompt_token)
if len(token) > 0:
config.set('Authentication', 'InstToken', token)
# Write out
with open(CONFIG_FILE, 'w') as f:
config.write(f)
else:
text = "Configuration file already exists at {}; process to create "\
"the file aborted. Please open the file and edit the "\
"entries manually.".format(CONFIG_FILE)
raise FileExistsError(text) | python | def create_config():
"""Initiates process to generate configuration file."""
file_exists = exists(CONFIG_FILE)
if not file_exists:
# Set directories
config.add_section('Directories')
defaults = [
('AbstractRetrieval', expanduser('~/.scopus/abstract_retrieval')),
('AffiliationSearch', expanduser('~/.scopus/affiliation_search')),
('AuthorRetrieval', expanduser('~/.scopus/author_retrieval')),
('AuthorSearch', expanduser('~/.scopus/author_search')),
('CitationOverview', expanduser('~/.scopus/citation_overview')),
('ContentAffiliationRetrieval', expanduser('~/.scopus/affiliation_retrieval')),
('ScopusSearch', expanduser('~/.scopus/scopus_search'))
]
for key, value in defaults:
config.set('Directories', key, value)
if not exists(value):
makedirs(value)
# Set authentication
config.add_section('Authentication')
prompt_key = "Please enter your API Key, obtained from "\
"http://dev.elsevier.com/myapikey.html: \n"
if py3:
key = input(prompt_key)
else:
key = raw_input(prompt_key)
config.set('Authentication', 'APIKey', key)
prompt_token = "API Keys are sufficient for most users. If you "\
"have to use Authtoken authentication, please enter "\
"the token, otherwise press Enter: \n"
if py3:
token = input(prompt_token)
else:
token = raw_input(prompt_token)
if len(token) > 0:
config.set('Authentication', 'InstToken', token)
# Write out
with open(CONFIG_FILE, 'w') as f:
config.write(f)
else:
text = "Configuration file already exists at {}; process to create "\
"the file aborted. Please open the file and edit the "\
"entries manually.".format(CONFIG_FILE)
raise FileExistsError(text) | [
"def",
"create_config",
"(",
")",
":",
"file_exists",
"=",
"exists",
"(",
"CONFIG_FILE",
")",
"if",
"not",
"file_exists",
":",
"# Set directories",
"config",
".",
"add_section",
"(",
"'Directories'",
")",
"defaults",
"=",
"[",
"(",
"'AbstractRetrieval'",
",",
... | Initiates process to generate configuration file. | [
"Initiates",
"process",
"to",
"generate",
"configuration",
"file",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/utils/create_config.py#L10-L54 | train | 203,590 |
scopus-api/scopus | scopus/utils/get_encoded_text.py | get_encoded_text | def get_encoded_text(container, xpath):
"""Return text for element at xpath in the container xml if it is there.
Parameters
----------
container : xml.etree.ElementTree.Element
The element to be searched in.
xpath : str
The path to be looked for.
Returns
-------
result : str
"""
try:
return "".join(container.find(xpath, ns).itertext())
except AttributeError:
return None | python | def get_encoded_text(container, xpath):
"""Return text for element at xpath in the container xml if it is there.
Parameters
----------
container : xml.etree.ElementTree.Element
The element to be searched in.
xpath : str
The path to be looked for.
Returns
-------
result : str
"""
try:
return "".join(container.find(xpath, ns).itertext())
except AttributeError:
return None | [
"def",
"get_encoded_text",
"(",
"container",
",",
"xpath",
")",
":",
"try",
":",
"return",
"\"\"",
".",
"join",
"(",
"container",
".",
"find",
"(",
"xpath",
",",
"ns",
")",
".",
"itertext",
"(",
")",
")",
"except",
"AttributeError",
":",
"return",
"Non... | Return text for element at xpath in the container xml if it is there.
Parameters
----------
container : xml.etree.ElementTree.Element
The element to be searched in.
xpath : str
The path to be looked for.
Returns
-------
result : str | [
"Return",
"text",
"for",
"element",
"at",
"xpath",
"in",
"the",
"container",
"xml",
"if",
"it",
"is",
"there",
"."
] | 27ce02dd3095bfdab9d3e8475543d7c17767d1ab | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/utils/get_encoded_text.py#L15-L33 | train | 203,591 |
sixty-north/cosmic-ray | src/cosmic_ray/cli.py | main | def main(argv=None):
""" Invoke the cosmic ray evaluation.
:param argv: the command line arguments
"""
signal.signal(
signal.SIGINT,
lambda *args: sys.exit(_SIGNAL_EXIT_CODE_BASE + signal.SIGINT))
if hasattr(signal, 'SIGINFO'):
signal.signal(
getattr(signal, 'SIGINFO'),
lambda *args: report_progress(sys.stderr))
try:
return docopt_subcommands.main(
commands=dsc,
argv=argv,
doc_template=DOC_TEMPLATE,
exit_at_end=False)
except docopt.DocoptExit as exc:
print(exc, file=sys.stderr)
return ExitCode.USAGE
except FileNotFoundError as exc:
print(exc, file=sys.stderr)
return ExitCode.NO_INPUT
except PermissionError as exc:
print(exc, file=sys.stderr)
return ExitCode.NO_PERM
except cosmic_ray.config.ConfigError as exc:
print(repr(exc), file=sys.stderr)
if exc.__cause__ is not None:
print(exc.__cause__, file=sys.stderr)
return ExitCode.CONFIG
except subprocess.CalledProcessError as exc:
print('Error in subprocess', file=sys.stderr)
print(exc, file=sys.stderr)
return exc.returncode | python | def main(argv=None):
""" Invoke the cosmic ray evaluation.
:param argv: the command line arguments
"""
signal.signal(
signal.SIGINT,
lambda *args: sys.exit(_SIGNAL_EXIT_CODE_BASE + signal.SIGINT))
if hasattr(signal, 'SIGINFO'):
signal.signal(
getattr(signal, 'SIGINFO'),
lambda *args: report_progress(sys.stderr))
try:
return docopt_subcommands.main(
commands=dsc,
argv=argv,
doc_template=DOC_TEMPLATE,
exit_at_end=False)
except docopt.DocoptExit as exc:
print(exc, file=sys.stderr)
return ExitCode.USAGE
except FileNotFoundError as exc:
print(exc, file=sys.stderr)
return ExitCode.NO_INPUT
except PermissionError as exc:
print(exc, file=sys.stderr)
return ExitCode.NO_PERM
except cosmic_ray.config.ConfigError as exc:
print(repr(exc), file=sys.stderr)
if exc.__cause__ is not None:
print(exc.__cause__, file=sys.stderr)
return ExitCode.CONFIG
except subprocess.CalledProcessError as exc:
print('Error in subprocess', file=sys.stderr)
print(exc, file=sys.stderr)
return exc.returncode | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"lambda",
"*",
"args",
":",
"sys",
".",
"exit",
"(",
"_SIGNAL_EXIT_CODE_BASE",
"+",
"signal",
".",
"SIGINT",
")",
")",
"if",
"hasattr",
"("... | Invoke the cosmic ray evaluation.
:param argv: the command line arguments | [
"Invoke",
"the",
"cosmic",
"ray",
"evaluation",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/cli.py#L279-L316 | train | 203,592 |
sixty-north/cosmic-ray | src/cosmic_ray/operators/util.py | extend_name | def extend_name(suffix):
"""A factory for class decorators that modify the class name by appending some text to it.
Example:
@extend_name('_Foo')
class Class:
pass
assert Class.__name__ == 'Class_Foo'
"""
def dec(cls):
name = '{}{}'.format(cls.__name__, suffix)
setattr(cls, '__name__', name)
return cls
return dec | python | def extend_name(suffix):
"""A factory for class decorators that modify the class name by appending some text to it.
Example:
@extend_name('_Foo')
class Class:
pass
assert Class.__name__ == 'Class_Foo'
"""
def dec(cls):
name = '{}{}'.format(cls.__name__, suffix)
setattr(cls, '__name__', name)
return cls
return dec | [
"def",
"extend_name",
"(",
"suffix",
")",
":",
"def",
"dec",
"(",
"cls",
")",
":",
"name",
"=",
"'{}{}'",
".",
"format",
"(",
"cls",
".",
"__name__",
",",
"suffix",
")",
"setattr",
"(",
"cls",
",",
"'__name__'",
",",
"name",
")",
"return",
"cls",
"... | A factory for class decorators that modify the class name by appending some text to it.
Example:
@extend_name('_Foo')
class Class:
pass
assert Class.__name__ == 'Class_Foo' | [
"A",
"factory",
"for",
"class",
"decorators",
"that",
"modify",
"the",
"class",
"name",
"by",
"appending",
"some",
"text",
"to",
"it",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/operators/util.py#L4-L21 | train | 203,593 |
sixty-north/cosmic-ray | src/cosmic_ray/operators/number_replacer.py | NumberReplacer.mutate | def mutate(self, node, index):
"""Modify the numeric value on `node`."""
assert index < len(OFFSETS), 'received count with no associated offset'
assert isinstance(node, parso.python.tree.Number)
val = eval(node.value) + OFFSETS[index] # pylint: disable=W0123
return parso.python.tree.Number(' ' + str(val), node.start_pos) | python | def mutate(self, node, index):
"""Modify the numeric value on `node`."""
assert index < len(OFFSETS), 'received count with no associated offset'
assert isinstance(node, parso.python.tree.Number)
val = eval(node.value) + OFFSETS[index] # pylint: disable=W0123
return parso.python.tree.Number(' ' + str(val), node.start_pos) | [
"def",
"mutate",
"(",
"self",
",",
"node",
",",
"index",
")",
":",
"assert",
"index",
"<",
"len",
"(",
"OFFSETS",
")",
",",
"'received count with no associated offset'",
"assert",
"isinstance",
"(",
"node",
",",
"parso",
".",
"python",
".",
"tree",
".",
"N... | Modify the numeric value on `node`. | [
"Modify",
"the",
"numeric",
"value",
"on",
"node",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/operators/number_replacer.py#L25-L32 | train | 203,594 |
sixty-north/cosmic-ray | src/cosmic_ray/operators/unary_operator_replacement.py | _prohibited | def _prohibited(from_op, to_op):
"Determines if from_op is allowed to be mutated to to_op."
# 'not' can only be removed but not replaced with
# '+', '-' or '~' b/c that may lead to strange results
if from_op is UnaryOperators.Not:
if to_op is not UnaryOperators.Nothing:
return True
# '+1' => '1' yields equivalent mutations
if from_op is UnaryOperators.UAdd:
if to_op is UnaryOperators.Nothing:
return True
return False | python | def _prohibited(from_op, to_op):
"Determines if from_op is allowed to be mutated to to_op."
# 'not' can only be removed but not replaced with
# '+', '-' or '~' b/c that may lead to strange results
if from_op is UnaryOperators.Not:
if to_op is not UnaryOperators.Nothing:
return True
# '+1' => '1' yields equivalent mutations
if from_op is UnaryOperators.UAdd:
if to_op is UnaryOperators.Nothing:
return True
return False | [
"def",
"_prohibited",
"(",
"from_op",
",",
"to_op",
")",
":",
"# 'not' can only be removed but not replaced with",
"# '+', '-' or '~' b/c that may lead to strange results",
"if",
"from_op",
"is",
"UnaryOperators",
".",
"Not",
":",
"if",
"to_op",
"is",
"not",
"UnaryOperators... | Determines if from_op is allowed to be mutated to to_op. | [
"Determines",
"if",
"from_op",
"is",
"allowed",
"to",
"be",
"mutated",
"to",
"to_op",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/operators/unary_operator_replacement.py#L86-L99 | train | 203,595 |
sixty-north/cosmic-ray | src/cosmic_ray/config.py | load_config | def load_config(filename=None):
"""Load a configuration from a file or stdin.
If `filename` is `None` or "-", then configuration gets read from stdin.
Returns: A `ConfigDict`.
Raises: ConfigError: If there is an error loading the config.
"""
try:
with _config_stream(filename) as handle:
filename = handle.name
return deserialize_config(handle.read())
except (OSError, toml.TomlDecodeError, UnicodeDecodeError) as exc:
raise ConfigError(
'Error loading configuration from {}'.format(filename)) from exc | python | def load_config(filename=None):
"""Load a configuration from a file or stdin.
If `filename` is `None` or "-", then configuration gets read from stdin.
Returns: A `ConfigDict`.
Raises: ConfigError: If there is an error loading the config.
"""
try:
with _config_stream(filename) as handle:
filename = handle.name
return deserialize_config(handle.read())
except (OSError, toml.TomlDecodeError, UnicodeDecodeError) as exc:
raise ConfigError(
'Error loading configuration from {}'.format(filename)) from exc | [
"def",
"load_config",
"(",
"filename",
"=",
"None",
")",
":",
"try",
":",
"with",
"_config_stream",
"(",
"filename",
")",
"as",
"handle",
":",
"filename",
"=",
"handle",
".",
"name",
"return",
"deserialize_config",
"(",
"handle",
".",
"read",
"(",
")",
"... | Load a configuration from a file or stdin.
If `filename` is `None` or "-", then configuration gets read from stdin.
Returns: A `ConfigDict`.
Raises: ConfigError: If there is an error loading the config. | [
"Load",
"a",
"configuration",
"from",
"a",
"file",
"or",
"stdin",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/config.py#L11-L26 | train | 203,596 |
sixty-north/cosmic-ray | src/cosmic_ray/config.py | _config_stream | def _config_stream(filename):
"""Given a configuration's filename, this returns a stream from which a configuration can be read.
If `filename` is `None` or '-' then stream will be `sys.stdin`. Otherwise,
it's the open file handle for the filename.
"""
if filename is None or filename == '-':
log.info('Reading config from stdin')
yield sys.stdin
else:
with open(filename, mode='rt') as handle:
log.info('Reading config from %r', filename)
yield handle | python | def _config_stream(filename):
"""Given a configuration's filename, this returns a stream from which a configuration can be read.
If `filename` is `None` or '-' then stream will be `sys.stdin`. Otherwise,
it's the open file handle for the filename.
"""
if filename is None or filename == '-':
log.info('Reading config from stdin')
yield sys.stdin
else:
with open(filename, mode='rt') as handle:
log.info('Reading config from %r', filename)
yield handle | [
"def",
"_config_stream",
"(",
"filename",
")",
":",
"if",
"filename",
"is",
"None",
"or",
"filename",
"==",
"'-'",
":",
"log",
".",
"info",
"(",
"'Reading config from stdin'",
")",
"yield",
"sys",
".",
"stdin",
"else",
":",
"with",
"open",
"(",
"filename",... | Given a configuration's filename, this returns a stream from which a configuration can be read.
If `filename` is `None` or '-' then stream will be `sys.stdin`. Otherwise,
it's the open file handle for the filename. | [
"Given",
"a",
"configuration",
"s",
"filename",
"this",
"returns",
"a",
"stream",
"from",
"which",
"a",
"configuration",
"can",
"be",
"read",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/config.py#L112-L124 | train | 203,597 |
sixty-north/cosmic-ray | src/cosmic_ray/config.py | ConfigDict.sub | def sub(self, *segments):
"Get a sub-configuration."
d = self
for segment in segments:
try:
d = d[segment]
except KeyError:
return ConfigDict({})
return d | python | def sub(self, *segments):
"Get a sub-configuration."
d = self
for segment in segments:
try:
d = d[segment]
except KeyError:
return ConfigDict({})
return d | [
"def",
"sub",
"(",
"self",
",",
"*",
"segments",
")",
":",
"d",
"=",
"self",
"for",
"segment",
"in",
"segments",
":",
"try",
":",
"d",
"=",
"d",
"[",
"segment",
"]",
"except",
"KeyError",
":",
"return",
"ConfigDict",
"(",
"{",
"}",
")",
"return",
... | Get a sub-configuration. | [
"Get",
"a",
"sub",
"-",
"configuration",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/config.py#L60-L68 | train | 203,598 |
sixty-north/cosmic-ray | src/cosmic_ray/config.py | ConfigDict.python_version | def python_version(self):
"""Get the configured Python version.
If this is not set in the config, then it defaults to the version of the current runtime.
Returns: A string of the form "MAJOR.MINOR", e.g. "3.6".
"""
v = self.get('python-version', '')
if v == '':
v = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
return v | python | def python_version(self):
"""Get the configured Python version.
If this is not set in the config, then it defaults to the version of the current runtime.
Returns: A string of the form "MAJOR.MINOR", e.g. "3.6".
"""
v = self.get('python-version', '')
if v == '':
v = "{}.{}".format(sys.version_info.major, sys.version_info.minor)
return v | [
"def",
"python_version",
"(",
"self",
")",
":",
"v",
"=",
"self",
".",
"get",
"(",
"'python-version'",
",",
"''",
")",
"if",
"v",
"==",
"''",
":",
"v",
"=",
"\"{}.{}\"",
".",
"format",
"(",
"sys",
".",
"version_info",
".",
"major",
",",
"sys",
".",... | Get the configured Python version.
If this is not set in the config, then it defaults to the version of the current runtime.
Returns: A string of the form "MAJOR.MINOR", e.g. "3.6". | [
"Get",
"the",
"configured",
"Python",
"version",
"."
] | c654e074afbb7b7fcbc23359083c1287c0d3e991 | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/config.py#L71-L81 | train | 203,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.