INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Determines if type is in the database :param tp: :return:
def type_in_db(self, tp, params): """ Determines if type is in the database :param tp: :return: """ tw = TypeWrapper(tp, params) return self.version_db.is_versioned(tw)
Loads version from the stream / version database # TODO: instance vs. tp. :param tp: :param params: :return:
async def get_version(self, tp, params): """ Loads version from the stream / version database # TODO: instance vs. tp. :param tp: :param params: :return: """ tw = TypeWrapper(tp, params) if not tw.is_versioned(): # self.registry.set_tr...
Stores version to the stream if not stored yet :param tp: :param params: :param version: :param elem: :return:
async def set_version(self, tp, params, version=None, elem=None): """ Stores version to the stream if not stored yet :param tp: :param params: :param version: :param elem: :return: """ self.registry.set_tr(None) tw = TypeWrapper(tp, params...
Symmetric version management :param tp: :param params: :param version: :return:
async def version(self, tp, params, version=None, elem=None): """ Symmetric version management :param tp: :param params: :param version: :return: """ if self.writing: return await self.set_version(tp, params, version, elem) else: ...
Uvarint :param elem: :return:
async def uvarint(self, elem): """ Uvarint :param elem: :return: """ if self.writing: return await dump_uvarint(self.iobj, elem) else: return await load_uvarint(self.iobj)
Integer types :param elem: :param elem_type: :param params: :return:
async def uint(self, elem, elem_type, params=None): """ Integer types :param elem: :param elem_type: :param params: :return: """ one_b_type = x.is_type(elem_type, (x.Int8, x.UInt8)) if self.writing: return (await x.dump_uint(self.iobj, ...
Unicode type :param elem: :return:
async def unicode_type(self, elem): """ Unicode type :param elem: :return: """ if self.writing: await dump_uvarint(self.iobj, len(elem)) await self.iobj.awrite(bytes(elem, 'utf8')) else: ivalue = await load_uvarint(self.iobj) ...
Loads/dumps blob :return:
async def blob(self, elem=None, elem_type=None, params=None): """ Loads/dumps blob :return: """ elem_type = elem_type if elem_type else elem.__class__ version = await self.version(elem_type, params, elem=elem) if self.is_tracked(): return self.get_tra...
Dumps blob message to the writer. Supports both blob and raw value. :param writer: :param elem: :param elem_type: :param params: :return:
async def blob_dump(self, elem, elem_type, params=None): """ Dumps blob message to the writer. Supports both blob and raw value. :param writer: :param elem: :param elem_type: :param params: :return: """ elem_is_blob = isinstance(elem, x.Bl...
Loads blob from reader to the element. Returns the loaded blob. :param reader: :param elem_type: :param params: :param elem: :return:
async def blob_load(self, elem_type, params=None, elem=None): """ Loads blob from reader to the element. Returns the loaded blob. :param reader: :param elem_type: :param params: :param elem: :return: """ ivalue = await load_uvarint(self.iobj) ...
Loads/dumps container :return:
async def container(self, container=None, container_type=None, params=None): """ Loads/dumps container :return: """ # Container versioning is a bit tricky, primitive type containers are not versioned. elem_type = x.container_elem_type(container_type, params) raw_c...
Container size :param container_len: :param container_type: :param params: :return:
async def container_size(self, container_len=None, container_type=None, params=None): """ Container size :param container_len: :param container_type: :param params: :return: """ if hasattr(container_type, 'boost_serialize'): raise ValueError('n...
Single cont value :param elem: :param container_type: :param params: :param field_archiver: :return:
async def container_val(self, elem, container_type, params=None): """ Single cont value :param elem: :param container_type: :param params: :param field_archiver: :return: """ if hasattr(container_type, 'boost_serialize'): raise ValueErr...
Dumps container of elements to the writer. :param writer: :param container: :param container_type: :param params: :param field_archiver: :return:
async def container_dump(self, container, container_type, params=None): """ Dumps container of elements to the writer. :param writer: :param container: :param container_type: :param params: :param field_archiver: :return: """ await self.co...
Loads container of elements from the reader. Supports the container ref. Returns loaded container. :param container_type: :param params: :param container: :param field_archiver: :return:
async def container_load(self, container_type, params=None, container=None): """ Loads container of elements from the reader. Supports the container ref. Returns loaded container. :param container_type: :param params: :param container: :param field_archiver: ...
Loads/dumps tuple :return:
async def tuple(self, elem=None, elem_type=None, params=None): """ Loads/dumps tuple :return: """ version = await self.version(elem_type, params, elem=elem) if self.is_tracked(): return self.get_tracked() if hasattr(elem_type, 'boost_serialize'): ...
Dumps tuple of elements to the writer. :param elem: :param elem_type: :param params: :return:
async def dump_tuple(self, elem, elem_type, params=None): """ Dumps tuple of elements to the writer. :param elem: :param elem_type: :param params: :return: """ if len(elem) != len(elem_type.f_specs()): raise ValueError('Fixed size tuple has no...
Loads/dumps variant type :param elem: :param elem_type: :param params: :return:
async def variant(self, elem=None, elem_type=None, params=None): """ Loads/dumps variant type :param elem: :param elem_type: :param params: :return: """ elem_type = elem_type if elem_type else elem.__class__ version = await self.version(elem_type, ...
Dumps variant type to the writer. Supports both wrapped and raw variant. :param writer: :param elem: :param elem_type: :param params: :return:
async def dump_variant(self, elem, elem_type=None, params=None): """ Dumps variant type to the writer. Supports both wrapped and raw variant. :param writer: :param elem: :param elem_type: :param params: :return: """ if isinstance(elem, x.V...
Loads variant type from the reader. Supports both wrapped and raw variant. :param reader: :param elem_type: :param params: :param elem: :param wrapped: :return:
async def load_variant(self, elem_type, params=None, elem=None, wrapped=None): """ Loads variant type from the reader. Supports both wrapped and raw variant. :param reader: :param elem_type: :param params: :param elem: :param wrapped: :return: ...
Root level init :return:
async def root(self): """ Root level init :return: """ if self.writing: await self.iobj.awrite(binascii.unhexlify(b'011673657269616c697a6174696f6e3a3a617263686976650000')) else: hdr = bytearray(2) await self.iobj.areadinto(hdr) ...
Root-level message. First entry in the archive. Archive headers processing :return:
async def root_message(self, msg, msg_type=None): """ Root-level message. First entry in the archive. Archive headers processing :return: """ await self.root() await self.message(msg, msg_type)
Loads/dumps message :param msg: :param msg_type: :param use_version: :return:
async def message(self, msg, msg_type=None, use_version=None): """ Loads/dumps message :param msg: :param msg_type: :param use_version: :return: """ elem_type = msg_type if msg_type is not None else msg.__class__ version = await self.version(elem_t...
Load/dump individual message fields :param msg: :param fields: :param field_archiver: :return:
async def message_fields(self, msg, fields): """ Load/dump individual message fields :param msg: :param fields: :param field_archiver: :return: """ for field in fields: try: self.tracker.push_field(field[0]) awai...
Dumps message to the writer. :param msg: :param msg_type: :return:
async def dump_message(self, msg, msg_type=None): """ Dumps message to the writer. :param msg: :param msg_type: :return: """ mtype = msg.__class__ if msg_type is None else msg_type fields = mtype.f_specs() for field in fields: await se...
Loads message if the given type from the reader. Supports reading directly to existing message. :param msg_type: :param msg: :return:
async def load_message(self, msg_type, msg=None): """ Loads message if the given type from the reader. Supports reading directly to existing message. :param msg_type: :param msg: :return: """ msg = msg_type() if msg is None else msg fields = msg_t...
:param resource: Resource (not necessary fetched) :param next_resource_name: string :rtype: (resource_type, resource_path)
def _get_next_resource(self, resource, next_resource_name, selectors): """ :param resource: Resource (not necessary fetched) :param next_resource_name: string :rtype: (resource_type, resource_path) """ # don't fetch twice if 'id_perms' not in resource: ...
Handle HTTP errors returned by the API server
def contrail_error_handler(f): """Handle HTTP errors returned by the API server """ @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except HttpError as e: # Replace message by details to provide a # meaningful message ...
Initialize a session to Contrail API server :param os_auth_type: auth plugin to use: - http: basic HTTP authentification - v2password: keystone v2 auth - v3password: keystone v3 auth :type os_auth_type: str
def make(self, host="localhost", port=8082, protocol="http", base_uri="", os_auth_type="http", **kwargs): """Initialize a session to Contrail API server :param os_auth_type: auth plugin to use: - http: basic HTTP authentification - v2password: keystone v2 auth - v3pa...
POST data to the api-server :param url: resource location (eg: "/type/uuid") :type url: str :param cls: JSONEncoder class :type cls: JSONEncoder
def post_json(self, url, data, cls=None, **kwargs): """ POST data to the api-server :param url: resource location (eg: "/type/uuid") :type url: str :param cls: JSONEncoder class :type cls: JSONEncoder """ kwargs['data'] = to_json(data, cls=cls) kw...
PUT data to the api-server :param url: resource location (eg: "/type/uuid") :type url: str :param cls: JSONEncoder class :type cls: JSONEncoder
def put_json(self, url, data, cls=None, **kwargs): """ PUT data to the api-server :param url: resource location (eg: "/type/uuid") :type url: str :param cls: JSONEncoder class :type cls: JSONEncoder """ kwargs['data'] = to_json(data, cls=cls) kwar...
Return uuid for fq_name :param fq_name: resource fq name :type fq_name: FQName :param type: resource type :type type: str :rtype: UUIDv4 str :raises HttpError: fq_name not found
def fqname_to_id(self, fq_name, type): """ Return uuid for fq_name :param fq_name: resource fq name :type fq_name: FQName :param type: resource type :type type: str :rtype: UUIDv4 str :raises HttpError: fq_name not found """ data = { ...
Return fq_name and type for uuid If `type` is provided check that uuid is actually a resource of type `type`. Raise HttpError if it's not the case. :param uuid: resource uuid :type uuid: UUIDv4 str :param type: resource type :type type: str :rtype: dict...
def id_to_fqname(self, uuid, type=None): """ Return fq_name and type for uuid If `type` is provided check that uuid is actually a resource of type `type`. Raise HttpError if it's not the case. :param uuid: resource uuid :type uuid: UUIDv4 str :param type...
Search for a key in the key-value store. :param key: string :rtype: string
def search_kv_store(self, key): """Search for a key in the key-value store. :param key: string :rtype: string """ data = { 'operation': 'RETRIEVE', 'key': key } return self.post_json(self.make_url("/useragent-kv"), data)['value']
Add a key-value store entry. :param key: string :param value: string
def add_kv_store(self, key, value): """Add a key-value store entry. :param key: string :param value: string """ data = { 'operation': 'STORE', 'key': key, 'value': value } return self.post(self.make_url("/useragent-kv"), data=t...
Remove a key-value store entry. :param key: string
def remove_kv_store(self, key): """Remove a key-value store entry. :param key: string """ data = { 'operation': 'DELETE', 'key': key } return self.post(self.make_url("/useragent-kv"), data=to_json(data), headers=self.defau...
Returns the given operations array sorted with duplicates removed. @param ops checker.Ops @return: checker.Ops
def canonical_ops(ops): ''' Returns the given operations array sorted with duplicates removed. @param ops checker.Ops @return: checker.Ops ''' new_ops = sorted(set(ops), key=lambda x: (x.entity, x.action)) return new_ops
Return operations suitable for serializing as part of a MacaroonId. It assumes that ops has been canonicalized and that there's at least one operation.
def _macaroon_id_ops(ops): '''Return operations suitable for serializing as part of a MacaroonId. It assumes that ops has been canonicalized and that there's at least one operation. ''' id_ops = [] for entity, entity_ops in itertools.groupby(ops, lambda x: x.entity): actions = map(lambd...
Takes a macaroon with the given version from the oven, associates it with the given operations and attaches the given caveats. There must be at least one operation specified. The macaroon will expire at the given time - a time_before first party caveat will be added with that time. ...
def macaroon(self, version, expiry, caveats, ops): ''' Takes a macaroon with the given version from the oven, associates it with the given operations and attaches the given caveats. There must be at least one operation specified. The macaroon will expire at the given time - a time_before...
Returns a new multi-op entity name string that represents all the given operations and caveats. It returns the same value regardless of the ordering of the operations. It assumes that the operations have been canonicalized and that there's at least one operation. :param ops: ...
def ops_entity(self, ops): ''' Returns a new multi-op entity name string that represents all the given operations and caveats. It returns the same value regardless of the ordering of the operations. It assumes that the operations have been canonicalized and that there's at least one ...
This method makes the oven satisfy the MacaroonOpStore protocol required by the Checker class. For macaroons minted with previous bakery versions, it always returns a single LoginOp operation. :param macaroons: :return:
def macaroon_ops(self, macaroons): ''' This method makes the oven satisfy the MacaroonOpStore protocol required by the Checker class. For macaroons minted with previous bakery versions, it always returns a single LoginOp operation. :param macaroons: :return: '''...
Add an item to the end of the list.
def append(self, value): """Add an item to the end of the list.""" return super(Collection, self).append( self._ensure_value_is_valid(value))
Extend the list by appending all the items in the given list.
def extend(self, iterable): """Extend the list by appending all the items in the given list.""" return super(Collection, self).extend( self._ensure_iterable_is_valid(iterable))
Insert an item at a given position.
def insert(self, index, value): """Insert an item at a given position.""" return super(Collection, self).insert( index, self._ensure_value_is_valid(value))
Ensure that value is a valid collection's value.
def _ensure_value_is_valid(self, value): """Ensure that value is a valid collection's value.""" if not isinstance(value, self.__class__.value_type): raise TypeError('{0} is not valid collection value, instance ' 'of {1} required'.format( ...
Returns container element type :param container_type: :param params: :return:
def container_elem_type(container_type, params): """ Returns container element type :param container_type: :param params: :return: """ elem_type = params[0] if params else None if elem_type is None: elem_type = container_type.ELEM_TYPE return elem_type
Generates element array of given size and initializes with given type. Supports container type, used for pre-allocation before deserialization. :param size: :param elem_type: :return:
def gen_elem_array(size, elem_type=None): """ Generates element array of given size and initializes with given type. Supports container type, used for pre-allocation before deserialization. :param size: :param elem_type: :return: """ if elem_type is None or not callable(elem_type): ...
Check that a given DOI is a valid canonical DOI. :param doi: The DOI to be checked. :returns: Boolean indicating whether the DOI is valid or not. >>> is_valid('10.1209/0295-5075/111/40005') True >>> is_valid('10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7') True >>> is_valid('10.10...
def is_valid(doi): """ Check that a given DOI is a valid canonical DOI. :param doi: The DOI to be checked. :returns: Boolean indicating whether the DOI is valid or not. >>> is_valid('10.1209/0295-5075/111/40005') True >>> is_valid('10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7') ...
Convert a list of canonical DOIs to a list of DOIs URLs. :param dois: List of canonical DOIs. Can also be a single canonical DOI. :returns: A list of DOIs URLs (resp. a single value). >>> to_url(['10.1209/0295-5075/111/40005']) ['http://dx.doi.org/10.1209/0295-5075/111/40005'] >>> to_url('10.1209...
def to_url(dois): """ Convert a list of canonical DOIs to a list of DOIs URLs. :param dois: List of canonical DOIs. Can also be a single canonical DOI. :returns: A list of DOIs URLs (resp. a single value). >>> to_url(['10.1209/0295-5075/111/40005']) ['http://dx.doi.org/10.1209/0295-5075/111/40...
Get an OA version for a given DOI. .. note:: Uses beta.dissem.in API. :param doi: A canonical DOI. :returns: The URL of the OA version of the given DOI, or ``None``. >>> get_oa_version('10.1209/0295-5075/111/40005') 'http://arxiv.org/abs/1506.06690'
def get_oa_version(doi): """ Get an OA version for a given DOI. .. note:: Uses beta.dissem.in API. :param doi: A canonical DOI. :returns: The URL of the OA version of the given DOI, or ``None``. >>> get_oa_version('10.1209/0295-5075/111/40005') 'http://arxiv.org/abs/1506.06690' ...
Get OA policy for a given DOI. .. note:: Uses beta.dissem.in API. :param doi: A canonical DOI. :returns: The OpenAccess policy for the associated publications, or \ ``None`` if unknown. >>> tmp = get_oa_policy('10.1209/0295-5075/111/40005'); (tmp["published"], tmp["preprint"], tm...
def get_oa_policy(doi): """ Get OA policy for a given DOI. .. note:: Uses beta.dissem.in API. :param doi: A canonical DOI. :returns: The OpenAccess policy for the associated publications, or \ ``None`` if unknown. >>> tmp = get_oa_policy('10.1209/0295-5075/111/40005'); (t...
Get the original link behind the DOI. :param doi: A canonical DOI. :returns: The canonical URL behind the DOI, or ``None``. >>> get_linked_version('10.1209/0295-5075/111/40005') 'http://stacks.iop.org/0295-5075/111/i=4/a=40005?key=crossref.9ad851948a976ecdf216d4929b0b6f01'
def get_linked_version(doi): """ Get the original link behind the DOI. :param doi: A canonical DOI. :returns: The canonical URL behind the DOI, or ``None``. >>> get_linked_version('10.1209/0295-5075/111/40005') 'http://stacks.iop.org/0295-5075/111/i=4/a=40005?key=crossref.9ad851948a976ecdf216d...
Get a BibTeX entry for a given DOI. .. note:: Adapted from https://gist.github.com/jrsmith3/5513926. :param doi: The canonical DOI to get BibTeX from. :returns: A BibTeX string or ``None``. >>> get_bibtex('10.1209/0295-5075/111/40005') '@article{Verney_2015,\\n\\tdoi = {10.1209/0295-5075...
def get_bibtex(doi): """ Get a BibTeX entry for a given DOI. .. note:: Adapted from https://gist.github.com/jrsmith3/5513926. :param doi: The canonical DOI to get BibTeX from. :returns: A BibTeX string or ``None``. >>> get_bibtex('10.1209/0295-5075/111/40005') '@article{Verney_20...
Configures the logging module with a given dictionary, which in most cases was loaded from a configuration file. If no dictionary is provided, it falls back to a default configuration. See `Python docs <https://docs.python.org/3.5/library/logging.config.html#logging.config.dictConfig>`...
def _configure_logging(self, logger_dict=None): """ Configures the logging module with a given dictionary, which in most cases was loaded from a configuration file. If no dictionary is provided, it falls back to a default configuration. See `Python docs <https://docs.py...
Dumps blob message to the writer. Supports both blob and raw value. :param writer: :param elem: :param elem_type: :param params: :return:
async def dump_blob(writer, elem, elem_type, params=None): """ Dumps blob message to the writer. Supports both blob and raw value. :param writer: :param elem: :param elem_type: :param params: :return: """ elem_is_blob = isinstance(elem, BlobType) elem_params = elem if elem_i...
Loads blob from reader to the element. Returns the loaded blob. :param reader: :param elem_type: :param params: :param elem: :return:
async def load_blob(reader, elem_type, params=None, elem=None): """ Loads blob from reader to the element. Returns the loaded blob. :param reader: :param elem_type: :param params: :param elem: :return: """ ivalue = elem_type.SIZE if elem_type.FIX_SIZE else await load_uvarint(reader)...
Dumps string as UTF8 encoded string :param writer: :param elem: :return:
async def dump_unicode(writer, elem): """ Dumps string as UTF8 encoded string :param writer: :param elem: :return: """ await dump_uvarint(writer, len(elem)) await writer.awrite(bytes(elem, 'utf8'))
Loads UTF8 string :param reader: :return:
async def load_unicode(reader): """ Loads UTF8 string :param reader: :return: """ ivalue = await load_uvarint(reader) fvalue = bytearray(ivalue) await reader.areadinto(fvalue) return str(fvalue, 'utf8')
Prepares container for serialization :param size: :param container: :return:
async def prepare_container(self, size, container, elem_type=None): """ Prepares container for serialization :param size: :param container: :return: """ if not self.writing: if container is None: return gen_elem_array(size, elem_type) ...
Loads/dumps blob :return:
async def blob(self, elem=None, elem_type=None, params=None): """ Loads/dumps blob :return: """ elem_type = elem_type if elem_type else elem.__class__ if hasattr(elem_type, "serialize_archive"): elem = elem_type() if elem is None else elem return a...
Loads/dumps container :return:
async def container(self, container=None, container_type=None, params=None): """ Loads/dumps container :return: """ if hasattr(container_type, "serialize_archive"): container = container_type() if container is None else container return await container.ser...
Container size :param container_len: :param container_type: :param params: :return:
async def container_size( self, container_len=None, container_type=None, params=None ): """ Container size :param container_len: :param container_type: :param params: :return: """ if hasattr(container_type, "serialize_archive"): ...
Single cont value :param elem: :param container_type: :param params: :return:
async def container_val(self, elem, container_type, params=None): """ Single cont value :param elem: :param container_type: :param params: :return: """ if hasattr(container_type, "serialize_archive"): raise ValueError("not supported") i...
Loads/dumps tuple :return:
async def tuple(self, elem=None, elem_type=None, params=None): """ Loads/dumps tuple :return: """ if hasattr(elem_type, "serialize_archive"): container = elem_type() if elem is None else elem return await container.serialize_archive( self, ...
Loads/dumps variant type :param elem: :param elem_type: :param params: :return:
async def variant(self, elem=None, elem_type=None, params=None, wrapped=None): """ Loads/dumps variant type :param elem: :param elem_type: :param params: :return: """ elem_type = elem_type if elem_type else elem.__class__ if hasattr(elem_type, "ser...
Loads/dumps message :param msg: :param msg_type: :param use_version: :return:
async def message(self, msg, msg_type=None, use_version=None): """ Loads/dumps message :param msg: :param msg_type: :param use_version: :return: """ elem_type = msg_type if msg_type is not None else msg.__class__ msg = elem_type() if msg is None el...
Dumps/Loads message field :param msg: :param field: :param fvalue: explicit value for dump :return:
async def message_field(self, msg, field, fvalue=None): """ Dumps/Loads message field :param msg: :param field: :param fvalue: explicit value for dump :return: """ fname, ftype, params = field[0], field[1], field[2:] try: self.tracker.p...
Archive field :param elem: :param elem_type: :param params: :return:
async def field(self, elem=None, elem_type=None, params=None): """ Archive field :param elem: :param elem_type: :param params: :return: """ elem_type = elem_type if elem_type else elem.__class__ fvalue = None etype = self._get_type(elem_ty...
Dumps container size - per element streaming :param writer: :param container_len: :param container_type: :param params: :return:
async def _dump_container_size( self, writer, container_len, container_type, params=None ): """ Dumps container size - per element streaming :param writer: :param container_len: :param container_type: :param params: :return: """ if ...
Single elem dump :param writer: :param elem: :param container_type: :param params: :return:
async def _dump_container_val(self, writer, elem, container_type, params=None): """ Single elem dump :param writer: :param elem: :param container_type: :param params: :return: """ elem_type = container_elem_type(container_type, params) awai...
Dumps container of elements to the writer. :param writer: :param container: :param container_type: :param params: :return:
async def _dump_container(self, writer, container, container_type, params=None): """ Dumps container of elements to the writer. :param writer: :param container: :param container_type: :param params: :return: """ await self._dump_container_size(wri...
Loads container of elements from the reader. Supports the container ref. Returns loaded container. :param reader: :param container_type: :param params: :param container: :return:
async def _load_container( self, reader, container_type, params=None, container=None ): """ Loads container of elements from the reader. Supports the container ref. Returns loaded container. :param reader: :param container_type: :param params: :pa...
Dumps tuple of elements to the writer. :param writer: :param elem: :param elem_type: :param params: :return:
async def _dump_tuple(self, writer, elem, elem_type, params=None): """ Dumps tuple of elements to the writer. :param writer: :param elem: :param elem_type: :param params: :return: """ if len(elem) != len(elem_type.f_specs()): raise Val...
Loads tuple of elements from the reader. Supports the tuple ref. Returns loaded tuple. :param reader: :param elem_type: :param params: :param container: :return:
async def _load_tuple(self, reader, elem_type, params=None, elem=None): """ Loads tuple of elements from the reader. Supports the tuple ref. Returns loaded tuple. :param reader: :param elem_type: :param params: :param container: :return: """ ...
Dumps a message field to the writer. Field is defined by the message field specification. :param writer: :param msg: :param field: :param fvalue: :return:
async def _dump_message_field(self, writer, msg, field, fvalue=None): """ Dumps a message field to the writer. Field is defined by the message field specification. :param writer: :param msg: :param field: :param fvalue: :return: """ fname, ftype, ...
Loads message field from the reader. Field is defined by the message field specification. Returns loaded value, supports field reference. :param reader: :param msg: :param field: :return:
async def _load_message_field(self, reader, msg, field): """ Loads message field from the reader. Field is defined by the message field specification. Returns loaded value, supports field reference. :param reader: :param msg: :param field: :return: """ ...
Dumps variant type to the writer. Supports both wrapped and raw variant. :param writer: :param elem: :param elem_type: :param params: :return:
async def _dump_variant(self, writer, elem, elem_type=None, params=None): """ Dumps variant type to the writer. Supports both wrapped and raw variant. :param writer: :param elem: :param elem_type: :param params: :return: """ if isinstance(...
Loads variant type from the reader. Supports both wrapped and raw variant. :param reader: :param elem_type: :param params: :param elem: :param wrapped: :return:
async def _load_variant( self, reader, elem_type, params=None, elem=None, wrapped=None ): """ Loads variant type from the reader. Supports both wrapped and raw variant. :param reader: :param elem_type: :param params: :param elem: :param wr...
Manually starts timer with the message. :param message: The display message.
def start(self, message): """ Manually starts timer with the message. :param message: The display message. """ self._start = time.clock() VSGLogger.info("{0:<20} - Started".format(message))
Manually stops timer with the message. :param message: The display message.
def stop(self, message): """ Manually stops timer with the message. :param message: The display message. """ self._stop = time.clock() VSGLogger.info("{0:<20} - Finished [{1}s]".format(message, self.pprint(self._stop - self._start)))
Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds :param seconds: The time in seconds.
def pprint(self, seconds): """ Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds :param seconds: The time in seconds. """ return ("%d:%02d:%02d.%03d", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))
Search for a valid identifier (DOI, ISBN, arXiv, HAL) in a given file. .. note:: This function returns the first matching identifier, that is the most likely to be relevant for this file. However, it may fail and return an identifier taken from the references or another paper. .. note...
def find_identifiers(src): """ Search for a valid identifier (DOI, ISBN, arXiv, HAL) in a given file. .. note:: This function returns the first matching identifier, that is the most likely to be relevant for this file. However, it may fail and return an identifier taken from the re...
Try to fetch BibTeX from a found identifier. .. note:: Calls the functions in the respective identifiers module. :param identifier: a tuple (type, identifier) with a valid type. :returns: A BibTeX string or ``None`` if an error occurred. # TODO: Should return a BiBTeX object?
def get_bibtex(identifier): """ Try to fetch BibTeX from a found identifier. .. note:: Calls the functions in the respective identifiers module. :param identifier: a tuple (type, identifier) with a valid type. :returns: A BibTeX string or ``None`` if an error occurred. # TODO: Should ...
Only try to parse as JSON if the JSON content type header is set.
def initialize(self,*args,**kwargs): """ Only try to parse as JSON if the JSON content type header is set. """ super(JSONHandler,self).initialize(*args,**kwargs) content_type = self.request.headers.get('Content-Type', '') if 'application/json' in content_type.lowe...
Parse a BibTeX file to get a clean list of plaintext citations. :param bibtex: Either the path to the BibTeX file or the content of a \ BibTeX file. :returns: A list of cleaned plaintext citations.
def get_plaintext_citations(bibtex): """ Parse a BibTeX file to get a clean list of plaintext citations. :param bibtex: Either the path to the BibTeX file or the content of a \ BibTeX file. :returns: A list of cleaned plaintext citations. """ parser = BibTexParser() parser.cust...
Loads INI configuration into this module's attributes.
def init(filename=ConfigPath): """Loads INI configuration into this module's attributes.""" section, parts = "DEFAULT", filename.rsplit(":", 1) if len(parts) > 1 and os.path.isfile(parts[0]): filename, section = parts if not os.path.isfile(filename): return vardict, parser = globals(), config...
Saves this module's changed attributes to INI configuration.
def save(filename=ConfigPath): """Saves this module's changed attributes to INI configuration.""" default_values = defaults() parser = configparser.RawConfigParser() parser.optionxform = str # Force case-sensitivity on names try: save_types = basestring, int, float, tuple, list, dict, ...
Returns a once-assembled dict of this module's storable attributes.
def defaults(values={}): """Returns a once-assembled dict of this module's storable attributes.""" if values: return values save_types = basestring, int, float, tuple, list, dict, type(None) for k, v in globals().items(): if isinstance(v, save_types) and not k.startswith("_"): values[k] = v...
Fix malformed pdf files when data are present after '%%EOF' ..note :: Originally from sciunto, https://github.com/sciunto/tear-pages :param pdfFile: PDF filepath :param destination: destination
def fix_pdf(pdf_file, destination): """ Fix malformed pdf files when data are present after '%%EOF' ..note :: Originally from sciunto, https://github.com/sciunto/tear-pages :param pdfFile: PDF filepath :param destination: destination """ tmp = tempfile.NamedTemporaryFile() wit...
Copy filename to a tempfile, write pages to filename except the teared one. ..note :: Adapted from sciunto's code, https://github.com/sciunto/tear-pages :param filename: PDF filepath :param teared_pages: Numbers of the pages to tear. Default to first page \ only.
def tearpage_backend(filename, teared_pages=None): """ Copy filename to a tempfile, write pages to filename except the teared one. ..note :: Adapted from sciunto's code, https://github.com/sciunto/tear-pages :param filename: PDF filepath :param teared_pages: Numbers of the pages to tear. ...
Check whether a given paper needs some pages to be teared or not. :params bibtex: The bibtex entry associated to the paper, to guess \ whether tearing is needed. :returns: A list of pages to tear.
def tearpage_needed(bibtex): """ Check whether a given paper needs some pages to be teared or not. :params bibtex: The bibtex entry associated to the paper, to guess \ whether tearing is needed. :returns: A list of pages to tear. """ for publisher in BAD_JOURNALS: if publish...
Tear some pages of the file if needed. :params filename: Path to the file to handle. :params bibtex: BibTeX dict associated to this file, as the one given by \ ``bibtexparser``. (Mandatory if force is not specified) :params force: If a list of integers, force the tearing of the \ sp...
def tearpage(filename, bibtex=None, force=None): """ Tear some pages of the file if needed. :params filename: Path to the file to handle. :params bibtex: BibTeX dict associated to this file, as the one given by \ ``bibtexparser``. (Mandatory if force is not specified) :params force: If ...
Creates or returns a singleton :class:`.Connection` object
def connect(*args, **kwargs): """Creates or returns a singleton :class:`.Connection` object""" global __CONNECTION if __CONNECTION is None: __CONNECTION = Connection(*args, **kwargs) return __CONNECTION
Checks out a file into the default changelist :param filename: File to check out :type filename: str :param connection: Connection object to use :type connection: :py:class:`Connection`
def edit(filename, connection=None): """Checks out a file into the default changelist :param filename: File to check out :type filename: str :param connection: Connection object to use :type connection: :py:class:`Connection` """ c = connection or connect() rev = c.ls(filename) if r...
Syncs a file :param filename: File to check out :type filename: str :param connection: Connection object to use :type connection: :py:class:`Connection`
def sync(filename, connection=None): """Syncs a file :param filename: File to check out :type filename: str :param connection: Connection object to use :type connection: :py:class:`Connection` """ c = connection or connect() rev = c.ls(filename) if rev: rev[0].sync()
Edits or Adds a filename ensuring the file is in perforce and editable :param filename: File to check out :type filename: str :param connection: Connection object to use :type connection: :py:class:`Connection`
def open(filename, connection=None): """Edits or Adds a filename ensuring the file is in perforce and editable :param filename: File to check out :type filename: str :param connection: Connection object to use :type connection: :py:class:`Connection` """ c = connection or connect() res ...
Set name for Faultset :param name: Name of Faultset :param fsObj: ScaleIO FS object :return: POST request response :rtype: Requests POST response object
def set_faultset_name(self, name, fsObj): """ Set name for Faultset :param name: Name of Faultset :param fsObj: ScaleIO FS object :return: POST request response :rtype: Requests POST response object """ # Set name of FaultSet self.conn.connection._...
Check that a given arXiv ID is a valid one. :param arxiv_id: The arXiv ID to be checked. :returns: Boolean indicating whether the arXiv ID is valid or not. >>> is_valid('1506.06690') True >>> is_valid('1506.06690v1') True >>> is_valid('arXiv:1506.06690') True >>> is_valid('arXiv...
def is_valid(arxiv_id): """ Check that a given arXiv ID is a valid one. :param arxiv_id: The arXiv ID to be checked. :returns: Boolean indicating whether the arXiv ID is valid or not. >>> is_valid('1506.06690') True >>> is_valid('1506.06690v1') True >>> is_valid('arXiv:1506.06690...
Get a BibTeX entry for a given arXiv ID. .. note:: Using awesome https://pypi.python.org/pypi/arxiv2bib/ module. :param arxiv_id: The canonical arXiv id to get BibTeX from. :returns: A BibTeX string or ``None``. >>> get_bibtex('1506.06690') "@article{1506.06690v2,\\nAuthor = {Luca...
def get_bibtex(arxiv_id): """ Get a BibTeX entry for a given arXiv ID. .. note:: Using awesome https://pypi.python.org/pypi/arxiv2bib/ module. :param arxiv_id: The canonical arXiv id to get BibTeX from. :returns: A BibTeX string or ``None``. >>> get_bibtex('1506.06690') "@article...
Convert a list of canonical DOIs to a list of DOIs URLs. :param dois: List of canonical DOIs. :returns: A list of DOIs URLs. >>> to_url('1506.06690') 'http://arxiv.org/abs/1506.06690' >>> to_url('1506.06690v1') 'http://arxiv.org/abs/1506.06690v1'
def to_url(arxiv_ids): """ Convert a list of canonical DOIs to a list of DOIs URLs. :param dois: List of canonical DOIs. :returns: A list of DOIs URLs. >>> to_url('1506.06690') 'http://arxiv.org/abs/1506.06690' >>> to_url('1506.06690v1') 'http://arxiv.org/abs/1506.06690v1' """ ...