_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q261800 | extract_names | validation | def extract_names(source):
"""Extract names from a function definition
Looks for a function definition in the source.
Only the first function definition is examined.
Returns:
a list names(identifiers) used in the body of the function
excluding function parameters.
"""
if source is None:
return None
source = dedent(source)
| python | {
"resource": ""
} |
q261801 | is_funcdef | validation | def is_funcdef(src):
"""True if src is a function definition"""
module_node = ast.parse(dedent(src))
if len(module_node.body) == 1 and isinstance(
| python | {
"resource": ""
} |
q261802 | remove_decorator | validation | def remove_decorator(source: str):
"""Remove decorators from function definition"""
lines = source.splitlines()
atok = asttokens.ASTTokens(source, parse=True)
for node in ast.walk(atok.tree):
if isinstance(node, ast.FunctionDef):
break
if node.decorator_list:
deco_first = node.decorator_list[0]
| python | {
"resource": ""
} |
q261803 | replace_funcname | validation | def replace_funcname(source: str, name: str):
"""Replace function name"""
lines = source.splitlines()
atok = asttokens.ASTTokens(source, parse=True)
for node in ast.walk(atok.tree):
if isinstance(node, ast.FunctionDef):
break
i = node.first_token.index
for i in range(node.first_token.index, node.last_token.index):
if (atok.tokens[i].type == token.NAME
and atok.tokens[i].string == "def"): | python | {
"resource": ""
} |
q261804 | has_lambda | validation | def has_lambda(src):
"""True if only one lambda expression is included"""
module_node = ast.parse(dedent(src))
lambdaexp = [node for node | python | {
"resource": ""
} |
q261805 | Formula._reload | validation | def _reload(self, module=None):
"""Reload the source function from the source module.
**Internal use only**
Update the source function of the formula.
This method is used to updated the underlying formula
when the source code of the module in which the source function
is read from is modified.
If the formula was not created from a module, an error is raised.
If ``module_`` is not given, the source module of the formula is
reloaded. If ``module_`` is given and matches the source module,
| python | {
"resource": ""
} |
q261806 | get_description | validation | def get_description():
"""Get long description from README.""" | python | {
"resource": ""
} |
q261807 | CellsView.to_frame | validation | def to_frame(self, *args):
"""Convert the cells in the view into a DataFrame object.
If ``args`` is not given, this method returns a DataFrame that
has an Index or a MultiIndex depending of the number of
cells parameters and columns each of which corresponds to each
cells included in the view.
``args`` can be given to calculate cells values and limit the
DataFrame indexes to the given arguments.
The cells in this view may have different number of parameters,
but parameters shared among multiple cells
must appear in the same position in all the parameter lists.
For example,
Having ``foo()``, ``bar(x)`` and ``baz(x, y=1)`` is okay
because the shared parameter ``x`` is always the first parameter,
but | python | {
"resource": ""
} |
q261808 | StaticSpace.new_cells | validation | def new_cells(self, name=None, formula=None):
"""Create a cells in the space.
Args:
name: If omitted, the model is named automatically ``CellsN``,
where ``N`` is an available number.
func: The function to | python | {
"resource": ""
} |
q261809 | StaticSpace.import_funcs | validation | def import_funcs(self, module):
"""Create a cells from a module."""
| python | {
"resource": ""
} |
q261810 | BaseSpaceImpl.get_object | validation | def get_object(self, name):
"""Retrieve an object by a dotted name relative to the space."""
parts = name.split(".")
| python | {
"resource": ""
} |
q261811 | BaseSpaceImpl._get_dynamic_base | validation | def _get_dynamic_base(self, bases_):
"""Create or get the base space from a list of spaces
if a direct base space in `bases` is dynamic, replace it with
its base.
"""
bases = tuple(
base.bases[0] if base.is_dynamic() else base for base in bases_
| python | {
"resource": ""
} |
q261812 | BaseSpaceImpl._new_dynspace | validation | def _new_dynspace(
self,
name=None,
bases=None,
formula=None,
refs=None,
arguments=None,
source=None,
):
"""Create a new dynamic root space."""
if name is None:
name = self.spacenamer.get_next(self.namespace)
if name in self.namespace:
raise ValueError("Name '%s' already exists." % name)
if not is_valid_name(name):
raise ValueError("Invalid name '%s'." % name)
space = RootDynamicSpaceImpl(
parent=self,
name=name,
| python | {
"resource": ""
} |
q261813 | BaseSpaceImpl.get_dynspace | validation | def get_dynspace(self, args, kwargs=None):
"""Create a dynamic root space
Called from interface methods
"""
node = get_node(self, *convert_args(args, kwargs))
key = node[KEY]
if key in self.param_spaces:
return self.param_spaces[key]
else:
last_self = self.system.self
self.system.self = self
try:
space_args = self.eval_formula(node)
finally:
self.system.self = last_self
if space_args is None:
space_args = {"bases": [self]} # Default
else:
if "bases" in space_args:
bases = get_impls(space_args["bases"])
if isinstance(bases, StaticSpaceImpl):
space_args["bases"] = [bases]
| python | {
"resource": ""
} |
q261814 | StaticSpaceImpl.set_attr | validation | def set_attr(self, name, value):
"""Implementation of attribute setting
``space.name = value`` by user script
Called from ``Space.__setattr__``
"""
if not is_valid_name(name):
raise ValueError("Invalid name '%s'" % name)
if name in self.namespace:
if name in self.refs:
if name in self.self_refs:
self.new_ref(name, value)
else:
raise | python | {
"resource": ""
} |
q261815 | StaticSpaceImpl.del_attr | validation | def del_attr(self, name):
"""Implementation of attribute deletion
``del space.name`` by user script
Called from ``StaticSpace.__delattr__``
"""
if name in self.namespace:
if name in self.cells:
self.del_cells(name)
elif name in self.spaces:
self.del_space(name)
elif name in self.refs:
| python | {
"resource": ""
} |
q261816 | StaticSpaceImpl.del_space | validation | def del_space(self, name):
"""Delete a space."""
if name not in self.spaces:
raise ValueError("Space '%s' does not exist" % name)
if name in self.static_spaces:
space = self.static_spaces[name]
if space.is_derived:
raise ValueError(
"%s has derived spaces" % repr(space.interface)
)
else:
self.static_spaces.del_item(name)
self.model.spacegraph.remove_node(space)
| python | {
"resource": ""
} |
q261817 | StaticSpaceImpl.del_cells | validation | def del_cells(self, name):
"""Implementation of cells deletion
``del space.name`` where name is a cells, or
``del space.cells['name']``
"""
if name in self.cells:
cells = self.cells[name]
| python | {
"resource": ""
} |
q261818 | cellsiter_to_dataframe | validation | def cellsiter_to_dataframe(cellsiter, args, drop_allna=True):
"""Convert multiple cells to a frame.
If args is an empty sequence, all values are included.
If args is specified, cellsiter must have shareable parameters.
Args:
cellsiter: A mapping from cells names to CellsImpl objects.
args: A sequence of arguments
"""
from modelx.core.cells import shareable_parameters
if len(args):
indexes = shareable_parameters(cellsiter)
else:
indexes = get_all_params(cellsiter.values())
result = None
for cells in cellsiter.values():
df = cells_to_dataframe(cells, args)
if drop_allna and df.isnull().all().all():
continue # Ignore all NA or empty
if df.index.names != [None]:
if isinstance(df.index, pd.MultiIndex):
if _pd_ver < (0, 20):
df = _reset_naindex(df)
df = df.reset_index()
missing_params = set(indexes) - set(df)
for params in missing_params:
df[params] = np.nan
if result is None:
result = df
else:
try:
result = pd.merge(result, df, how="outer")
except MergeError:
# When no common column exists, i.e. all cells are scalars.
result = pd.concat([result, df], axis=1)
except ValueError:
# When common columns are not coercible (numeric vs object),
# Make the numeric column object type
cols = set(result.columns) & set(df.columns)
for col in cols:
# When only either of them has object dtype
| python | {
"resource": ""
} |
q261819 | cells_to_series | validation | def cells_to_series(cells, args):
"""Convert a CellImpl into a Series.
`args` must be a sequence of argkeys.
`args` can be longer or shorter then the number of cell's parameters.
If shorter, then defaults are filled if any, else raise error.
If longer, then redundant args are ignored.
"""
paramlen = len(cells.formula.parameters)
is_multidx = paramlen > 1
if len(cells.data) == 0:
data = {}
indexes = None
elif paramlen == 0: # Const Cells
data = list(cells.data.values())
indexes = [np.nan]
else:
if len(args) > 0:
defaults = tuple(
param.default
for param in cells.formula.signature.parameters.values()
)
| python | {
"resource": ""
} |
q261820 | DependencyGraph.clear_obj | validation | def clear_obj(self, obj):
""""Remove all nodes with `obj` and their descendants."""
obj_nodes = self.get_nodes_with(obj)
removed = set()
for node in obj_nodes:
if | python | {
"resource": ""
} |
q261821 | DependencyGraph.get_nodes_with | validation | def get_nodes_with(self, obj):
"""Return nodes with `obj`."""
result = set()
if nx.__version__[0] == "1":
nodes = self.nodes_iter()
else:
nodes | python | {
"resource": ""
} |
q261822 | DependencyGraph.add_path | validation | def add_path(self, nodes, **attr):
"""In replacement for Deprecated add_path method"""
if nx.__version__[0] == "1":
| python | {
"resource": ""
} |
q261823 | Model.rename | validation | def rename(self, name):
"""Rename the model itself""" | python | {
"resource": ""
} |
q261824 | ModelImpl.rename | validation | def rename(self, name):
"""Rename self. Must be called only by its system."""
if is_valid_name(name):
if name not in self.system.models:
self.name = name
return | python | {
"resource": ""
} |
q261825 | ModelImpl.clear_descendants | validation | def clear_descendants(self, source, clear_source=True):
"""Clear values and nodes calculated from `source`."""
| python | {
"resource": ""
} |
q261826 | ModelImpl.clear_obj | validation | def clear_obj(self, obj):
"""Clear values and nodes of `obj` and their dependants."""
removed = self.cellgraph.clear_obj(obj)
| python | {
"resource": ""
} |
q261827 | ModelImpl.get_object | validation | def get_object(self, name):
"""Retrieve an object by a dotted name relative to the model."""
parts = name.split(".")
space = self.spaces[parts.pop(0)]
| python | {
"resource": ""
} |
q261828 | ModelImpl.get_dynamic_base | validation | def get_dynamic_base(self, bases: tuple):
"""Create of get a base space for a tuple of bases"""
try:
return self._dynamic_bases_inverse[bases]
except KeyError:
| python | {
"resource": ""
} |
q261829 | SpaceGraph.check_mro | validation | def check_mro(self, bases):
"""Check if C3 MRO is possible with given bases"""
try:
self.add_node("temp")
for base in bases:
nx.DiGraph.add_edge(self, base, "temp")
| python | {
"resource": ""
} |
q261830 | get_command_names | validation | def get_command_names():
"""
Returns a list of command names supported
"""
ret = []
for f in os.listdir(COMMAND_MODULE_PATH):
if | python | {
"resource": ""
} |
q261831 | get | validation | def get(vals, key, default_val=None):
"""
Returns a dictionary value
"""
val = vals
for part in key.split('.'):
if isinstance(val, dict):
val = val.get(part, None)
| python | {
"resource": ""
} |
q261832 | parse_option_settings | validation | def parse_option_settings(option_settings):
"""
Parses option_settings as they are defined in the configuration file
"""
ret = []
for namespace, params in | python | {
"resource": ""
} |
q261833 | parse_env_config | validation | def parse_env_config(config, env_name):
"""
Parses an environment config
"""
all_env = get(config, 'app.all_environments', {})
env | python | {
"resource": ""
} |
q261834 | create_archive | validation | def create_archive(directory, filename, config={}, ignore_predicate=None, ignored_files=['.git', '.svn']):
"""
Creates an archive from a directory and returns
the file that was created.
"""
with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as zip_file:
root_len = len(os.path.abspath(directory))
# create it
out("Creating archive: " + str(filename))
for root, dirs, files in os.walk(directory, followlinks=True):
archive_root = os.path.abspath(root)[root_len + 1:]
for f in files:
fullpath = os.path.join(root, f)
archive_name = os.path.join(archive_root, f)
# ignore the file we're creating
if filename in fullpath:
continue
# ignored files
if ignored_files is not None:
| python | {
"resource": ""
} |
q261835 | add_config_files_to_archive | validation | def add_config_files_to_archive(directory, filename, config={}):
"""
Adds configuration files to an existing archive
"""
with zipfile.ZipFile(filename, 'a') as zip_file:
for conf in config:
for conf, tree in list(conf.items()):
if 'yaml' in tree:
content = yaml.dump(tree['yaml'], default_flow_style=False)
else:
content = tree.get('content', '')
| python | {
"resource": ""
} |
q261836 | EbsHelper.swap_environment_cnames | validation | def swap_environment_cnames(self, from_env_name, to_env_name):
"""
Swaps cnames for an environment
| python | {
"resource": ""
} |
q261837 | EbsHelper.upload_archive | validation | def upload_archive(self, filename, key, auto_create_bucket=True):
"""
Uploads an application archive version to s3
"""
try:
bucket = self.s3.get_bucket(self.aws.bucket)
if ((
self.aws.region != 'us-east-1' and self.aws.region != 'eu-west-1') and bucket.get_location() != self.aws.region) or (
self.aws.region == 'us-east-1' and bucket.get_location() != '') or (
self.aws.region == 'eu-west-1' and bucket.get_location() != 'eu-west-1'):
| python | {
"resource": ""
} |
q261838 | EbsHelper.application_exists | validation | def application_exists(self):
"""
Returns whether or not the given app_name exists
"""
response = self.ebs.describe_applications(application_names=[self.app_name])
| python | {
"resource": ""
} |
q261839 | EbsHelper.create_environment | validation | def create_environment(self, env_name, version_label=None,
solution_stack_name=None, cname_prefix=None, description=None,
option_settings=None, tier_name='WebServer', tier_type='Standard', tier_version='1.1'):
"""
Creates a new environment
"""
out("Creating environment: " + str(env_name) + ", tier_name:" + str(tier_name) + ", tier_type:" + str(tier_type))
| python | {
"resource": ""
} |
q261840 | EbsHelper.environment_exists | validation | def environment_exists(self, env_name):
"""
Returns whether or not the given environment exists
"""
response = self.ebs.describe_environments(application_name=self.app_name, environment_names=[env_name],
| python | {
"resource": ""
} |
q261841 | EbsHelper.get_environments | validation | def get_environments(self):
"""
Returns the environments
"""
response = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False)
| python | {
"resource": ""
} |
q261842 | EbsHelper.update_environment | validation | def update_environment(self, environment_name, description=None, option_settings=[], tier_type=None, tier_name=None,
tier_version='1.0'):
"""
Updates an application version
"""
out("Updating environment: " + str(environment_name))
messages = self.ebs.validate_configuration_settings(self.app_name, option_settings,
environment_name=environment_name)
messages = messages['ValidateConfigurationSettingsResponse']['ValidateConfigurationSettingsResult']['Messages']
ok = True
for message in messages:
if message['Severity'] == 'error':
ok = False
| python | {
"resource": ""
} |
q261843 | EbsHelper.environment_name_for_cname | validation | def environment_name_for_cname(self, env_cname):
"""
Returns an environment name for the given cname
"""
envs = self.get_environments()
for env in envs:
| python | {
"resource": ""
} |
q261844 | EbsHelper.deploy_version | validation | def deploy_version(self, environment_name, version_label):
"""
Deploys a version to an environment
"""
out("Deploying " + str(version_label) + " to " + | python | {
"resource": ""
} |
q261845 | EbsHelper.get_versions | validation | def get_versions(self):
"""
Returns the versions available
"""
response = self.ebs.describe_application_versions(application_name=self.app_name)
return | python | {
"resource": ""
} |
q261846 | EbsHelper.create_application_version | validation | def create_application_version(self, version_label, key):
"""
Creates an application version
"""
out("Creating application version " + str(version_label) + " for " + str(key))
| python | {
"resource": ""
} |
q261847 | EbsHelper.delete_unused_versions | validation | def delete_unused_versions(self, versions_to_keep=10):
"""
Deletes unused versions
"""
# get versions in use
environments = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False)
environments = environments['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']
versions_in_use = []
for env in environments:
versions_in_use.append(env['VersionLabel'])
# get all versions
versions = self.ebs.describe_application_versions(application_name=self.app_name)
versions = versions['DescribeApplicationVersionsResponse']['DescribeApplicationVersionsResult'][
'ApplicationVersions']
versions = sorted(versions, reverse=True, key=functools.cmp_to_key(lambda x, y: (x['DateCreated'] > y['DateCreated']) - (x['DateCreated'] < y['DateCreated'])))
# delete versions in use
for version in versions[versions_to_keep:]:
| python | {
"resource": ""
} |
q261848 | EbsHelper.describe_events | validation | def describe_events(self, environment_name, next_token=None, start_time=None):
"""
Describes events from the given environment
"""
events = self.ebs.describe_events(
application_name=self.app_name,
environment_name=environment_name,
next_token=next_token,
| python | {
"resource": ""
} |
q261849 | add_arguments | validation | def add_arguments(parser):
"""
adds arguments for the swap urls command
"""
parser.add_argument('-o', '--old-environment', help='Old environment name', required=True)
| python | {
"resource": ""
} |
q261850 | execute | validation | def execute(helper, config, args):
"""
Swaps old and new URLs.
If old_environment was active, new_environment will become the active environment
"""
old_env_name = args.old_environment
new_env_name = args.new_environment
# swap C-Names
out("Assuming that {} is the currently active environment...".format(old_env_name)) | python | {
"resource": ""
} |
q261851 | execute | validation | def execute(helper, config, args):
"""
dump command dumps things
"""
env = parse_env_config(config, args.environment)
option_settings = env.get('option_settings', {})
| python | {
"resource": ""
} |
q261852 | execute | validation | def execute(helper, config, args):
"""
The init command
"""
# check to see if the application exists
if not helper.application_exists():
helper.create_application(get(config, 'app.description'))
else:
out("Application "+get(config, 'app.app_name')+" exists")
# create environments
environment_names = []
environments_to_wait_for_green = []
for env_name, env_config in list(get(config, 'app.environments').items()):
environment_names.append(env_name)
env_config = parse_env_config(config, env_name)
if not helper.environment_exists(env_name):
option_settings = parse_option_settings(env_config.get('option_settings', {}))
helper.create_environment(env_name,
solution_stack_name=env_config.get('solution_stack_name'),
cname_prefix=env_config.get('cname_prefix', None),
description=env_config.get('description', None),
option_settings=option_settings,
tier_name=env_config.get('tier_name'),
tier_type=env_config.get('tier_type'),
tier_version=env_config.get('tier_version'),
version_label=args.version_label)
environments_to_wait_for_green.append(env_name)
else:
out("Environment "+env_name)
# get the environments
environments_to_wait_for_term = []
if args.delete:
| python | {
"resource": ""
} |
q261853 | join_phonemes | validation | def join_phonemes(*args):
"""Joins a Hangul letter from Korean phonemes."""
# Normalize arguments as onset, nucleus, coda.
if len(args) == 1:
# tuple of (onset, nucleus[, coda])
args = args[0]
if len(args) == 2:
args += (CODAS[0],)
try:
onset, nucleus, coda = args
except | python | {
"resource": ""
} |
q261854 | execute | validation | def execute(helper, config, args):
"""
Waits for an environment to be healthy
"""
| python | {
"resource": ""
} |
q261855 | add_arguments | validation | def add_arguments(parser):
"""
Args for the init command
"""
parser.add_argument('-e', '--environment', help='Environment name', required=False, nargs='+')
| python | {
"resource": ""
} |
q261856 | execute | validation | def execute(helper, config, args):
"""
Describes recent events for an environment.
"""
environment_name = args.environment
| python | {
"resource": ""
} |
q261857 | execute | validation | def execute(helper, config, args):
"""
Lists solution stacks
"""
out("Available solution stacks")
for stack in | python | {
"resource": ""
} |
q261858 | pick_coda_from_letter | validation | def pick_coda_from_letter(letter):
"""Picks only a coda from a Hangul letter. It returns ``None`` if the
given letter is not Hangul.
"""
try:
__, __, coda = \
| python | {
"resource": ""
} |
q261859 | pick_coda_from_decimal | validation | def pick_coda_from_decimal(decimal):
"""Picks only a coda from a decimal."""
decimal = Decimal(decimal)
__, digits, exp = decimal.as_tuple()
if exp < 0:
return DIGIT_CODAS[digits[-1]]
__, digits, exp = | python | {
"resource": ""
} |
q261860 | deposit_fetcher | validation | def deposit_fetcher(record_uuid, data):
"""Fetch a deposit identifier.
:param record_uuid: Record UUID.
:param data: Record content.
:returns: A :class:`invenio_pidstore.fetchers.FetchedPID` that contains
data['_deposit']['id'] as pid_value.
""" | python | {
"resource": ""
} |
q261861 | deposit_minter | validation | def deposit_minter(record_uuid, data):
"""Mint a deposit identifier.
A PID with the following characteristics is created:
.. code-block:: python
{
"object_type": "rec",
"object_uuid": record_uuid,
"pid_value": "<new-pid-value>",
"pid_type": "depid",
}
The following deposit meta information are updated:
.. code-block:: python
deposit['_deposit'] = {
"id": "<new-pid-value>",
"status": "draft",
}
:param record_uuid: Record UUID.
:param data: | python | {
"resource": ""
} |
q261862 | admin_permission_factory | validation | def admin_permission_factory():
"""Factory for creating a permission for an admin `deposit-admin-access`.
If `invenio-access` module is installed, it returns a
:class:`invenio_access.permissions.DynamicPermission` object.
Otherwise, it returns a :class:`flask_principal.Permission` object.
:returns: Permission instance.
"""
try:
pkg_resources.get_distribution('invenio-access')
| python | {
"resource": ""
} |
q261863 | create_blueprint | validation | def create_blueprint(endpoints):
"""Create Invenio-Deposit-UI blueprint.
See: :data:`invenio_deposit.config.DEPOSIT_RECORDS_UI_ENDPOINTS`.
:param endpoints: List of endpoints configuration.
:returns: The configured blueprint.
"""
from invenio_records_ui.views import create_url_rule
blueprint = Blueprint(
'invenio_deposit_ui',
__name__,
static_folder='../static',
template_folder='../templates',
url_prefix='',
)
@blueprint.errorhandler(PIDDeletedError)
def tombstone_errorhandler(error):
"""Render tombstone page."""
return render_template(
current_app.config['DEPOSIT_UI_TOMBSTONE_TEMPLATE'],
| python | {
"resource": ""
} |
q261864 | default_view_method | validation | def default_view_method(pid, record, template=None):
"""Default view method.
Sends ``record_viewed`` signal and renders template.
"""
record_viewed.send(
current_app._get_current_object(),
pid=pid,
record=record,
)
deposit_type = request.values.get('type')
| python | {
"resource": ""
} |
q261865 | DepositProvider.create | validation | def create(cls, object_type=None, object_uuid=None, **kwargs):
"""Create a new deposit identifier.
:param object_type: The object type (Default: ``None``)
:param object_uuid: The object UUID (Default: ``None``)
:param kwargs: It contains the pid value.
"""
assert | python | {
"resource": ""
} |
q261866 | extract_actions_from_class | validation | def extract_actions_from_class(record_class):
"""Extract actions from class."""
for name in dir(record_class):
method = getattr(record_class, name, None)
| python | {
"resource": ""
} |
q261867 | check_oauth2_scope | validation | def check_oauth2_scope(can_method, *myscopes):
"""Base permission factory that check OAuth2 scope and can_method.
:param can_method: Permission check function that accept a record in input
and return a boolean.
:param myscopes: List of scopes required to permit the access.
:returns: A :class:`flask_principal.Permission` factory.
"""
def check(record, *args, **kwargs):
| python | {
"resource": ""
} |
q261868 | can_elasticsearch | validation | def can_elasticsearch(record):
"""Check if a given record is indexed.
:param record: A record object.
:returns: If the record is indexed returns `True`, otherwise `False`.
"""
search | python | {
"resource": ""
} |
q261869 | create_error_handlers | validation | def create_error_handlers(blueprint):
"""Create error handlers on blueprint."""
blueprint.errorhandler(PIDInvalidAction)(create_api_errorhandler(
status=403, | python | {
"resource": ""
} |
q261870 | create_blueprint | validation | def create_blueprint(endpoints):
"""Create Invenio-Deposit-REST blueprint.
See: :data:`invenio_deposit.config.DEPOSIT_REST_ENDPOINTS`.
:param endpoints: List of endpoints configuration.
:returns: The configured blueprint.
"""
blueprint = Blueprint(
'invenio_deposit_rest',
__name__,
url_prefix='',
)
create_error_handlers(blueprint)
for endpoint, options in (endpoints or {}).items():
options = deepcopy(options)
if 'files_serializers' in options:
files_serializers = options.get('files_serializers')
files_serializers = {mime: obj_or_import_string(func)
for mime, func in files_serializers.items()}
del options['files_serializers']
else:
files_serializers = {}
if 'record_serializers' in options:
serializers = options.get('record_serializers')
serializers = {mime: obj_or_import_string(func)
for mime, func in serializers.items()}
else:
serializers = {}
file_list_route = options.pop(
'file_list_route',
'{0}/files'.format(options['item_route'])
)
file_item_route = options.pop(
'file_item_route',
'{0}/files/<path:key>'.format(options['item_route'])
)
options.setdefault('search_class', DepositSearch)
search_class = obj_or_import_string(options['search_class'])
# records rest endpoints will use the deposit class as record class
options.setdefault('record_class', Deposit)
record_class = obj_or_import_string(options['record_class'])
# backward compatibility for indexer class
options.setdefault('indexer_class', None)
for rule in records_rest_url_rules(endpoint, **options):
blueprint.add_url_rule(**rule)
search_class_kwargs = {}
if options.get('search_index'):
search_class_kwargs['index'] = options['search_index']
if options.get('search_type'):
search_class_kwargs['doc_type'] = options['search_type']
ctx = dict(
read_permission_factory=obj_or_import_string(
options.get('read_permission_factory_imp')
),
create_permission_factory=obj_or_import_string(
options.get('create_permission_factory_imp')
),
update_permission_factory=obj_or_import_string(
options.get('update_permission_factory_imp')
),
delete_permission_factory=obj_or_import_string(
options.get('delete_permission_factory_imp')
| python | {
"resource": ""
} |
q261871 | DepositActionResource.post | validation | def post(self, pid, record, action):
"""Handle deposit action.
After the action is executed, a
:class:`invenio_deposit.signals.post_action` signal is sent.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:param action: The action to execute.
"""
record = getattr(record, action)(pid=pid)
db.session.commit()
# Refresh the PID and record metadata
db.session.refresh(pid)
db.session.refresh(record.model)
post_action.send(current_app._get_current_object(), action=action,
| python | {
"resource": ""
} |
q261872 | DepositFilesResource.get | validation | def get(self, pid, record):
"""Get files.
Permission required: `read_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the | python | {
"resource": ""
} |
q261873 | DepositFilesResource.post | validation | def post(self, pid, record):
"""Handle POST deposit files.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
"""
# load the file
uploaded_file = request.files['file']
# file name
key = secure_filename(
request.form.get('name') or uploaded_file.filename
)
# check if already exists a file with this name
if key in record.files:
| python | {
"resource": ""
} |
q261874 | DepositFilesResource.put | validation | def put(self, pid, record):
"""Handle the sort of the files through the PUT deposit files.
Expected input in body PUT:
.. code-block:: javascript
[
{
"id": 1
},
{
"id": 2
},
...
}
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:returns: The files.
"""
try:
| python | {
"resource": ""
} |
q261875 | DepositFileResource.get | validation | def get(self, pid, record, key, version_id, **kwargs):
"""Get file.
Permission required: `read_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:param key: Unique identifier for the file in the deposit.
:param version_id: File version. Optional. If no version is provided,
the last version is retrieved.
:returns: the file content.
"""
try:
| python | {
"resource": ""
} |
q261876 | DepositFileResource.put | validation | def put(self, pid, record, key):
"""Handle the file rename through the PUT deposit file.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:param key: Unique identifier for the file in the deposit.
"""
try:
data = json.loads(request.data.decode('utf-8'))
new_key = data['filename']
except KeyError:
raise WrongFile()
new_key_secure = secure_filename(new_key)
if not new_key_secure or | python | {
"resource": ""
} |
q261877 | DepositFileResource.delete | validation | def delete(self, pid, record, key):
"""Handle DELETE deposit file.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:param | python | {
"resource": ""
} |
q261878 | records | validation | def records():
"""Load records."""
import pkg_resources
from dojson.contrib.marc21 import marc21
from dojson.contrib.marc21.utils import create_record, split_blob
from flask_login import login_user, logout_user
from invenio_accounts.models import User
from invenio_deposit.api import Deposit
users = User.query.all()
# pkg resources the demodata
data_path = pkg_resources.resource_filename(
'invenio_records', 'data/marc21/bibliographic.xml'
)
with open(data_path) as source:
with current_app.test_request_context():
indexer = RecordIndexer()
with db.session.begin_nested():
for index, data in | python | {
"resource": ""
} |
q261879 | location | validation | def location():
"""Load default location."""
d = current_app.config['DATADIR']
with db.session.begin_nested():
Location.query.delete()
loc | python | {
"resource": ""
} |
q261880 | _DepositState.jsonschemas | validation | def jsonschemas(self):
"""Load deposit JSON schemas."""
_jsonschemas = {
k: v['jsonschema']
for k, v in self.app.config['DEPOSIT_RECORDS_UI_ENDPOINTS'].items()
| python | {
"resource": ""
} |
q261881 | _DepositState.schemaforms | validation | def schemaforms(self):
"""Load deposit schema forms."""
_schemaforms = {
k: v['schemaform']
for k, v in self.app.config['DEPOSIT_RECORDS_UI_ENDPOINTS'].items()
| python | {
"resource": ""
} |
q261882 | deposit_links_factory | validation | def deposit_links_factory(pid):
"""Factory for record links generation.
The dictionary is formed as:
.. code-block:: python
{
'files': '/url/to/files',
'publish': '/url/to/publish',
'edit': '/url/to/edit',
'discard': '/url/to/discard',
...
}
:param pid: The record PID object.
:returns: A dictionary that contains all the links.
"""
links = default_links_factory(pid)
def _url(name, **kwargs):
"""URL builder."""
endpoint = '.{0}_{1}'.format(
current_records_rest.default_endpoint_prefixes[pid.pid_type],
name,
)
return url_for(endpoint, pid_value=pid.pid_value, _external=True,
| python | {
"resource": ""
} |
q261883 | process_minter | validation | def process_minter(value):
"""Load minter from PIDStore registry based on given value.
:param value: Name of the minter.
:returns: The minter.
"""
try:
return current_pidstore.minters[value]
except KeyError:
raise click.BadParameter(
| python | {
"resource": ""
} |
q261884 | process_schema | validation | def process_schema(value):
"""Load schema from JSONSchema registry based on given value.
:param value: Schema path, relative to the directory when it was
registered.
:returns: The schema absolute path.
"""
schemas = current_app.extensions['invenio-jsonschemas'].schemas
try:
return schemas[value]
except KeyError:
| python | {
"resource": ""
} |
q261885 | json_serializer | validation | def json_serializer(pid, data, *args):
"""Build a JSON Flask response using the given data.
:param pid: The `invenio_pidstore.models.PersistentIdentifier` of the
record.
:param data: The record metadata.
:returns: A Flask response with JSON data.
:rtype: :py:class:`flask.Response`.
"""
if data is not None:
| python | {
"resource": ""
} |
q261886 | file_serializer | validation | def file_serializer(obj):
"""Serialize a object.
:param obj: A :class:`invenio_files_rest.models.ObjectVersion` instance.
:returns: A dictionary | python | {
"resource": ""
} |
q261887 | json_files_serializer | validation | def json_files_serializer(objs, status=None):
"""JSON Files Serializer.
:parma objs: A list of:class:`invenio_files_rest.models.ObjectVersion`
instances.
:param status: A HTTP Status. (Default: ``None``)
:returns: A Flask | python | {
"resource": ""
} |
q261888 | index_deposit_after_publish | validation | def index_deposit_after_publish(sender, action=None, pid=None, deposit=None):
"""Index the record after publishing.
.. note:: if the record is not published, it doesn't index.
:param sender: Who send the signal. | python | {
"resource": ""
} |
q261889 | index | validation | def index(method=None, delete=False):
"""Decorator to update index.
:param method: Function wrapped. (Default: ``None``)
:param delete: If `True` delete the indexed record. (Default: ``None``)
"""
if method is None:
return partial(index, delete=delete)
@wraps(method)
| python | {
"resource": ""
} |
q261890 | preserve | validation | def preserve(method=None, result=True, fields=None):
"""Preserve fields in deposit.
:param method: Function to execute. (Default: ``None``)
:param result: If `True` returns the result of method execution,
otherwise `self`. (Default: ``True``)
:param fields: List of fields to preserve (default: ``('_deposit',)``).
"""
| python | {
"resource": ""
} |
q261891 | Deposit.pid | validation | def pid(self):
"""Return an instance of deposit PID."""
pid = self.deposit_fetcher(self.id, self)
| python | {
"resource": ""
} |
q261892 | Deposit.record_schema | validation | def record_schema(self):
"""Convert deposit schema to a valid record schema."""
schema_path = current_jsonschemas.url_to_path(self['$schema'])
| python | {
"resource": ""
} |
q261893 | Deposit.build_deposit_schema | validation | def build_deposit_schema(self, record):
"""Convert record schema to a valid deposit schema.
:param record: The record used to build deposit schema.
:returns: The absolute URL to the schema or | python | {
"resource": ""
} |
q261894 | Deposit.fetch_published | validation | def fetch_published(self):
"""Return a tuple with PID and published record."""
pid_type = self['_deposit']['pid']['type']
pid_value = self['_deposit']['pid']['value']
resolver = Resolver(
pid_type=pid_type, object_type='rec',
| python | {
"resource": ""
} |
q261895 | Deposit.merge_with_published | validation | def merge_with_published(self):
"""Merge changes with latest published version."""
pid, first = self.fetch_published()
lca = first.revisions[self['_deposit']['pid']['revision_id']]
# ignore _deposit and $schema field
args = [lca.dumps(), first.dumps(), self.dumps()]
for arg in args:
| python | {
"resource": ""
} |
q261896 | Deposit.commit | validation | def commit(self, *args, **kwargs):
"""Store changes on current instance in database and index it."""
| python | {
"resource": ""
} |
q261897 | Deposit.create | validation | def create(cls, data, id_=None):
"""Create a deposit.
Initialize the follow information inside the deposit:
.. code-block:: python
deposit['_deposit'] = {
'id': pid_value,
'status': 'draft',
'owners': [user_id],
'created_by': user_id,
}
The deposit index is updated.
:param data: Input dictionary to fill the deposit.
:param id_: Default uuid for the deposit.
:returns: The new created deposit.
"""
data.setdefault('$schema', current_jsonschemas.path_to_url(
current_app.config['DEPOSIT_DEFAULT_JSONSCHEMA']
))
if '_deposit' not in data:
| python | {
"resource": ""
} |
q261898 | Deposit._process_files | validation | def _process_files(self, record_id, data):
"""Snapshot bucket and add files in record during first publishing."""
if self.files:
assert not self.files.bucket.locked
self.files.bucket.locked = True
snapshot = self.files.bucket.snapshot(lock=True)
data['_files'] = self.files.dumps(bucket=snapshot.id)
| python | {
"resource": ""
} |
q261899 | Deposit._publish_new | validation | def _publish_new(self, id_=None):
"""Publish new deposit.
:param id_: The forced record UUID.
"""
minter = current_pidstore.minters[
current_app.config['DEPOSIT_PID_MINTER']
]
id_ = id_ or uuid.uuid4()
record_pid = minter(id_, self)
self['_deposit']['pid'] = {
'type': record_pid.pid_type,
'value': record_pid.pid_value,
'revision_id': 0,
}
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.