INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Load data from the: class: stdnet. BackendDataServer. | def load_data(self, data, callback=None):
'''Load ``data`` from the :class:`stdnet.BackendDataServer`.'''
return self.backend.execute(
self.value_pickler.load_iterable(data, self.session), callback) |
Iteratir over values of: class: PairMixin. | def values(self):
'''Iteratir over values of :class:`PairMixin`.'''
if self.cache.cache is None:
backend = self.read_backend
return backend.execute(backend.structure(self).values(),
self.load_values)
else:
return self.... |
Add a * pair * to the structure. | def pair(self, pair):
'''Add a *pair* to the structure.'''
if len(pair) == 1:
# if only one value is passed, the value must implement a
# score function which retrieve the first value of the pair
# (score in zset, timevalue in timeseries, field value in
... |
Remove * keys * from the key - value container. | def remove(self, *keys):
'''Remove *keys* from the key-value container.'''
dumps = self.pickler.dumps
self.cache.remove([dumps(v) for v in keys]) |
Count the number of elements bewteen * start * and * stop *. | def count(self, start, stop):
'''Count the number of elements bewteen *start* and *stop*.'''
s1 = self.pickler.dumps(start)
s2 = self.pickler.dumps(stop)
return self.backend_structure().count(s1, s2) |
Return the range by rank between start and end. | def irange(self, start=0, end=-1, callback=None, withscores=True,
**options):
'''Return the range by rank between start and end.'''
backend = self.read_backend
res = backend.structure(self).irange(start, end,
withscores=withscores,... |
pop a range by score from the: class: OrderedMixin | def pop_range(self, start, stop, callback=None, withscores=True):
'''pop a range by score from the :class:`OrderedMixin`'''
s1 = self.pickler.dumps(start)
s2 = self.pickler.dumps(stop)
backend = self.backend
res = backend.structure(self).pop_range(s1, s2, withscores=withscor... |
pop a range from the: class: OrderedMixin | def ipop_range(self, start=0, stop=-1, callback=None, withscores=True):
'''pop a range from the :class:`OrderedMixin`'''
backend = self.backend
res = backend.structure(self).ipop_range(start, stop,
withscores=withscores)
if not callba... |
Appends a copy of * value * at the end of the: class: Sequence. | def push_back(self, value):
'''Appends a copy of *value* at the end of the :class:`Sequence`.'''
self.cache.push_back(self.value_pickler.dumps(value))
return self |
Remove the last element from the: class: Sequence. | def pop_back(self):
'''Remove the last element from the :class:`Sequence`.'''
backend = self.backend
return backend.execute(backend.structure(self).pop_back(),
self.value_pickler.loads) |
Add * value * to the set | def add(self, value):
'''Add *value* to the set'''
return self.cache.update((self.value_pickler.dumps(value),)) |
Add iterable * values * to the set | def update(self, values):
'''Add iterable *values* to the set'''
d = self.value_pickler.dumps
return self.cache.update(tuple((d(v) for v in values))) |
Remove an element * value * from a set if it is a member. | def discard(self, value):
'''Remove an element *value* from a set if it is a member.'''
return self.cache.remove((self.value_pickler.dumps(value),)) |
Remove an iterable of * values * from the set. | def difference_update(self, values):
'''Remove an iterable of *values* from the set.'''
d = self.value_pickler.dumps
return self.cache.remove(tuple((d(v) for v in values))) |
Remove the first element from of the list. | def pop_front(self):
'''Remove the first element from of the list.'''
backend = self.backend
return backend.execute(backend.structure(self).pop_front(),
self.value_pickler.loads) |
Remove the last element from of the list. If no elements are available blocks for at least timeout seconds. | def block_pop_back(self, timeout=10):
'''Remove the last element from of the list. If no elements are
available, blocks for at least ``timeout`` seconds.'''
value = yield self.backend_structure().block_pop_back(timeout)
if value is not None:
yield self.value_pickler.loads(value) |
Remove the first element from of the list. If no elements are available blocks for at least timeout seconds. | def block_pop_front(self, timeout=10):
'''Remove the first element from of the list. If no elements are
available, blocks for at least ``timeout`` seconds.'''
value = yield self.backend_structure().block_pop_front(timeout)
if value is not None:
yield self.value_pickler.loads(val... |
Appends a copy of value to the beginning of the list. | def push_front(self, value):
'''Appends a copy of ``value`` to the beginning of the list.'''
self.cache.push_front(self.value_pickler.dumps(value)) |
The rank of a given * value *. This is the position of * value * in the: class: OrderedMixin container. | def rank(self, value):
'''The rank of a given *value*. This is the position of *value*
in the :class:`OrderedMixin` container.'''
value = self.value_pickler.dumps(value)
return self.backend_structure().rank(value) |
The rank of a given * dte * in the timeseries | def rank(self, dte):
'''The rank of a given *dte* in the timeseries'''
timestamp = self.pickler.dumps(dte)
return self.backend_structure().rank(timestamp) |
Pop a value at * index * from the: class: TS. Return None if index is not out of bound. | def ipop(self, index):
'''Pop a value at *index* from the :class:`TS`. Return ``None`` if
index is not out of bound.'''
backend = self.backend
res = backend.structure(self).ipop(index)
return backend.execute(res,
lambda r: self._load_get_data(r, index... |
The times between times * start * and * stop *. | def times(self, start, stop, callback=None, **kwargs):
'''The times between times *start* and *stop*.'''
s1 = self.pickler.dumps(start)
s2 = self.pickler.dumps(stop)
backend = self.read_backend
res = backend.structure(self).times(s1, s2, **kwargs)
return backend.exe... |
The times between rank * start * and * stop *. | def itimes(self, start=0, stop=-1, callback=None, **kwargs):
'''The times between rank *start* and *stop*.'''
backend = self.read_backend
res = backend.structure(self).itimes(start, stop, **kwargs)
return backend.execute(res, callback or self.load_keys) |
A: class: Q performs a series of operations and ultimately generate of set of matched elements ids. If on the other hand a different field is required it can be specified with the: meth: get_field method. For example lets say a model has a field called object_id which contains ids of another model we could use:: qs = s... | def get_field(self, field):
'''A :class:`Q` performs a series of operations and ultimately
generate of set of matched elements ``ids``. If on the other hand, a
different field is required, it can be specified with the :meth:`get_field`
method. For example, lets say a model has a field called ``object_id``
... |
Create a new: class: Query with additional clauses corresponding to where or limit in a SQL SELECT statement.: parameter kwargs: dictionary of limiting clauses.: rtype: a new: class: Query instance. For example:: qs = session. query ( MyModel ) result = qs. filter ( group = planet ) | def filter(self, **kwargs):
'''Create a new :class:`Query` with additional clauses corresponding to
``where`` or ``limit`` in a ``SQL SELECT`` statement.
:parameter kwargs: dictionary of limiting clauses.
:rtype: a new :class:`Query` instance.
For example::
qs = session.query(MyModel)
resul... |
Returns a new: class: Query with additional clauses corresponding to EXCEPT in a SQL SELECT statement.: parameter kwargs: dictionary of limiting clauses.: rtype: a new: class: Query instance. Using an equivalent example to the: meth: filter method:: qs = session. query ( MyModel ) result1 = qs. exclude ( group = planet... | def exclude(self, **kwargs):
'''Returns a new :class:`Query` with additional clauses corresponding
to ``EXCEPT`` in a ``SQL SELECT`` statement.
:parameter kwargs: dictionary of limiting clauses.
:rtype: a new :class:`Query` instance.
Using an equivalent example to the :meth:`filter` method::
qs ... |
Return a new: class: Query obtained form the union of this: class: Query with one or more * queries *. For example lets say we want to have the union of two queries obtained from the: meth: filter method:: query = session. query ( MyModel ) qs = query. filter ( field1 = bla ). union ( query. filter ( field2 = foo )) | def union(self, *queries):
'''Return a new :class:`Query` obtained form the union of this
:class:`Query` with one or more *queries*.
For example, lets say we want to have the union
of two queries obtained from the :meth:`filter` method::
query = session.query(MyModel)
qs = query.filter(field1 = ... |
Return a new: class: Query obtained form the intersection of this: class: Query with one or more * queries *. Workds the same way as the: meth: union method. | def intersect(self, *queries):
'''Return a new :class:`Query` obtained form the intersection of this
:class:`Query` with one or more *queries*. Workds the same way as
the :meth:`union` method.'''
q = self._clone()
q.intersections += queries
return q |
Sort the query by the given field: parameter ordering: a string indicating the class: Field name to sort by. If prefixed with - the sorting will be in descending order otherwise in ascending order.: return type: a new: class: Query instance. | def sort_by(self, ordering):
'''Sort the query by the given field
:parameter ordering: a string indicating the class:`Field` name to sort by.
If prefixed with ``-``, the sorting will be in descending order, otherwise
in ascending order.
:return type: a new :class:`Query` instance.
'''
i... |
Search * text * in model. A search engine needs to be installed for this function to be available.: parameter text: a string to search.: return type: a new: class: Query instance. | def search(self, text, lookup=None):
'''Search *text* in model. A search engine needs to be installed
for this function to be available.
:parameter text: a string to search.
:return type: a new :class:`Query` instance.
'''
q = self._clone()
q.text = (text, lookup)
return q |
For: ref: backend <db - index > supporting scripting it is possible to construct complex queries which execute the scripting * code * against each element in the query. The * coe * should reference an instance of: attr: model by this keyword.: parameter code: a valid expression in the scripting language of the database... | def where(self, code, load_only=None):
'''For :ref:`backend <db-index>` supporting scripting, it is possible
to construct complex queries which execute the scripting *code* against
each element in the query. The *coe* should reference an instance of
:attr:`model` by ``this`` keyword.
:parameter code: a v... |
Return a new: class: QueryElem for * q * applying a text search. | def search_queries(self, q):
'''Return a new :class:`QueryElem` for *q* applying a text search.'''
if self.text:
searchengine = self.session.router.search_engine
if searchengine:
return searchengine.search_model(q, *self.text)
else:
... |
It returns a new: class: Query that automatically follows the foreign - key relationship related.: parameter related: A field name corresponding to a: class: ForeignKey in: attr: Query. model.: parameter related_fields: optional: class: Field names for the related model to load. If not provided all fields will be loade... | def load_related(self, related, *related_fields):
'''It returns a new :class:`Query` that automatically
follows the foreign-key relationship ``related``.
:parameter related: A field name corresponding to a :class:`ForeignKey`
in :attr:`Query.model`.
:parameter related_fields: optional :class:`Field` ... |
This is provides a: ref: performance boost <increase - performance > in cases when you need to load a subset of fields of your model. The boost achieved is less than the one obtained when using: meth: Query. load_related since it does not reduce the number of requests to the database. However it can save you lots of ba... | def load_only(self, *fields):
'''This is provides a :ref:`performance boost <increase-performance>`
in cases when you need to load a subset of fields of your model. The boost
achieved is less than the one obtained when using
:meth:`Query.load_related`, since it does not reduce the number of requests
to the... |
Works like: meth: load_only to provides a: ref: performance boost <increase - performance > in cases when you need to load all fields except a subset specified by * fields *. | def dont_load(self, *fields):
'''Works like :meth:`load_only` to provides a
:ref:`performance boost <increase-performance>` in cases when you need
to load all fields except a subset specified by *fields*.
'''
q = self._clone()
fs = unique_tuple(q.exclude_fields, fields)
q.exclude_... |
Return an instance of a model matching the query. A special case is the query on id which provides a direct access to the: attr: session instances. If the given primary key is present in the session the object is returned directly without performing any query. | def get(self, **kwargs):
'''Return an instance of a model matching the query. A special case is
the query on ``id`` which provides a direct access to the :attr:`session`
instances. If the given primary key is present in the session, the object
is returned directly without performing any query.'''
r... |
Build the: class: QueryElement representing this query. | def construct(self):
'''Build the :class:`QueryElement` representing this query.'''
if self.__construct is None:
self.__construct = self._construct()
return self.__construct |
Build and return the: class: stdnet. utils. async. BackendQuery. This is a lazy method in the sense that it is evaluated once only and its result stored for future retrieval. | def backend_query(self, **kwargs):
'''Build and return the :class:`stdnet.utils.async.BackendQuery`.
This is a lazy method in the sense that it is evaluated once only and its
result stored for future retrieval.'''
q = self.construct()
return q if isinstance(q, EmptyQuery) else q.backend_que... |
Aggregate lookup parameters. | def aggregate(self, kwargs):
'''Aggregate lookup parameters.'''
meta = self._meta
fields = meta.dfields
field_lookups = {}
for name, value in iteritems(kwargs):
bits = name.split(JSPLITTER)
field_name = bits.pop(0)
if field_name not in ... |
Generator of all model in model. | def models_from_model(model, include_related=False, exclude=None):
'''Generator of all model in model.'''
if exclude is None:
exclude = set()
if model and model not in exclude:
exclude.add(model)
if isinstance(model, ModelType) and not model._meta.abstract:
yield model
... |
A generator of: class: StdModel classes found in * application *. | def model_iterator(application, include_related=True, exclude=None):
'''A generator of :class:`StdModel` classes found in *application*.
:parameter application: A python dotted path or an iterable over python
dotted-paths where models are defined.
Only models defined in these paths are considered.
For exampl... |
Set the search engine for this: class: Router. | def set_search_engine(self, engine):
'''Set the search ``engine`` for this :class:`Router`.'''
self._search_engine = engine
self._search_engine.set_router(self) |
Register a: class: Model with this: class: Router. If the model was already registered it does nothing. | def register(self, model, backend=None, read_backend=None,
include_related=True, **params):
'''Register a :class:`Model` with this :class:`Router`. If the
model was already registered it does nothing.
:param model: a :class:`Model` class.
:param backend: a :class:`stdnet.BackendDataServer` or ... |
Retrieve a: class: Model from its universally unique identifier uuid. If the uuid does not match any instance an exception will raise. | def from_uuid(self, uuid, session=None):
'''Retrieve a :class:`Model` from its universally unique identifier
``uuid``. If the ``uuid`` does not match any instance an exception will raise.
'''
elems = uuid.split('.')
if len(elems) == 2:
model = get_model_from_hash(elems[0])
... |
Flush: attr: registered_models. | def flush(self, exclude=None, include=None, dryrun=False):
'''Flush :attr:`registered_models`.
:param exclude: optional list of model names to exclude.
:param include: optional list of model names to include.
:param dryrun: Doesn't remove anything, simply collect managers
to... |
Unregister a model if provided otherwise it unregister all registered models. Return a list of unregistered model managers or None if no managers were removed. | def unregister(self, model=None):
'''Unregister a ``model`` if provided, otherwise it unregister all
registered models. Return a list of unregistered model managers or ``None``
if no managers were removed.'''
if model is not None:
try:
manager = self._registered_models.pop(mo... |
A higher level registration functions for group of models located on application modules. It uses the: func: model_iterator function to iterate through all: class: Model models available in applications and register them using the: func: register low level method. | def register_applications(self, applications, models=None, backends=None):
'''A higher level registration functions for group of models located
on application modules.
It uses the :func:`model_iterator` function to iterate
through all :class:`Model` models available in ``applications``
and register them using t... |
Execute a script. | def execute_script(self, name, keys, *args, **options):
'''Execute a script.
makes sure all required scripts are loaded.
'''
script = get_script(name)
if not script:
raise redis.RedisError('No such script "%s"' % name)
address = self.address()
if addr... |
Register a: class: StdModel with this search: class: SearchEngine. When registering a model every time an instance is created it will be indexed by the search engine.: param model: a: class: StdModel class.: param related: a list of related fields to include in the index. | def register(self, model, related=None):
'''Register a :class:`StdModel` with this search :class:`SearchEngine`.
When registering a model, every time an instance is created, it will be
indexed by the search engine.
:param model: a :class:`StdModel` class.
:param related: a list of related fields to inclu... |
Generator of indexable words in * text *. This functions loop through the: attr: word_middleware attribute to process the text.: param text: string from which to extract words.: param for_search: flag indicating if the the words will be used for search or to index the database. This flug is used in conjunction with the... | def words_from_text(self, text, for_search=False):
'''Generator of indexable words in *text*.
This functions loop through the :attr:`word_middleware` attribute
to process the text.
:param text: string from which to extract words.
:param for_search: flag indicating if the the words will be used for search... |
Add a * middleware * function to the list of: attr: word_middleware for preprocessing words to be indexed.: param middleware: a callable receving an iterable over words.: param for_search: flag indicating if the * middleware * can be used for the text to search. Default: True. | def add_word_middleware(self, middleware, for_search=True):
'''Add a *middleware* function to the list of :attr:`word_middleware`,
for preprocessing words to be indexed.
:param middleware: a callable receving an iterable over words.
:param for_search: flag indicating if the *middleware* can be used for th... |
Return a query for model when it needs to be indexed. | def query(self, model):
'''Return a query for ``model`` when it needs to be indexed.
'''
session = self.router.session()
fields = tuple((f.name for f in model._meta.scalarfields
if f.type == 'text'))
qs = session.query(model).load_only(*fields)
... |
Returns a PEP 386 - compliant version number from * version *. | def get_version(version):
"Returns a PEP 386-compliant version number from *version*."
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
parts = 2 if version[2] == 0 else 3
main = '.'.join(map(str, version[:parts]))
sub = ''
if version[3] == 'alpha' and ve... |
Returns the value of the planet radius over the stellar radius for a given depth: py: obj: d given the: py: class: everest. pysyzygy transit: py: obj: kwargs. | def Get_RpRs(d, **kwargs):
'''
Returns the value of the planet radius over the stellar radius
for a given depth :py:obj:`d`, given
the :py:class:`everest.pysyzygy` transit :py:obj:`kwargs`.
'''
if ps is None:
raise Exception("Unable to import `pysyzygy`.")
def Depth(RpRs, **kwa... |
Returns the value of the stellar density for a given transit duration: py: obj: dur given the: py: class: everest. pysyzygy transit: py: obj: kwargs. | def Get_rhos(dur, **kwargs):
'''
Returns the value of the stellar density for a given transit
duration :py:obj:`dur`, given
the :py:class:`everest.pysyzygy` transit :py:obj:`kwargs`.
'''
if ps is None:
raise Exception("Unable to import `pysyzygy`.")
assert dur >= 0.01 and dur <... |
A Mandel - Agol <http:// adsabs. harvard. edu/ abs/ 2002ApJ... 580L. 171M > _ transit model but with the depth and the duration as primary input variables. | def Transit(time, t0=0., dur=0.1, per=3.56789, depth=0.001, **kwargs):
'''
A `Mandel-Agol <http://adsabs.harvard.edu/abs/2002ApJ...580L.171M>`_
transit model, but with the depth and the duration as primary
input variables.
:param numpy.ndarray time: The time array
:param float t0: The time of f... |
Given a startdate and an enddate dates evaluate the date intervals from which data is not available. It return a list of two - dimensional tuples containing start and end date for the interval. The list could contain 0 1 or 2 tuples. | def intervals(self, startdate, enddate, parseinterval=None):
'''Given a ``startdate`` and an ``enddate`` dates, evaluate the
date intervals from which data is not available. It return a list
of two-dimensional tuples containing start and end date for the
interval. The list could cont... |
Return the front pair of the structure | def front(self, *fields):
'''Return the front pair of the structure'''
v, f = tuple(self.irange(0, 0, fields=fields))
if v:
return (v[0], dict(((field, f[field][0]) for field in f))) |
Perform a multivariate statistic calculation of this: class: ColumnTS from * start * to * end *.: param start: Optional index ( rank ) where to start the analysis.: param end: Optional index ( rank ) where to end the analysis.: param fields: Optional subset of: meth: fields to perform analysis on. If not provided all f... | def istats(self, start=0, end=-1, fields=None):
'''Perform a multivariate statistic calculation of this
:class:`ColumnTS` from *start* to *end*.
:param start: Optional index (rank) where to start the analysis.
:param end: Optional index (rank) where to end the analysis.
:param fields: Optional subset of ... |
Perform a multivariate statistic calculation of this: class: ColumnTS from a * start * date/ datetime to an * end * date/ datetime.: param start: Start date for analysis.: param end: End date for analysis.: param fields: Optional subset of: meth: fields to perform analysis on. If not provided all fields are included in... | def stats(self, start, end, fields=None):
'''Perform a multivariate statistic calculation of this
:class:`ColumnTS` from a *start* date/datetime to an
*end* date/datetime.
:param start: Start date for analysis.
:param end: End date for analysis.
:param fields: Optional subset of :meth:`fields` to perfo... |
Perform cross multivariate statistics calculation of this: class: ColumnTS and other optional * series * from * start * to * end *.: parameter start: the start rank.: parameter start: the end rank: parameter field: name of field to perform multivariate statistics.: parameter series: a list of two elements tuple contain... | def imulti_stats(self, start=0, end=-1, series=None, fields=None,
stats=None):
'''Perform cross multivariate statistics calculation of
this :class:`ColumnTS` and other optional *series* from *start*
to *end*.
:parameter start: the start rank.
:parameter start: the end rank
:paramet... |
Merge this: class: ColumnTS with several other * series *.: parameters series: a list of tuples where the nth element is a tuple of the form:: ( wight_n ts_n1 ts_n2... ts_nMn ) The result will be calculated using the formula:: ts = weight_1 * ts_11 * ts_12 *... * ts_1M1 + weight_2 * ts_21 * ts_22 *... * ts_2M2 +... | def merge(self, *series, **kwargs):
'''Merge this :class:`ColumnTS` with several other *series*.
:parameters series: a list of tuples where the nth element is a tuple
of the form::
(wight_n, ts_n1, ts_n2, ..., ts_nMn)
The result will be calculated using the formula::
ts = weight_1*ts_1... |
Merge series and return the results without storing data in the backend server. | def merged_series(cls, *series, **kwargs):
'''Merge ``series`` and return the results without storing data
in the backend server.'''
router, backend = cls.check_router(None, *series)
if backend:
target = router.register(cls(), backend)
router.session().add(target)
... |
Return the 0 - based index ( rank ) of score. If the score is not available it returns a negative integer which absolute score is the left most closest index with score less than * score *. | def rank(self, score):
'''Return the 0-based index (rank) of ``score``. If the score is not
available it returns a negative integer which absolute score is the
left most closest index with score less than *score*.'''
node = self.__head
rank = 0
for i in range(self.__level-1, -1, -1):
... |
Create a new instance of: attr: model from a * state * tuple. | def make_object(self, state=None, backend=None):
'''Create a new instance of :attr:`model` from a *state* tuple.'''
model = self.model
obj = model.__new__(model)
self.load_state(obj, state, backend)
return obj |
Perform validation for * instance * and stores serialized data indexes and errors into local cache. Return True if the instance is ready to be saved to database. | def is_valid(self, instance):
'''Perform validation for *instance* and stores serialized data,
indexes and errors into local cache.
Return ``True`` if the instance is ready to be saved to database.'''
dbdata = instance.dbdata
data = dbdata['cleaned_data'] = {}
errors = dbdata['erro... |
Return a two elements tuple containing a list of fields names and a list of field attribute names. | def backend_fields(self, fields):
'''Return a two elements tuple containing a list
of fields names and a list of field attribute names.'''
dfields = self.dfields
processed = set()
names = []
atts = []
pkname = self.pkname()
for name in fields:
... |
Model metadata in a dictionary | def as_dict(self):
'''Model metadata in a dictionary'''
pk = self.pk
id_type = 3
if pk.type == 'auto':
id_type = 1
return {'id_name': pk.name,
'id_type': id_type,
'sorted': bool(self.ordering),
'autoincr': self.... |
Return the current: class: ModelState for this: class: Model. If kwargs parameters are passed a new: class: ModelState is created otherwise it returns the cached value. | def get_state(self, **kwargs):
'''Return the current :class:`ModelState` for this :class:`Model`.
If ``kwargs`` parameters are passed a new :class:`ModelState` is created,
otherwise it returns the cached value.'''
dbdata = self.dbdata
if 'state' not in dbdata or kwargs:
dbdata[... |
Universally unique identifier for an instance of a: class: Model. | def uuid(self):
'''Universally unique identifier for an instance of a :class:`Model`.
'''
pk = self.pkvalue()
if not pk:
raise self.DoesNotExist(
'Object not saved. Cannot obtain universally unique id')
return self.get_uuid(pk) |
The: class: stdnet. BackendDatServer for this instance. It can be None. | def backend(self, client=None):
'''The :class:`stdnet.BackendDatServer` for this instance.
It can be ``None``.
'''
session = self.session
if session:
return session.model(self).backend |
The read: class: stdnet. BackendDatServer for this instance. It can be None. | def read_backend(self, client=None):
'''The read :class:`stdnet.BackendDatServer` for this instance.
It can be ``None``.
'''
session = self.session
if session:
return session.model(self).read_backend |
Create a: class: Model class for objects requiring and interface similar to: class: StdModel. We refers to this type of models as: ref: local models <local - models > since instances of such models are not persistent on a: class: stdnet. BackendDataServer. | def create_model(name, *attributes, **params):
'''Create a :class:`Model` class for objects requiring
and interface similar to :class:`StdModel`. We refers to this type
of models as :ref:`local models <local-models>` since instances of such
models are not persistent on a :class:`stdnet.BackendDataServer`.
:param n... |
Generator of fields loaded from database | def loadedfields(self):
'''Generator of fields loaded from database'''
if self._loadedfields is None:
for field in self._meta.scalarfields:
yield field
else:
fields = self._meta.dfields
processed = set()
for name in self._loadedfiel... |
Generator of fields values pairs. Fields correspond to the ones which have been loaded ( usually all of them ) or not loaded but modified. Check the: ref: load_only <performance - loadonly > query function for more details. | def fieldvalue_pairs(self, exclude_cache=False):
'''Generator of fields,values pairs. Fields correspond to
the ones which have been loaded (usually all of them) or
not loaded but modified.
Check the :ref:`load_only <performance-loadonly>` query function for more
details.
If *exclude_cache* evaluates to ``True`... |
Set cache fields to None. Check: attr: Field. as_cache for information regarding fields which are considered cache. | def clear_cache_fields(self):
'''Set cache fields to ``None``. Check :attr:`Field.as_cache`
for information regarding fields which are considered cache.'''
for field in self._meta.scalarfields:
if field.as_cache:
setattr(self, field.name, None) |
Retrieve the value for the attribute name. The name can be nested following the: ref: double underscore <tutorial - underscore > notation for example group__name. If the attribute is not available it raises: class: AttributeError. | def get_attr_value(self, name):
'''Retrieve the ``value`` for the attribute ``name``. The ``name``
can be nested following the :ref:`double underscore <tutorial-underscore>`
notation, for example ``group__name``. If the attribute is not available it
raises :class:`AttributeError`.'''
if name in self._me... |
Utility method for cloning the instance as a new object. | def clone(self, **data):
'''Utility method for cloning the instance as a new object.
:parameter data: additional which override field data.
:rtype: a new instance of this class.
'''
meta = self._meta
session = self.session
pkname = meta.pkname()
pkvalue = data.pop(pkname, None)
... |
Return a dictionary of serialised scalar field for pickling. If the * exclude_cache * flag is True fields with: attr: Field. as_cache attribute set to True will be excluded. | def todict(self, exclude_cache=False):
'''Return a dictionary of serialised scalar field for pickling.
If the *exclude_cache* flag is ``True``, fields with :attr:`Field.as_cache`
attribute set to ``True`` will be excluded.'''
odict = {}
for field, value in self.fieldvalue_pairs(exclude_cache=exc... |
Load extra fields to this: class: StdModel. | def load_fields(self, *fields):
'''Load extra fields to this :class:`StdModel`.'''
if self._loadedfields is not None:
if self.session is None:
raise SessionNotAvailable('No session available')
meta = self._meta
kwargs = {meta.pkname(): self.pkvalue()}
... |
Load a the: class: ForeignKey field name if this is part of the fields of this model and if the related object is not already loaded. It is used by the lazy loading mechanism of: ref: one - to - many <one - to - many > relationships. | def load_related_model(self, name, load_only=None, dont_load=None):
'''Load a the :class:`ForeignKey` field ``name`` if this is part of the
fields of this model and if the related object is not already loaded.
It is used by the lazy loading mechanism of :ref:`one-to-many <one-to-many>`
relationships.
:paramete... |
Load a: class: StdModel from possibly base64encoded data. | def from_base64_data(cls, **kwargs):
'''Load a :class:`StdModel` from possibly base64encoded data.
This method is used to load models from data obtained from the :meth:`tojson`
method.'''
o = cls()
meta = cls._meta
pkname = meta.pkname()
for name, value in iteritems(kwargs):
... |
De - trend a K2 FITS file using: py: class: everest. detrender. rPLD. | def DetrendFITS(fitsfile, raw=False, season=None, clobber=False, **kwargs):
"""
De-trend a K2 FITS file using :py:class:`everest.detrender.rPLD`.
:param str fitsfile: The full path to the FITS file
:param ndarray aperture: A 2D integer array corresponding to the \
desired photometric apertur... |
Returns a: py: obj: DataContainer instance with the raw data for the target. | def GetData(fitsfile, EPIC, campaign, clobber=False,
saturation_tolerance=-0.1,
bad_bits=[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17],
get_hires=False, get_nearby=False,
aperture=None, **kwargs):
'''
Returns a :py:obj:`DataContainer` instance with the
r... |
Returns the axis instance where the title will be printed | def title(self):
'''
Returns the axis instance where the title will be printed
'''
return self.title_left(on=False), self.title_center(on=False), \
self.title_right(on=False) |
Returns the axis instance where the footer will be printed | def footer(self):
'''
Returns the axis instance where the footer will be printed
'''
return self.footer_left(on=False), self.footer_center(on=False), \
self.footer_right(on=False) |
Returns the axis instance at the top right of the page where the postage stamp and aperture is displayed | def top_right(self):
'''
Returns the axis instance at the top right of the page,
where the postage stamp and aperture is displayed
'''
res = self.body_top_right[self.tcount]()
self.tcount += 1
return res |
Returns the current axis instance on the left side of the page where each successive light curve is displayed | def left(self):
'''
Returns the current axis instance on the left side of
the page where each successive light curve is displayed
'''
res = self.body_left[self.lcount]()
self.lcount += 1
return res |
Returns the current axis instance on the right side of the page where cross - validation information is displayed | def right(self):
'''
Returns the current axis instance on the right side of the
page, where cross-validation information is displayed
'''
res = self.body_right[self.rcount]()
self.rcount += 1
return res |
Returns the axis instance where the light curves will be shown | def body(self):
'''
Returns the axis instance where the light curves will be shown
'''
res = self._body[self.bcount]()
self.bcount += 1
return res |
Calculate the Hash id of metaclass meta | def hashmodel(model, library=None):
'''Calculate the Hash id of metaclass ``meta``'''
library = library or 'python-stdnet'
meta = model._meta
sha = hashlib.sha1(to_bytes('{0}({1})'.format(library, meta)))
hash = sha.hexdigest()[:8]
meta.hash = hash
if hash in _model_dict:
rai... |
Bind a callback for a given sender. | def bind(self, callback, sender=None):
'''Bind a ``callback`` for a given ``sender``.'''
key = (_make_id(callback), _make_id(sender))
self.callbacks.append((key, callback)) |
Fire callbacks from a sender. | def fire(self, sender=None, **params):
'''Fire callbacks from a ``sender``.'''
keys = (_make_id(None), _make_id(sender))
results = []
for (_, key), callback in self.callbacks:
if key in keys:
results.append(callback(self, sender, **params))
retu... |
Execute a command and return a parsed response | def execute_command(self, cmnd, *args, **options):
"Execute a command and return a parsed response"
args, options = self.preprocess_command(cmnd, *args, **options)
return self.client.execute_command(cmnd, *args, **options) |
Returns the 10th - 90th percentile range of array: py: obj: x. | def _range10_90(x):
'''
Returns the 10th-90th percentile range of array :py:obj:`x`.
'''
x = np.delete(x, np.where(np.isnan(x)))
i = np.argsort(x)
a = int(0.1 * len(x))
b = int(0.9 * len(x))
return x[i][b] - x[i][a] |
Returns the campaign number ( s ) for a given EPIC target. If target is not found returns: py: obj: None. | def Campaign(EPIC, **kwargs):
'''
Returns the campaign number(s) for a given EPIC target. If target
is not found, returns :py:obj:`None`.
:param int EPIC: The EPIC number of the target.
'''
campaigns = []
for campaign, stars in GetK2Stars().items():
if EPIC in [s[0] for s in stars... |
Download and return a: py: obj: dict of all * K2 * stars organized by campaign. Saves each campaign to a. stars file in the everest/ missions/ k2/ tables directory. | def GetK2Stars(clobber=False):
'''
Download and return a :py:obj:`dict` of all *K2* stars organized by
campaign. Saves each campaign to a `.stars` file in the
`everest/missions/k2/tables` directory.
:param bool clobber: If :py:obj:`True`, download and overwrite \
existing files. Default ... |
Return all stars in a given * K2 * campaign. | def GetK2Campaign(campaign, clobber=False, split=False,
epics_only=False, cadence='lc'):
'''
Return all stars in a given *K2* campaign.
:param campaign: The *K2* campaign number. If this is an :py:class:`int`, \
returns all targets in that campaign. If a :py:class:`float` in \
... |
Returns the channel number for a given EPIC target. | def Channel(EPIC, campaign=None):
'''
Returns the channel number for a given EPIC target.
'''
if campaign is None:
campaign = Campaign(EPIC)
if hasattr(campaign, '__len__'):
raise AttributeError(
"Please choose a campaign/season for this target: %s." % campaign)
try... |
Returns the module number for a given EPIC target. | def Module(EPIC, campaign=None):
'''
Returns the module number for a given EPIC target.
'''
channel = Channel(EPIC, campaign=campaign)
nums = {2: 1, 3: 5, 4: 9, 6: 13, 7: 17, 8: 21, 9: 25,
10: 29, 11: 33, 12: 37, 13: 41, 14: 45, 15: 49,
16: 53, 17: 57, 18: 61, 19: 65, 20: 6... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.