repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
fedora-infra/datanommer | datanommer.models/alembic/versions/1d4feffd78fe_add_historic_user_an.py | _page | def _page(q, chunk=1000):
""" Quick utility to page a query, 1000 items at a time.
We need this so we don't OOM (out of memory) ourselves loading the world.
"""
offset = 0
while True:
r = False
for elem in q.limit(chunk).offset(offset):
r = True
yield elem
offset += chunk
if not r:
break | python | def _page(q, chunk=1000):
""" Quick utility to page a query, 1000 items at a time.
We need this so we don't OOM (out of memory) ourselves loading the world.
"""
offset = 0
while True:
r = False
for elem in q.limit(chunk).offset(offset):
r = True
yield elem
offset += chunk
if not r:
break | [
"def",
"_page",
"(",
"q",
",",
"chunk",
"=",
"1000",
")",
":",
"offset",
"=",
"0",
"while",
"True",
":",
"r",
"=",
"False",
"for",
"elem",
"in",
"q",
".",
"limit",
"(",
"chunk",
")",
".",
"offset",
"(",
"offset",
")",
":",
"r",
"=",
"True",
"... | Quick utility to page a query, 1000 items at a time.
We need this so we don't OOM (out of memory) ourselves loading the world. | [
"Quick",
"utility",
"to",
"page",
"a",
"query",
"1000",
"items",
"at",
"a",
"time",
".",
"We",
"need",
"this",
"so",
"we",
"don",
"t",
"OOM",
"(",
"out",
"of",
"memory",
")",
"ourselves",
"loading",
"the",
"world",
"."
] | train | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/datanommer.models/alembic/versions/1d4feffd78fe_add_historic_user_an.py#L48-L61 |
fedora-infra/datanommer | datanommer.models/alembic/versions/1d4feffd78fe_add_historic_user_an.py | upgrade | def upgrade():
""" This takes a *really* long time. Like, hours. """
config_paths = context.config.get_main_option('fedmsg_config_dir')
filenames = fedmsg.config._gather_configs_in(config_paths)
config = fedmsg.config.load_config(filenames=filenames)
make_processors(**config)
engine = op.get_bind().engine
m.init(engine=engine)
for msg in _page(m.Message.query.order_by(m.Message.timestamp)):
print("processing %s %s" % (msg.timestamp, msg.topic))
if msg.users and msg.packages:
continue
changed = False
if not msg.users:
new_usernames = msg2usernames(msg.__json__(), **config)
print("Updating users to %r" % new_usernames)
changed = changed or new_usernames
for new_username in new_usernames:
new_user = m.User.get_or_create(new_username)
msg.users.append(new_user)
if not msg.packages:
new_packagenames = msg2packages(msg.__json__(), **config)
print("Updating packages to %r" % new_packagenames)
changed = changed or new_usernames
for new_packagename in new_packagenames:
new_package = m.Package.get_or_create(new_packagename)
msg.packages.append(new_package)
if changed and random.random() < 0.01:
# Only save if something changed.. and only do it every so often.
# We do this so that if we crash, we can kind of pick up where
# we left off. But if we do it on every change: too slow.
print(" * Saving!")
m.session.commit()
m.session.commit() | python | def upgrade():
""" This takes a *really* long time. Like, hours. """
config_paths = context.config.get_main_option('fedmsg_config_dir')
filenames = fedmsg.config._gather_configs_in(config_paths)
config = fedmsg.config.load_config(filenames=filenames)
make_processors(**config)
engine = op.get_bind().engine
m.init(engine=engine)
for msg in _page(m.Message.query.order_by(m.Message.timestamp)):
print("processing %s %s" % (msg.timestamp, msg.topic))
if msg.users and msg.packages:
continue
changed = False
if not msg.users:
new_usernames = msg2usernames(msg.__json__(), **config)
print("Updating users to %r" % new_usernames)
changed = changed or new_usernames
for new_username in new_usernames:
new_user = m.User.get_or_create(new_username)
msg.users.append(new_user)
if not msg.packages:
new_packagenames = msg2packages(msg.__json__(), **config)
print("Updating packages to %r" % new_packagenames)
changed = changed or new_usernames
for new_packagename in new_packagenames:
new_package = m.Package.get_or_create(new_packagename)
msg.packages.append(new_package)
if changed and random.random() < 0.01:
# Only save if something changed.. and only do it every so often.
# We do this so that if we crash, we can kind of pick up where
# we left off. But if we do it on every change: too slow.
print(" * Saving!")
m.session.commit()
m.session.commit() | [
"def",
"upgrade",
"(",
")",
":",
"config_paths",
"=",
"context",
".",
"config",
".",
"get_main_option",
"(",
"'fedmsg_config_dir'",
")",
"filenames",
"=",
"fedmsg",
".",
"config",
".",
"_gather_configs_in",
"(",
"config_paths",
")",
"config",
"=",
"fedmsg",
".... | This takes a *really* long time. Like, hours. | [
"This",
"takes",
"a",
"*",
"really",
"*",
"long",
"time",
".",
"Like",
"hours",
"."
] | train | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/datanommer.models/alembic/versions/1d4feffd78fe_add_historic_user_an.py#L64-L107 |
fedora-infra/datanommer | tools/gource/datanommer2gitlog.py | run | def run(cmd):
""" Execute a shell command.
Both envoy and python-sh failed me...
commands, although deprecated, feels like the easiest tool to use.
"""
status, output = commands.getstatusoutput(cmd)
if status:
print(output)
return status == 0 | python | def run(cmd):
""" Execute a shell command.
Both envoy and python-sh failed me...
commands, although deprecated, feels like the easiest tool to use.
"""
status, output = commands.getstatusoutput(cmd)
if status:
print(output)
return status == 0 | [
"def",
"run",
"(",
"cmd",
")",
":",
"status",
",",
"output",
"=",
"commands",
".",
"getstatusoutput",
"(",
"cmd",
")",
"if",
"status",
":",
"print",
"(",
"output",
")",
"return",
"status",
"==",
"0"
] | Execute a shell command.
Both envoy and python-sh failed me...
commands, although deprecated, feels like the easiest tool to use. | [
"Execute",
"a",
"shell",
"command",
"."
] | train | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/tools/gource/datanommer2gitlog.py#L43-L53 |
fedora-infra/datanommer | tools/gource/datanommer2gitlog.py | read_datanommer_entries_from_filedump | def read_datanommer_entries_from_filedump():
""" Read in all datanommer entries from a file created with:
$ datanommer-dump > myfile.json
"""
# TODO -- un-hardcode this filename when I need to run this next time.
#filename = "../myfile.json"
filename = "../datanommer-dump-2012-11-22.json"
print("Reading %s" % filename)
progress = progressbar.ProgressBar(widgets=[
progressbar.widgets.Percentage(),
progressbar.widgets.Bar(),
progressbar.widgets.ETA(),
])
def _entries():
failed = 0
with open(filename, 'r') as f:
raw = f.read()
lines = raw.split('\n}\n')
for line in progress(lines):
try:
yield json.loads(line + "\n}")
except:
failed += 1
print(" * Failed to parse %i json objects" % failed)
def comp(a, b):
return cmp(a['timestamp'], b['timestamp'])
result = sorted(list(_entries()), cmp=comp)
print(" * Read and sorted %i messages" % len(result))
print()
return result | python | def read_datanommer_entries_from_filedump():
""" Read in all datanommer entries from a file created with:
$ datanommer-dump > myfile.json
"""
# TODO -- un-hardcode this filename when I need to run this next time.
#filename = "../myfile.json"
filename = "../datanommer-dump-2012-11-22.json"
print("Reading %s" % filename)
progress = progressbar.ProgressBar(widgets=[
progressbar.widgets.Percentage(),
progressbar.widgets.Bar(),
progressbar.widgets.ETA(),
])
def _entries():
failed = 0
with open(filename, 'r') as f:
raw = f.read()
lines = raw.split('\n}\n')
for line in progress(lines):
try:
yield json.loads(line + "\n}")
except:
failed += 1
print(" * Failed to parse %i json objects" % failed)
def comp(a, b):
return cmp(a['timestamp'], b['timestamp'])
result = sorted(list(_entries()), cmp=comp)
print(" * Read and sorted %i messages" % len(result))
print()
return result | [
"def",
"read_datanommer_entries_from_filedump",
"(",
")",
":",
"# TODO -- un-hardcode this filename when I need to run this next time.",
"#filename = \"../myfile.json\"",
"filename",
"=",
"\"../datanommer-dump-2012-11-22.json\"",
"print",
"(",
"\"Reading %s\"",
"%",
"filename",
")",
... | Read in all datanommer entries from a file created with:
$ datanommer-dump > myfile.json | [
"Read",
"in",
"all",
"datanommer",
"entries",
"from",
"a",
"file",
"created",
"with",
":"
] | train | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/tools/gource/datanommer2gitlog.py#L56-L90 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/factories/factory_interface.py | FactoryInterface.create_or_update | def create_or_update(self,
identifier: Identifier,
data: Dict[str, Any],
) -> Tuple[object, bool]:
"""
Create or update a model.
:param identifier: An object with :attr:`class_name` and :attr:`key`
attributes
:param data: A dictionary keyed by column name, with values being the
converted values to set on the model instance
:return: A two-tuple of model instance and whether or not it was created.
"""
raise NotImplementedError | python | def create_or_update(self,
identifier: Identifier,
data: Dict[str, Any],
) -> Tuple[object, bool]:
"""
Create or update a model.
:param identifier: An object with :attr:`class_name` and :attr:`key`
attributes
:param data: A dictionary keyed by column name, with values being the
converted values to set on the model instance
:return: A two-tuple of model instance and whether or not it was created.
"""
raise NotImplementedError | [
"def",
"create_or_update",
"(",
"self",
",",
"identifier",
":",
"Identifier",
",",
"data",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
")",
"->",
"Tuple",
"[",
"object",
",",
"bool",
"]",
":",
"raise",
"NotImplementedError"
] | Create or update a model.
:param identifier: An object with :attr:`class_name` and :attr:`key`
attributes
:param data: A dictionary keyed by column name, with values being the
converted values to set on the model instance
:return: A two-tuple of model instance and whether or not it was created. | [
"Create",
"or",
"update",
"a",
"model",
"."
] | train | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/factories/factory_interface.py#L15-L28 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/factories/factory_interface.py | FactoryInterface.maybe_convert_values | def maybe_convert_values(self,
identifier: Identifier,
data: Dict[str, Any],
) -> Dict[str, Any]:
"""
Takes a dictionary of raw values for a specific identifier, as parsed
from the YAML file, and depending upon the type of db column the data
is meant for, decides what to do with the value (eg leave it alone,
convert a string to a date/time instance, or convert identifiers to
model instances by calling :meth:`self.loader.convert_identifiers`)
:param identifier: An object with :attr:`class_name` and :attr:`key`
attributes
:param data: A dictionary keyed by column name, with values being the
raw values as parsed from the YAML
:return: A dictionary keyed by column name, with values being the
converted values meant to be set on the model instance
"""
raise NotImplementedError | python | def maybe_convert_values(self,
identifier: Identifier,
data: Dict[str, Any],
) -> Dict[str, Any]:
"""
Takes a dictionary of raw values for a specific identifier, as parsed
from the YAML file, and depending upon the type of db column the data
is meant for, decides what to do with the value (eg leave it alone,
convert a string to a date/time instance, or convert identifiers to
model instances by calling :meth:`self.loader.convert_identifiers`)
:param identifier: An object with :attr:`class_name` and :attr:`key`
attributes
:param data: A dictionary keyed by column name, with values being the
raw values as parsed from the YAML
:return: A dictionary keyed by column name, with values being the
converted values meant to be set on the model instance
"""
raise NotImplementedError | [
"def",
"maybe_convert_values",
"(",
"self",
",",
"identifier",
":",
"Identifier",
",",
"data",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"raise",
"NotImplementedError"
] | Takes a dictionary of raw values for a specific identifier, as parsed
from the YAML file, and depending upon the type of db column the data
is meant for, decides what to do with the value (eg leave it alone,
convert a string to a date/time instance, or convert identifiers to
model instances by calling :meth:`self.loader.convert_identifiers`)
:param identifier: An object with :attr:`class_name` and :attr:`key`
attributes
:param data: A dictionary keyed by column name, with values being the
raw values as parsed from the YAML
:return: A dictionary keyed by column name, with values being the
converted values meant to be set on the model instance | [
"Takes",
"a",
"dictionary",
"of",
"raw",
"values",
"for",
"a",
"specific",
"identifier",
"as",
"parsed",
"from",
"the",
"YAML",
"file",
"and",
"depending",
"upon",
"the",
"type",
"of",
"db",
"column",
"the",
"data",
"is",
"meant",
"for",
"decides",
"what",... | train | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/factories/factory_interface.py#L40-L58 |
Accelize/pycosio | pycosio/storage/azure_file.py | _AzureFileSystem.copy | def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio.storage.azure._AzureBaseSystem subclass):
The source storage system.
"""
with _handle_azure_exception():
self.client.copy_file(
copy_source=(other_system or self)._format_src_url(src, self),
**self.get_client_kwargs(dst)) | python | def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio.storage.azure._AzureBaseSystem subclass):
The source storage system.
"""
with _handle_azure_exception():
self.client.copy_file(
copy_source=(other_system or self)._format_src_url(src, self),
**self.get_client_kwargs(dst)) | [
"def",
"copy",
"(",
"self",
",",
"src",
",",
"dst",
",",
"other_system",
"=",
"None",
")",
":",
"with",
"_handle_azure_exception",
"(",
")",
":",
"self",
".",
"client",
".",
"copy_file",
"(",
"copy_source",
"=",
"(",
"other_system",
"or",
"self",
")",
... | Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio.storage.azure._AzureBaseSystem subclass):
The source storage system. | [
"Copy",
"object",
"of",
"the",
"same",
"storage",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure_file.py#L30-L43 |
Accelize/pycosio | pycosio/storage/azure_file.py | _AzureFileSystem.get_client_kwargs | def get_client_kwargs(self, path):
"""
Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args
"""
# Remove query string from URL
path = path.split('?', 1)[0]
share_name, relpath = self.split_locator(path)
kwargs = dict(share_name=share_name)
# Directory
if relpath and relpath[-1] == '/':
kwargs['directory_name'] = relpath.rstrip('/')
# File
elif relpath:
try:
kwargs['directory_name'], kwargs['file_name'] = relpath.rsplit(
'/', 1)
except ValueError:
kwargs['directory_name'] = ''
kwargs['file_name'] = relpath
# Else, Share only
return kwargs | python | def get_client_kwargs(self, path):
"""
Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args
"""
# Remove query string from URL
path = path.split('?', 1)[0]
share_name, relpath = self.split_locator(path)
kwargs = dict(share_name=share_name)
# Directory
if relpath and relpath[-1] == '/':
kwargs['directory_name'] = relpath.rstrip('/')
# File
elif relpath:
try:
kwargs['directory_name'], kwargs['file_name'] = relpath.rsplit(
'/', 1)
except ValueError:
kwargs['directory_name'] = ''
kwargs['file_name'] = relpath
# Else, Share only
return kwargs | [
"def",
"get_client_kwargs",
"(",
"self",
",",
"path",
")",
":",
"# Remove query string from URL",
"path",
"=",
"path",
".",
"split",
"(",
"'?'",
",",
"1",
")",
"[",
"0",
"]",
"share_name",
",",
"relpath",
"=",
"self",
".",
"split_locator",
"(",
"path",
"... | Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args | [
"Get",
"base",
"keyword",
"arguments",
"for",
"client",
"for",
"a",
"specific",
"path",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure_file.py#L56-L87 |
Accelize/pycosio | pycosio/storage/azure_file.py | _AzureFileSystem._head | def _head(self, client_kwargs):
"""
Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_azure_exception():
# File
if 'file_name' in client_kwargs:
result = self.client.get_file_properties(**client_kwargs)
# Directory
elif 'directory_name' in client_kwargs:
result = self.client.get_directory_properties(**client_kwargs)
# Share
else:
result = self.client.get_share_properties(**client_kwargs)
return self._model_to_dict(result) | python | def _head(self, client_kwargs):
"""
Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_azure_exception():
# File
if 'file_name' in client_kwargs:
result = self.client.get_file_properties(**client_kwargs)
# Directory
elif 'directory_name' in client_kwargs:
result = self.client.get_directory_properties(**client_kwargs)
# Share
else:
result = self.client.get_share_properties(**client_kwargs)
return self._model_to_dict(result) | [
"def",
"_head",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_azure_exception",
"(",
")",
":",
"# File",
"if",
"'file_name'",
"in",
"client_kwargs",
":",
"result",
"=",
"self",
".",
"client",
".",
"get_file_properties",
"(",
"*",
"*",
"client... | Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header. | [
"Returns",
"object",
"or",
"bucket",
"HTTP",
"header",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure_file.py#L112-L135 |
Accelize/pycosio | pycosio/storage/azure_file.py | _AzureFileSystem._list_locators | def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_azure_exception():
for share in self.client.list_shares():
yield share.name, self._model_to_dict(share) | python | def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_azure_exception():
for share in self.client.list_shares():
yield share.name, self._model_to_dict(share) | [
"def",
"_list_locators",
"(",
"self",
")",
":",
"with",
"_handle_azure_exception",
"(",
")",
":",
"for",
"share",
"in",
"self",
".",
"client",
".",
"list_shares",
"(",
")",
":",
"yield",
"share",
".",
"name",
",",
"self",
".",
"_model_to_dict",
"(",
"sha... | Lists locators.
Returns:
generator of tuple: locator name str, locator header dict | [
"Lists",
"locators",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure_file.py#L137-L146 |
Accelize/pycosio | pycosio/storage/azure_file.py | _AzureFileSystem._list_objects | def _list_objects(self, client_kwargs, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict,
directory bool
"""
client_kwargs = self._update_listing_client_kwargs(
client_kwargs, max_request_entries)
with _handle_azure_exception():
for obj in self.client.list_directories_and_files(**client_kwargs):
yield (obj.name, self._model_to_dict(obj),
isinstance(obj, _Directory)) | python | def _list_objects(self, client_kwargs, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict,
directory bool
"""
client_kwargs = self._update_listing_client_kwargs(
client_kwargs, max_request_entries)
with _handle_azure_exception():
for obj in self.client.list_directories_and_files(**client_kwargs):
yield (obj.name, self._model_to_dict(obj),
isinstance(obj, _Directory)) | [
"def",
"_list_objects",
"(",
"self",
",",
"client_kwargs",
",",
"max_request_entries",
")",
":",
"client_kwargs",
"=",
"self",
".",
"_update_listing_client_kwargs",
"(",
"client_kwargs",
",",
"max_request_entries",
")",
"with",
"_handle_azure_exception",
"(",
")",
":"... | Lists objects.
args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict,
directory bool | [
"Lists",
"objects",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure_file.py#L148-L167 |
Accelize/pycosio | pycosio/storage/azure_file.py | _AzureFileSystem._make_dir | def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_azure_exception():
# Directory
if 'directory_name' in client_kwargs:
return self.client.create_directory(
share_name=client_kwargs['share_name'],
directory_name=client_kwargs['directory_name'])
# Share
return self.client.create_share(**client_kwargs) | python | def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_azure_exception():
# Directory
if 'directory_name' in client_kwargs:
return self.client.create_directory(
share_name=client_kwargs['share_name'],
directory_name=client_kwargs['directory_name'])
# Share
return self.client.create_share(**client_kwargs) | [
"def",
"_make_dir",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_azure_exception",
"(",
")",
":",
"# Directory",
"if",
"'directory_name'",
"in",
"client_kwargs",
":",
"return",
"self",
".",
"client",
".",
"create_directory",
"(",
"share_name",
"... | Make a directory.
args:
client_kwargs (dict): Client arguments. | [
"Make",
"a",
"directory",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure_file.py#L169-L184 |
Accelize/pycosio | pycosio/storage/azure_file.py | _AzureFileSystem._remove | def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_azure_exception():
# File
if 'file_name' in client_kwargs:
return self.client.delete_file(
share_name=client_kwargs['share_name'],
directory_name=client_kwargs['directory_name'],
file_name=client_kwargs['file_name'])
# Directory
elif 'directory_name' in client_kwargs:
return self.client.delete_directory(
share_name=client_kwargs['share_name'],
directory_name=client_kwargs['directory_name'])
# Share
return self.client.delete_share(
share_name=client_kwargs['share_name']) | python | def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_azure_exception():
# File
if 'file_name' in client_kwargs:
return self.client.delete_file(
share_name=client_kwargs['share_name'],
directory_name=client_kwargs['directory_name'],
file_name=client_kwargs['file_name'])
# Directory
elif 'directory_name' in client_kwargs:
return self.client.delete_directory(
share_name=client_kwargs['share_name'],
directory_name=client_kwargs['directory_name'])
# Share
return self.client.delete_share(
share_name=client_kwargs['share_name']) | [
"def",
"_remove",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_azure_exception",
"(",
")",
":",
"# File",
"if",
"'file_name'",
"in",
"client_kwargs",
":",
"return",
"self",
".",
"client",
".",
"delete_file",
"(",
"share_name",
"=",
"client_kwa... | Remove an object.
args:
client_kwargs (dict): Client arguments. | [
"Remove",
"an",
"object",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure_file.py#L186-L209 |
Accelize/pycosio | pycosio/storage/azure_file.py | AzureFileRawIO._update_range | def _update_range(self, data, **kwargs):
"""
Update range with data
Args:
data (bytes): data.
"""
self._client.update_range(data=data, **kwargs) | python | def _update_range(self, data, **kwargs):
"""
Update range with data
Args:
data (bytes): data.
"""
self._client.update_range(data=data, **kwargs) | [
"def",
"_update_range",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_client",
".",
"update_range",
"(",
"data",
"=",
"data",
",",
"*",
"*",
"kwargs",
")"
] | Update range with data
Args:
data (bytes): data. | [
"Update",
"range",
"with",
"data"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure_file.py#L267-L274 |
fedora-infra/datanommer | tools/active-contrib.py | handle_bodhi | def handle_bodhi(msg):
""" Given a bodhi message, return the FAS username. """
if 'bodhi.update.comment' in msg.topic:
username = msg.msg['comment']['author']
elif 'bodhi.buildroot_override' in msg.topic:
username = msg.msg['override']['submitter']
else:
username = msg.msg.get('update', {}).get('submitter')
return username | python | def handle_bodhi(msg):
""" Given a bodhi message, return the FAS username. """
if 'bodhi.update.comment' in msg.topic:
username = msg.msg['comment']['author']
elif 'bodhi.buildroot_override' in msg.topic:
username = msg.msg['override']['submitter']
else:
username = msg.msg.get('update', {}).get('submitter')
return username | [
"def",
"handle_bodhi",
"(",
"msg",
")",
":",
"if",
"'bodhi.update.comment'",
"in",
"msg",
".",
"topic",
":",
"username",
"=",
"msg",
".",
"msg",
"[",
"'comment'",
"]",
"[",
"'author'",
"]",
"elif",
"'bodhi.buildroot_override'",
"in",
"msg",
".",
"topic",
"... | Given a bodhi message, return the FAS username. | [
"Given",
"a",
"bodhi",
"message",
"return",
"the",
"FAS",
"username",
"."
] | train | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/tools/active-contrib.py#L64-L73 |
fedora-infra/datanommer | tools/active-contrib.py | handle_wiki | def handle_wiki(msg):
""" Given a wiki message, return the FAS username. """
if 'wiki.article.edit' in msg.topic:
username = msg.msg['user']
elif 'wiki.upload.complete' in msg.topic:
username = msg.msg['user_text']
else:
raise ValueError("Unhandled topic.")
return username | python | def handle_wiki(msg):
""" Given a wiki message, return the FAS username. """
if 'wiki.article.edit' in msg.topic:
username = msg.msg['user']
elif 'wiki.upload.complete' in msg.topic:
username = msg.msg['user_text']
else:
raise ValueError("Unhandled topic.")
return username | [
"def",
"handle_wiki",
"(",
"msg",
")",
":",
"if",
"'wiki.article.edit'",
"in",
"msg",
".",
"topic",
":",
"username",
"=",
"msg",
".",
"msg",
"[",
"'user'",
"]",
"elif",
"'wiki.upload.complete'",
"in",
"msg",
".",
"topic",
":",
"username",
"=",
"msg",
"."... | Given a wiki message, return the FAS username. | [
"Given",
"a",
"wiki",
"message",
"return",
"the",
"FAS",
"username",
"."
] | train | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/tools/active-contrib.py#L76-L86 |
Accelize/pycosio | pycosio/_core/functions_core.py | is_storage | def is_storage(url, storage=None):
"""
Check if file is a local file or a storage file.
File is considered local if:
- URL is a local path.
- URL starts by "file://"
- a "storage" is provided.
Args:
url (str): file path or URL
storage (str): Storage name.
Returns:
bool: return True if file is local.
"""
if storage:
return True
split_url = url.split('://', 1)
if len(split_url) == 2 and split_url[0].lower() != 'file':
return True
return False | python | def is_storage(url, storage=None):
"""
Check if file is a local file or a storage file.
File is considered local if:
- URL is a local path.
- URL starts by "file://"
- a "storage" is provided.
Args:
url (str): file path or URL
storage (str): Storage name.
Returns:
bool: return True if file is local.
"""
if storage:
return True
split_url = url.split('://', 1)
if len(split_url) == 2 and split_url[0].lower() != 'file':
return True
return False | [
"def",
"is_storage",
"(",
"url",
",",
"storage",
"=",
"None",
")",
":",
"if",
"storage",
":",
"return",
"True",
"split_url",
"=",
"url",
".",
"split",
"(",
"'://'",
",",
"1",
")",
"if",
"len",
"(",
"split_url",
")",
"==",
"2",
"and",
"split_url",
"... | Check if file is a local file or a storage file.
File is considered local if:
- URL is a local path.
- URL starts by "file://"
- a "storage" is provided.
Args:
url (str): file path or URL
storage (str): Storage name.
Returns:
bool: return True if file is local. | [
"Check",
"if",
"file",
"is",
"a",
"local",
"file",
"or",
"a",
"storage",
"file",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_core.py#L10-L31 |
Accelize/pycosio | pycosio/_core/functions_core.py | format_and_is_storage | def format_and_is_storage(path):
"""
Checks if path is storage and format it.
If path is an opened file-like object, returns is storage as True.
Args:
path (path-like object or file-like object):
Returns:
tuple: str or file-like object (Updated path),
bool (True if is storage).
"""
if not hasattr(path, 'read'):
path = fsdecode(path).replace('\\', '/')
return path, is_storage(path)
return path, True | python | def format_and_is_storage(path):
"""
Checks if path is storage and format it.
If path is an opened file-like object, returns is storage as True.
Args:
path (path-like object or file-like object):
Returns:
tuple: str or file-like object (Updated path),
bool (True if is storage).
"""
if not hasattr(path, 'read'):
path = fsdecode(path).replace('\\', '/')
return path, is_storage(path)
return path, True | [
"def",
"format_and_is_storage",
"(",
"path",
")",
":",
"if",
"not",
"hasattr",
"(",
"path",
",",
"'read'",
")",
":",
"path",
"=",
"fsdecode",
"(",
"path",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"return",
"path",
",",
"is_storage",
"(",
... | Checks if path is storage and format it.
If path is an opened file-like object, returns is storage as True.
Args:
path (path-like object or file-like object):
Returns:
tuple: str or file-like object (Updated path),
bool (True if is storage). | [
"Checks",
"if",
"path",
"is",
"storage",
"and",
"format",
"it",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_core.py#L34-L50 |
Accelize/pycosio | pycosio/_core/functions_core.py | equivalent_to | def equivalent_to(std_function):
"""
Decorates a cloud object compatible function
to provides fall back to standard function if
used on local files.
Args:
std_function (function): standard function to
used with local files.
Returns:
function: new function
"""
def decorate(cos_function):
"""Decorator argument handler"""
@wraps(cos_function)
def decorated(path, *args, **kwargs):
"""Decorated function"""
# Handles path-like objects
path = fsdecode(path).replace('\\', '/')
# Storage object: Handle with Cloud object storage
# function
if is_storage(path):
with handle_os_exceptions():
return cos_function(path, *args, **kwargs)
# Local file: Redirect to standard function
return std_function(path, *args, **kwargs)
return decorated
return decorate | python | def equivalent_to(std_function):
"""
Decorates a cloud object compatible function
to provides fall back to standard function if
used on local files.
Args:
std_function (function): standard function to
used with local files.
Returns:
function: new function
"""
def decorate(cos_function):
"""Decorator argument handler"""
@wraps(cos_function)
def decorated(path, *args, **kwargs):
"""Decorated function"""
# Handles path-like objects
path = fsdecode(path).replace('\\', '/')
# Storage object: Handle with Cloud object storage
# function
if is_storage(path):
with handle_os_exceptions():
return cos_function(path, *args, **kwargs)
# Local file: Redirect to standard function
return std_function(path, *args, **kwargs)
return decorated
return decorate | [
"def",
"equivalent_to",
"(",
"std_function",
")",
":",
"def",
"decorate",
"(",
"cos_function",
")",
":",
"\"\"\"Decorator argument handler\"\"\"",
"@",
"wraps",
"(",
"cos_function",
")",
"def",
"decorated",
"(",
"path",
",",
"*",
"args",
",",
"*",
"*",
"kwargs... | Decorates a cloud object compatible function
to provides fall back to standard function if
used on local files.
Args:
std_function (function): standard function to
used with local files.
Returns:
function: new function | [
"Decorates",
"a",
"cloud",
"object",
"compatible",
"function",
"to",
"provides",
"fall",
"back",
"to",
"standard",
"function",
"if",
"used",
"on",
"local",
"files",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_core.py#L53-L88 |
Accelize/pycosio | pycosio/storage/oss.py | _handle_oss_error | def _handle_oss_error():
"""
Handle OSS exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _OssError as exception:
if exception.status in _ERROR_CODES:
raise _ERROR_CODES[exception.status](
exception.details.get('Message', ''))
raise | python | def _handle_oss_error():
"""
Handle OSS exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _OssError as exception:
if exception.status in _ERROR_CODES:
raise _ERROR_CODES[exception.status](
exception.details.get('Message', ''))
raise | [
"def",
"_handle_oss_error",
"(",
")",
":",
"try",
":",
"yield",
"except",
"_OssError",
"as",
"exception",
":",
"if",
"exception",
".",
"status",
"in",
"_ERROR_CODES",
":",
"raise",
"_ERROR_CODES",
"[",
"exception",
".",
"status",
"]",
"(",
"exception",
".",
... | Handle OSS exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error. | [
"Handle",
"OSS",
"exception",
"and",
"convert",
"to",
"class",
"IO",
"exceptions"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L25-L39 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem.copy | def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused.
"""
copy_source = self.get_client_kwargs(src)
copy_destination = self.get_client_kwargs(dst)
with _handle_oss_error():
bucket = self._get_bucket(copy_destination)
bucket.copy_object(
source_bucket_name=copy_source['bucket_name'],
source_key=copy_source['key'],
target_key=copy_destination['key']) | python | def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused.
"""
copy_source = self.get_client_kwargs(src)
copy_destination = self.get_client_kwargs(dst)
with _handle_oss_error():
bucket = self._get_bucket(copy_destination)
bucket.copy_object(
source_bucket_name=copy_source['bucket_name'],
source_key=copy_source['key'],
target_key=copy_destination['key']) | [
"def",
"copy",
"(",
"self",
",",
"src",
",",
"dst",
",",
"other_system",
"=",
"None",
")",
":",
"copy_source",
"=",
"self",
".",
"get_client_kwargs",
"(",
"src",
")",
"copy_destination",
"=",
"self",
".",
"get_client_kwargs",
"(",
"dst",
")",
"with",
"_h... | Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused. | [
"Copy",
"object",
"of",
"the",
"same",
"storage",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L67-L83 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem._get_client | def _get_client(self):
"""
OSS2 Auth client
Returns:
oss2.Auth or oss2.StsAuth: client
"""
return (_oss.StsAuth if 'security_token' in self._storage_parameters
else _oss.Auth if self._storage_parameters
else _oss.AnonymousAuth)(**self._storage_parameters) | python | def _get_client(self):
"""
OSS2 Auth client
Returns:
oss2.Auth or oss2.StsAuth: client
"""
return (_oss.StsAuth if 'security_token' in self._storage_parameters
else _oss.Auth if self._storage_parameters
else _oss.AnonymousAuth)(**self._storage_parameters) | [
"def",
"_get_client",
"(",
"self",
")",
":",
"return",
"(",
"_oss",
".",
"StsAuth",
"if",
"'security_token'",
"in",
"self",
".",
"_storage_parameters",
"else",
"_oss",
".",
"Auth",
"if",
"self",
".",
"_storage_parameters",
"else",
"_oss",
".",
"AnonymousAuth",... | OSS2 Auth client
Returns:
oss2.Auth or oss2.StsAuth: client | [
"OSS2",
"Auth",
"client"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L102-L111 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem._get_roots | def _get_roots(self):
"""
Return URL roots for this storage.
Returns:
tuple of str or re.Pattern: URL roots
"""
return (
# OSS Scheme
# - oss://<bucket>/<key>
'oss://',
# URL (With common aliyuncs.com endpoint):
# - http://<bucket>.oss-<region>.aliyuncs.com/<key>
# - https://<bucket>.oss-<region>.aliyuncs.com/<key>
# Note: "oss-<region>.aliyuncs.com" may be replaced by another
# endpoint
_re.compile((r'https?://[\w-]+.%s' % self._endpoint.split(
'//', 1)[1]).replace('.', r'\.'))) | python | def _get_roots(self):
"""
Return URL roots for this storage.
Returns:
tuple of str or re.Pattern: URL roots
"""
return (
# OSS Scheme
# - oss://<bucket>/<key>
'oss://',
# URL (With common aliyuncs.com endpoint):
# - http://<bucket>.oss-<region>.aliyuncs.com/<key>
# - https://<bucket>.oss-<region>.aliyuncs.com/<key>
# Note: "oss-<region>.aliyuncs.com" may be replaced by another
# endpoint
_re.compile((r'https?://[\w-]+.%s' % self._endpoint.split(
'//', 1)[1]).replace('.', r'\.'))) | [
"def",
"_get_roots",
"(",
"self",
")",
":",
"return",
"(",
"# OSS Scheme",
"# - oss://<bucket>/<key>",
"'oss://'",
",",
"# URL (With common aliyuncs.com endpoint):",
"# - http://<bucket>.oss-<region>.aliyuncs.com/<key>",
"# - https://<bucket>.oss-<region>.aliyuncs.com/<key>",
"# Note: ... | Return URL roots for this storage.
Returns:
tuple of str or re.Pattern: URL roots | [
"Return",
"URL",
"roots",
"for",
"this",
"storage",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L113-L134 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem._get_bucket | def _get_bucket(self, client_kwargs):
"""
Get bucket object.
Returns:
oss2.Bucket
"""
return _oss.Bucket(self.client, endpoint=self._endpoint,
bucket_name=client_kwargs['bucket_name']) | python | def _get_bucket(self, client_kwargs):
"""
Get bucket object.
Returns:
oss2.Bucket
"""
return _oss.Bucket(self.client, endpoint=self._endpoint,
bucket_name=client_kwargs['bucket_name']) | [
"def",
"_get_bucket",
"(",
"self",
",",
"client_kwargs",
")",
":",
"return",
"_oss",
".",
"Bucket",
"(",
"self",
".",
"client",
",",
"endpoint",
"=",
"self",
".",
"_endpoint",
",",
"bucket_name",
"=",
"client_kwargs",
"[",
"'bucket_name'",
"]",
")"
] | Get bucket object.
Returns:
oss2.Bucket | [
"Get",
"bucket",
"object",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L136-L144 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem.islink | def islink(self, path=None, header=None):
"""
Returns True if object is a symbolic link.
Args:
path (str): File path or URL.
header (dict): Object header.
Returns:
bool: True if object is Symlink.
"""
if header is None:
header = self._head(self.get_client_kwargs(path))
for key in ('x-oss-object-type', 'type'):
try:
return header.pop(key) == 'Symlink'
except KeyError:
continue
return False | python | def islink(self, path=None, header=None):
"""
Returns True if object is a symbolic link.
Args:
path (str): File path or URL.
header (dict): Object header.
Returns:
bool: True if object is Symlink.
"""
if header is None:
header = self._head(self.get_client_kwargs(path))
for key in ('x-oss-object-type', 'type'):
try:
return header.pop(key) == 'Symlink'
except KeyError:
continue
return False | [
"def",
"islink",
"(",
"self",
",",
"path",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"if",
"header",
"is",
"None",
":",
"header",
"=",
"self",
".",
"_head",
"(",
"self",
".",
"get_client_kwargs",
"(",
"path",
")",
")",
"for",
"key",
"in",
... | Returns True if object is a symbolic link.
Args:
path (str): File path or URL.
header (dict): Object header.
Returns:
bool: True if object is Symlink. | [
"Returns",
"True",
"if",
"object",
"is",
"a",
"symbolic",
"link",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L146-L165 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem._head | def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
return bucket.head_object(
key=client_kwargs['key']).headers
# Bucket
return bucket.get_bucket_info().headers | python | def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
return bucket.head_object(
key=client_kwargs['key']).headers
# Bucket
return bucket.get_bucket_info().headers | [
"def",
"_head",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_oss_error",
"(",
")",
":",
"bucket",
"=",
"self",
".",
"_get_bucket",
"(",
"client_kwargs",
")",
"# Object",
"if",
"'key'",
"in",
"client_kwargs",
":",
"return",
"bucket",
".",
"... | Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header. | [
"Returns",
"object",
"HTTP",
"header",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L167-L186 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem._make_dir | def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
return bucket.put_object(
key=client_kwargs['key'], data=b'')
# Bucket
return bucket.create_bucket() | python | def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
return bucket.put_object(
key=client_kwargs['key'], data=b'')
# Bucket
return bucket.create_bucket() | [
"def",
"_make_dir",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_oss_error",
"(",
")",
":",
"bucket",
"=",
"self",
".",
"_get_bucket",
"(",
"client_kwargs",
")",
"# Object",
"if",
"'key'",
"in",
"client_kwargs",
":",
"return",
"bucket",
".",... | Make a directory.
args:
client_kwargs (dict): Client arguments. | [
"Make",
"a",
"directory",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L188-L204 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem._remove | def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
return bucket.delete_object(key=client_kwargs['key'])
# Bucket
return bucket.delete_bucket() | python | def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
return bucket.delete_object(key=client_kwargs['key'])
# Bucket
return bucket.delete_bucket() | [
"def",
"_remove",
"(",
"self",
",",
"client_kwargs",
")",
":",
"with",
"_handle_oss_error",
"(",
")",
":",
"bucket",
"=",
"self",
".",
"_get_bucket",
"(",
"client_kwargs",
")",
"# Object",
"if",
"'key'",
"in",
"client_kwargs",
":",
"return",
"bucket",
".",
... | Remove an object.
args:
client_kwargs (dict): Client arguments. | [
"Remove",
"an",
"object",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L206-L221 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem._model_to_dict | def _model_to_dict(model, ignore):
"""
Convert OSS model to dict.
Args:
model (oss2.models.RequestResult): Model.
ignore (tuple of str): Keys to not insert to dict.
Returns:
dict: Model dict version.
"""
return {attr: value for attr, value in model.__dict__.items()
if not attr.startswith('_') and attr not in ignore} | python | def _model_to_dict(model, ignore):
"""
Convert OSS model to dict.
Args:
model (oss2.models.RequestResult): Model.
ignore (tuple of str): Keys to not insert to dict.
Returns:
dict: Model dict version.
"""
return {attr: value for attr, value in model.__dict__.items()
if not attr.startswith('_') and attr not in ignore} | [
"def",
"_model_to_dict",
"(",
"model",
",",
"ignore",
")",
":",
"return",
"{",
"attr",
":",
"value",
"for",
"attr",
",",
"value",
"in",
"model",
".",
"__dict__",
".",
"items",
"(",
")",
"if",
"not",
"attr",
".",
"startswith",
"(",
"'_'",
")",
"and",
... | Convert OSS model to dict.
Args:
model (oss2.models.RequestResult): Model.
ignore (tuple of str): Keys to not insert to dict.
Returns:
dict: Model dict version. | [
"Convert",
"OSS",
"model",
"to",
"dict",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L224-L236 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem._list_locators | def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_oss_error():
response = _oss.Service(
self.client, endpoint=self._endpoint).list_buckets()
for bucket in response.buckets:
yield bucket.name, self._model_to_dict(bucket, ('name',)) | python | def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_oss_error():
response = _oss.Service(
self.client, endpoint=self._endpoint).list_buckets()
for bucket in response.buckets:
yield bucket.name, self._model_to_dict(bucket, ('name',)) | [
"def",
"_list_locators",
"(",
"self",
")",
":",
"with",
"_handle_oss_error",
"(",
")",
":",
"response",
"=",
"_oss",
".",
"Service",
"(",
"self",
".",
"client",
",",
"endpoint",
"=",
"self",
".",
"_endpoint",
")",
".",
"list_buckets",
"(",
")",
"for",
... | Lists locators.
Returns:
generator of tuple: locator name str, locator header dict | [
"Lists",
"locators",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L238-L250 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem._list_objects | def _list_objects(self, client_kwargs, path, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict
"""
kwargs = dict()
if max_request_entries:
kwargs['max_keys'] = max_request_entries
bucket = self._get_bucket(client_kwargs)
while True:
with _handle_oss_error():
response = bucket.list_objects(prefix=path, **kwargs)
if not response.object_list:
# In case of empty dir, return empty dir path:
# if empty result, the dir do not exists.
raise _ObjectNotFoundError('Not found: %s' % path)
for obj in response.object_list:
yield obj.key, self._model_to_dict(obj, ('key',))
# Handles results on more than one page
if response.next_marker:
client_kwargs['marker'] = response.next_marker
else:
# End of results
break | python | def _list_objects(self, client_kwargs, path, max_request_entries):
"""
Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict
"""
kwargs = dict()
if max_request_entries:
kwargs['max_keys'] = max_request_entries
bucket = self._get_bucket(client_kwargs)
while True:
with _handle_oss_error():
response = bucket.list_objects(prefix=path, **kwargs)
if not response.object_list:
# In case of empty dir, return empty dir path:
# if empty result, the dir do not exists.
raise _ObjectNotFoundError('Not found: %s' % path)
for obj in response.object_list:
yield obj.key, self._model_to_dict(obj, ('key',))
# Handles results on more than one page
if response.next_marker:
client_kwargs['marker'] = response.next_marker
else:
# End of results
break | [
"def",
"_list_objects",
"(",
"self",
",",
"client_kwargs",
",",
"path",
",",
"max_request_entries",
")",
":",
"kwargs",
"=",
"dict",
"(",
")",
"if",
"max_request_entries",
":",
"kwargs",
"[",
"'max_keys'",
"]",
"=",
"max_request_entries",
"bucket",
"=",
"self"... | Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict | [
"Lists",
"objects",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L252-L288 |
Accelize/pycosio | pycosio/storage/oss.py | OSSRawIO._read_range | def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
if start >= self._size:
# EOF. Do not detect using 416 (Out of range) error, 200 returned.
return bytes()
# Get object bytes range
with _handle_oss_error():
response = self._bucket.get_object(key=self._key, headers=dict(
Range=self._http_range(
# Returns full file if end > size
start, end if end <= self._size else self._size)))
# Get object content
return response.read() | python | def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
if start >= self._size:
# EOF. Do not detect using 416 (Out of range) error, 200 returned.
return bytes()
# Get object bytes range
with _handle_oss_error():
response = self._bucket.get_object(key=self._key, headers=dict(
Range=self._http_range(
# Returns full file if end > size
start, end if end <= self._size else self._size)))
# Get object content
return response.read() | [
"def",
"_read_range",
"(",
"self",
",",
"start",
",",
"end",
"=",
"0",
")",
":",
"if",
"start",
">=",
"self",
".",
"_size",
":",
"# EOF. Do not detect using 416 (Out of range) error, 200 returned.",
"return",
"bytes",
"(",
")",
"# Get object bytes range",
"with",
... | Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read | [
"Read",
"a",
"range",
"of",
"bytes",
"in",
"stream",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L327-L351 |
Accelize/pycosio | pycosio/storage/oss.py | OSSRawIO._readall | def _readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
with _handle_oss_error():
return self._bucket.get_object(key=self._key).read() | python | def _readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
with _handle_oss_error():
return self._bucket.get_object(key=self._key).read() | [
"def",
"_readall",
"(",
"self",
")",
":",
"with",
"_handle_oss_error",
"(",
")",
":",
"return",
"self",
".",
"_bucket",
".",
"get_object",
"(",
"key",
"=",
"self",
".",
"_key",
")",
".",
"read",
"(",
")"
] | Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content | [
"Read",
"and",
"return",
"all",
"the",
"bytes",
"from",
"the",
"stream",
"until",
"EOF",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L353-L361 |
Accelize/pycosio | pycosio/storage/oss.py | OSSRawIO._flush | def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
with _handle_oss_error():
self._bucket.put_object(key=self._key, data=buffer.tobytes()) | python | def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
with _handle_oss_error():
self._bucket.put_object(key=self._key, data=buffer.tobytes()) | [
"def",
"_flush",
"(",
"self",
",",
"buffer",
")",
":",
"with",
"_handle_oss_error",
"(",
")",
":",
"self",
".",
"_bucket",
".",
"put_object",
"(",
"key",
"=",
"self",
".",
"_key",
",",
"data",
"=",
"buffer",
".",
"tobytes",
"(",
")",
")"
] | Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content. | [
"Flush",
"the",
"write",
"buffers",
"of",
"the",
"stream",
"if",
"applicable",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L363-L371 |
Accelize/pycosio | pycosio/storage/oss.py | OSSBufferedIO._flush | def _flush(self):
"""
Flush the write buffers of the stream.
"""
# Initialize multipart upload
if self._upload_id is None:
with _handle_oss_error():
self._upload_id = self._bucket.init_multipart_upload(
self._key).upload_id
# Upload part with workers
response = self._workers.submit(
self._bucket.upload_part, key=self._key, upload_id=self._upload_id,
part_number=self._seek, data=self._get_buffer().tobytes())
# Save part information
self._write_futures.append(
dict(response=response, part_number=self._seek)) | python | def _flush(self):
"""
Flush the write buffers of the stream.
"""
# Initialize multipart upload
if self._upload_id is None:
with _handle_oss_error():
self._upload_id = self._bucket.init_multipart_upload(
self._key).upload_id
# Upload part with workers
response = self._workers.submit(
self._bucket.upload_part, key=self._key, upload_id=self._upload_id,
part_number=self._seek, data=self._get_buffer().tobytes())
# Save part information
self._write_futures.append(
dict(response=response, part_number=self._seek)) | [
"def",
"_flush",
"(",
"self",
")",
":",
"# Initialize multipart upload",
"if",
"self",
".",
"_upload_id",
"is",
"None",
":",
"with",
"_handle_oss_error",
"(",
")",
":",
"self",
".",
"_upload_id",
"=",
"self",
".",
"_bucket",
".",
"init_multipart_upload",
"(",
... | Flush the write buffers of the stream. | [
"Flush",
"the",
"write",
"buffers",
"of",
"the",
"stream",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L403-L420 |
Accelize/pycosio | pycosio/storage/oss.py | OSSBufferedIO._close_writable | def _close_writable(self):
"""
Close the object in write mode.
"""
# Wait parts upload completion
parts = [_PartInfo(part_number=future['part_number'],
etag=future['response'].result().etag)
for future in self._write_futures]
# Complete multipart upload
with _handle_oss_error():
try:
self._bucket.complete_multipart_upload(
key=self._key, upload_id=self._upload_id, parts=parts)
except _OssError:
# Clean up failed upload
self._bucket.abort_multipart_upload(
key=self._key, upload_id=self._upload_id)
raise | python | def _close_writable(self):
"""
Close the object in write mode.
"""
# Wait parts upload completion
parts = [_PartInfo(part_number=future['part_number'],
etag=future['response'].result().etag)
for future in self._write_futures]
# Complete multipart upload
with _handle_oss_error():
try:
self._bucket.complete_multipart_upload(
key=self._key, upload_id=self._upload_id, parts=parts)
except _OssError:
# Clean up failed upload
self._bucket.abort_multipart_upload(
key=self._key, upload_id=self._upload_id)
raise | [
"def",
"_close_writable",
"(",
"self",
")",
":",
"# Wait parts upload completion",
"parts",
"=",
"[",
"_PartInfo",
"(",
"part_number",
"=",
"future",
"[",
"'part_number'",
"]",
",",
"etag",
"=",
"future",
"[",
"'response'",
"]",
".",
"result",
"(",
")",
".",... | Close the object in write mode. | [
"Close",
"the",
"object",
"in",
"write",
"mode",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L422-L440 |
Accelize/pycosio | pycosio/_core/functions_io.py | cos_open | def cos_open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, storage=None, storage_parameters=None, unsecure=None,
**kwargs):
"""
Open file and return a corresponding file object.
Equivalent to "io.open" or builtin "open".
File can also be binary opened file-like object.
Args:
file (path-like object or file-like object): File path, object URL or
opened file-like object.
mode (str): mode in which the file is opened (default to 'rb').
see "io.open" for all possible modes. Note that all modes may
not be supported by all kind of file and storage.
buffering (int): Set the buffering policy.
-1 to use default behavior,
0 to switch buffering off,
1 to select line buffering (only usable in text mode),
and an integer > 1 to indicate the size in bytes of a
fixed-size chunk buffer.
See "io.open" for more information.
encoding (str): The name of the encoding used to
decode or encode the file. This should only be used in text mode.
See "io.open" for more information.
errors (str): Specifies how encoding and decoding errors
are to be handled.
This should only be used in text mode.
See "io.open" for more information.
newline (str): Controls how universal newlines mode works.
This should only be used in text mode.
See "io.open" for more information.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
kwargs: Other arguments to pass to opened object.
Note that theses arguments may not be compatible with
all kind of file and storage.
Returns:
file-like object: opened file.
Raises:
OSError: If the file cannot be opened.
FileExistsError: File open in 'x' mode already exists.
"""
# Handles file-like objects:
if hasattr(file, 'read'):
with _text_io_wrapper(file, mode, encoding, errors, newline) as wrapped:
yield wrapped
return
# Handles path-like objects
file = fsdecode(file).replace('\\', '/')
# Storage object
if is_storage(file, storage):
with get_instance(
name=file, cls='raw' if buffering == 0 else 'buffered',
storage=storage, storage_parameters=storage_parameters,
mode=mode, unsecure=unsecure, **kwargs) as stream:
with _text_io_wrapper(stream, mode=mode, encoding=encoding,
errors=errors, newline=newline) as wrapped:
yield wrapped
# Local file: Redirect to "io.open"
else:
with io_open(file, mode, buffering, encoding, errors, newline,
**kwargs) as stream:
yield stream | python | def cos_open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, storage=None, storage_parameters=None, unsecure=None,
**kwargs):
"""
Open file and return a corresponding file object.
Equivalent to "io.open" or builtin "open".
File can also be binary opened file-like object.
Args:
file (path-like object or file-like object): File path, object URL or
opened file-like object.
mode (str): mode in which the file is opened (default to 'rb').
see "io.open" for all possible modes. Note that all modes may
not be supported by all kind of file and storage.
buffering (int): Set the buffering policy.
-1 to use default behavior,
0 to switch buffering off,
1 to select line buffering (only usable in text mode),
and an integer > 1 to indicate the size in bytes of a
fixed-size chunk buffer.
See "io.open" for more information.
encoding (str): The name of the encoding used to
decode or encode the file. This should only be used in text mode.
See "io.open" for more information.
errors (str): Specifies how encoding and decoding errors
are to be handled.
This should only be used in text mode.
See "io.open" for more information.
newline (str): Controls how universal newlines mode works.
This should only be used in text mode.
See "io.open" for more information.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
kwargs: Other arguments to pass to opened object.
Note that theses arguments may not be compatible with
all kind of file and storage.
Returns:
file-like object: opened file.
Raises:
OSError: If the file cannot be opened.
FileExistsError: File open in 'x' mode already exists.
"""
# Handles file-like objects:
if hasattr(file, 'read'):
with _text_io_wrapper(file, mode, encoding, errors, newline) as wrapped:
yield wrapped
return
# Handles path-like objects
file = fsdecode(file).replace('\\', '/')
# Storage object
if is_storage(file, storage):
with get_instance(
name=file, cls='raw' if buffering == 0 else 'buffered',
storage=storage, storage_parameters=storage_parameters,
mode=mode, unsecure=unsecure, **kwargs) as stream:
with _text_io_wrapper(stream, mode=mode, encoding=encoding,
errors=errors, newline=newline) as wrapped:
yield wrapped
# Local file: Redirect to "io.open"
else:
with io_open(file, mode, buffering, encoding, errors, newline,
**kwargs) as stream:
yield stream | [
"def",
"cos_open",
"(",
"file",
",",
"mode",
"=",
"'r'",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
"newline",
"=",
"None",
",",
"storage",
"=",
"None",
",",
"storage_parameters",
"=",
"None",
",",... | Open file and return a corresponding file object.
Equivalent to "io.open" or builtin "open".
File can also be binary opened file-like object.
Args:
file (path-like object or file-like object): File path, object URL or
opened file-like object.
mode (str): mode in which the file is opened (default to 'rb').
see "io.open" for all possible modes. Note that all modes may
not be supported by all kind of file and storage.
buffering (int): Set the buffering policy.
-1 to use default behavior,
0 to switch buffering off,
1 to select line buffering (only usable in text mode),
and an integer > 1 to indicate the size in bytes of a
fixed-size chunk buffer.
See "io.open" for more information.
encoding (str): The name of the encoding used to
decode or encode the file. This should only be used in text mode.
See "io.open" for more information.
errors (str): Specifies how encoding and decoding errors
are to be handled.
This should only be used in text mode.
See "io.open" for more information.
newline (str): Controls how universal newlines mode works.
This should only be used in text mode.
See "io.open" for more information.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
kwargs: Other arguments to pass to opened object.
Note that theses arguments may not be compatible with
all kind of file and storage.
Returns:
file-like object: opened file.
Raises:
OSError: If the file cannot be opened.
FileExistsError: File open in 'x' mode already exists. | [
"Open",
"file",
"and",
"return",
"a",
"corresponding",
"file",
"object",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_io.py#L12-L85 |
Accelize/pycosio | pycosio/_core/functions_io.py | _text_io_wrapper | def _text_io_wrapper(stream, mode, encoding, errors, newline):
"""Wrap a binary stream to Text stream.
Args:
stream (file-like object): binary stream.
mode (str): Open mode.
encoding (str): Stream encoding.
errors (str): Decoding error handling.
newline (str): Universal newlines
"""
# Text mode, if not already a text stream
# That has the "encoding" attribute
if "t" in mode and not hasattr(stream, 'encoding'):
text_stream = TextIOWrapper(
stream, encoding=encoding, errors=errors, newline=newline)
yield text_stream
text_stream.flush()
# Binary mode (Or already text stream)
else:
yield stream | python | def _text_io_wrapper(stream, mode, encoding, errors, newline):
"""Wrap a binary stream to Text stream.
Args:
stream (file-like object): binary stream.
mode (str): Open mode.
encoding (str): Stream encoding.
errors (str): Decoding error handling.
newline (str): Universal newlines
"""
# Text mode, if not already a text stream
# That has the "encoding" attribute
if "t" in mode and not hasattr(stream, 'encoding'):
text_stream = TextIOWrapper(
stream, encoding=encoding, errors=errors, newline=newline)
yield text_stream
text_stream.flush()
# Binary mode (Or already text stream)
else:
yield stream | [
"def",
"_text_io_wrapper",
"(",
"stream",
",",
"mode",
",",
"encoding",
",",
"errors",
",",
"newline",
")",
":",
"# Text mode, if not already a text stream",
"# That has the \"encoding\" attribute",
"if",
"\"t\"",
"in",
"mode",
"and",
"not",
"hasattr",
"(",
"stream",
... | Wrap a binary stream to Text stream.
Args:
stream (file-like object): binary stream.
mode (str): Open mode.
encoding (str): Stream encoding.
errors (str): Decoding error handling.
newline (str): Universal newlines | [
"Wrap",
"a",
"binary",
"stream",
"to",
"Text",
"stream",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_io.py#L89-L109 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/utils.py | random_model | def random_model(ctx, model_class_name):
"""
Get a random model identifier by class name. For example::
# db/fixtures/Category.yml
{% for i in range(0, 10) %}
category{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
category: {{ random_model('Category') }}
Will render to something like the following::
# db/fixtures/Post.yml (rendered)
a blog_post:
category: "Category(category7)"
:param ctx: The context variables of the current template (passed automatically)
:param model_class_name: The class name of the model to get.
"""
model_identifiers = ctx['model_identifiers'][model_class_name]
if not model_identifiers:
return 'None'
idx = random.randrange(0, len(model_identifiers))
return '"%s(%s)"' % (model_class_name, model_identifiers[idx]) | python | def random_model(ctx, model_class_name):
"""
Get a random model identifier by class name. For example::
# db/fixtures/Category.yml
{% for i in range(0, 10) %}
category{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
category: {{ random_model('Category') }}
Will render to something like the following::
# db/fixtures/Post.yml (rendered)
a blog_post:
category: "Category(category7)"
:param ctx: The context variables of the current template (passed automatically)
:param model_class_name: The class name of the model to get.
"""
model_identifiers = ctx['model_identifiers'][model_class_name]
if not model_identifiers:
return 'None'
idx = random.randrange(0, len(model_identifiers))
return '"%s(%s)"' % (model_class_name, model_identifiers[idx]) | [
"def",
"random_model",
"(",
"ctx",
",",
"model_class_name",
")",
":",
"model_identifiers",
"=",
"ctx",
"[",
"'model_identifiers'",
"]",
"[",
"model_class_name",
"]",
"if",
"not",
"model_identifiers",
":",
"return",
"'None'",
"idx",
"=",
"random",
".",
"randrange... | Get a random model identifier by class name. For example::
# db/fixtures/Category.yml
{% for i in range(0, 10) %}
category{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
category: {{ random_model('Category') }}
Will render to something like the following::
# db/fixtures/Post.yml (rendered)
a blog_post:
category: "Category(category7)"
:param ctx: The context variables of the current template (passed automatically)
:param model_class_name: The class name of the model to get. | [
"Get",
"a",
"random",
"model",
"identifier",
"by",
"class",
"name",
".",
"For",
"example",
"::"
] | train | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/utils.py#L28-L55 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/utils.py | random_models | def random_models(ctx, model_class_name, min_count=0, max_count=3):
"""
Get a random model identifier by class name. Example usage::
# db/fixtures/Tag.yml
{% for i in range(0, 10) %}
tag{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
tags: {{ random_models('Tag') }}
Will render to something like the following::
# db/fixtures/Post.yml (rendered)
a blog_post:
tags: ["Tag(tag2, tag5)"]
:param ctx: The context variables of the current template (passed automatically)
:param model_class_name: The class name of the models to get.
:param min_count: The minimum number of models to return.
:param max_count: The maximum number of models to return.
"""
model_identifiers = ctx['model_identifiers'][model_class_name]
num_models = random.randint(min_count, min(max_count, len(model_identifiers)))
if num_models == 0:
return '[]'
added = set()
while len(added) < num_models:
idx = random.randrange(0, len(model_identifiers))
added.add(model_identifiers[idx])
return '["%s(%s)"]' % (model_class_name, ','.join(added)) | python | def random_models(ctx, model_class_name, min_count=0, max_count=3):
"""
Get a random model identifier by class name. Example usage::
# db/fixtures/Tag.yml
{% for i in range(0, 10) %}
tag{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
tags: {{ random_models('Tag') }}
Will render to something like the following::
# db/fixtures/Post.yml (rendered)
a blog_post:
tags: ["Tag(tag2, tag5)"]
:param ctx: The context variables of the current template (passed automatically)
:param model_class_name: The class name of the models to get.
:param min_count: The minimum number of models to return.
:param max_count: The maximum number of models to return.
"""
model_identifiers = ctx['model_identifiers'][model_class_name]
num_models = random.randint(min_count, min(max_count, len(model_identifiers)))
if num_models == 0:
return '[]'
added = set()
while len(added) < num_models:
idx = random.randrange(0, len(model_identifiers))
added.add(model_identifiers[idx])
return '["%s(%s)"]' % (model_class_name, ','.join(added)) | [
"def",
"random_models",
"(",
"ctx",
",",
"model_class_name",
",",
"min_count",
"=",
"0",
",",
"max_count",
"=",
"3",
")",
":",
"model_identifiers",
"=",
"ctx",
"[",
"'model_identifiers'",
"]",
"[",
"model_class_name",
"]",
"num_models",
"=",
"random",
".",
"... | Get a random model identifier by class name. Example usage::
# db/fixtures/Tag.yml
{% for i in range(0, 10) %}
tag{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
tags: {{ random_models('Tag') }}
Will render to something like the following::
# db/fixtures/Post.yml (rendered)
a blog_post:
tags: ["Tag(tag2, tag5)"]
:param ctx: The context variables of the current template (passed automatically)
:param model_class_name: The class name of the models to get.
:param min_count: The minimum number of models to return.
:param max_count: The maximum number of models to return. | [
"Get",
"a",
"random",
"model",
"identifier",
"by",
"class",
"name",
".",
"Example",
"usage",
"::"
] | train | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/utils.py#L58-L92 |
Accelize/pycosio | pycosio/_core/io_file_system.py | FileSystemBase.list_objects | def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None):
"""
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only first level objects.
Else, returns full tree.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict
"""
entries = 0
next_values = []
max_request_entries_arg = None
if not relative:
path = self.relpath(path)
# From root
if not path:
objects = self._list_locators()
# Sub directory
else:
objects = self._list_objects(
self.get_client_kwargs(path), max_request_entries)
# Yield file hierarchy
for obj in objects:
# Generate first level objects entries
try:
name, header, is_directory = obj
except ValueError:
# Locators
name, header = obj
is_directory = True
# Start to generate subdirectories content
if is_directory and not first_level:
name = next_path = name.rstrip('/') + '/'
if path:
next_path = '/'.join((path.rstrip('/'), name))
if max_request_entries is not None:
max_request_entries_arg = max_request_entries - entries
next_values.append((
name, self._generate_async(self.list_objects(
next_path, relative=True,
max_request_entries=max_request_entries_arg))))
entries += 1
yield name, header
if entries == max_request_entries:
return
for next_name, generator in next_values:
# Generate other levels objects entries
for name, header in generator:
entries += 1
yield '/'.join((next_name.rstrip('/'), name)), header
if entries == max_request_entries:
return | python | def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None):
"""
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only first level objects.
Else, returns full tree.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict
"""
entries = 0
next_values = []
max_request_entries_arg = None
if not relative:
path = self.relpath(path)
# From root
if not path:
objects = self._list_locators()
# Sub directory
else:
objects = self._list_objects(
self.get_client_kwargs(path), max_request_entries)
# Yield file hierarchy
for obj in objects:
# Generate first level objects entries
try:
name, header, is_directory = obj
except ValueError:
# Locators
name, header = obj
is_directory = True
# Start to generate subdirectories content
if is_directory and not first_level:
name = next_path = name.rstrip('/') + '/'
if path:
next_path = '/'.join((path.rstrip('/'), name))
if max_request_entries is not None:
max_request_entries_arg = max_request_entries - entries
next_values.append((
name, self._generate_async(self.list_objects(
next_path, relative=True,
max_request_entries=max_request_entries_arg))))
entries += 1
yield name, header
if entries == max_request_entries:
return
for next_name, generator in next_values:
# Generate other levels objects entries
for name, header in generator:
entries += 1
yield '/'.join((next_name.rstrip('/'), name)), header
if entries == max_request_entries:
return | [
"def",
"list_objects",
"(",
"self",
",",
"path",
"=",
"''",
",",
"relative",
"=",
"False",
",",
"first_level",
"=",
"False",
",",
"max_request_entries",
"=",
"None",
")",
":",
"entries",
"=",
"0",
"next_values",
"=",
"[",
"]",
"max_request_entries_arg",
"=... | List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only first level objects.
Else, returns full tree.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict | [
"List",
"objects",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_file_system.py#L13-L82 |
fedora-infra/datanommer | tools/first-week-of-datanommer/tstamptobuckets.py | CollisionDict.hash_key | def hash_key(self, key):
""" "Hash" all keys in a timerange to the same value. """
for i, destination_key in enumerate(self._dict):
if key < destination_key:
return destination_key
return key | python | def hash_key(self, key):
""" "Hash" all keys in a timerange to the same value. """
for i, destination_key in enumerate(self._dict):
if key < destination_key:
return destination_key
return key | [
"def",
"hash_key",
"(",
"self",
",",
"key",
")",
":",
"for",
"i",
",",
"destination_key",
"in",
"enumerate",
"(",
"self",
".",
"_dict",
")",
":",
"if",
"key",
"<",
"destination_key",
":",
"return",
"destination_key",
"return",
"key"
] | "Hash" all keys in a timerange to the same value. | [
"Hash",
"all",
"keys",
"in",
"a",
"timerange",
"to",
"the",
"same",
"value",
"."
] | train | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/tools/first-week-of-datanommer/tstamptobuckets.py#L31-L37 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/fixtures_loader.py | FixturesLoader.create_all | def create_all(self, progress_callback: Optional[callable] = None) -> Dict[str, object]:
"""
Creates all the models discovered from fixture files in :attr:`fixtures_dir`.
:param progress_callback: An optional function to track progress. It must take three
parameters:
- an :class:`Identifier`
- the model instance
- and a boolean specifying whether the model was created
:return: A dictionary keyed by identifier where the values are model instances.
"""
if not self._loaded:
self._load_data()
# build up a directed acyclic graph to determine the model instantiation order
dag = nx.DiGraph()
for model_class_name, dependencies in self.relationships.items():
dag.add_node(model_class_name)
for dep in dependencies:
dag.add_edge(model_class_name, dep)
try:
creation_order = reversed(list(nx.topological_sort(dag)))
except nx.NetworkXUnfeasible:
raise Exception('Circular dependency detected between models: '
', '.join(['{a} -> {b}'.format(a=a, b=b)
for a, b in nx.find_cycle(dag)]))
# create or update the models in the determined order
rv = {}
for model_class_name in creation_order:
for identifier_key, data in self.model_fixtures[model_class_name].items():
identifier = Identifier(model_class_name, identifier_key)
data = self.factory.maybe_convert_values(identifier, data)
self._cache[identifier_key] = data
model_instance, created = self.factory.create_or_update(identifier, data)
if progress_callback:
progress_callback(identifier, model_instance, created)
rv[identifier_key] = model_instance
self.factory.commit()
return rv | python | def create_all(self, progress_callback: Optional[callable] = None) -> Dict[str, object]:
"""
Creates all the models discovered from fixture files in :attr:`fixtures_dir`.
:param progress_callback: An optional function to track progress. It must take three
parameters:
- an :class:`Identifier`
- the model instance
- and a boolean specifying whether the model was created
:return: A dictionary keyed by identifier where the values are model instances.
"""
if not self._loaded:
self._load_data()
# build up a directed acyclic graph to determine the model instantiation order
dag = nx.DiGraph()
for model_class_name, dependencies in self.relationships.items():
dag.add_node(model_class_name)
for dep in dependencies:
dag.add_edge(model_class_name, dep)
try:
creation_order = reversed(list(nx.topological_sort(dag)))
except nx.NetworkXUnfeasible:
raise Exception('Circular dependency detected between models: '
', '.join(['{a} -> {b}'.format(a=a, b=b)
for a, b in nx.find_cycle(dag)]))
# create or update the models in the determined order
rv = {}
for model_class_name in creation_order:
for identifier_key, data in self.model_fixtures[model_class_name].items():
identifier = Identifier(model_class_name, identifier_key)
data = self.factory.maybe_convert_values(identifier, data)
self._cache[identifier_key] = data
model_instance, created = self.factory.create_or_update(identifier, data)
if progress_callback:
progress_callback(identifier, model_instance, created)
rv[identifier_key] = model_instance
self.factory.commit()
return rv | [
"def",
"create_all",
"(",
"self",
",",
"progress_callback",
":",
"Optional",
"[",
"callable",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"object",
"]",
":",
"if",
"not",
"self",
".",
"_loaded",
":",
"self",
".",
"_load_data",
"(",
")",
"# ... | Creates all the models discovered from fixture files in :attr:`fixtures_dir`.
:param progress_callback: An optional function to track progress. It must take three
parameters:
- an :class:`Identifier`
- the model instance
- and a boolean specifying whether the model was created
:return: A dictionary keyed by identifier where the values are model instances. | [
"Creates",
"all",
"the",
"models",
"discovered",
"from",
"fixture",
"files",
"in",
":",
"attr",
":",
"fixtures_dir",
"."
] | train | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/fixtures_loader.py#L53-L95 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/fixtures_loader.py | FixturesLoader.convert_identifiers | def convert_identifiers(self, identifiers: Union[Identifier, List[Identifier]]):
"""
Convert an individual :class:`Identifier` to a model instance,
or a list of Identifiers to a list of model instances.
"""
if not identifiers:
return identifiers
def _create_or_update(identifier):
data = self._cache[identifier.key]
return self.factory.create_or_update(identifier, data)[0]
if isinstance(identifiers, Identifier):
return _create_or_update(identifiers)
elif isinstance(identifiers, list) and isinstance(identifiers[0], Identifier):
return [_create_or_update(identifier) for identifier in identifiers]
else:
raise TypeError('`identifiers` must be an Identifier or list of Identifiers.') | python | def convert_identifiers(self, identifiers: Union[Identifier, List[Identifier]]):
"""
Convert an individual :class:`Identifier` to a model instance,
or a list of Identifiers to a list of model instances.
"""
if not identifiers:
return identifiers
def _create_or_update(identifier):
data = self._cache[identifier.key]
return self.factory.create_or_update(identifier, data)[0]
if isinstance(identifiers, Identifier):
return _create_or_update(identifiers)
elif isinstance(identifiers, list) and isinstance(identifiers[0], Identifier):
return [_create_or_update(identifier) for identifier in identifiers]
else:
raise TypeError('`identifiers` must be an Identifier or list of Identifiers.') | [
"def",
"convert_identifiers",
"(",
"self",
",",
"identifiers",
":",
"Union",
"[",
"Identifier",
",",
"List",
"[",
"Identifier",
"]",
"]",
")",
":",
"if",
"not",
"identifiers",
":",
"return",
"identifiers",
"def",
"_create_or_update",
"(",
"identifier",
")",
... | Convert an individual :class:`Identifier` to a model instance,
or a list of Identifiers to a list of model instances. | [
"Convert",
"an",
"individual",
":",
"class",
":",
"Identifier",
"to",
"a",
"model",
"instance",
"or",
"a",
"list",
"of",
"Identifiers",
"to",
"a",
"list",
"of",
"model",
"instances",
"."
] | train | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/fixtures_loader.py#L97-L114 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/fixtures_loader.py | FixturesLoader._load_data | def _load_data(self):
"""
Load all fixtures from :attr:`fixtures_dir`
"""
filenames = []
model_identifiers = defaultdict(list)
# attempt to load fixture files from given directories (first pass)
# for each valid model fixture file, read it into the cache and get the
# list of identifier keys from it
for fixtures_dir in self.fixture_dirs:
for filename in os.listdir(fixtures_dir):
path = os.path.join(fixtures_dir, filename)
file_ext = filename[filename.find('.')+1:]
# make sure it's a valid fixture file
if os.path.isfile(path) and file_ext in {'yml', 'yaml'}:
filenames.append(filename)
with open(path) as f:
self._cache[filename] = f.read()
# preload to determine identifier keys
with self._preloading_env() as env:
rendered_yaml = env.get_template(filename).render()
data = yaml.load(rendered_yaml)
if data:
class_name = filename[:filename.rfind('.')]
model_identifiers[class_name] = list(data.keys())
# second pass where we can render the jinja templates with knowledge of all
# the model identifier keys (allows random_model and random_models to work)
for filename in filenames:
self._load_from_yaml(filename, model_identifiers)
self._loaded = True | python | def _load_data(self):
"""
Load all fixtures from :attr:`fixtures_dir`
"""
filenames = []
model_identifiers = defaultdict(list)
# attempt to load fixture files from given directories (first pass)
# for each valid model fixture file, read it into the cache and get the
# list of identifier keys from it
for fixtures_dir in self.fixture_dirs:
for filename in os.listdir(fixtures_dir):
path = os.path.join(fixtures_dir, filename)
file_ext = filename[filename.find('.')+1:]
# make sure it's a valid fixture file
if os.path.isfile(path) and file_ext in {'yml', 'yaml'}:
filenames.append(filename)
with open(path) as f:
self._cache[filename] = f.read()
# preload to determine identifier keys
with self._preloading_env() as env:
rendered_yaml = env.get_template(filename).render()
data = yaml.load(rendered_yaml)
if data:
class_name = filename[:filename.rfind('.')]
model_identifiers[class_name] = list(data.keys())
# second pass where we can render the jinja templates with knowledge of all
# the model identifier keys (allows random_model and random_models to work)
for filename in filenames:
self._load_from_yaml(filename, model_identifiers)
self._loaded = True | [
"def",
"_load_data",
"(",
"self",
")",
":",
"filenames",
"=",
"[",
"]",
"model_identifiers",
"=",
"defaultdict",
"(",
"list",
")",
"# attempt to load fixture files from given directories (first pass)",
"# for each valid model fixture file, read it into the cache and get the",
"# ... | Load all fixtures from :attr:`fixtures_dir` | [
"Load",
"all",
"fixtures",
"from",
":",
"attr",
":",
"fixtures_dir"
] | train | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/fixtures_loader.py#L116-L150 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/fixtures_loader.py | FixturesLoader._load_from_yaml | def _load_from_yaml(self, filename: str, model_identifiers: Dict[str, List[str]]):
"""
Load fixtures from the given filename
"""
class_name = filename[:filename.rfind('.')]
rendered_yaml = self.env.get_template(filename).render(
model_identifiers=model_identifiers)
fixture_data, self.relationships[class_name] = self._post_process_yaml_data(
yaml.load(rendered_yaml),
self.factory.get_relationships(class_name))
for identifier_key, data in fixture_data.items():
self.model_fixtures[class_name][identifier_key] = data | python | def _load_from_yaml(self, filename: str, model_identifiers: Dict[str, List[str]]):
"""
Load fixtures from the given filename
"""
class_name = filename[:filename.rfind('.')]
rendered_yaml = self.env.get_template(filename).render(
model_identifiers=model_identifiers)
fixture_data, self.relationships[class_name] = self._post_process_yaml_data(
yaml.load(rendered_yaml),
self.factory.get_relationships(class_name))
for identifier_key, data in fixture_data.items():
self.model_fixtures[class_name][identifier_key] = data | [
"def",
"_load_from_yaml",
"(",
"self",
",",
"filename",
":",
"str",
",",
"model_identifiers",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
")",
":",
"class_name",
"=",
"filename",
"[",
":",
"filename",
".",
"rfind",
"(",
"'.'",
")",
"]... | Load fixtures from the given filename | [
"Load",
"fixtures",
"from",
"the",
"given",
"filename"
] | train | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/fixtures_loader.py#L152-L164 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/fixtures_loader.py | FixturesLoader._post_process_yaml_data | def _post_process_yaml_data(self,
fixture_data: Dict[str, Dict[str, Any]],
relationship_columns: Set[str],
) -> Tuple[Dict[str, Dict[str, Any]], List[str]]:
"""
Convert and normalize identifier strings to Identifiers, as well as determine
class relationships.
"""
rv = {}
relationships = set()
if not fixture_data:
return rv, relationships
for identifier_id, data in fixture_data.items():
new_data = {}
for col_name, value in data.items():
if col_name not in relationship_columns:
new_data[col_name] = value
continue
identifiers = normalize_identifiers(value)
if identifiers:
relationships.add(identifiers[0].class_name)
if isinstance(value, str) and len(identifiers) <= 1:
new_data[col_name] = identifiers[0] if identifiers else None
else:
new_data[col_name] = identifiers
rv[identifier_id] = new_data
return rv, list(relationships) | python | def _post_process_yaml_data(self,
fixture_data: Dict[str, Dict[str, Any]],
relationship_columns: Set[str],
) -> Tuple[Dict[str, Dict[str, Any]], List[str]]:
"""
Convert and normalize identifier strings to Identifiers, as well as determine
class relationships.
"""
rv = {}
relationships = set()
if not fixture_data:
return rv, relationships
for identifier_id, data in fixture_data.items():
new_data = {}
for col_name, value in data.items():
if col_name not in relationship_columns:
new_data[col_name] = value
continue
identifiers = normalize_identifiers(value)
if identifiers:
relationships.add(identifiers[0].class_name)
if isinstance(value, str) and len(identifiers) <= 1:
new_data[col_name] = identifiers[0] if identifiers else None
else:
new_data[col_name] = identifiers
rv[identifier_id] = new_data
return rv, list(relationships) | [
"def",
"_post_process_yaml_data",
"(",
"self",
",",
"fixture_data",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"relationship_columns",
":",
"Set",
"[",
"str",
"]",
",",
")",
"->",
"Tuple",
"[",
"Dict",
"[",
"str",
",... | Convert and normalize identifier strings to Identifiers, as well as determine
class relationships. | [
"Convert",
"and",
"normalize",
"identifier",
"strings",
"to",
"Identifiers",
"as",
"well",
"as",
"determine",
"class",
"relationships",
"."
] | train | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/fixtures_loader.py#L166-L196 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/fixtures_loader.py | FixturesLoader._ensure_env | def _ensure_env(self, env: Union[jinja2.Environment, None]):
"""
Make sure the jinja environment is minimally configured.
"""
if not env:
env = jinja2.Environment()
if not env.loader:
env.loader = jinja2.FunctionLoader(lambda filename: self._cache[filename])
if 'faker' not in env.globals:
faker = Faker()
faker.seed(1234)
env.globals['faker'] = faker
if 'random_model' not in env.globals:
env.globals['random_model'] = jinja2.contextfunction(random_model)
if 'random_models' not in env.globals:
env.globals['random_models'] = jinja2.contextfunction(random_models)
return env | python | def _ensure_env(self, env: Union[jinja2.Environment, None]):
"""
Make sure the jinja environment is minimally configured.
"""
if not env:
env = jinja2.Environment()
if not env.loader:
env.loader = jinja2.FunctionLoader(lambda filename: self._cache[filename])
if 'faker' not in env.globals:
faker = Faker()
faker.seed(1234)
env.globals['faker'] = faker
if 'random_model' not in env.globals:
env.globals['random_model'] = jinja2.contextfunction(random_model)
if 'random_models' not in env.globals:
env.globals['random_models'] = jinja2.contextfunction(random_models)
return env | [
"def",
"_ensure_env",
"(",
"self",
",",
"env",
":",
"Union",
"[",
"jinja2",
".",
"Environment",
",",
"None",
"]",
")",
":",
"if",
"not",
"env",
":",
"env",
"=",
"jinja2",
".",
"Environment",
"(",
")",
"if",
"not",
"env",
".",
"loader",
":",
"env",
... | Make sure the jinja environment is minimally configured. | [
"Make",
"sure",
"the",
"jinja",
"environment",
"is",
"minimally",
"configured",
"."
] | train | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/fixtures_loader.py#L198-L214 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/fixtures_loader.py | FixturesLoader._preloading_env | def _preloading_env(self):
"""
A "stripped" jinja environment.
"""
ctx = self.env.globals
try:
ctx['random_model'] = lambda *a, **kw: None
ctx['random_models'] = lambda *a, **kw: None
yield self.env
finally:
ctx['random_model'] = jinja2.contextfunction(random_model)
ctx['random_models'] = jinja2.contextfunction(random_models) | python | def _preloading_env(self):
"""
A "stripped" jinja environment.
"""
ctx = self.env.globals
try:
ctx['random_model'] = lambda *a, **kw: None
ctx['random_models'] = lambda *a, **kw: None
yield self.env
finally:
ctx['random_model'] = jinja2.contextfunction(random_model)
ctx['random_models'] = jinja2.contextfunction(random_models) | [
"def",
"_preloading_env",
"(",
"self",
")",
":",
"ctx",
"=",
"self",
".",
"env",
".",
"globals",
"try",
":",
"ctx",
"[",
"'random_model'",
"]",
"=",
"lambda",
"*",
"a",
",",
"*",
"*",
"kw",
":",
"None",
"ctx",
"[",
"'random_models'",
"]",
"=",
"lam... | A "stripped" jinja environment. | [
"A",
"stripped",
"jinja",
"environment",
"."
] | train | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/fixtures_loader.py#L217-L228 |
Accelize/pycosio | pycosio/_core/storage_manager.py | get_instance | def get_instance(name, cls='system', storage=None, storage_parameters=None,
unsecure=None, *args, **kwargs):
"""
Get a cloud object storage instance.
Args:
name (str): File name, path or URL.
cls (str): Type of class to instantiate.
'raw', 'buffered' or 'system'.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
args, kwargs: Instance arguments
Returns:
pycosio._core.io_base.ObjectIOBase subclass: Instance
"""
system_parameters = _system_parameters(
unsecure=unsecure, storage_parameters=storage_parameters)
# Gets storage information
with _MOUNT_LOCK:
for root in MOUNTED:
if ((isinstance(root, Pattern) and root.match(name)) or
(not isinstance(root, Pattern) and
name.startswith(root))):
info = MOUNTED[root]
# Get stored storage parameters
stored_parameters = info.get('system_parameters') or dict()
if not system_parameters:
same_parameters = True
system_parameters = stored_parameters
elif system_parameters == stored_parameters:
same_parameters = True
else:
same_parameters = False
# Copy not specified parameters from default
system_parameters.update({
key: value for key, value in stored_parameters.items()
if key not in system_parameters})
break
# If not found, tries to mount before getting
else:
mount_info = mount(
storage=storage, name=name, **system_parameters)
info = mount_info[tuple(mount_info)[0]]
same_parameters = True
# Returns system class
if cls == 'system':
if same_parameters:
return info['system_cached']
else:
return info['system'](
roots=info['roots'], **system_parameters)
# Returns other classes
if same_parameters:
if 'storage_parameters' not in system_parameters:
system_parameters['storage_parameters'] = dict()
system_parameters['storage_parameters'][
'pycosio.system_cached'] = info['system_cached']
kwargs.update(system_parameters)
return info[cls](name=name, *args, **kwargs) | python | def get_instance(name, cls='system', storage=None, storage_parameters=None,
unsecure=None, *args, **kwargs):
"""
Get a cloud object storage instance.
Args:
name (str): File name, path or URL.
cls (str): Type of class to instantiate.
'raw', 'buffered' or 'system'.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
args, kwargs: Instance arguments
Returns:
pycosio._core.io_base.ObjectIOBase subclass: Instance
"""
system_parameters = _system_parameters(
unsecure=unsecure, storage_parameters=storage_parameters)
# Gets storage information
with _MOUNT_LOCK:
for root in MOUNTED:
if ((isinstance(root, Pattern) and root.match(name)) or
(not isinstance(root, Pattern) and
name.startswith(root))):
info = MOUNTED[root]
# Get stored storage parameters
stored_parameters = info.get('system_parameters') or dict()
if not system_parameters:
same_parameters = True
system_parameters = stored_parameters
elif system_parameters == stored_parameters:
same_parameters = True
else:
same_parameters = False
# Copy not specified parameters from default
system_parameters.update({
key: value for key, value in stored_parameters.items()
if key not in system_parameters})
break
# If not found, tries to mount before getting
else:
mount_info = mount(
storage=storage, name=name, **system_parameters)
info = mount_info[tuple(mount_info)[0]]
same_parameters = True
# Returns system class
if cls == 'system':
if same_parameters:
return info['system_cached']
else:
return info['system'](
roots=info['roots'], **system_parameters)
# Returns other classes
if same_parameters:
if 'storage_parameters' not in system_parameters:
system_parameters['storage_parameters'] = dict()
system_parameters['storage_parameters'][
'pycosio.system_cached'] = info['system_cached']
kwargs.update(system_parameters)
return info[cls](name=name, *args, **kwargs) | [
"def",
"get_instance",
"(",
"name",
",",
"cls",
"=",
"'system'",
",",
"storage",
"=",
"None",
",",
"storage_parameters",
"=",
"None",
",",
"unsecure",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"system_parameters",
"=",
"_system_pa... | Get a cloud object storage instance.
Args:
name (str): File name, path or URL.
cls (str): Type of class to instantiate.
'raw', 'buffered' or 'system'.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
args, kwargs: Instance arguments
Returns:
pycosio._core.io_base.ObjectIOBase subclass: Instance | [
"Get",
"a",
"cloud",
"object",
"storage",
"instance",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/storage_manager.py#L30-L99 |
Accelize/pycosio | pycosio/_core/storage_manager.py | mount | def mount(storage=None, name='', storage_parameters=None,
unsecure=None, extra_root=None):
"""
Mount a new storage.
Args:
storage (str): Storage name.
name (str): File URL. If storage is not specified,
URL scheme will be used as storage value.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
extra_root (str): Extra root that can be used in
replacement of root in path. This can be used to
provides support for shorter URLS.
Example: with root "https://www.mycloud.com/user"
and extra_root "mycloud://" it is possible to access object
using "mycloud://container/object" instead of
"https://www.mycloud.com/user/container/object".
Returns:
dict: keys are mounted storage, values are dicts of storage information.
"""
# Tries to infer storage from name
if storage is None:
if '://' in name:
storage = name.split('://', 1)[0].lower()
# Alias HTTPS to HTTP
storage = 'http' if storage == 'https' else storage
else:
raise ValueError(
'No storage specified and unable to infer it from file name.')
# Saves get_storage_parameters
system_parameters = _system_parameters(
unsecure=unsecure, storage_parameters=storage_parameters)
storage_info = dict(storage=storage, system_parameters=system_parameters)
# Finds module containing target subclass
for package in STORAGE_PACKAGE:
try:
module = import_module('%s.%s' % (package, storage))
break
except ImportError:
continue
else:
raise ImportError('No storage named "%s" found' % storage)
# Case module is a mount redirection to mount multiple storage at once
if hasattr(module, 'MOUNT_REDIRECT'):
if extra_root:
raise ValueError(
("Can't define extra_root with %s. "
"%s can't have a common root.") % (
storage, ', '.join(extra_root)))
result = dict()
for storage in getattr(module, 'MOUNT_REDIRECT'):
result[storage] = mount(
storage=storage, storage_parameters=storage_parameters,
unsecure=unsecure)
return result
# Finds storage subclass
classes_items = tuple(_BASE_CLASSES.items())
for member_name in dir(module):
member = getattr(module, member_name)
for cls_name, cls in classes_items:
# Skip if not subclass of the target class
try:
if not issubclass(member, cls) or member is cls:
continue
except TypeError:
continue
# The class may have been flag as default or not-default
default_flag = '_%s__DEFAULT_CLASS' % member.__name__.strip('_')
try:
is_default = getattr(member, default_flag)
except AttributeError:
is_default = None
# Skip if explicitly flagged as non default
if is_default is False:
continue
# Skip if is an abstract class not explicitly flagged as default
elif is_default is not True and member.__abstractmethods__:
continue
# Is the default class
storage_info[cls_name] = member
break
# Caches a system instance
storage_info['system_cached'] = storage_info['system'](**system_parameters)
# Gets roots
roots = storage_info['system_cached'].roots
# Adds extra root
if extra_root:
roots = list(roots)
roots.append(extra_root)
roots = tuple(roots)
storage_info['system_cached'].roots = storage_info['roots'] = roots
# Mounts
with _MOUNT_LOCK:
for root in roots:
MOUNTED[root] = storage_info
# Reorder to have correct lookup
items = OrderedDict(
(key, MOUNTED[key]) for key in reversed(
sorted(MOUNTED, key=_compare_root)))
MOUNTED.clear()
MOUNTED.update(items)
return {storage: storage_info} | python | def mount(storage=None, name='', storage_parameters=None,
unsecure=None, extra_root=None):
"""
Mount a new storage.
Args:
storage (str): Storage name.
name (str): File URL. If storage is not specified,
URL scheme will be used as storage value.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
extra_root (str): Extra root that can be used in
replacement of root in path. This can be used to
provides support for shorter URLS.
Example: with root "https://www.mycloud.com/user"
and extra_root "mycloud://" it is possible to access object
using "mycloud://container/object" instead of
"https://www.mycloud.com/user/container/object".
Returns:
dict: keys are mounted storage, values are dicts of storage information.
"""
# Tries to infer storage from name
if storage is None:
if '://' in name:
storage = name.split('://', 1)[0].lower()
# Alias HTTPS to HTTP
storage = 'http' if storage == 'https' else storage
else:
raise ValueError(
'No storage specified and unable to infer it from file name.')
# Saves get_storage_parameters
system_parameters = _system_parameters(
unsecure=unsecure, storage_parameters=storage_parameters)
storage_info = dict(storage=storage, system_parameters=system_parameters)
# Finds module containing target subclass
for package in STORAGE_PACKAGE:
try:
module = import_module('%s.%s' % (package, storage))
break
except ImportError:
continue
else:
raise ImportError('No storage named "%s" found' % storage)
# Case module is a mount redirection to mount multiple storage at once
if hasattr(module, 'MOUNT_REDIRECT'):
if extra_root:
raise ValueError(
("Can't define extra_root with %s. "
"%s can't have a common root.") % (
storage, ', '.join(extra_root)))
result = dict()
for storage in getattr(module, 'MOUNT_REDIRECT'):
result[storage] = mount(
storage=storage, storage_parameters=storage_parameters,
unsecure=unsecure)
return result
# Finds storage subclass
classes_items = tuple(_BASE_CLASSES.items())
for member_name in dir(module):
member = getattr(module, member_name)
for cls_name, cls in classes_items:
# Skip if not subclass of the target class
try:
if not issubclass(member, cls) or member is cls:
continue
except TypeError:
continue
# The class may have been flag as default or not-default
default_flag = '_%s__DEFAULT_CLASS' % member.__name__.strip('_')
try:
is_default = getattr(member, default_flag)
except AttributeError:
is_default = None
# Skip if explicitly flagged as non default
if is_default is False:
continue
# Skip if is an abstract class not explicitly flagged as default
elif is_default is not True and member.__abstractmethods__:
continue
# Is the default class
storage_info[cls_name] = member
break
# Caches a system instance
storage_info['system_cached'] = storage_info['system'](**system_parameters)
# Gets roots
roots = storage_info['system_cached'].roots
# Adds extra root
if extra_root:
roots = list(roots)
roots.append(extra_root)
roots = tuple(roots)
storage_info['system_cached'].roots = storage_info['roots'] = roots
# Mounts
with _MOUNT_LOCK:
for root in roots:
MOUNTED[root] = storage_info
# Reorder to have correct lookup
items = OrderedDict(
(key, MOUNTED[key]) for key in reversed(
sorted(MOUNTED, key=_compare_root)))
MOUNTED.clear()
MOUNTED.update(items)
return {storage: storage_info} | [
"def",
"mount",
"(",
"storage",
"=",
"None",
",",
"name",
"=",
"''",
",",
"storage_parameters",
"=",
"None",
",",
"unsecure",
"=",
"None",
",",
"extra_root",
"=",
"None",
")",
":",
"# Tries to infer storage from name",
"if",
"storage",
"is",
"None",
":",
"... | Mount a new storage.
Args:
storage (str): Storage name.
name (str): File URL. If storage is not specified,
URL scheme will be used as storage value.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
extra_root (str): Extra root that can be used in
replacement of root in path. This can be used to
provides support for shorter URLS.
Example: with root "https://www.mycloud.com/user"
and extra_root "mycloud://" it is possible to access object
using "mycloud://container/object" instead of
"https://www.mycloud.com/user/container/object".
Returns:
dict: keys are mounted storage, values are dicts of storage information. | [
"Mount",
"a",
"new",
"storage",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/storage_manager.py#L102-L223 |
Accelize/pycosio | pycosio/_core/storage_manager.py | _system_parameters | def _system_parameters(**kwargs):
"""
Returns system keyword arguments removing Nones.
Args:
kwargs: system keyword arguments.
Returns:
dict: system keyword arguments.
"""
return {key: value for key, value in kwargs.items()
if (value is not None or value == {})} | python | def _system_parameters(**kwargs):
"""
Returns system keyword arguments removing Nones.
Args:
kwargs: system keyword arguments.
Returns:
dict: system keyword arguments.
"""
return {key: value for key, value in kwargs.items()
if (value is not None or value == {})} | [
"def",
"_system_parameters",
"(",
"*",
"*",
"kwargs",
")",
":",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"(",
"value",
"is",
"not",
"None",
"or",
"value",
"==",
"{",
"}",
")",
"... | Returns system keyword arguments removing Nones.
Args:
kwargs: system keyword arguments.
Returns:
dict: system keyword arguments. | [
"Returns",
"system",
"keyword",
"arguments",
"removing",
"Nones",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/storage_manager.py#L226-L237 |
asottile/pymonkey | pymonkey.py | manual_argument_parsing | def manual_argument_parsing(argv):
"""sadness because argparse doesn't quite do what we want."""
# Special case these for a better error message
if not argv or argv == ['-h'] or argv == ['--help']:
print_help_and_exit()
try:
dashdash_index = argv.index('--')
except ValueError:
print_std_err('Must separate command by `--`')
print_help_and_exit()
patches, cmd = argv[:dashdash_index], argv[dashdash_index + 1:]
if '--help' in patches or '-h' in patches:
print_help_and_exit()
if '--all' in patches:
all_patches = True
patches.remove('--all')
else:
all_patches = False
unknown_options = [patch for patch in patches if patch.startswith('-')]
if unknown_options:
print_std_err('Unknown options: {!r}'.format(unknown_options))
print_help_and_exit()
if patches and all_patches:
print_std_err('--all and patches specified: {!r}'.format(patches))
print_help_and_exit()
return Arguments(all=all_patches, patches=tuple(patches), cmd=tuple(cmd)) | python | def manual_argument_parsing(argv):
"""sadness because argparse doesn't quite do what we want."""
# Special case these for a better error message
if not argv or argv == ['-h'] or argv == ['--help']:
print_help_and_exit()
try:
dashdash_index = argv.index('--')
except ValueError:
print_std_err('Must separate command by `--`')
print_help_and_exit()
patches, cmd = argv[:dashdash_index], argv[dashdash_index + 1:]
if '--help' in patches or '-h' in patches:
print_help_and_exit()
if '--all' in patches:
all_patches = True
patches.remove('--all')
else:
all_patches = False
unknown_options = [patch for patch in patches if patch.startswith('-')]
if unknown_options:
print_std_err('Unknown options: {!r}'.format(unknown_options))
print_help_and_exit()
if patches and all_patches:
print_std_err('--all and patches specified: {!r}'.format(patches))
print_help_and_exit()
return Arguments(all=all_patches, patches=tuple(patches), cmd=tuple(cmd)) | [
"def",
"manual_argument_parsing",
"(",
"argv",
")",
":",
"# Special case these for a better error message",
"if",
"not",
"argv",
"or",
"argv",
"==",
"[",
"'-h'",
"]",
"or",
"argv",
"==",
"[",
"'--help'",
"]",
":",
"print_help_and_exit",
"(",
")",
"try",
":",
"... | sadness because argparse doesn't quite do what we want. | [
"sadness",
"because",
"argparse",
"doesn",
"t",
"quite",
"do",
"what",
"we",
"want",
"."
] | train | https://github.com/asottile/pymonkey/blob/f2e55590c7064019e928eddc41dad5d288722ce6/pymonkey.py#L57-L90 |
asottile/pymonkey | pymonkey.py | make_entry_point | def make_entry_point(patches, original_entry_point):
"""Use this to make a console_script entry point for your application
which applies patches.
:param patches: iterable of pymonkey patches to apply. Ex: ('my-patch,)
:param original_entry_point: Such as 'pip'
"""
def entry(argv=None):
argv = argv if argv is not None else sys.argv[1:]
return main(
tuple(patches) + ('--', original_entry_point) + tuple(argv)
)
return entry | python | def make_entry_point(patches, original_entry_point):
"""Use this to make a console_script entry point for your application
which applies patches.
:param patches: iterable of pymonkey patches to apply. Ex: ('my-patch,)
:param original_entry_point: Such as 'pip'
"""
def entry(argv=None):
argv = argv if argv is not None else sys.argv[1:]
return main(
tuple(patches) + ('--', original_entry_point) + tuple(argv)
)
return entry | [
"def",
"make_entry_point",
"(",
"patches",
",",
"original_entry_point",
")",
":",
"def",
"entry",
"(",
"argv",
"=",
"None",
")",
":",
"argv",
"=",
"argv",
"if",
"argv",
"is",
"not",
"None",
"else",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"return",
"m... | Use this to make a console_script entry point for your application
which applies patches.
:param patches: iterable of pymonkey patches to apply. Ex: ('my-patch,)
:param original_entry_point: Such as 'pip' | [
"Use",
"this",
"to",
"make",
"a",
"console_script",
"entry",
"point",
"for",
"your",
"application",
"which",
"applies",
"patches",
".",
":",
"param",
"patches",
":",
"iterable",
"of",
"pymonkey",
"patches",
"to",
"apply",
".",
"Ex",
":",
"(",
"my",
"-",
... | train | https://github.com/asottile/pymonkey/blob/f2e55590c7064019e928eddc41dad5d288722ce6/pymonkey.py#L252-L264 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.client | def client(self):
"""
Storage client
Returns:
client
"""
if self._client is None:
self._client = self._get_client()
return self._client | python | def client(self):
"""
Storage client
Returns:
client
"""
if self._client is None:
self._client = self._get_client()
return self._client | [
"def",
"client",
"(",
"self",
")",
":",
"if",
"self",
".",
"_client",
"is",
"None",
":",
"self",
".",
"_client",
"=",
"self",
".",
"_get_client",
"(",
")",
"return",
"self",
".",
"_client"
] | Storage client
Returns:
client | [
"Storage",
"client"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L85-L94 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.exists | def exists(self, path=None, client_kwargs=None, assume_exists=None):
"""
Return True if path refers to an existing path.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if exists.
"""
try:
self.head(path, client_kwargs)
except ObjectNotFoundError:
return False
except ObjectPermissionError:
if assume_exists is None:
raise
return assume_exists
return True | python | def exists(self, path=None, client_kwargs=None, assume_exists=None):
"""
Return True if path refers to an existing path.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if exists.
"""
try:
self.head(path, client_kwargs)
except ObjectNotFoundError:
return False
except ObjectPermissionError:
if assume_exists is None:
raise
return assume_exists
return True | [
"def",
"exists",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"assume_exists",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"head",
"(",
"path",
",",
"client_kwargs",
")",
"except",
"ObjectNotFoundError",
":",
"return... | Return True if path refers to an existing path.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if exists. | [
"Return",
"True",
"if",
"path",
"refers",
"to",
"an",
"existing",
"path",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L123-L147 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.getctime | def getctime(self, path=None, client_kwargs=None, header=None):
"""
Return the creation time of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module).
"""
return self._getctime_from_header(
self.head(path, client_kwargs, header)) | python | def getctime(self, path=None, client_kwargs=None, header=None):
"""
Return the creation time of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module).
"""
return self._getctime_from_header(
self.head(path, client_kwargs, header)) | [
"def",
"getctime",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getctime_from_header",
"(",
"self",
".",
"head",
"(",
"path",
",",
"client_kwargs",
",",
"header",... | Return the creation time of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module). | [
"Return",
"the",
"creation",
"time",
"of",
"path",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L171-L185 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.getmtime | def getmtime(self, path=None, client_kwargs=None, header=None):
"""
Return the time of last access of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module).
"""
return self._getmtime_from_header(
self.head(path, client_kwargs, header)) | python | def getmtime(self, path=None, client_kwargs=None, header=None):
"""
Return the time of last access of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module).
"""
return self._getmtime_from_header(
self.head(path, client_kwargs, header)) | [
"def",
"getmtime",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getmtime_from_header",
"(",
"self",
".",
"head",
"(",
"path",
",",
"client_kwargs",
",",
"header",... | Return the time of last access of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module). | [
"Return",
"the",
"time",
"of",
"last",
"access",
"of",
"path",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L199-L213 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase._get_time | def _get_time(header, keys, name):
"""
Get time from header
Args:
header (dict): Object header.
keys (tuple of str): Header keys.
name (str): Method name.
Returns:
float: The number of seconds since the epoch
"""
for key in keys:
try:
date_value = header.pop(key)
except KeyError:
continue
try:
# String to convert
return to_timestamp(parse(date_value))
except TypeError:
# Already number
return float(date_value)
raise UnsupportedOperation(name) | python | def _get_time(header, keys, name):
"""
Get time from header
Args:
header (dict): Object header.
keys (tuple of str): Header keys.
name (str): Method name.
Returns:
float: The number of seconds since the epoch
"""
for key in keys:
try:
date_value = header.pop(key)
except KeyError:
continue
try:
# String to convert
return to_timestamp(parse(date_value))
except TypeError:
# Already number
return float(date_value)
raise UnsupportedOperation(name) | [
"def",
"_get_time",
"(",
"header",
",",
"keys",
",",
"name",
")",
":",
"for",
"key",
"in",
"keys",
":",
"try",
":",
"date_value",
"=",
"header",
".",
"pop",
"(",
"key",
")",
"except",
"KeyError",
":",
"continue",
"try",
":",
"# String to convert",
"ret... | Get time from header
Args:
header (dict): Object header.
keys (tuple of str): Header keys.
name (str): Method name.
Returns:
float: The number of seconds since the epoch | [
"Get",
"time",
"from",
"header"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L228-L251 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.getsize | def getsize(self, path=None, client_kwargs=None, header=None):
"""
Return the size, in bytes, of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
int: Size in bytes.
"""
return self._getsize_from_header(self.head(path, client_kwargs, header)) | python | def getsize(self, path=None, client_kwargs=None, header=None):
"""
Return the size, in bytes, of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
int: Size in bytes.
"""
return self._getsize_from_header(self.head(path, client_kwargs, header)) | [
"def",
"getsize",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getsize_from_header",
"(",
"self",
".",
"head",
"(",
"path",
",",
"client_kwargs",
",",
"header",
... | Return the size, in bytes, of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
int: Size in bytes. | [
"Return",
"the",
"size",
"in",
"bytes",
"of",
"path",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L262-L274 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase._getsize_from_header | def _getsize_from_header(self, header):
"""
Return the size from header
Args:
header (dict): Object header.
Returns:
int: Size in bytes.
"""
# By default, assumes that information are in a standard HTTP header
for key in self._SIZE_KEYS:
try:
return int(header.pop(key))
except KeyError:
continue
else:
raise UnsupportedOperation('getsize') | python | def _getsize_from_header(self, header):
"""
Return the size from header
Args:
header (dict): Object header.
Returns:
int: Size in bytes.
"""
# By default, assumes that information are in a standard HTTP header
for key in self._SIZE_KEYS:
try:
return int(header.pop(key))
except KeyError:
continue
else:
raise UnsupportedOperation('getsize') | [
"def",
"_getsize_from_header",
"(",
"self",
",",
"header",
")",
":",
"# By default, assumes that information are in a standard HTTP header",
"for",
"key",
"in",
"self",
".",
"_SIZE_KEYS",
":",
"try",
":",
"return",
"int",
"(",
"header",
".",
"pop",
"(",
"key",
")"... | Return the size from header
Args:
header (dict): Object header.
Returns:
int: Size in bytes. | [
"Return",
"the",
"size",
"from",
"header"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L276-L293 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.isdir | def isdir(self, path=None, client_kwargs=None, virtual_dir=True,
assume_exists=None):
"""
Return True if path is an existing directory.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
virtual_dir (bool): If True, checks if directory exists virtually
if an object path if not exists as a specific object.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if directory exists.
"""
relative = self.relpath(path)
if not relative:
# Root always exists and is a directory
return True
if path[-1] == '/' or self.is_locator(relative, relative=True):
exists = self.exists(path=path, client_kwargs=client_kwargs,
assume_exists=assume_exists)
if exists:
return True
# Some directories only exists virtually in object path and don't
# have headers.
elif virtual_dir:
try:
next(self.list_objects(relative, relative=True,
max_request_entries=1))
return True
except (StopIteration, ObjectNotFoundError,
UnsupportedOperation):
return False
return False | python | def isdir(self, path=None, client_kwargs=None, virtual_dir=True,
assume_exists=None):
"""
Return True if path is an existing directory.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
virtual_dir (bool): If True, checks if directory exists virtually
if an object path if not exists as a specific object.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if directory exists.
"""
relative = self.relpath(path)
if not relative:
# Root always exists and is a directory
return True
if path[-1] == '/' or self.is_locator(relative, relative=True):
exists = self.exists(path=path, client_kwargs=client_kwargs,
assume_exists=assume_exists)
if exists:
return True
# Some directories only exists virtually in object path and don't
# have headers.
elif virtual_dir:
try:
next(self.list_objects(relative, relative=True,
max_request_entries=1))
return True
except (StopIteration, ObjectNotFoundError,
UnsupportedOperation):
return False
return False | [
"def",
"isdir",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"virtual_dir",
"=",
"True",
",",
"assume_exists",
"=",
"None",
")",
":",
"relative",
"=",
"self",
".",
"relpath",
"(",
"path",
")",
"if",
"not",
"relative",
... | Return True if path is an existing directory.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
virtual_dir (bool): If True, checks if directory exists virtually
if an object path if not exists as a specific object.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if directory exists. | [
"Return",
"True",
"if",
"path",
"is",
"an",
"existing",
"directory",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L295-L335 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.isfile | def isfile(self, path=None, client_kwargs=None, assume_exists=None):
"""
Return True if path is an existing regular file.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if file exists.
"""
relative = self.relpath(path)
if not relative:
# Root always exists and is a directory
return False
if path[-1] != '/' and not self.is_locator(path, relative=True):
return self.exists(path=path, client_kwargs=client_kwargs,
assume_exists=assume_exists)
return False | python | def isfile(self, path=None, client_kwargs=None, assume_exists=None):
"""
Return True if path is an existing regular file.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if file exists.
"""
relative = self.relpath(path)
if not relative:
# Root always exists and is a directory
return False
if path[-1] != '/' and not self.is_locator(path, relative=True):
return self.exists(path=path, client_kwargs=client_kwargs,
assume_exists=assume_exists)
return False | [
"def",
"isfile",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"assume_exists",
"=",
"None",
")",
":",
"relative",
"=",
"self",
".",
"relpath",
"(",
"path",
")",
"if",
"not",
"relative",
":",
"# Root always exists and is a ... | Return True if path is an existing regular file.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if file exists. | [
"Return",
"True",
"if",
"path",
"is",
"an",
"existing",
"regular",
"file",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L337-L361 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.head | def head(self, path=None, client_kwargs=None, header=None):
"""
Returns object HTTP header.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
dict: HTTP header.
"""
if header is not None:
return header
elif client_kwargs is None:
client_kwargs = self.get_client_kwargs(path)
return self._head(client_kwargs) | python | def head(self, path=None, client_kwargs=None, header=None):
"""
Returns object HTTP header.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
dict: HTTP header.
"""
if header is not None:
return header
elif client_kwargs is None:
client_kwargs = self.get_client_kwargs(path)
return self._head(client_kwargs) | [
"def",
"head",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"if",
"header",
"is",
"not",
"None",
":",
"return",
"header",
"elif",
"client_kwargs",
"is",
"None",
":",
"client_kwargs",
"=... | Returns object HTTP header.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
dict: HTTP header. | [
"Returns",
"object",
"HTTP",
"header",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L385-L401 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.relpath | def relpath(self, path):
"""
Get path relative to storage.
args:
path (str): Absolute path or URL.
Returns:
str: relative path.
"""
for root in self.roots:
# Root is regex, convert to matching root string
if isinstance(root, Pattern):
match = root.match(path)
if not match:
continue
root = match.group(0)
# Split root and relative path
try:
relative = path.split(root, 1)[1]
# Strip "/" only at path start. "/" is used to known if
# path is a directory on some cloud storage.
return relative.lstrip('/')
except IndexError:
continue
return path | python | def relpath(self, path):
"""
Get path relative to storage.
args:
path (str): Absolute path or URL.
Returns:
str: relative path.
"""
for root in self.roots:
# Root is regex, convert to matching root string
if isinstance(root, Pattern):
match = root.match(path)
if not match:
continue
root = match.group(0)
# Split root and relative path
try:
relative = path.split(root, 1)[1]
# Strip "/" only at path start. "/" is used to known if
# path is a directory on some cloud storage.
return relative.lstrip('/')
except IndexError:
continue
return path | [
"def",
"relpath",
"(",
"self",
",",
"path",
")",
":",
"for",
"root",
"in",
"self",
".",
"roots",
":",
"# Root is regex, convert to matching root string",
"if",
"isinstance",
"(",
"root",
",",
"Pattern",
")",
":",
"match",
"=",
"root",
".",
"match",
"(",
"p... | Get path relative to storage.
args:
path (str): Absolute path or URL.
Returns:
str: relative path. | [
"Get",
"path",
"relative",
"to",
"storage",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L423-L450 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.is_locator | def is_locator(self, path, relative=False):
"""
Returns True if path refer to a locator.
Depending the storage, locator may be a bucket or container name,
a hostname, ...
args:
path (str): path or URL.
relative (bool): Path is relative to current root.
Returns:
bool: True if locator.
"""
if not relative:
path = self.relpath(path)
# Bucket is the main directory
return path and '/' not in path.rstrip('/') | python | def is_locator(self, path, relative=False):
"""
Returns True if path refer to a locator.
Depending the storage, locator may be a bucket or container name,
a hostname, ...
args:
path (str): path or URL.
relative (bool): Path is relative to current root.
Returns:
bool: True if locator.
"""
if not relative:
path = self.relpath(path)
# Bucket is the main directory
return path and '/' not in path.rstrip('/') | [
"def",
"is_locator",
"(",
"self",
",",
"path",
",",
"relative",
"=",
"False",
")",
":",
"if",
"not",
"relative",
":",
"path",
"=",
"self",
".",
"relpath",
"(",
"path",
")",
"# Bucket is the main directory",
"return",
"path",
"and",
"'/'",
"not",
"in",
"p... | Returns True if path refer to a locator.
Depending the storage, locator may be a bucket or container name,
a hostname, ...
args:
path (str): path or URL.
relative (bool): Path is relative to current root.
Returns:
bool: True if locator. | [
"Returns",
"True",
"if",
"path",
"refer",
"to",
"a",
"locator",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L452-L469 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.split_locator | def split_locator(self, path):
"""
Split the path into a pair (locator, path).
args:
path (str): Absolute path or URL.
Returns:
tuple of str: locator, path.
"""
relative = self.relpath(path)
try:
locator, tail = relative.split('/', 1)
except ValueError:
locator = relative
tail = ''
return locator, tail | python | def split_locator(self, path):
"""
Split the path into a pair (locator, path).
args:
path (str): Absolute path or URL.
Returns:
tuple of str: locator, path.
"""
relative = self.relpath(path)
try:
locator, tail = relative.split('/', 1)
except ValueError:
locator = relative
tail = ''
return locator, tail | [
"def",
"split_locator",
"(",
"self",
",",
"path",
")",
":",
"relative",
"=",
"self",
".",
"relpath",
"(",
"path",
")",
"try",
":",
"locator",
",",
"tail",
"=",
"relative",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"except",
"ValueError",
":",
"locator... | Split the path into a pair (locator, path).
args:
path (str): Absolute path or URL.
Returns:
tuple of str: locator, path. | [
"Split",
"the",
"path",
"into",
"a",
"pair",
"(",
"locator",
"path",
")",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L471-L487 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.make_dir | def make_dir(self, path, relative=False):
"""
Make a directory.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
"""
if not relative:
path = self.relpath(path)
self._make_dir(self.get_client_kwargs(self.ensure_dir_path(
path, relative=True))) | python | def make_dir(self, path, relative=False):
"""
Make a directory.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
"""
if not relative:
path = self.relpath(path)
self._make_dir(self.get_client_kwargs(self.ensure_dir_path(
path, relative=True))) | [
"def",
"make_dir",
"(",
"self",
",",
"path",
",",
"relative",
"=",
"False",
")",
":",
"if",
"not",
"relative",
":",
"path",
"=",
"self",
".",
"relpath",
"(",
"path",
")",
"self",
".",
"_make_dir",
"(",
"self",
".",
"get_client_kwargs",
"(",
"self",
"... | Make a directory.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root. | [
"Make",
"a",
"directory",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L489-L500 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.remove | def remove(self, path, relative=False):
"""
Remove an object.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
"""
if not relative:
path = self.relpath(path)
self._remove(self.get_client_kwargs(path)) | python | def remove(self, path, relative=False):
"""
Remove an object.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
"""
if not relative:
path = self.relpath(path)
self._remove(self.get_client_kwargs(path)) | [
"def",
"remove",
"(",
"self",
",",
"path",
",",
"relative",
"=",
"False",
")",
":",
"if",
"not",
"relative",
":",
"path",
"=",
"self",
".",
"relpath",
"(",
"path",
")",
"self",
".",
"_remove",
"(",
"self",
".",
"get_client_kwargs",
"(",
"path",
")",
... | Remove an object.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root. | [
"Remove",
"an",
"object",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L511-L521 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.ensure_dir_path | def ensure_dir_path(self, path, relative=False):
"""
Ensure the path is a dir path.
Should end with '/' except for schemes and locators.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
Returns:
path: dir path
"""
if not relative:
rel_path = self.relpath(path)
else:
rel_path = path
# Locator
if self.is_locator(rel_path, relative=True):
path = path.rstrip('/')
# Directory
elif rel_path:
path = path.rstrip('/') + '/'
# else: root
return path | python | def ensure_dir_path(self, path, relative=False):
"""
Ensure the path is a dir path.
Should end with '/' except for schemes and locators.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
Returns:
path: dir path
"""
if not relative:
rel_path = self.relpath(path)
else:
rel_path = path
# Locator
if self.is_locator(rel_path, relative=True):
path = path.rstrip('/')
# Directory
elif rel_path:
path = path.rstrip('/') + '/'
# else: root
return path | [
"def",
"ensure_dir_path",
"(",
"self",
",",
"path",
",",
"relative",
"=",
"False",
")",
":",
"if",
"not",
"relative",
":",
"rel_path",
"=",
"self",
".",
"relpath",
"(",
"path",
")",
"else",
":",
"rel_path",
"=",
"path",
"# Locator",
"if",
"self",
".",
... | Ensure the path is a dir path.
Should end with '/' except for schemes and locators.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
Returns:
path: dir path | [
"Ensure",
"the",
"path",
"is",
"a",
"dir",
"path",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L532-L558 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.list_objects | def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None):
"""
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only first level objects.
Else, returns full tree.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict
"""
entries = 0
max_request_entries_arg = None
if not relative:
path = self.relpath(path)
# From root
if not path:
locators = self._list_locators()
# Yields locators
if first_level:
for locator in locators:
entries += 1
yield locator
if entries == max_request_entries:
return
return
# Yields each locator objects
for loc_path, loc_header in locators:
# Yields locator itself
loc_path = loc_path.strip('/')
entries += 1
yield loc_path, loc_header
if entries == max_request_entries:
return
# Yields locator content is read access to it
if max_request_entries is not None:
max_request_entries_arg = max_request_entries - entries
try:
for obj_path, obj_header in self._list_objects(
self.get_client_kwargs(loc_path), '',
max_request_entries_arg):
entries += 1
yield ('/'.join((loc_path, obj_path.lstrip('/'))),
obj_header)
if entries == max_request_entries:
return
except ObjectPermissionError:
# No read access to locator
continue
return
# From locator or sub directory
locator, path = self.split_locator(path)
if first_level:
seen = set()
if max_request_entries is not None:
max_request_entries_arg = max_request_entries - entries
for obj_path, header in self._list_objects(
self.get_client_kwargs(locator), path, max_request_entries_arg):
if path:
try:
obj_path = obj_path.split(path, 1)[1]
except IndexError:
# Not sub path of path
continue
obj_path = obj_path.lstrip('/')
# Skips parent directory
if not obj_path:
continue
# Yields first level locator objects only
if first_level:
# Directory
try:
obj_path, _ = obj_path.strip('/').split('/', 1)
obj_path += '/'
# Avoids to use the header of the object instead of the
# non existing header of the directory that only exists
# virtually in object path.
header = dict()
# File
except ValueError:
pass
if obj_path not in seen:
entries += 1
yield obj_path, header
if entries == max_request_entries:
return
seen.add(obj_path)
# Yields locator objects
else:
entries += 1
yield obj_path, header
if entries == max_request_entries:
return | python | def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None):
"""
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only first level objects.
Else, returns full tree.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict
"""
entries = 0
max_request_entries_arg = None
if not relative:
path = self.relpath(path)
# From root
if not path:
locators = self._list_locators()
# Yields locators
if first_level:
for locator in locators:
entries += 1
yield locator
if entries == max_request_entries:
return
return
# Yields each locator objects
for loc_path, loc_header in locators:
# Yields locator itself
loc_path = loc_path.strip('/')
entries += 1
yield loc_path, loc_header
if entries == max_request_entries:
return
# Yields locator content is read access to it
if max_request_entries is not None:
max_request_entries_arg = max_request_entries - entries
try:
for obj_path, obj_header in self._list_objects(
self.get_client_kwargs(loc_path), '',
max_request_entries_arg):
entries += 1
yield ('/'.join((loc_path, obj_path.lstrip('/'))),
obj_header)
if entries == max_request_entries:
return
except ObjectPermissionError:
# No read access to locator
continue
return
# From locator or sub directory
locator, path = self.split_locator(path)
if first_level:
seen = set()
if max_request_entries is not None:
max_request_entries_arg = max_request_entries - entries
for obj_path, header in self._list_objects(
self.get_client_kwargs(locator), path, max_request_entries_arg):
if path:
try:
obj_path = obj_path.split(path, 1)[1]
except IndexError:
# Not sub path of path
continue
obj_path = obj_path.lstrip('/')
# Skips parent directory
if not obj_path:
continue
# Yields first level locator objects only
if first_level:
# Directory
try:
obj_path, _ = obj_path.strip('/').split('/', 1)
obj_path += '/'
# Avoids to use the header of the object instead of the
# non existing header of the directory that only exists
# virtually in object path.
header = dict()
# File
except ValueError:
pass
if obj_path not in seen:
entries += 1
yield obj_path, header
if entries == max_request_entries:
return
seen.add(obj_path)
# Yields locator objects
else:
entries += 1
yield obj_path, header
if entries == max_request_entries:
return | [
"def",
"list_objects",
"(",
"self",
",",
"path",
"=",
"''",
",",
"relative",
"=",
"False",
",",
"first_level",
"=",
"False",
",",
"max_request_entries",
"=",
"None",
")",
":",
"entries",
"=",
"0",
"max_request_entries_arg",
"=",
"None",
"if",
"not",
"relat... | List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only first level objects.
Else, returns full tree.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict | [
"List",
"objects",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L560-L678 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.stat | def stat(self, path=None, client_kwargs=None, header=None):
"""
Get the status of an object.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
os.stat_result: Stat result object
"""
# Should contain at least the strict minimum of os.stat_result
stat = OrderedDict((
("st_mode", 0), ("st_ino", 0), ("st_dev", 0), ("st_nlink", 0),
("st_uid", 0), ("st_gid", 0), ("st_size", 0), ("st_atime", 0),
("st_mtime", 0), ("st_ctime", 0)))
# Populate standard os.stat_result values with object header content
header = self.head(path, client_kwargs, header)
for key, method in (
('st_size', self._getsize_from_header),
('st_ctime', self._getctime_from_header),
('st_mtime', self._getmtime_from_header),):
try:
stat[key] = int(method(header))
except UnsupportedOperation:
continue
# File mode
if self.islink(path=path, header=header):
# Symlink
stat['st_mode'] = S_IFLNK
elif ((not path or path[-1] == '/' or self.is_locator(path)) and not
stat['st_size']):
# Directory
stat['st_mode'] = S_IFDIR
else:
# File
stat['st_mode'] = S_IFREG
# Add storage specific keys
sub = self._CHAR_FILTER.sub
for key, value in tuple(header.items()):
stat['st_' + sub('', key.lower())] = value
# Convert to "os.stat_result" like object
stat_result = namedtuple('stat_result', tuple(stat))
stat_result.__name__ = 'os.stat_result'
stat_result.__module__ = 'pycosio'
return stat_result(**stat) | python | def stat(self, path=None, client_kwargs=None, header=None):
"""
Get the status of an object.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
os.stat_result: Stat result object
"""
# Should contain at least the strict minimum of os.stat_result
stat = OrderedDict((
("st_mode", 0), ("st_ino", 0), ("st_dev", 0), ("st_nlink", 0),
("st_uid", 0), ("st_gid", 0), ("st_size", 0), ("st_atime", 0),
("st_mtime", 0), ("st_ctime", 0)))
# Populate standard os.stat_result values with object header content
header = self.head(path, client_kwargs, header)
for key, method in (
('st_size', self._getsize_from_header),
('st_ctime', self._getctime_from_header),
('st_mtime', self._getmtime_from_header),):
try:
stat[key] = int(method(header))
except UnsupportedOperation:
continue
# File mode
if self.islink(path=path, header=header):
# Symlink
stat['st_mode'] = S_IFLNK
elif ((not path or path[-1] == '/' or self.is_locator(path)) and not
stat['st_size']):
# Directory
stat['st_mode'] = S_IFDIR
else:
# File
stat['st_mode'] = S_IFREG
# Add storage specific keys
sub = self._CHAR_FILTER.sub
for key, value in tuple(header.items()):
stat['st_' + sub('', key.lower())] = value
# Convert to "os.stat_result" like object
stat_result = namedtuple('stat_result', tuple(stat))
stat_result.__name__ = 'os.stat_result'
stat_result.__module__ = 'pycosio'
return stat_result(**stat) | [
"def",
"stat",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"# Should contain at least the strict minimum of os.stat_result",
"stat",
"=",
"OrderedDict",
"(",
"(",
"(",
"\"st_mode\"",
",",
"0",
... | Get the status of an object.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
os.stat_result: Stat result object | [
"Get",
"the",
"status",
"of",
"an",
"object",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L718-L768 |
fedora-infra/datanommer | datanommer.models/datanommer/models/__init__.py | init | def init(uri=None, alembic_ini=None, engine=None, create=False):
""" Initialize a connection. Create tables if requested."""
if uri and engine:
raise ValueError("uri and engine cannot both be specified")
if uri is None and not engine:
uri = 'sqlite:////tmp/datanommer.db'
log.warning("No db uri given. Using %r" % uri)
if uri and not engine:
engine = create_engine(uri)
if 'sqlite' in engine.driver:
# Enable nested transaction support under SQLite
# See https://stackoverflow.com/questions/1654857/nested-transactions-with-sqlalchemy-and-sqlite
@event.listens_for(engine, "connect")
def do_connect(dbapi_connection, connection_record):
# disable pysqlite's emitting of the BEGIN statement entirely.
# also stops it from emitting COMMIT before any DDL.
dbapi_connection.isolation_level = None
@event.listens_for(engine, "begin")
def do_begin(conn):
# emit our own BEGIN
conn.execute("BEGIN")
# We need to hang our own attribute on the sqlalchemy session to stop
# ourselves from initializing twice. That is only a problem is the code
# calling us isn't consistent.
if getattr(session, '_datanommer_initialized', None):
log.warning("Session already initialized. Bailing")
return
session._datanommer_initialized = True
session.configure(bind=engine)
DeclarativeBase.query = session.query_property()
# Loads the alembic configuration and generates the version table, with
# the most recent revision stamped as head
if alembic_ini is not None:
from alembic.config import Config
from alembic import command
alembic_cfg = Config(alembic_ini)
command.stamp(alembic_cfg, "head")
if create:
DeclarativeBase.metadata.create_all(engine) | python | def init(uri=None, alembic_ini=None, engine=None, create=False):
""" Initialize a connection. Create tables if requested."""
if uri and engine:
raise ValueError("uri and engine cannot both be specified")
if uri is None and not engine:
uri = 'sqlite:////tmp/datanommer.db'
log.warning("No db uri given. Using %r" % uri)
if uri and not engine:
engine = create_engine(uri)
if 'sqlite' in engine.driver:
# Enable nested transaction support under SQLite
# See https://stackoverflow.com/questions/1654857/nested-transactions-with-sqlalchemy-and-sqlite
@event.listens_for(engine, "connect")
def do_connect(dbapi_connection, connection_record):
# disable pysqlite's emitting of the BEGIN statement entirely.
# also stops it from emitting COMMIT before any DDL.
dbapi_connection.isolation_level = None
@event.listens_for(engine, "begin")
def do_begin(conn):
# emit our own BEGIN
conn.execute("BEGIN")
# We need to hang our own attribute on the sqlalchemy session to stop
# ourselves from initializing twice. That is only a problem is the code
# calling us isn't consistent.
if getattr(session, '_datanommer_initialized', None):
log.warning("Session already initialized. Bailing")
return
session._datanommer_initialized = True
session.configure(bind=engine)
DeclarativeBase.query = session.query_property()
# Loads the alembic configuration and generates the version table, with
# the most recent revision stamped as head
if alembic_ini is not None:
from alembic.config import Config
from alembic import command
alembic_cfg = Config(alembic_ini)
command.stamp(alembic_cfg, "head")
if create:
DeclarativeBase.metadata.create_all(engine) | [
"def",
"init",
"(",
"uri",
"=",
"None",
",",
"alembic_ini",
"=",
"None",
",",
"engine",
"=",
"None",
",",
"create",
"=",
"False",
")",
":",
"if",
"uri",
"and",
"engine",
":",
"raise",
"ValueError",
"(",
"\"uri and engine cannot both be specified\"",
")",
"... | Initialize a connection. Create tables if requested. | [
"Initialize",
"a",
"connection",
".",
"Create",
"tables",
"if",
"requested",
"."
] | train | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/datanommer.models/datanommer/models/__init__.py#L65-L112 |
fedora-infra/datanommer | datanommer.models/datanommer/models/__init__.py | add | def add(envelope):
""" Take a dict-like fedmsg envelope and store the headers and message
in the table.
"""
message = envelope['body']
timestamp = message.get('timestamp', None)
try:
if timestamp:
timestamp = datetime.datetime.utcfromtimestamp(timestamp)
else:
timestamp = datetime.datetime.utcnow()
except Exception:
pass
headers = envelope.get('headers', None)
msg_id = message.get('msg_id', None)
if not msg_id and headers:
msg_id = headers.get('message-id', None)
if not msg_id:
msg_id = six.text_type(timestamp.year) + six.u('-') + six.text_type(uuid.uuid4())
obj = Message(
i=message.get('i', 0),
msg_id=msg_id,
topic=message['topic'],
timestamp=timestamp,
username=message.get('username', None),
crypto=message.get('crypto', None),
certificate=message.get('certificate', None),
signature=message.get('signature', None),
)
obj.msg = message['msg']
obj.headers = headers
try:
session.add(obj)
session.flush()
except IntegrityError:
log.warning('Skipping message from %s with duplicate id: %s',
message['topic'], msg_id)
session.rollback()
return
usernames = fedmsg.meta.msg2usernames(message)
packages = fedmsg.meta.msg2packages(message)
# Do a little sanity checking on fedmsg.meta results
if None in usernames:
# Notify developers so they can fix msg2usernames
log.error('NoneType found in usernames of %r' % msg_id)
# And prune out the bad value
usernames = [name for name in usernames if name is not None]
if None in packages:
# Notify developers so they can fix msg2packages
log.error('NoneType found in packages of %r' % msg_id)
# And prune out the bad value
packages = [pkg for pkg in packages if pkg is not None]
# If we've never seen one of these users before, then:
# 1) make sure they exist in the db (create them if necessary)
# 2) mark an in memory cache so we can remember that they exist without
# having to hit the db.
for username in usernames:
if username not in _users_seen:
# Create the user in the DB if necessary
User.get_or_create(username)
# Then just mark an in memory cache noting that we've seen them.
_users_seen.add(username)
for package in packages:
if package not in _packages_seen:
Package.get_or_create(package)
_packages_seen.add(package)
session.flush()
# These two blocks would normally be a simple "obj.users.append(user)" kind
# of statement, but here we drop down out of sqlalchemy's ORM and into the
# sql abstraction in order to gain a little performance boost.
values = [{'username': username, 'msg': obj.id} for username in usernames]
if values:
session.execute(user_assoc_table.insert(), values)
values = [{'package': package, 'msg': obj.id} for package in packages]
if values:
session.execute(pack_assoc_table.insert(), values)
# TODO -- can we avoid committing every time?
session.flush()
session.commit() | python | def add(envelope):
""" Take a dict-like fedmsg envelope and store the headers and message
in the table.
"""
message = envelope['body']
timestamp = message.get('timestamp', None)
try:
if timestamp:
timestamp = datetime.datetime.utcfromtimestamp(timestamp)
else:
timestamp = datetime.datetime.utcnow()
except Exception:
pass
headers = envelope.get('headers', None)
msg_id = message.get('msg_id', None)
if not msg_id and headers:
msg_id = headers.get('message-id', None)
if not msg_id:
msg_id = six.text_type(timestamp.year) + six.u('-') + six.text_type(uuid.uuid4())
obj = Message(
i=message.get('i', 0),
msg_id=msg_id,
topic=message['topic'],
timestamp=timestamp,
username=message.get('username', None),
crypto=message.get('crypto', None),
certificate=message.get('certificate', None),
signature=message.get('signature', None),
)
obj.msg = message['msg']
obj.headers = headers
try:
session.add(obj)
session.flush()
except IntegrityError:
log.warning('Skipping message from %s with duplicate id: %s',
message['topic'], msg_id)
session.rollback()
return
usernames = fedmsg.meta.msg2usernames(message)
packages = fedmsg.meta.msg2packages(message)
# Do a little sanity checking on fedmsg.meta results
if None in usernames:
# Notify developers so they can fix msg2usernames
log.error('NoneType found in usernames of %r' % msg_id)
# And prune out the bad value
usernames = [name for name in usernames if name is not None]
if None in packages:
# Notify developers so they can fix msg2packages
log.error('NoneType found in packages of %r' % msg_id)
# And prune out the bad value
packages = [pkg for pkg in packages if pkg is not None]
# If we've never seen one of these users before, then:
# 1) make sure they exist in the db (create them if necessary)
# 2) mark an in memory cache so we can remember that they exist without
# having to hit the db.
for username in usernames:
if username not in _users_seen:
# Create the user in the DB if necessary
User.get_or_create(username)
# Then just mark an in memory cache noting that we've seen them.
_users_seen.add(username)
for package in packages:
if package not in _packages_seen:
Package.get_or_create(package)
_packages_seen.add(package)
session.flush()
# These two blocks would normally be a simple "obj.users.append(user)" kind
# of statement, but here we drop down out of sqlalchemy's ORM and into the
# sql abstraction in order to gain a little performance boost.
values = [{'username': username, 'msg': obj.id} for username in usernames]
if values:
session.execute(user_assoc_table.insert(), values)
values = [{'package': package, 'msg': obj.id} for package in packages]
if values:
session.execute(pack_assoc_table.insert(), values)
# TODO -- can we avoid committing every time?
session.flush()
session.commit() | [
"def",
"add",
"(",
"envelope",
")",
":",
"message",
"=",
"envelope",
"[",
"'body'",
"]",
"timestamp",
"=",
"message",
".",
"get",
"(",
"'timestamp'",
",",
"None",
")",
"try",
":",
"if",
"timestamp",
":",
"timestamp",
"=",
"datetime",
".",
"datetime",
"... | Take a dict-like fedmsg envelope and store the headers and message
in the table. | [
"Take",
"a",
"dict",
"-",
"like",
"fedmsg",
"envelope",
"and",
"store",
"the",
"headers",
"and",
"message",
"in",
"the",
"table",
"."
] | train | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/datanommer.models/datanommer/models/__init__.py#L115-L205 |
fedora-infra/datanommer | datanommer.models/datanommer/models/__init__.py | Singleton.get_or_create | def get_or_create(cls, name):
"""
Return the instance of the class with the specified name. If it doesn't
already exist, create it.
"""
obj = cls.query.filter_by(name=name).one_or_none()
if obj:
return obj
try:
with session.begin_nested():
obj = cls(name=name)
session.add(obj)
session.flush()
return obj
except IntegrityError:
log.debug('Collision when adding %s(name="%s"), returning existing object',
cls.__name__, name)
return cls.query.filter_by(name=name).one() | python | def get_or_create(cls, name):
"""
Return the instance of the class with the specified name. If it doesn't
already exist, create it.
"""
obj = cls.query.filter_by(name=name).one_or_none()
if obj:
return obj
try:
with session.begin_nested():
obj = cls(name=name)
session.add(obj)
session.flush()
return obj
except IntegrityError:
log.debug('Collision when adding %s(name="%s"), returning existing object',
cls.__name__, name)
return cls.query.filter_by(name=name).one() | [
"def",
"get_or_create",
"(",
"cls",
",",
"name",
")",
":",
"obj",
"=",
"cls",
".",
"query",
".",
"filter_by",
"(",
"name",
"=",
"name",
")",
".",
"one_or_none",
"(",
")",
"if",
"obj",
":",
"return",
"obj",
"try",
":",
"with",
"session",
".",
"begin... | Return the instance of the class with the specified name. If it doesn't
already exist, create it. | [
"Return",
"the",
"instance",
"of",
"the",
"class",
"with",
"the",
"specified",
"name",
".",
"If",
"it",
"doesn",
"t",
"already",
"exist",
"create",
"it",
"."
] | train | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/datanommer.models/datanommer/models/__init__.py#L295-L312 |
fedora-infra/datanommer | datanommer.models/datanommer/models/__init__.py | Message.grep | def grep(cls, start=None, end=None,
page=1, rows_per_page=100,
order="asc", msg_id=None,
users=None, not_users=None,
packages=None, not_packages=None,
categories=None, not_categories=None,
topics=None, not_topics=None,
contains=None,
defer=False):
""" Flexible query interface for messages.
Arguments are filters. start and end should be :mod:`datetime` objs.
Other filters should be lists of strings. They are applied in a
conjunctive-normal-form (CNF) kind of way
for example, the following::
users = ['ralph', 'lmacken']
categories = ['bodhi', 'wiki']
should return messages where
(user=='ralph' OR user=='lmacken') AND
(category=='bodhi' OR category=='wiki')
Furthermore, you can use a negative version of each argument.
users = ['ralph']
not_categories = ['bodhi', 'wiki']
should return messages where
(user == 'ralph') AND
NOT (category == 'bodhi' OR category == 'wiki')
----
If the `defer` argument evaluates to True, the query won't actually
be executed, but a SQLAlchemy query object returned instead.
"""
users = users or []
not_users = not_users or []
packages = packages or []
not_packs = not_packages or []
categories = categories or []
not_cats = not_categories or []
topics = topics or []
not_topics = not_topics or []
contains = contains or []
query = Message.query
# A little argument validation. We could provide some defaults in
# these mixed cases.. but instead we'll just leave it up to our caller.
if (start != None and end == None) or (end != None and start == None):
raise ValueError("Either both start and end must be specified "
"or neither must be specified")
if start and end:
query = query.filter(between(Message.timestamp, start, end))
if msg_id:
query = query.filter(Message.msg_id == msg_id)
# Add the four positive filters as necessary
if users:
query = query.filter(or_(
*[Message.users.any(User.name == u) for u in users]
))
if packages:
query = query.filter(or_(
*[Message.packages.any(Package.name == p) for p in packages]
))
if categories:
query = query.filter(or_(
*[Message.category == category for category in categories]
))
if topics:
query = query.filter(or_(
*[Message.topic == topic for topic in topics]
))
if contains:
query = query.filter(or_(
*[Message._msg.like('%%%s%%' % contain)
for contain in contains]
))
# And then the four negative filters as necessary
if not_users:
query = query.filter(not_(or_(
*[Message.users.any(User.name == u) for u in not_users]
)))
if not_packs:
query = query.filter(not_(or_(
*[Message.packages.any(Package.name == p) for p in not_packs]
)))
if not_cats:
query = query.filter(not_(or_(
*[Message.category == category for category in not_cats]
)))
if not_topics:
query = query.filter(not_(or_(
*[Message.topic == topic for topic in not_topics]
)))
# Finally, tag on our pagination arguments
total = query.count()
query = query.order_by(getattr(Message.timestamp, order)())
if rows_per_page is None:
pages = 1
else:
pages = int(math.ceil(total / float(rows_per_page)))
query = query.offset(rows_per_page * (page - 1)).limit(rows_per_page)
if defer:
return total, page, query
else:
# Execute!
messages = query.all()
return total, pages, messages | python | def grep(cls, start=None, end=None,
page=1, rows_per_page=100,
order="asc", msg_id=None,
users=None, not_users=None,
packages=None, not_packages=None,
categories=None, not_categories=None,
topics=None, not_topics=None,
contains=None,
defer=False):
""" Flexible query interface for messages.
Arguments are filters. start and end should be :mod:`datetime` objs.
Other filters should be lists of strings. They are applied in a
conjunctive-normal-form (CNF) kind of way
for example, the following::
users = ['ralph', 'lmacken']
categories = ['bodhi', 'wiki']
should return messages where
(user=='ralph' OR user=='lmacken') AND
(category=='bodhi' OR category=='wiki')
Furthermore, you can use a negative version of each argument.
users = ['ralph']
not_categories = ['bodhi', 'wiki']
should return messages where
(user == 'ralph') AND
NOT (category == 'bodhi' OR category == 'wiki')
----
If the `defer` argument evaluates to True, the query won't actually
be executed, but a SQLAlchemy query object returned instead.
"""
users = users or []
not_users = not_users or []
packages = packages or []
not_packs = not_packages or []
categories = categories or []
not_cats = not_categories or []
topics = topics or []
not_topics = not_topics or []
contains = contains or []
query = Message.query
# A little argument validation. We could provide some defaults in
# these mixed cases.. but instead we'll just leave it up to our caller.
if (start != None and end == None) or (end != None and start == None):
raise ValueError("Either both start and end must be specified "
"or neither must be specified")
if start and end:
query = query.filter(between(Message.timestamp, start, end))
if msg_id:
query = query.filter(Message.msg_id == msg_id)
# Add the four positive filters as necessary
if users:
query = query.filter(or_(
*[Message.users.any(User.name == u) for u in users]
))
if packages:
query = query.filter(or_(
*[Message.packages.any(Package.name == p) for p in packages]
))
if categories:
query = query.filter(or_(
*[Message.category == category for category in categories]
))
if topics:
query = query.filter(or_(
*[Message.topic == topic for topic in topics]
))
if contains:
query = query.filter(or_(
*[Message._msg.like('%%%s%%' % contain)
for contain in contains]
))
# And then the four negative filters as necessary
if not_users:
query = query.filter(not_(or_(
*[Message.users.any(User.name == u) for u in not_users]
)))
if not_packs:
query = query.filter(not_(or_(
*[Message.packages.any(Package.name == p) for p in not_packs]
)))
if not_cats:
query = query.filter(not_(or_(
*[Message.category == category for category in not_cats]
)))
if not_topics:
query = query.filter(not_(or_(
*[Message.topic == topic for topic in not_topics]
)))
# Finally, tag on our pagination arguments
total = query.count()
query = query.order_by(getattr(Message.timestamp, order)())
if rows_per_page is None:
pages = 1
else:
pages = int(math.ceil(total / float(rows_per_page)))
query = query.offset(rows_per_page * (page - 1)).limit(rows_per_page)
if defer:
return total, page, query
else:
# Execute!
messages = query.all()
return total, pages, messages | [
"def",
"grep",
"(",
"cls",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"page",
"=",
"1",
",",
"rows_per_page",
"=",
"100",
",",
"order",
"=",
"\"asc\"",
",",
"msg_id",
"=",
"None",
",",
"users",
"=",
"None",
",",
"not_users",
"=",
"N... | Flexible query interface for messages.
Arguments are filters. start and end should be :mod:`datetime` objs.
Other filters should be lists of strings. They are applied in a
conjunctive-normal-form (CNF) kind of way
for example, the following::
users = ['ralph', 'lmacken']
categories = ['bodhi', 'wiki']
should return messages where
(user=='ralph' OR user=='lmacken') AND
(category=='bodhi' OR category=='wiki')
Furthermore, you can use a negative version of each argument.
users = ['ralph']
not_categories = ['bodhi', 'wiki']
should return messages where
(user == 'ralph') AND
NOT (category == 'bodhi' OR category == 'wiki')
----
If the `defer` argument evaluates to True, the query won't actually
be executed, but a SQLAlchemy query object returned instead. | [
"Flexible",
"query",
"interface",
"for",
"messages",
"."
] | train | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/datanommer.models/datanommer/models/__init__.py#L335-L464 |
Accelize/pycosio | pycosio/_core/functions_os_path.py | isdir | def isdir(path):
"""
Return True if path is an existing directory.
Equivalent to "os.path.isdir".
Args:
path (path-like object): Path or URL.
Returns:
bool: True if directory exists.
"""
system = get_instance(path)
# User may use directory path without trailing '/'
# like on standard file systems
return system.isdir(system.ensure_dir_path(path)) | python | def isdir(path):
"""
Return True if path is an existing directory.
Equivalent to "os.path.isdir".
Args:
path (path-like object): Path or URL.
Returns:
bool: True if directory exists.
"""
system = get_instance(path)
# User may use directory path without trailing '/'
# like on standard file systems
return system.isdir(system.ensure_dir_path(path)) | [
"def",
"isdir",
"(",
"path",
")",
":",
"system",
"=",
"get_instance",
"(",
"path",
")",
"# User may use directory path without trailing '/'",
"# like on standard file systems",
"return",
"system",
".",
"isdir",
"(",
"system",
".",
"ensure_dir_path",
"(",
"path",
")",
... | Return True if path is an existing directory.
Equivalent to "os.path.isdir".
Args:
path (path-like object): Path or URL.
Returns:
bool: True if directory exists. | [
"Return",
"True",
"if",
"path",
"is",
"an",
"existing",
"directory",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os_path.py#L108-L124 |
Accelize/pycosio | pycosio/_core/functions_os_path.py | relpath | def relpath(path, start=None):
"""
Return a relative file path to path either from the
current directory or from an optional start directory.
For storage objects, "path" and "start" are relative to
storage root.
"/" are not stripped on storage objects path. The ending slash is required
on some storage to signify that target is a directory.
Equivalent to "os.path.relpath".
Args:
path (path-like object): Path or URL.
start (path-like object): Relative from this optional directory.
Default to "os.curdir" for local files.
Returns:
str: Relative path.
"""
relative = get_instance(path).relpath(path)
if start:
# Storage relative path
# Replaces "\" by "/" for Windows.
return os_path_relpath(relative, start=start).replace('\\', '/')
return relative | python | def relpath(path, start=None):
"""
Return a relative file path to path either from the
current directory or from an optional start directory.
For storage objects, "path" and "start" are relative to
storage root.
"/" are not stripped on storage objects path. The ending slash is required
on some storage to signify that target is a directory.
Equivalent to "os.path.relpath".
Args:
path (path-like object): Path or URL.
start (path-like object): Relative from this optional directory.
Default to "os.curdir" for local files.
Returns:
str: Relative path.
"""
relative = get_instance(path).relpath(path)
if start:
# Storage relative path
# Replaces "\" by "/" for Windows.
return os_path_relpath(relative, start=start).replace('\\', '/')
return relative | [
"def",
"relpath",
"(",
"path",
",",
"start",
"=",
"None",
")",
":",
"relative",
"=",
"get_instance",
"(",
"path",
")",
".",
"relpath",
"(",
"path",
")",
"if",
"start",
":",
"# Storage relative path",
"# Replaces \"\\\" by \"/\" for Windows.",
"return",
"os_path_... | Return a relative file path to path either from the
current directory or from an optional start directory.
For storage objects, "path" and "start" are relative to
storage root.
"/" are not stripped on storage objects path. The ending slash is required
on some storage to signify that target is a directory.
Equivalent to "os.path.relpath".
Args:
path (path-like object): Path or URL.
start (path-like object): Relative from this optional directory.
Default to "os.curdir" for local files.
Returns:
str: Relative path. | [
"Return",
"a",
"relative",
"file",
"path",
"to",
"path",
"either",
"from",
"the",
"current",
"directory",
"or",
"from",
"an",
"optional",
"start",
"directory",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os_path.py#L176-L202 |
Accelize/pycosio | pycosio/_core/functions_os_path.py | samefile | def samefile(path1, path2):
"""
Return True if both pathname arguments refer to the same file or directory.
Equivalent to "os.path.samefile".
Args:
path1 (path-like object): Path or URL.
path2 (path-like object): Path or URL.
Returns:
bool: True if same file or directory.
"""
# Handles path-like objects and checks if storage
path1, path1_is_storage = format_and_is_storage(path1)
path2, path2_is_storage = format_and_is_storage(path2)
# Local files: Redirects to "os.path.samefile"
if not path1_is_storage and not path2_is_storage:
return os_path_samefile(path1, path2)
# One path is local, the other storage
if not path1_is_storage or not path2_is_storage:
return False
with handle_os_exceptions():
# Paths don't use same storage
system = get_instance(path1)
if system is not get_instance(path2):
return False
# Relative path are different
elif system.relpath(path1) != system.relpath(path2):
return False
# Same files
return True | python | def samefile(path1, path2):
"""
Return True if both pathname arguments refer to the same file or directory.
Equivalent to "os.path.samefile".
Args:
path1 (path-like object): Path or URL.
path2 (path-like object): Path or URL.
Returns:
bool: True if same file or directory.
"""
# Handles path-like objects and checks if storage
path1, path1_is_storage = format_and_is_storage(path1)
path2, path2_is_storage = format_and_is_storage(path2)
# Local files: Redirects to "os.path.samefile"
if not path1_is_storage and not path2_is_storage:
return os_path_samefile(path1, path2)
# One path is local, the other storage
if not path1_is_storage or not path2_is_storage:
return False
with handle_os_exceptions():
# Paths don't use same storage
system = get_instance(path1)
if system is not get_instance(path2):
return False
# Relative path are different
elif system.relpath(path1) != system.relpath(path2):
return False
# Same files
return True | [
"def",
"samefile",
"(",
"path1",
",",
"path2",
")",
":",
"# Handles path-like objects and checks if storage",
"path1",
",",
"path1_is_storage",
"=",
"format_and_is_storage",
"(",
"path1",
")",
"path2",
",",
"path2_is_storage",
"=",
"format_and_is_storage",
"(",
"path2",... | Return True if both pathname arguments refer to the same file or directory.
Equivalent to "os.path.samefile".
Args:
path1 (path-like object): Path or URL.
path2 (path-like object): Path or URL.
Returns:
bool: True if same file or directory. | [
"Return",
"True",
"if",
"both",
"pathname",
"arguments",
"refer",
"to",
"the",
"same",
"file",
"or",
"directory",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os_path.py#L205-L241 |
Accelize/pycosio | pycosio/_core/functions_os_path.py | splitdrive | def splitdrive(path):
"""
Split the path into a pair (drive, tail) where drive is either a
mount point or the empty string. On systems which do not use drive
specifications, drive will always be the empty string.
In all cases, drive + tail will be the same as path.
Equivalent to "os.path.splitdrive".
Args:
path (path-like object): Path or URL.
Returns:
tuple of str: drive, tail.
"""
relative = get_instance(path).relpath(path)
drive = path.rsplit(relative, 1)[0]
if drive and not drive[-2:] == '//':
# Keep "/" tail side
relative = '/' + relative
drive = drive.rstrip('/')
return drive, relative | python | def splitdrive(path):
"""
Split the path into a pair (drive, tail) where drive is either a
mount point or the empty string. On systems which do not use drive
specifications, drive will always be the empty string.
In all cases, drive + tail will be the same as path.
Equivalent to "os.path.splitdrive".
Args:
path (path-like object): Path or URL.
Returns:
tuple of str: drive, tail.
"""
relative = get_instance(path).relpath(path)
drive = path.rsplit(relative, 1)[0]
if drive and not drive[-2:] == '//':
# Keep "/" tail side
relative = '/' + relative
drive = drive.rstrip('/')
return drive, relative | [
"def",
"splitdrive",
"(",
"path",
")",
":",
"relative",
"=",
"get_instance",
"(",
"path",
")",
".",
"relpath",
"(",
"path",
")",
"drive",
"=",
"path",
".",
"rsplit",
"(",
"relative",
",",
"1",
")",
"[",
"0",
"]",
"if",
"drive",
"and",
"not",
"drive... | Split the path into a pair (drive, tail) where drive is either a
mount point or the empty string. On systems which do not use drive
specifications, drive will always be the empty string.
In all cases, drive + tail will be the same as path.
Equivalent to "os.path.splitdrive".
Args:
path (path-like object): Path or URL.
Returns:
tuple of str: drive, tail. | [
"Split",
"the",
"path",
"into",
"a",
"pair",
"(",
"drive",
"tail",
")",
"where",
"drive",
"is",
"either",
"a",
"mount",
"point",
"or",
"the",
"empty",
"string",
".",
"On",
"systems",
"which",
"do",
"not",
"use",
"drive",
"specifications",
"drive",
"will"... | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os_path.py#L245-L267 |
Accelize/pycosio | pycosio/_core/exceptions.py | handle_os_exceptions | def handle_os_exceptions():
"""
Handles pycosio exceptions and raise standard OS exceptions.
"""
try:
yield
# Convert pycosio exception to equivalent OSError
except ObjectException:
exc_type, exc_value, _ = exc_info()
raise _OS_EXCEPTIONS.get(exc_type, OSError)(exc_value)
# Re-raise generic exceptions
except (OSError, same_file_error, UnsupportedOperation):
raise
# Raise generic OSError for other exceptions
except Exception:
exc_type, exc_value, _ = exc_info()
raise OSError('%s%s' % (
exc_type, (', %s' % exc_value) if exc_value else '')) | python | def handle_os_exceptions():
"""
Handles pycosio exceptions and raise standard OS exceptions.
"""
try:
yield
# Convert pycosio exception to equivalent OSError
except ObjectException:
exc_type, exc_value, _ = exc_info()
raise _OS_EXCEPTIONS.get(exc_type, OSError)(exc_value)
# Re-raise generic exceptions
except (OSError, same_file_error, UnsupportedOperation):
raise
# Raise generic OSError for other exceptions
except Exception:
exc_type, exc_value, _ = exc_info()
raise OSError('%s%s' % (
exc_type, (', %s' % exc_value) if exc_value else '')) | [
"def",
"handle_os_exceptions",
"(",
")",
":",
"try",
":",
"yield",
"# Convert pycosio exception to equivalent OSError",
"except",
"ObjectException",
":",
"exc_type",
",",
"exc_value",
",",
"_",
"=",
"exc_info",
"(",
")",
"raise",
"_OS_EXCEPTIONS",
".",
"get",
"(",
... | Handles pycosio exceptions and raise standard OS exceptions. | [
"Handles",
"pycosio",
"exceptions",
"and",
"raise",
"standard",
"OS",
"exceptions",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/exceptions.py#L36-L56 |
Accelize/pycosio | pycosio/_core/functions_os.py | listdir | def listdir(path='.'):
"""
Return a list containing the names of the entries in the directory given by
path.
Equivalent to "os.listdir".
Args:
path (path-like object): Path or URL.
Returns:
list of str: Entries names.
"""
return [name.rstrip('/') for name, _ in
get_instance(path).list_objects(path, first_level=True)] | python | def listdir(path='.'):
"""
Return a list containing the names of the entries in the directory given by
path.
Equivalent to "os.listdir".
Args:
path (path-like object): Path or URL.
Returns:
list of str: Entries names.
"""
return [name.rstrip('/') for name, _ in
get_instance(path).list_objects(path, first_level=True)] | [
"def",
"listdir",
"(",
"path",
"=",
"'.'",
")",
":",
"return",
"[",
"name",
".",
"rstrip",
"(",
"'/'",
")",
"for",
"name",
",",
"_",
"in",
"get_instance",
"(",
"path",
")",
".",
"list_objects",
"(",
"path",
",",
"first_level",
"=",
"True",
")",
"]"... | Return a list containing the names of the entries in the directory given by
path.
Equivalent to "os.listdir".
Args:
path (path-like object): Path or URL.
Returns:
list of str: Entries names. | [
"Return",
"a",
"list",
"containing",
"the",
"names",
"of",
"the",
"entries",
"in",
"the",
"directory",
"given",
"by",
"path",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L20-L34 |
Accelize/pycosio | pycosio/_core/functions_os.py | makedirs | def makedirs(name, mode=0o777, exist_ok=False):
"""
Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment
(not just the rightmost) will be created if it does not exist.
Equivalent to "os.makedirs".
Args:
name (path-like object): Path or URL.
mode (int): The mode parameter is passed to os.mkdir();
see the os.mkdir() description for how it is interpreted.
Not supported on cloud storage objects.
exist_ok (bool): Don't raises error if target directory already
exists.
Raises:
FileExistsError: if exist_ok is False and if the target directory
already exists.
"""
system = get_instance(name)
# Checks if directory not already exists
if not exist_ok and system.isdir(system.ensure_dir_path(name)):
raise ObjectExistsError("File exists: '%s'" % name)
# Create directory
system.make_dir(name) | python | def makedirs(name, mode=0o777, exist_ok=False):
"""
Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment
(not just the rightmost) will be created if it does not exist.
Equivalent to "os.makedirs".
Args:
name (path-like object): Path or URL.
mode (int): The mode parameter is passed to os.mkdir();
see the os.mkdir() description for how it is interpreted.
Not supported on cloud storage objects.
exist_ok (bool): Don't raises error if target directory already
exists.
Raises:
FileExistsError: if exist_ok is False and if the target directory
already exists.
"""
system = get_instance(name)
# Checks if directory not already exists
if not exist_ok and system.isdir(system.ensure_dir_path(name)):
raise ObjectExistsError("File exists: '%s'" % name)
# Create directory
system.make_dir(name) | [
"def",
"makedirs",
"(",
"name",
",",
"mode",
"=",
"0o777",
",",
"exist_ok",
"=",
"False",
")",
":",
"system",
"=",
"get_instance",
"(",
"name",
")",
"# Checks if directory not already exists",
"if",
"not",
"exist_ok",
"and",
"system",
".",
"isdir",
"(",
"sys... | Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment
(not just the rightmost) will be created if it does not exist.
Equivalent to "os.makedirs".
Args:
name (path-like object): Path or URL.
mode (int): The mode parameter is passed to os.mkdir();
see the os.mkdir() description for how it is interpreted.
Not supported on cloud storage objects.
exist_ok (bool): Don't raises error if target directory already
exists.
Raises:
FileExistsError: if exist_ok is False and if the target directory
already exists. | [
"Super",
"-",
"mkdir",
";",
"create",
"a",
"leaf",
"directory",
"and",
"all",
"intermediate",
"ones",
".",
"Works",
"like",
"mkdir",
"except",
"that",
"any",
"intermediate",
"path",
"segment",
"(",
"not",
"just",
"the",
"rightmost",
")",
"will",
"be",
"cre... | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L38-L65 |
Accelize/pycosio | pycosio/_core/functions_os.py | mkdir | def mkdir(path, mode=0o777, dir_fd=None):
"""
Create a directory named path with numeric mode mode.
Equivalent to "os.mkdir".
Args:
path (path-like object): Path or URL.
mode (int): The mode parameter is passed to os.mkdir();
see the os.mkdir() description for how it is interpreted.
Not supported on cloud storage objects.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects.
Raises:
FileExistsError : Directory already exists.
FileNotFoundError: Parent directory not exists.
"""
system = get_instance(path)
relative = system.relpath(path)
# Checks if parent directory exists
parent_dir = dirname(relative.rstrip('/'))
if parent_dir:
parent = path.rsplit(relative, 1)[0] + parent_dir + '/'
if not system.isdir(parent):
raise ObjectNotFoundError(
"No such file or directory: '%s'" % parent)
# Checks if directory not already exists
if system.isdir(system.ensure_dir_path(path)):
raise ObjectExistsError("File exists: '%s'" % path)
# Create directory
system.make_dir(relative, relative=True) | python | def mkdir(path, mode=0o777, dir_fd=None):
"""
Create a directory named path with numeric mode mode.
Equivalent to "os.mkdir".
Args:
path (path-like object): Path or URL.
mode (int): The mode parameter is passed to os.mkdir();
see the os.mkdir() description for how it is interpreted.
Not supported on cloud storage objects.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects.
Raises:
FileExistsError : Directory already exists.
FileNotFoundError: Parent directory not exists.
"""
system = get_instance(path)
relative = system.relpath(path)
# Checks if parent directory exists
parent_dir = dirname(relative.rstrip('/'))
if parent_dir:
parent = path.rsplit(relative, 1)[0] + parent_dir + '/'
if not system.isdir(parent):
raise ObjectNotFoundError(
"No such file or directory: '%s'" % parent)
# Checks if directory not already exists
if system.isdir(system.ensure_dir_path(path)):
raise ObjectExistsError("File exists: '%s'" % path)
# Create directory
system.make_dir(relative, relative=True) | [
"def",
"mkdir",
"(",
"path",
",",
"mode",
"=",
"0o777",
",",
"dir_fd",
"=",
"None",
")",
":",
"system",
"=",
"get_instance",
"(",
"path",
")",
"relative",
"=",
"system",
".",
"relpath",
"(",
"path",
")",
"# Checks if parent directory exists",
"parent_dir",
... | Create a directory named path with numeric mode mode.
Equivalent to "os.mkdir".
Args:
path (path-like object): Path or URL.
mode (int): The mode parameter is passed to os.mkdir();
see the os.mkdir() description for how it is interpreted.
Not supported on cloud storage objects.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects.
Raises:
FileExistsError : Directory already exists.
FileNotFoundError: Parent directory not exists. | [
"Create",
"a",
"directory",
"named",
"path",
"with",
"numeric",
"mode",
"mode",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L69-L104 |
Accelize/pycosio | pycosio/_core/functions_os.py | remove | def remove(path, dir_fd=None):
"""
Remove a file.
Equivalent to "os.remove" and "os.unlink".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects.
"""
system = get_instance(path)
# Only support files
if system.is_locator(path) or path[-1] == '/':
raise is_a_directory_error("Is a directory: '%s'" % path)
# Remove
system.remove(path) | python | def remove(path, dir_fd=None):
"""
Remove a file.
Equivalent to "os.remove" and "os.unlink".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects.
"""
system = get_instance(path)
# Only support files
if system.is_locator(path) or path[-1] == '/':
raise is_a_directory_error("Is a directory: '%s'" % path)
# Remove
system.remove(path) | [
"def",
"remove",
"(",
"path",
",",
"dir_fd",
"=",
"None",
")",
":",
"system",
"=",
"get_instance",
"(",
"path",
")",
"# Only support files",
"if",
"system",
".",
"is_locator",
"(",
"path",
")",
"or",
"path",
"[",
"-",
"1",
"]",
"==",
"'/'",
":",
"rai... | Remove a file.
Equivalent to "os.remove" and "os.unlink".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects. | [
"Remove",
"a",
"file",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L108-L127 |
Accelize/pycosio | pycosio/_core/functions_os.py | rmdir | def rmdir(path, dir_fd=None):
"""
Remove a directory.
Equivalent to "os.rmdir".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.rmdir() description for how it is interpreted.
Not supported on cloud storage objects.
"""
system = get_instance(path)
system.remove(system.ensure_dir_path(path)) | python | def rmdir(path, dir_fd=None):
"""
Remove a directory.
Equivalent to "os.rmdir".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.rmdir() description for how it is interpreted.
Not supported on cloud storage objects.
"""
system = get_instance(path)
system.remove(system.ensure_dir_path(path)) | [
"def",
"rmdir",
"(",
"path",
",",
"dir_fd",
"=",
"None",
")",
":",
"system",
"=",
"get_instance",
"(",
"path",
")",
"system",
".",
"remove",
"(",
"system",
".",
"ensure_dir_path",
"(",
"path",
")",
")"
] | Remove a directory.
Equivalent to "os.rmdir".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.rmdir() description for how it is interpreted.
Not supported on cloud storage objects. | [
"Remove",
"a",
"directory",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L135-L148 |
Accelize/pycosio | pycosio/_core/functions_os.py | scandir | def scandir(path='.'):
"""
Return an iterator of os.DirEntry objects corresponding to the entries in
the directory given by path. The entries are yielded in arbitrary order,
and the special entries '.' and '..' are not included.
Equivalent to "os.scandir".
Args:
path (path-like object): Path or URL.
If path is of type bytes (directly or indirectly through the
PathLike interface), the type of the name and path attributes
of each os.DirEntry will be bytes; in all other circumstances,
they will be of type str.
Returns:
Generator of os.DirEntry: Entries information.
"""
# Handles path-like objects
scandir_path = fsdecode(path).replace('\\', '/')
if not is_storage(scandir_path):
return os_scandir(scandir_path)
return _scandir_generator(
is_bytes=isinstance(fspath(path), (bytes, bytearray)),
scandir_path=scandir_path, system=get_instance(scandir_path)) | python | def scandir(path='.'):
"""
Return an iterator of os.DirEntry objects corresponding to the entries in
the directory given by path. The entries are yielded in arbitrary order,
and the special entries '.' and '..' are not included.
Equivalent to "os.scandir".
Args:
path (path-like object): Path or URL.
If path is of type bytes (directly or indirectly through the
PathLike interface), the type of the name and path attributes
of each os.DirEntry will be bytes; in all other circumstances,
they will be of type str.
Returns:
Generator of os.DirEntry: Entries information.
"""
# Handles path-like objects
scandir_path = fsdecode(path).replace('\\', '/')
if not is_storage(scandir_path):
return os_scandir(scandir_path)
return _scandir_generator(
is_bytes=isinstance(fspath(path), (bytes, bytearray)),
scandir_path=scandir_path, system=get_instance(scandir_path)) | [
"def",
"scandir",
"(",
"path",
"=",
"'.'",
")",
":",
"# Handles path-like objects",
"scandir_path",
"=",
"fsdecode",
"(",
"path",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"if",
"not",
"is_storage",
"(",
"scandir_path",
")",
":",
"return",
"os_s... | Return an iterator of os.DirEntry objects corresponding to the entries in
the directory given by path. The entries are yielded in arbitrary order,
and the special entries '.' and '..' are not included.
Equivalent to "os.scandir".
Args:
path (path-like object): Path or URL.
If path is of type bytes (directly or indirectly through the
PathLike interface), the type of the name and path attributes
of each os.DirEntry will be bytes; in all other circumstances,
they will be of type str.
Returns:
Generator of os.DirEntry: Entries information. | [
"Return",
"an",
"iterator",
"of",
"os",
".",
"DirEntry",
"objects",
"corresponding",
"to",
"the",
"entries",
"in",
"the",
"directory",
"given",
"by",
"path",
".",
"The",
"entries",
"are",
"yielded",
"in",
"arbitrary",
"order",
"and",
"the",
"special",
"entri... | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L374-L400 |
Accelize/pycosio | pycosio/_core/functions_os.py | _scandir_generator | def _scandir_generator(is_bytes, scandir_path, system):
"""
scandir generator
Args:
is_bytes (bool): True if DirEntry must handle path as bytes.
scandir_path (str): Path.
system (pycosio._core.io_system.SystemBase subclass):
Storage system.
Yields:
DirEntry: Directory entries
"""
with handle_os_exceptions():
for name, header in system.list_objects(scandir_path, first_level=True):
yield DirEntry(
scandir_path=scandir_path, system=system, name=name,
header=header, bytes_path=is_bytes) | python | def _scandir_generator(is_bytes, scandir_path, system):
"""
scandir generator
Args:
is_bytes (bool): True if DirEntry must handle path as bytes.
scandir_path (str): Path.
system (pycosio._core.io_system.SystemBase subclass):
Storage system.
Yields:
DirEntry: Directory entries
"""
with handle_os_exceptions():
for name, header in system.list_objects(scandir_path, first_level=True):
yield DirEntry(
scandir_path=scandir_path, system=system, name=name,
header=header, bytes_path=is_bytes) | [
"def",
"_scandir_generator",
"(",
"is_bytes",
",",
"scandir_path",
",",
"system",
")",
":",
"with",
"handle_os_exceptions",
"(",
")",
":",
"for",
"name",
",",
"header",
"in",
"system",
".",
"list_objects",
"(",
"scandir_path",
",",
"first_level",
"=",
"True",
... | scandir generator
Args:
is_bytes (bool): True if DirEntry must handle path as bytes.
scandir_path (str): Path.
system (pycosio._core.io_system.SystemBase subclass):
Storage system.
Yields:
DirEntry: Directory entries | [
"scandir",
"generator"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L403-L420 |
Accelize/pycosio | pycosio/_core/functions_os.py | DirEntry.name | def name(self):
"""
The entry’s base filename, relative to the scandir() path argument.
Returns:
str: name.
"""
name = self._name.rstrip('/')
if self._bytes_path:
name = fsencode(name)
return name | python | def name(self):
"""
The entry’s base filename, relative to the scandir() path argument.
Returns:
str: name.
"""
name = self._name.rstrip('/')
if self._bytes_path:
name = fsencode(name)
return name | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"_name",
".",
"rstrip",
"(",
"'/'",
")",
"if",
"self",
".",
"_bytes_path",
":",
"name",
"=",
"fsencode",
"(",
"name",
")",
"return",
"name"
] | The entry’s base filename, relative to the scandir() path argument.
Returns:
str: name. | [
"The",
"entry’s",
"base",
"filename",
"relative",
"to",
"the",
"scandir",
"()",
"path",
"argument",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L249-L259 |
Accelize/pycosio | pycosio/_core/functions_os.py | DirEntry.path | def path(self):
"""
The entry’s full path name:
equivalent to os.path.join(scandir_path, entry.name)
where scandir_path is the scandir() path argument.
The path is only absolute if the scandir() path argument was absolute.
Returns:
str: name.
"""
path = self._path.rstrip('/')
if self._bytes_path:
path = fsencode(path)
return path | python | def path(self):
"""
The entry’s full path name:
equivalent to os.path.join(scandir_path, entry.name)
where scandir_path is the scandir() path argument.
The path is only absolute if the scandir() path argument was absolute.
Returns:
str: name.
"""
path = self._path.rstrip('/')
if self._bytes_path:
path = fsencode(path)
return path | [
"def",
"path",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"_path",
".",
"rstrip",
"(",
"'/'",
")",
"if",
"self",
".",
"_bytes_path",
":",
"path",
"=",
"fsencode",
"(",
"path",
")",
"return",
"path"
] | The entry’s full path name:
equivalent to os.path.join(scandir_path, entry.name)
where scandir_path is the scandir() path argument.
The path is only absolute if the scandir() path argument was absolute.
Returns:
str: name. | [
"The",
"entry’s",
"full",
"path",
"name",
":",
"equivalent",
"to",
"os",
".",
"path",
".",
"join",
"(",
"scandir_path",
"entry",
".",
"name",
")",
"where",
"scandir_path",
"is",
"the",
"scandir",
"()",
"path",
"argument",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L263-L277 |
Accelize/pycosio | pycosio/_core/functions_os.py | DirEntry.is_dir | def is_dir(self, follow_symlinks=True):
"""
Return True if this entry is a directory or a symbolic link pointing to
a directory; return False if the entry is or points to any other kind
of file, or if it doesn’t exist anymore.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Returns:
bool: True if directory exists.
"""
try:
return (self._system.isdir(
path=self._path, client_kwargs=self._client_kwargs,
virtual_dir=False) or
# Some directories only exists virtually in object path and
# don't have headers.
bool(S_ISDIR(self.stat().st_mode)))
except ObjectPermissionError:
# The directory was listed, but unable to head it or access to its
# content
return True | python | def is_dir(self, follow_symlinks=True):
"""
Return True if this entry is a directory or a symbolic link pointing to
a directory; return False if the entry is or points to any other kind
of file, or if it doesn’t exist anymore.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Returns:
bool: True if directory exists.
"""
try:
return (self._system.isdir(
path=self._path, client_kwargs=self._client_kwargs,
virtual_dir=False) or
# Some directories only exists virtually in object path and
# don't have headers.
bool(S_ISDIR(self.stat().st_mode)))
except ObjectPermissionError:
# The directory was listed, but unable to head it or access to its
# content
return True | [
"def",
"is_dir",
"(",
"self",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"try",
":",
"return",
"(",
"self",
".",
"_system",
".",
"isdir",
"(",
"path",
"=",
"self",
".",
"_path",
",",
"client_kwargs",
"=",
"self",
".",
"_client_kwargs",
",",
"virtua... | Return True if this entry is a directory or a symbolic link pointing to
a directory; return False if the entry is or points to any other kind
of file, or if it doesn’t exist anymore.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Returns:
bool: True if directory exists. | [
"Return",
"True",
"if",
"this",
"entry",
"is",
"a",
"directory",
"or",
"a",
"symbolic",
"link",
"pointing",
"to",
"a",
"directory",
";",
"return",
"False",
"if",
"the",
"entry",
"is",
"or",
"points",
"to",
"any",
"other",
"kind",
"of",
"file",
"or",
"i... | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L292-L319 |
Accelize/pycosio | pycosio/_core/functions_os.py | DirEntry.is_file | def is_file(self, follow_symlinks=True):
"""
Return True if this entry is a file or a symbolic link pointing to a
file; return False if the entry is or points to a directory or other
non-file entry, or if it doesn’t exist anymore.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Returns:
bool: True if directory exists.
"""
return self._system.isfile(
path=self._path, client_kwargs=self._client_kwargs) | python | def is_file(self, follow_symlinks=True):
"""
Return True if this entry is a file or a symbolic link pointing to a
file; return False if the entry is or points to a directory or other
non-file entry, or if it doesn’t exist anymore.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Returns:
bool: True if directory exists.
"""
return self._system.isfile(
path=self._path, client_kwargs=self._client_kwargs) | [
"def",
"is_file",
"(",
"self",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"return",
"self",
".",
"_system",
".",
"isfile",
"(",
"path",
"=",
"self",
".",
"_path",
",",
"client_kwargs",
"=",
"self",
".",
"_client_kwargs",
")"
] | Return True if this entry is a file or a symbolic link pointing to a
file; return False if the entry is or points to a directory or other
non-file entry, or if it doesn’t exist anymore.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Returns:
bool: True if directory exists. | [
"Return",
"True",
"if",
"this",
"entry",
"is",
"a",
"file",
"or",
"a",
"symbolic",
"link",
"pointing",
"to",
"a",
"file",
";",
"return",
"False",
"if",
"the",
"entry",
"is",
"or",
"points",
"to",
"a",
"directory",
"or",
"other",
"non",
"-",
"file",
"... | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L322-L338 |
Accelize/pycosio | pycosio/_core/functions_os.py | DirEntry.stat | def stat(self, follow_symlinks=True):
"""
Return a stat_result object for this entry.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Returns:
os.stat_result: Stat result object
"""
return self._system.stat(
path=self._path, client_kwargs=self._client_kwargs,
header=self._header) | python | def stat(self, follow_symlinks=True):
"""
Return a stat_result object for this entry.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Returns:
os.stat_result: Stat result object
"""
return self._system.stat(
path=self._path, client_kwargs=self._client_kwargs,
header=self._header) | [
"def",
"stat",
"(",
"self",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"return",
"self",
".",
"_system",
".",
"stat",
"(",
"path",
"=",
"self",
".",
"_path",
",",
"client_kwargs",
"=",
"self",
".",
"_client_kwargs",
",",
"header",
"=",
"self",
".",... | Return a stat_result object for this entry.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Returns:
os.stat_result: Stat result object | [
"Return",
"a",
"stat_result",
"object",
"for",
"this",
"entry",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L353-L368 |
Accelize/pycosio | pycosio/_core/io_base_buffered.py | ObjectBufferedIOBase.close | def close(self):
"""
Flush the write buffers of the stream if applicable and
close the object.
"""
if self._writable and not self._closed:
self._closed = True
with self._seek_lock:
self._flush_raw_or_buffered()
if self._seek:
with handle_os_exceptions():
self._close_writable() | python | def close(self):
"""
Flush the write buffers of the stream if applicable and
close the object.
"""
if self._writable and not self._closed:
self._closed = True
with self._seek_lock:
self._flush_raw_or_buffered()
if self._seek:
with handle_os_exceptions():
self._close_writable() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_writable",
"and",
"not",
"self",
".",
"_closed",
":",
"self",
".",
"_closed",
"=",
"True",
"with",
"self",
".",
"_seek_lock",
":",
"self",
".",
"_flush_raw_or_buffered",
"(",
")",
"if",
"self"... | Flush the write buffers of the stream if applicable and
close the object. | [
"Flush",
"the",
"write",
"buffers",
"of",
"the",
"stream",
"if",
"applicable",
"and",
"close",
"the",
"object",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_buffered.py#L120-L131 |
Accelize/pycosio | pycosio/_core/io_base_buffered.py | ObjectBufferedIOBase.flush | def flush(self):
"""
Flush the write buffers of the stream if applicable.
"""
if self._writable:
with self._seek_lock:
self._flush_raw_or_buffered()
# Clear the buffer
self._write_buffer = bytearray(self._buffer_size)
self._buffer_seek = 0 | python | def flush(self):
"""
Flush the write buffers of the stream if applicable.
"""
if self._writable:
with self._seek_lock:
self._flush_raw_or_buffered()
# Clear the buffer
self._write_buffer = bytearray(self._buffer_size)
self._buffer_seek = 0 | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"_writable",
":",
"with",
"self",
".",
"_seek_lock",
":",
"self",
".",
"_flush_raw_or_buffered",
"(",
")",
"# Clear the buffer",
"self",
".",
"_write_buffer",
"=",
"bytearray",
"(",
"self",
".",
"_b... | Flush the write buffers of the stream if applicable. | [
"Flush",
"the",
"write",
"buffers",
"of",
"the",
"stream",
"if",
"applicable",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_buffered.py#L144-L154 |
Accelize/pycosio | pycosio/_core/io_base_buffered.py | ObjectBufferedIOBase._flush_raw_or_buffered | def _flush_raw_or_buffered(self):
"""
Flush using raw of buffered methods.
"""
# Flush only if bytes written
# This avoid no required process/thread
# creation and network call.
# This step is performed by raw stream.
if self._buffer_seek and self._seek:
self._seek += 1
with handle_os_exceptions():
self._flush()
# If data lower than buffer size
# flush data with raw stream to reduce IO calls
elif self._buffer_seek:
self._raw._write_buffer = self._get_buffer()
self._raw._seek = self._buffer_seek
self._raw.flush() | python | def _flush_raw_or_buffered(self):
"""
Flush using raw of buffered methods.
"""
# Flush only if bytes written
# This avoid no required process/thread
# creation and network call.
# This step is performed by raw stream.
if self._buffer_seek and self._seek:
self._seek += 1
with handle_os_exceptions():
self._flush()
# If data lower than buffer size
# flush data with raw stream to reduce IO calls
elif self._buffer_seek:
self._raw._write_buffer = self._get_buffer()
self._raw._seek = self._buffer_seek
self._raw.flush() | [
"def",
"_flush_raw_or_buffered",
"(",
"self",
")",
":",
"# Flush only if bytes written",
"# This avoid no required process/thread",
"# creation and network call.",
"# This step is performed by raw stream.",
"if",
"self",
".",
"_buffer_seek",
"and",
"self",
".",
"_seek",
":",
"s... | Flush using raw of buffered methods. | [
"Flush",
"using",
"raw",
"of",
"buffered",
"methods",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_buffered.py#L156-L174 |
Accelize/pycosio | pycosio/_core/io_base_buffered.py | ObjectBufferedIOBase.peek | def peek(self, size=-1):
"""
Return bytes from the stream without advancing the position.
Args:
size (int): Number of bytes to read. -1 to read the full
stream.
Returns:
bytes: bytes read
"""
if not self._readable:
raise UnsupportedOperation('read')
with self._seek_lock:
self._raw.seek(self._seek)
return self._raw._peek(size) | python | def peek(self, size=-1):
"""
Return bytes from the stream without advancing the position.
Args:
size (int): Number of bytes to read. -1 to read the full
stream.
Returns:
bytes: bytes read
"""
if not self._readable:
raise UnsupportedOperation('read')
with self._seek_lock:
self._raw.seek(self._seek)
return self._raw._peek(size) | [
"def",
"peek",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"not",
"self",
".",
"_readable",
":",
"raise",
"UnsupportedOperation",
"(",
"'read'",
")",
"with",
"self",
".",
"_seek_lock",
":",
"self",
".",
"_raw",
".",
"seek",
"(",
"self",
... | Return bytes from the stream without advancing the position.
Args:
size (int): Number of bytes to read. -1 to read the full
stream.
Returns:
bytes: bytes read | [
"Return",
"bytes",
"from",
"the",
"stream",
"without",
"advancing",
"the",
"position",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_buffered.py#L194-L210 |
Accelize/pycosio | pycosio/_core/io_base_buffered.py | ObjectBufferedIOBase._preload_range | def _preload_range(self):
"""Preload data for reading"""
queue = self._read_queue
size = self._buffer_size
start = self._seek
end = int(start + size * self._max_buffers)
workers_submit = self._workers.submit
indexes = tuple(range(start, end, size))
# Drops buffer out of current range
for seek in tuple(queue):
if seek not in indexes:
del queue[seek]
# Launch buffer preloading for current range
read_range = self._read_range
for seek in indexes:
if seek not in queue:
queue[seek] = workers_submit(read_range, seek, seek + size) | python | def _preload_range(self):
"""Preload data for reading"""
queue = self._read_queue
size = self._buffer_size
start = self._seek
end = int(start + size * self._max_buffers)
workers_submit = self._workers.submit
indexes = tuple(range(start, end, size))
# Drops buffer out of current range
for seek in tuple(queue):
if seek not in indexes:
del queue[seek]
# Launch buffer preloading for current range
read_range = self._read_range
for seek in indexes:
if seek not in queue:
queue[seek] = workers_submit(read_range, seek, seek + size) | [
"def",
"_preload_range",
"(",
"self",
")",
":",
"queue",
"=",
"self",
".",
"_read_queue",
"size",
"=",
"self",
".",
"_buffer_size",
"start",
"=",
"self",
".",
"_seek",
"end",
"=",
"int",
"(",
"start",
"+",
"size",
"*",
"self",
".",
"_max_buffers",
")",... | Preload data for reading | [
"Preload",
"data",
"for",
"reading"
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_buffered.py#L212-L230 |
Accelize/pycosio | pycosio/_core/io_base_buffered.py | ObjectBufferedIOBase.read | def read(self, size=-1):
"""
Read and return up to size bytes,
with at most one call to the underlying raw stream’s.
Use at most one call to the underlying raw stream’s read method.
Args:
size (int): Number of bytes to read. -1 to read the
stream until end.
Returns:
bytes: Object content
"""
if not self._readable:
raise UnsupportedOperation('read')
# Checks if EOF
if self._seek == self._size:
return b''
# Returns existing buffer with no copy
if size == self._buffer_size:
queue_index = self._seek
# Starts initial preloading on first call
if queue_index == 0:
self._preload_range()
# Get buffer from future
with handle_os_exceptions():
buffer = self._read_queue.pop(queue_index).result()
# Append another buffer preload at end of queue
buffer_size = self._buffer_size
index = queue_index + buffer_size * self._max_buffers
if index < self._size:
self._read_queue[index] = self._workers.submit(
self._read_range, index, index + buffer_size)
# Update seek
self._seek += buffer_size
else:
self._seek = self._size
return buffer
# Uses a prealocated buffer
if size != -1:
buffer = bytearray(size)
# Uses a mutable buffer
else:
buffer = bytearray()
read_size = self.readinto(buffer)
return memoryview(buffer)[:read_size].tobytes() | python | def read(self, size=-1):
"""
Read and return up to size bytes,
with at most one call to the underlying raw stream’s.
Use at most one call to the underlying raw stream’s read method.
Args:
size (int): Number of bytes to read. -1 to read the
stream until end.
Returns:
bytes: Object content
"""
if not self._readable:
raise UnsupportedOperation('read')
# Checks if EOF
if self._seek == self._size:
return b''
# Returns existing buffer with no copy
if size == self._buffer_size:
queue_index = self._seek
# Starts initial preloading on first call
if queue_index == 0:
self._preload_range()
# Get buffer from future
with handle_os_exceptions():
buffer = self._read_queue.pop(queue_index).result()
# Append another buffer preload at end of queue
buffer_size = self._buffer_size
index = queue_index + buffer_size * self._max_buffers
if index < self._size:
self._read_queue[index] = self._workers.submit(
self._read_range, index, index + buffer_size)
# Update seek
self._seek += buffer_size
else:
self._seek = self._size
return buffer
# Uses a prealocated buffer
if size != -1:
buffer = bytearray(size)
# Uses a mutable buffer
else:
buffer = bytearray()
read_size = self.readinto(buffer)
return memoryview(buffer)[:read_size].tobytes() | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"not",
"self",
".",
"_readable",
":",
"raise",
"UnsupportedOperation",
"(",
"'read'",
")",
"# Checks if EOF",
"if",
"self",
".",
"_seek",
"==",
"self",
".",
"_size",
":",
"return",... | Read and return up to size bytes,
with at most one call to the underlying raw stream’s.
Use at most one call to the underlying raw stream’s read method.
Args:
size (int): Number of bytes to read. -1 to read the
stream until end.
Returns:
bytes: Object content | [
"Read",
"and",
"return",
"up",
"to",
"size",
"bytes",
"with",
"at",
"most",
"one",
"call",
"to",
"the",
"underlying",
"raw",
"stream’s",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_buffered.py#L242-L298 |
Accelize/pycosio | pycosio/_core/io_base_buffered.py | ObjectBufferedIOBase.readinto | def readinto(self, b):
"""
Read bytes into a pre-allocated, writable bytes-like object b,
and return the number of bytes read.
Args:
b (bytes-like object): buffer.
Returns:
int: number of bytes read
"""
if not self._readable:
raise UnsupportedOperation('read')
with self._seek_lock:
# Gets seek
seek = self._seek
# Initializes queue
queue = self._read_queue
if seek == 0:
# Starts initial preloading on first call
self._preload_range()
# Initializes read data buffer
size = len(b)
if size:
# Preallocated buffer:
# Use memory view to avoid copies
b_view = memoryview(b)
size_left = size
else:
# Dynamic buffer:
# Can't avoid copy, read until EOF
b_view = b
size_left = -1
b_end = 0
# Starts reading
buffer_size = self._buffer_size
while size_left > 0 or size_left == -1:
# Finds buffer position in queue and buffer seek
start = seek % buffer_size
queue_index = seek - start
# Gets preloaded buffer
try:
buffer = queue[queue_index]
except KeyError:
# EOF
break
# Get buffer from future
with handle_os_exceptions():
try:
queue[queue_index] = buffer = buffer.result()
# Already evaluated
except AttributeError:
pass
buffer_view = memoryview(buffer)
data_size = len(buffer)
# Checks if end of file reached
if not data_size:
break
# Gets theoretical range to copy
if size_left != -1:
end = start + size_left
else:
end = data_size - start
# Checks for end of buffer
if end >= data_size:
# Adjusts range to copy
end = data_size
# Removes consumed buffer from queue
del queue[queue_index]
# Append another buffer preload at end of queue
index = queue_index + buffer_size * self._max_buffers
if index < self._size:
queue[index] = self._workers.submit(
self._read_range, index, index + buffer_size)
# Gets read size, updates seek and updates size left
read_size = end - start
if size_left != -1:
size_left -= read_size
seek += read_size
# Defines read buffer range
b_start = b_end
b_end = b_start + read_size
# Copy data from preload buffer to read buffer
b_view[b_start:b_end] = buffer_view[start:end]
# Updates seek and sync raw
self._seek = seek
self._raw.seek(seek)
# Returns read size
return b_end | python | def readinto(self, b):
"""
Read bytes into a pre-allocated, writable bytes-like object b,
and return the number of bytes read.
Args:
b (bytes-like object): buffer.
Returns:
int: number of bytes read
"""
if not self._readable:
raise UnsupportedOperation('read')
with self._seek_lock:
# Gets seek
seek = self._seek
# Initializes queue
queue = self._read_queue
if seek == 0:
# Starts initial preloading on first call
self._preload_range()
# Initializes read data buffer
size = len(b)
if size:
# Preallocated buffer:
# Use memory view to avoid copies
b_view = memoryview(b)
size_left = size
else:
# Dynamic buffer:
# Can't avoid copy, read until EOF
b_view = b
size_left = -1
b_end = 0
# Starts reading
buffer_size = self._buffer_size
while size_left > 0 or size_left == -1:
# Finds buffer position in queue and buffer seek
start = seek % buffer_size
queue_index = seek - start
# Gets preloaded buffer
try:
buffer = queue[queue_index]
except KeyError:
# EOF
break
# Get buffer from future
with handle_os_exceptions():
try:
queue[queue_index] = buffer = buffer.result()
# Already evaluated
except AttributeError:
pass
buffer_view = memoryview(buffer)
data_size = len(buffer)
# Checks if end of file reached
if not data_size:
break
# Gets theoretical range to copy
if size_left != -1:
end = start + size_left
else:
end = data_size - start
# Checks for end of buffer
if end >= data_size:
# Adjusts range to copy
end = data_size
# Removes consumed buffer from queue
del queue[queue_index]
# Append another buffer preload at end of queue
index = queue_index + buffer_size * self._max_buffers
if index < self._size:
queue[index] = self._workers.submit(
self._read_range, index, index + buffer_size)
# Gets read size, updates seek and updates size left
read_size = end - start
if size_left != -1:
size_left -= read_size
seek += read_size
# Defines read buffer range
b_start = b_end
b_end = b_start + read_size
# Copy data from preload buffer to read buffer
b_view[b_start:b_end] = buffer_view[start:end]
# Updates seek and sync raw
self._seek = seek
self._raw.seek(seek)
# Returns read size
return b_end | [
"def",
"readinto",
"(",
"self",
",",
"b",
")",
":",
"if",
"not",
"self",
".",
"_readable",
":",
"raise",
"UnsupportedOperation",
"(",
"'read'",
")",
"with",
"self",
".",
"_seek_lock",
":",
"# Gets seek",
"seek",
"=",
"self",
".",
"_seek",
"# Initializes qu... | Read bytes into a pre-allocated, writable bytes-like object b,
and return the number of bytes read.
Args:
b (bytes-like object): buffer.
Returns:
int: number of bytes read | [
"Read",
"bytes",
"into",
"a",
"pre",
"-",
"allocated",
"writable",
"bytes",
"-",
"like",
"object",
"b",
"and",
"return",
"the",
"number",
"of",
"bytes",
"read",
"."
] | train | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_buffered.py#L316-L422 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.