sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def i2c_master_write_read(self, i2c_address, data, length):
"""Make an I2C write/read access.
First an I2C write access is issued. No stop condition will be
generated. Instead the read access begins with a repeated start.
This method is useful for accessing most addressable I2C devices... | Make an I2C write/read access.
First an I2C write access is issued. No stop condition will be
generated. Instead the read access begins with a repeated start.
This method is useful for accessing most addressable I2C devices like
EEPROMs, port expander, etc.
Basically, this is ... | entailment |
def poll(self, timeout=None):
"""Wait for an event to occur.
If `timeout` is given, if specifies the length of time in milliseconds
which the function will wait for events before returing. If `timeout`
is omitted, negative or None, the call will block until there is an
event.
... | Wait for an event to occur.
If `timeout` is given, if specifies the length of time in milliseconds
which the function will wait for events before returing. If `timeout`
is omitted, negative or None, the call will block until there is an
event.
Returns a list of events. In case ... | entailment |
def enable_i2c_slave(self, slave_address):
"""Enable I2C slave mode.
The device will respond to the specified slave_address if it is
addressed.
You can wait for the data with :func:`poll` and get it with
`i2c_slave_read`.
"""
ret = api.py_aa_i2c_slave_enable(sel... | Enable I2C slave mode.
The device will respond to the specified slave_address if it is
addressed.
You can wait for the data with :func:`poll` and get it with
`i2c_slave_read`. | entailment |
def i2c_slave_read(self):
"""Read the bytes from an I2C slave reception.
The bytes are returned as a string object.
"""
data = array.array('B', (0,) * self.BUFFER_SIZE)
status, addr, rx_len = api.py_aa_i2c_slave_read_ext(self.handle,
self.BUFFER_SIZE, data)
... | Read the bytes from an I2C slave reception.
The bytes are returned as a string object. | entailment |
def i2c_slave_last_transmit_size(self):
"""Returns the number of bytes transmitted by the slave."""
ret = api.py_aa_i2c_slave_write_stats(self.handle)
_raise_error_if_negative(ret)
return ret | Returns the number of bytes transmitted by the slave. | entailment |
def i2c_monitor_read(self):
"""Retrieved any data fetched by the monitor.
This function has an integrated timeout mechanism. You should use
:func:`poll` to determine if there is any data available.
Returns a list of data bytes and special symbols. There are three
special symbol... | Retrieved any data fetched by the monitor.
This function has an integrated timeout mechanism. You should use
:func:`poll` to determine if there is any data available.
Returns a list of data bytes and special symbols. There are three
special symbols: `I2C_MONITOR_NACK`, I2C_MONITOR_STAR... | entailment |
def spi_bitrate(self):
"""SPI bitrate in kHz. Not every bitrate is supported by the host
adapter. Therefore, the actual bitrate may be less than the value which
is set. The slowest bitrate supported is 125kHz. Any smaller value will
be rounded up to 125kHz.
The power-on default ... | SPI bitrate in kHz. Not every bitrate is supported by the host
adapter. Therefore, the actual bitrate may be less than the value which
is set. The slowest bitrate supported is 125kHz. Any smaller value will
be rounded up to 125kHz.
The power-on default value is 1000 kHz. | entailment |
def spi_configure(self, polarity, phase, bitorder):
"""Configure the SPI interface."""
ret = api.py_aa_spi_configure(self.handle, polarity, phase, bitorder)
_raise_error_if_negative(ret) | Configure the SPI interface. | entailment |
def spi_configure_mode(self, spi_mode):
"""Configure the SPI interface by the well known SPI modes."""
if spi_mode == SPI_MODE_0:
self.spi_configure(SPI_POL_RISING_FALLING,
SPI_PHASE_SAMPLE_SETUP, SPI_BITORDER_MSB)
elif spi_mode == SPI_MODE_3:
self.spi... | Configure the SPI interface by the well known SPI modes. | entailment |
def spi_write(self, data):
"""Write a stream of bytes to a SPI device."""
data_out = array.array('B', data)
data_in = array.array('B', (0,) * len(data_out))
ret = api.py_aa_spi_write(self.handle, len(data_out), data_out,
len(data_in), data_in)
_raise_error_if_nega... | Write a stream of bytes to a SPI device. | entailment |
def spi_ss_polarity(self, polarity):
"""Change the ouput polarity on the SS line.
Please note, that this only affects the master functions.
"""
ret = api.py_aa_spi_master_ss_polarity(self.handle, polarity)
_raise_error_if_negative(ret) | Change the ouput polarity on the SS line.
Please note, that this only affects the master functions. | entailment |
def edit_form(self, obj):
"""Customize edit form."""
form = super(OAISetModelView, self).edit_form(obj)
del form.spec
return form | Customize edit form. | entailment |
def flatten_nested_hash(hash_table):
"""
Flatten nested dictionary for GET / POST / DELETE API request
"""
def flatten(hash_table, brackets=True):
f = {}
for key, value in hash_table.items():
_key = '[' + str(key) + ']' if brackets else str(key)
if isinstance(valu... | Flatten nested dictionary for GET / POST / DELETE API request | entailment |
def sailthru_http_request(url, data, method, file_data=None, headers=None, request_timeout=10):
"""
Perform an HTTP GET / POST / DELETE request
"""
data = flatten_nested_hash(data)
method = method.upper()
params, data = (None, data) if method == 'POST' else (data, None)
sailthru_headers = {'... | Perform an HTTP GET / POST / DELETE request | entailment |
def _schema_from_verb(verb, partial=False):
"""Return an instance of schema for given verb."""
from .verbs import Verbs
return getattr(Verbs, verb)(partial=partial) | Return an instance of schema for given verb. | entailment |
def serialize(pagination, **kwargs):
"""Return resumption token serializer."""
if not pagination.has_next:
return
token_builder = URLSafeTimedSerializer(
current_app.config['SECRET_KEY'],
salt=kwargs['verb'],
)
schema = _schema_from_verb(kwargs['verb'], partial=False)
da... | Return resumption token serializer. | entailment |
def _deserialize(self, value, attr, data):
"""Serialize resumption token."""
token_builder = URLSafeTimedSerializer(
current_app.config['SECRET_KEY'],
salt=data['verb'],
)
result = token_builder.loads(value, max_age=current_app.config[
'OAISERVER_RESUM... | Serialize resumption token. | entailment |
def load(self, data, many=None, partial=None):
"""Deserialize a data structure to an object."""
result = super(ResumptionTokenSchema, self).load(
data, many=many, partial=partial
)
result.data.update(
result.data.get('resumptionToken', {}).get('kwargs', {})
... | Deserialize a data structure to an object. | entailment |
def make_request_validator(request):
"""Validate arguments in incomming request."""
verb = request.values.get('verb', '', type=str)
resumption_token = request.values.get('resumptionToken', None)
schema = Verbs if resumption_token is None else ResumptionVerbs
return getattr(schema, verb, OAISchema)(... | Validate arguments in incomming request. | entailment |
def from_iso_permissive(datestring, use_dateutil=True):
"""Parse an ISO8601-formatted datetime and return a datetime object.
Inspired by the marshmallow.utils.from_iso function, but also accepts
datestrings that don't contain the time.
"""
dateutil_available = False
try:... | Parse an ISO8601-formatted datetime and return a datetime object.
Inspired by the marshmallow.utils.from_iso function, but also accepts
datestrings that don't contain the time. | entailment |
def validate(self, data):
"""Check range between dates under keys ``from_`` and ``until``."""
if 'verb' in data and data['verb'] != self.__class__.__name__:
raise ValidationError(
# FIXME encode data
'This is not a valid OAI-PMH verb:{0}'.format(data['verb']),... | Check range between dates under keys ``from_`` and ``until``. | entailment |
def upgrade():
"""Upgrade database."""
op.create_table(
'oaiserver_set',
sa.Column('created', sa.DateTime(), nullable=False),
sa.Column('updated', sa.DateTime(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('spec', sa.String(length=255), nulla... | Upgrade database. | entailment |
def sets(self):
"""Get list of sets."""
if self.cache:
return self.cache.get(
self.app.config['OAISERVER_CACHE_KEY']) | Get list of sets. | entailment |
def sets(self, values):
"""Set list of sets."""
# if cache server is configured, save sets list
if self.cache:
self.cache.set(self.app.config['OAISERVER_CACHE_KEY'], values) | Set list of sets. | entailment |
def register_signals(self):
"""Register signals."""
from .receivers import OAIServerUpdater
# Register Record signals to update OAI informations
self.update_function = OAIServerUpdater()
records_signals.before_record_insert.connect(self.update_function,
... | Register signals. | entailment |
def register_signals_oaiset(self):
"""Register OAISet signals to update records."""
from .models import OAISet
from .receivers import after_insert_oai_set, \
after_update_oai_set, after_delete_oai_set
listen(OAISet, 'after_insert', after_insert_oai_set)
listen(OAISet,... | Register OAISet signals to update records. | entailment |
def unregister_signals(self):
"""Unregister signals."""
# Unregister Record signals
if hasattr(self, 'update_function'):
records_signals.before_record_insert.disconnect(
self.update_function)
records_signals.before_record_update.disconnect(
... | Unregister signals. | entailment |
def unregister_signals_oaiset(self):
"""Unregister signals oaiset."""
from .models import OAISet
from .receivers import after_insert_oai_set, \
after_update_oai_set, after_delete_oai_set
if contains(OAISet, 'after_insert', after_insert_oai_set):
remove(OAISet, 'af... | Unregister signals oaiset. | entailment |
def init_config(self, app):
"""Initialize configuration.
:param app: An instance of :class:`flask.Flask`.
"""
app.config.setdefault(
'OAISERVER_BASE_TEMPLATE',
app.config.get('BASE_TEMPLATE',
'invenio_oaiserver/base.html'))
app... | Initialize configuration.
:param app: An instance of :class:`flask.Flask`. | entailment |
def extract_params(params):
"""
Extracts the values of a set of parameters, recursing into nested dictionaries.
"""
values = []
if isinstance(params, dict):
for key, value in params.items():
values.extend(extract_params(value))
elif isinstance(params, list):
for value... | Extracts the values of a set of parameters, recursing into nested dictionaries. | entailment |
def get_signature_string(params, secret):
"""
Returns the unhashed signature string (secret + sorted list of param values) for an API call.
@param params: dictionary values to generate signature string
@param secret: secret string
"""
str_list = [str(item) for item in extract_params(params)]
... | Returns the unhashed signature string (secret + sorted list of param values) for an API call.
@param params: dictionary values to generate signature string
@param secret: secret string | entailment |
def send(self, template, email, _vars=None, options=None, schedule_time=None, limit=None):
"""
Remotely send an email template to a single email address.
http://docs.sailthru.com/api/send
@param template: template string
@param email: Email value
@param _vars: a key/value... | Remotely send an email template to a single email address.
http://docs.sailthru.com/api/send
@param template: template string
@param email: Email value
@param _vars: a key/value hash of the replacement vars to use in the send. Each var may be referenced as {varname} within the template i... | entailment |
def multi_send(self, template, emails, _vars=None, evars=None, schedule_time=None, options=None):
"""
Remotely send an email template to multiple email addresses.
http://docs.sailthru.com/api/send
@param template: template string
@param emails: List with email values or comma sep... | Remotely send an email template to multiple email addresses.
http://docs.sailthru.com/api/send
@param template: template string
@param emails: List with email values or comma separated email string
@param _vars: a key/value hash of the replacement vars to use in the send. Each var may be... | entailment |
def set_email(self, email, _vars=None, lists=None, templates=None, verified=0, optout=None, send=None, send_vars=None):
"""
DEPRECATED!
Update information about one of your users, including adding and removing the user from lists.
http://docs.sailthru.com/api/email
"""
_v... | DEPRECATED!
Update information about one of your users, including adding and removing the user from lists.
http://docs.sailthru.com/api/email | entailment |
def get_user(self, idvalue, options=None):
"""
get user by a given id
http://getstarted.sailthru.com/api/user
"""
options = options or {}
data = options.copy()
data['id'] = idvalue
return self.api_get('user', data) | get user by a given id
http://getstarted.sailthru.com/api/user | entailment |
def save_user(self, idvalue, options=None):
"""
save user by a given id
http://getstarted.sailthru.com/api/user
"""
options = options or {}
data = options.copy()
data['id'] = idvalue
return self.api_post('user', data) | save user by a given id
http://getstarted.sailthru.com/api/user | entailment |
def schedule_blast(self, name, list, schedule_time, from_name, from_email, subject, content_html, content_text, options=None):
"""
Schedule a mass mail blast
http://docs.sailthru.com/api/blast
@param name: name to give to this new blast
@param list: mailing list name to send to
... | Schedule a mass mail blast
http://docs.sailthru.com/api/blast
@param name: name to give to this new blast
@param list: mailing list name to send to
@param schedule_time: when the blast should send. Dates in the past will be scheduled for immediate delivery. Any English textual datetime ... | entailment |
def schedule_blast_from_template(self, template, list_name, schedule_time, options=None):
"""
Schedule a mass mail blast from template
http://docs.sailthru.com/api/blast
@param template: template to copy from
@param list_name: list to send to
@param schedule_time
... | Schedule a mass mail blast from template
http://docs.sailthru.com/api/blast
@param template: template to copy from
@param list_name: list to send to
@param schedule_time
@param options: additional optional params | entailment |
def schedule_blast_from_blast(self, blast_id, schedule_time, options=None):
"""
Schedule a mass mail blast from previous blast
http://docs.sailthru.com/api/blast
@param blast_id: blast_id to copy from
@param schedule_time
@param options: additional optional params
... | Schedule a mass mail blast from previous blast
http://docs.sailthru.com/api/blast
@param blast_id: blast_id to copy from
@param schedule_time
@param options: additional optional params | entailment |
def get_list(self, list_name, options=None):
"""
Get detailed metadata information about a list.
"""
options = options or {}
data = {'list': list_name}
data.update(options)
return self.api_get('list', data) | Get detailed metadata information about a list. | entailment |
def save_list(self, list_name, emails):
"""
Upload a list. The list import job is queued and will happen shortly after the API request.
http://docs.sailthru.com/api/list
@param list: list name
@param emails: List of email values or comma separated string
"""
data ... | Upload a list. The list import job is queued and will happen shortly after the API request.
http://docs.sailthru.com/api/list
@param list: list name
@param emails: List of email values or comma separated string | entailment |
def import_contacts(self, email, password, include_name=False):
"""
Fetch email contacts from a user's address book on one of the major email websites. Currently supports AOL, Gmail, Hotmail, and Yahoo! Mail.
"""
data = {'email': email,
'password': password}
if in... | Fetch email contacts from a user's address book on one of the major email websites. Currently supports AOL, Gmail, Hotmail, and Yahoo! Mail. | entailment |
def push_content(self, title, url,
images=None, date=None, expire_date=None,
description=None, location=None, price=None,
tags=None,
author=None, site_name=None,
spider=None, vars=None):
"""
Push a ... | Push a new piece of content to Sailthru.
Expected names for the `images` argument's map are "full" and "thumb"
Expected format for `location` should be [longitude,latitude]
@param title: title string for the content
@param url: URL string for the content
@param images: map of i... | entailment |
def save_alert(self, email, type, template, when=None, options=None):
"""
Add a new alert to a user. You can add either a realtime or a summary alert (daily/weekly).
http://docs.sailthru.com/api/alert
Usage:
email = 'praj@sailthru.com'
type = 'weekly'
... | Add a new alert to a user. You can add either a realtime or a summary alert (daily/weekly).
http://docs.sailthru.com/api/alert
Usage:
email = 'praj@sailthru.com'
type = 'weekly'
template = 'default'
when = '+5 hours'
alert_options = {'match': ... | entailment |
def delete_alert(self, email, alert_id):
"""
delete user alert
"""
data = {'email': email,
'alert_id': alert_id}
return self.api_delete('alert', data) | delete user alert | entailment |
def purchase(self, email, items=None, incomplete=None, message_id=None, options=None, extid=None):
"""
Record that a user has made a purchase, or has added items to their purchase total.
http://docs.sailthru.com/api/purchase
@param email: Email string
@param items: list of item d... | Record that a user has made a purchase, or has added items to their purchase total.
http://docs.sailthru.com/api/purchase
@param email: Email string
@param items: list of item dictionary with keys: id, title, price, qty, and url
@param message_id: message_id string
@param extid: ... | entailment |
def get_purchase(self, purchase_id, purchase_key='sid'):
"""
Retrieve information about a purchase using the system's unique ID or a client's ID
@param id_: a string that represents a unique_id or an extid.
@param key: a string that is either 'sid' or 'extid'.
"""
data = ... | Retrieve information about a purchase using the system's unique ID or a client's ID
@param id_: a string that represents a unique_id or an extid.
@param key: a string that is either 'sid' or 'extid'. | entailment |
def stats_list(self, list=None, date=None, headers=None):
"""
Retrieve information about your subscriber counts on a particular list, on a particular day.
http://docs.sailthru.com/api/stat
"""
data = {'stat': 'list'}
if list is not None:
data['list'] = list
... | Retrieve information about your subscriber counts on a particular list, on a particular day.
http://docs.sailthru.com/api/stat | entailment |
def stats_blast(self, blast_id=None, start_date=None, end_date=None, options=None):
"""
Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range.
http://docs.sailthru.com/api/stat
"""
options = options or {}
da... | Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range.
http://docs.sailthru.com/api/stat | entailment |
def stats_send(self, template, start_date, end_date, options=None):
"""
Retrieve information about a particular transactional or aggregated information
from transactionals from that template over a specified date range.
http://docs.sailthru.com/api/stat
"""
options = opti... | Retrieve information about a particular transactional or aggregated information
from transactionals from that template over a specified date range.
http://docs.sailthru.com/api/stat | entailment |
def receive_verify_post(self, post_params):
"""
Returns true if the incoming request is an authenticated verify post.
"""
if isinstance(post_params, dict):
required_params = ['action', 'email', 'send_id', 'sig']
if not self.check_for_valid_postback_actions(requir... | Returns true if the incoming request is an authenticated verify post. | entailment |
def receive_update_post(self, post_params):
"""
Update postbacks
"""
if isinstance(post_params, dict):
required_params = ['action', 'email', 'sig']
if not self.check_for_valid_postback_actions(required_params, post_params):
return False
el... | Update postbacks | entailment |
def receive_hardbounce_post(self, post_params):
"""
Hard bounce postbacks
"""
if isinstance(post_params, dict):
required_params = ['action', 'email', 'sig']
if not self.check_for_valid_postback_actions(required_params, post_params):
return False
... | Hard bounce postbacks | entailment |
def check_for_valid_postback_actions(self, required_keys, post_params):
"""
checks if post_params contain required keys
"""
for key in required_keys:
if key not in post_params:
return False
return True | checks if post_params contain required keys | entailment |
def api_get(self, action, data, headers=None):
"""
Perform an HTTP GET request, using the shared-secret auth hash.
@param action: API action call
@param data: dictionary values
"""
return self._api_request(action, data, 'GET', headers) | Perform an HTTP GET request, using the shared-secret auth hash.
@param action: API action call
@param data: dictionary values | entailment |
def api_post(self, action, data, binary_data_param=None):
"""
Perform an HTTP POST request, using the shared-secret auth hash.
@param action: API action call
@param data: dictionary values
"""
binary_data_param = binary_data_param or []
if binary_data_param:
... | Perform an HTTP POST request, using the shared-secret auth hash.
@param action: API action call
@param data: dictionary values | entailment |
def api_post_multipart(self, action, data, binary_data_param):
"""
Perform an HTTP Multipart POST request, using the shared-secret auth hash.
@param action: API action call
@param data: dictionary values
@param: binary_data_params: array of multipart keys
"""
bina... | Perform an HTTP Multipart POST request, using the shared-secret auth hash.
@param action: API action call
@param data: dictionary values
@param: binary_data_params: array of multipart keys | entailment |
def _api_request(self, action, data, request_type, headers=None):
"""
Make Request to Sailthru API with given data and api key, format and signature hash
"""
if 'file' in data:
file_data = {'file': open(data['file'], 'rb')}
else:
file_data = None
... | Make Request to Sailthru API with given data and api key, format and signature hash | entailment |
def get_last_rate_limit_info(self, action, method):
"""
Get rate limit information for last API call
:param action: API endpoint
:param method: Http method, GET, POST or DELETE
:return: dict|None
"""
method = method.upper()
if (action in self.last_rate_lim... | Get rate limit information for last API call
:param action: API endpoint
:param method: Http method, GET, POST or DELETE
:return: dict|None | entailment |
def linked_form(viewset, form_id=None, link=None, link_id=None, method=None):
"""
When having foreign key or m2m relationships between models A and B (B has foreign key to A named parent),
we want to have a form that sits on A's viewset but creates/edits B and sets it relationship to A
automatically.
... | When having foreign key or m2m relationships between models A and B (B has foreign key to A named parent),
we want to have a form that sits on A's viewset but creates/edits B and sets it relationship to A
automatically.
In order to do so, define linked_forms on A's viewset containing a call to linked_form ... | entailment |
def oaiid_minter(record_uuid, data):
"""Mint record identifiers.
:param record_uuid: The record UUID.
:param data: The record data.
:returns: A :class:`invenio_pidstore.models.PersistentIdentifier` instance.
"""
pid_value = data.get('_oai', {}).get('id')
if pid_value is None:
fetche... | Mint record identifiers.
:param record_uuid: The record UUID.
:param data: The record data.
:returns: A :class:`invenio_pidstore.models.PersistentIdentifier` instance. | entailment |
def validation_error(exception):
"""Return formatter validation error."""
messages = getattr(exception, 'messages', None)
if messages is None:
messages = getattr(exception, 'data', {'messages': None})['messages']
def extract_errors():
"""Extract errors from exception."""
if isin... | Return formatter validation error. | entailment |
def response(args):
"""Response endpoint."""
e_tree = getattr(xml, args['verb'].lower())(**args)
response = make_response(etree.tostring(
e_tree,
pretty_print=True,
xml_declaration=True,
encoding='UTF-8',
))
response.headers['Content-Type'] = 'text/xml'
return re... | Response endpoint. | entailment |
def create(cls, object_type=None, object_uuid=None, **kwargs):
"""Create a new record identifier.
:param object_type: The object type. (Default: ``None``)
:param object_uuid: The object UUID. (Default: ``None``)
"""
assert 'pid_value' in kwargs
kwargs.setdefault('status... | Create a new record identifier.
:param object_type: The object type. (Default: ``None``)
:param object_uuid: The object UUID. (Default: ``None``) | entailment |
def _create_percolator_mapping(index, doc_type):
"""Update mappings with the percolator field.
.. note::
This is only needed from ElasticSearch v5 onwards, because percolators
are now just a special type of field inside mappings.
"""
if ES_VERSION[0] >= 5:
current_search_client... | Update mappings with the percolator field.
.. note::
This is only needed from ElasticSearch v5 onwards, because percolators
are now just a special type of field inside mappings. | entailment |
def _percolate_query(index, doc_type, percolator_doc_type, document):
"""Get results for a percolate query."""
if ES_VERSION[0] in (2, 5):
results = current_search_client.percolate(
index=index, doc_type=doc_type, allow_no_indices=True,
ignore_unavailable=True, body={'doc': docum... | Get results for a percolate query. | entailment |
def _new_percolator(spec, search_pattern):
"""Create new percolator associated with the new set."""
if spec and search_pattern:
query = query_string_parser(search_pattern=search_pattern).to_dict()
for index in current_search.mappings.keys():
# Create the percolator doc_type in the ex... | Create new percolator associated with the new set. | entailment |
def _delete_percolator(spec, search_pattern):
"""Delete percolator associated with the new oaiset."""
if spec:
for index in current_search.mappings.keys():
# Create the percolator doc_type in the existing index for >= ES5
percolator_doc_type = _get_percolator_doc_type(index)
... | Delete percolator associated with the new oaiset. | entailment |
def _build_cache():
"""Build sets cache."""
sets = current_oaiserver.sets
if sets is None:
# build sets cache
sets = current_oaiserver.sets = [
oaiset.spec for oaiset in OAISet.query.filter(
OAISet.search_pattern.is_(None)).all()]
return sets | Build sets cache. | entailment |
def get_record_sets(record):
"""Find matching sets."""
# get lists of sets with search_pattern equals to None but already in the
# set list inside the record
record_sets = set(record.get('_oai', {}).get('sets', []))
for spec in _build_cache():
if spec in record_sets:
yield spec
... | Find matching sets. | entailment |
def _records_commit(record_ids):
"""Commit all records."""
for record_id in record_ids:
record = Record.get_record(record_id)
record.commit() | Commit all records. | entailment |
def update_affected_records(spec=None, search_pattern=None):
"""Update all affected records by OAISet change.
:param spec: The record spec.
:param search_pattern: The search pattern.
"""
chunk_size = current_app.config['OAISERVER_CELERY_TASK_CHUNK_SIZE']
record_ids = get_affected_records(spec=s... | Update all affected records by OAISet change.
:param spec: The record spec.
:param search_pattern: The search pattern. | entailment |
def envelope(**kwargs):
"""Create OAI-PMH envelope for response."""
e_oaipmh = Element(etree.QName(NS_OAIPMH, 'OAI-PMH'), nsmap=NSMAP)
e_oaipmh.set(etree.QName(NS_XSI, 'schemaLocation'),
'{0} {1}'.format(NS_OAIPMH, NS_OAIPMH_XSD))
e_tree = ElementTree(element=e_oaipmh)
if current_a... | Create OAI-PMH envelope for response. | entailment |
def error(errors):
"""Create error element."""
e_tree, e_oaipmh = envelope()
for code, message in errors:
e_error = SubElement(e_oaipmh, etree.QName(NS_OAIPMH, 'error'))
e_error.set('code', code)
e_error.text = message
return e_tree | Create error element. | entailment |
def verb(**kwargs):
"""Create OAI-PMH envelope for response with verb."""
e_tree, e_oaipmh = envelope(**kwargs)
e_element = SubElement(e_oaipmh, etree.QName(NS_OAIPMH, kwargs['verb']))
return e_tree, e_element | Create OAI-PMH envelope for response with verb. | entailment |
def identify(**kwargs):
"""Create OAI-PMH response for verb Identify."""
cfg = current_app.config
e_tree, e_identify = verb(**kwargs)
e_repositoryName = SubElement(
e_identify, etree.QName(NS_OAIPMH, 'repositoryName'))
e_repositoryName.text = cfg['OAISERVER_REPOSITORY_NAME']
e_baseURL... | Create OAI-PMH response for verb Identify. | entailment |
def resumption_token(parent, pagination, **kwargs):
"""Attach resumption token element to a parent."""
# Do not add resumptionToken if all results fit to the first page.
if pagination.page == 1 and not pagination.has_next:
return
token = serialize(pagination, **kwargs)
e_resumptionToken = S... | Attach resumption token element to a parent. | entailment |
def listsets(**kwargs):
"""Create OAI-PMH response for ListSets verb."""
e_tree, e_listsets = verb(**kwargs)
page = kwargs.get('resumptionToken', {}).get('page', 1)
size = current_app.config['OAISERVER_PAGE_SIZE']
oai_sets = OAISet.query.paginate(page=page, per_page=size, error_out=False)
for ... | Create OAI-PMH response for ListSets verb. | entailment |
def listmetadataformats(**kwargs):
"""Create OAI-PMH response for ListMetadataFormats verb."""
cfg = current_app.config
e_tree, e_listmetadataformats = verb(**kwargs)
if 'identifier' in kwargs:
# test if record exists
OAIIDProvider.get(pid_value=kwargs['identifier'])
for prefix, me... | Create OAI-PMH response for ListMetadataFormats verb. | entailment |
def header(parent, identifier, datestamp, sets=None, deleted=False):
"""Attach ``<header/>`` element to a parent."""
e_header = SubElement(parent, etree.QName(NS_OAIPMH, 'header'))
if deleted:
e_header.set('status', 'deleted')
e_identifier = SubElement(e_header, etree.QName(NS_OAIPMH, 'identifie... | Attach ``<header/>`` element to a parent. | entailment |
def getrecord(**kwargs):
"""Create OAI-PMH response for verb Identify."""
record_dumper = serializer(kwargs['metadataPrefix'])
pid = OAIIDProvider.get(pid_value=kwargs['identifier']).pid
record = Record.get_record(pid.object_uuid)
e_tree, e_getrecord = verb(**kwargs)
e_record = SubElement(e_get... | Create OAI-PMH response for verb Identify. | entailment |
def listidentifiers(**kwargs):
"""Create OAI-PMH response for verb ListIdentifiers."""
e_tree, e_listidentifiers = verb(**kwargs)
result = get_records(**kwargs)
for record in result.items:
pid = oaiid_fetcher(record['id'], record['json']['_source'])
header(
e_listidentifiers... | Create OAI-PMH response for verb ListIdentifiers. | entailment |
def listrecords(**kwargs):
"""Create OAI-PMH response for verb ListRecords."""
record_dumper = serializer(kwargs['metadataPrefix'])
e_tree, e_listrecords = verb(**kwargs)
result = get_records(**kwargs)
for record in result.items:
pid = oaiid_fetcher(record['id'], record['json']['_source'])... | Create OAI-PMH response for verb ListRecords. | entailment |
def oaiid_fetcher(record_uuid, data):
"""Fetch a record's identifier.
:param record_uuid: The record UUID.
:param data: The record data.
:returns: A :class:`invenio_pidstore.fetchers.FetchedPID` instance.
"""
pid_value = data.get('_oai', {}).get('id')
if pid_value is None:
raise Per... | Fetch a record's identifier.
:param record_uuid: The record UUID.
:param data: The record data.
:returns: A :class:`invenio_pidstore.fetchers.FetchedPID` instance. | entailment |
def validate_spec(self, key, value):
"""Forbit updates of set identifier."""
if self.spec and self.spec != value:
raise OAISetSpecUpdateError("Updating spec is not allowed.")
return value | Forbit updates of set identifier. | entailment |
def add_record(self, record):
"""Add a record to the OAISet.
:param record: Record to be added.
:type record: `invenio_records.api.Record` or derivative.
"""
record.setdefault('_oai', {}).setdefault('sets', [])
assert not self.has_record(record)
record['_oai'][... | Add a record to the OAISet.
:param record: Record to be added.
:type record: `invenio_records.api.Record` or derivative. | entailment |
def remove_record(self, record):
"""Remove a record from the OAISet.
:param record: Record to be removed.
:type record: `invenio_records.api.Record` or derivative.
"""
assert self.has_record(record)
record['_oai']['sets'] = [
s for s in record['_oai']['sets'... | Remove a record from the OAISet.
:param record: Record to be removed.
:type record: `invenio_records.api.Record` or derivative. | entailment |
def oaiserver(sets, records):
"""Initialize OAI-PMH server."""
from invenio_db import db
from invenio_oaiserver.models import OAISet
from invenio_records.api import Record
# create a OAI Set
with db.session.begin_nested():
for i in range(sets):
db.session.add(OAISet(
... | Initialize OAI-PMH server. | entailment |
def serializer(metadata_prefix):
"""Return etree_dumper instances.
:param metadata_prefix: One of the metadata identifiers configured in
``OAISERVER_METADATA_FORMATS``.
"""
metadataFormats = current_app.config['OAISERVER_METADATA_FORMATS']
serializer_ = metadataFormats[metadata_prefix]['ser... | Return etree_dumper instances.
:param metadata_prefix: One of the metadata identifiers configured in
``OAISERVER_METADATA_FORMATS``. | entailment |
def dumps_etree(pid, record, **kwargs):
"""Dump MARC21 compatible record.
:param pid: The :class:`invenio_pidstore.models.PersistentIdentifier`
instance.
:param record: The :class:`invenio_records.api.Record` instance.
:returns: A LXML Element instance.
"""
from dojson.contrib.to_marc21... | Dump MARC21 compatible record.
:param pid: The :class:`invenio_pidstore.models.PersistentIdentifier`
instance.
:param record: The :class:`invenio_records.api.Record` instance.
:returns: A LXML Element instance. | entailment |
def eprints_description(metadataPolicy, dataPolicy,
submissionPolicy=None, content=None):
"""Generate the eprints element for the identify response.
The eprints container is used by the e-print community to describe
the content and policies of repositories.
For the full specific... | Generate the eprints element for the identify response.
The eprints container is used by the e-print community to describe
the content and policies of repositories.
For the full specification and schema definition visit:
http://www.openarchives.org/OAI/2.0/guidelines-eprints.htm | entailment |
def oai_identifier_description(scheme, repositoryIdentifier,
delimiter, sampleIdentifier):
"""Generate the oai-identifier element for the identify response.
The OAI identifier format is intended to provide persistent resource
identifiers for items in repositories that impleme... | Generate the oai-identifier element for the identify response.
The OAI identifier format is intended to provide persistent resource
identifiers for items in repositories that implement OAI-PMH.
For the full specification and schema definition visit:
http://www.openarchives.org/OAI/2.0/guidelines-oai-id... | entailment |
def friends_description(baseURLs):
"""Generate the friends element for the identify response.
The friends container is recommended for use by repositories
to list confederate repositories.
For the schema definition visit:
http://www.openarchives.org/OAI/2.0/guidelines-friends.htm
"""
friend... | Generate the friends element for the identify response.
The friends container is recommended for use by repositories
to list confederate repositories.
For the schema definition visit:
http://www.openarchives.org/OAI/2.0/guidelines-friends.htm | entailment |
def after_insert_oai_set(mapper, connection, target):
"""Update records on OAISet insertion."""
_new_percolator(spec=target.spec, search_pattern=target.search_pattern)
sleep(2)
update_affected_records.delay(
search_pattern=target.search_pattern
) | Update records on OAISet insertion. | entailment |
def after_update_oai_set(mapper, connection, target):
"""Update records on OAISet update."""
_delete_percolator(spec=target.spec, search_pattern=target.search_pattern)
_new_percolator(spec=target.spec, search_pattern=target.search_pattern)
sleep(2)
update_affected_records.delay(
spec=target.... | Update records on OAISet update. | entailment |
def after_delete_oai_set(mapper, connection, target):
"""Update records on OAISet deletion."""
_delete_percolator(spec=target.spec, search_pattern=target.search_pattern)
sleep(2)
update_affected_records.delay(
spec=target.spec
) | Update records on OAISet deletion. | entailment |
def query_string_parser(search_pattern):
"""Elasticsearch query string parser."""
if not hasattr(current_oaiserver, 'query_parser'):
query_parser = current_app.config['OAISERVER_QUERY_PARSER']
if isinstance(query_parser, six.string_types):
query_parser = import_string(query_parser)
... | Elasticsearch query string parser. | entailment |
def get_affected_records(spec=None, search_pattern=None):
"""Get list of affected records.
:param spec: The record spec.
:param search_pattern: The search pattern.
:returns: An iterator to lazily find results.
"""
# spec pattern query
# ---------- ---------- -------
# None ... | Get list of affected records.
:param spec: The record spec.
:param search_pattern: The search pattern.
:returns: An iterator to lazily find results. | entailment |
def get_records(**kwargs):
"""Get records paginated."""
page_ = kwargs.get('resumptionToken', {}).get('page', 1)
size_ = current_app.config['OAISERVER_PAGE_SIZE']
scroll = current_app.config['OAISERVER_RESUMPTION_TOKEN_EXPIRE_TIME']
scroll_id = kwargs.get('resumptionToken', {}).get('scroll_id')
... | Get records paginated. | entailment |
def get_file_path(filename, local=True, relative_to_module=None, my_dir=my_dir):
"""
Look for an existing path matching filename.
Try to resolve relative to the module location if the path cannot by found
using "normal" resolution.
"""
# override my_dir if module is provided
if relative_to_m... | Look for an existing path matching filename.
Try to resolve relative to the module location if the path cannot by found
using "normal" resolution. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.