text stringlengths 81 112k |
|---|
Runs a Django management command
def management_command(self, command, *args, **kwargs):
"""
Runs a Django management command
"""
self.setup_django()
if 'verbosity' not in kwargs:
kwargs['verbosity'] = self.verbosity
if not self.use_colour:
kwargs... |
Prints this help (use --verbosity 2 for more details)
def help(self, context):
"""
Prints this help (use --verbosity 2 for more details)
"""
context.info('%s\n%s [global options] [task] [task options]...\n' % (self.name, sys.argv[0]))
def print_parameter(prn, p):
if... |
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
def login(request, user):
"""
Persist a user id and a backend in the request. This way a user doesn't
h... |
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `MojAnonymousUser` is returned.
def get_user(request):
"""
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `MojAnonymousUse... |
Removes the authenticated user's ID from the request and flushes their
session data.
def logout(request):
"""
Removes the authenticated user's ID from the request and flushes their
session data.
"""
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find... |
Save word embedding file.
Check :func:`word_embedding_loader.saver.glove.save` for the API.
def save(f, arr, vocab):
"""
Save word embedding file.
Check :func:`word_embedding_loader.saver.glove.save` for the API.
"""
f.write(('%d %d' % (arr.shape[0], arr.shape[1])).encode('utf-8'))
for word... |
Decorates a function to make it spoolable using uWSGI, but if no spooling mechanism is available,
the function is called synchronously. All decorated function arguments must be picklable and
the first annotated with `Context` will receive an object that defines the current execution state.
Return values are... |
return all the fields and their raw values for this Orm instance. This
property returns a dict with the field names and their current values
if you want to control the values for outputting to an api, use .jsonable()
def fields(self):
"""
return all the fields and their raw values for ... |
create an instance of cls with the passed in fields and set it into the db
fields -- dict -- field_name keys, with their respective values
**fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also
def create(cls, fields=None, **fields_kwargs):
"""
creat... |
take the passed in fields, combine them with missing fields that should
be there and then run all those through appropriate methods to hydrate this
orm.
The method replaces cls.hydrate() since it was becoming hard to understand
what was going on with all these methods that did things ju... |
this runs all the fields through their iget methods to mimic them
freshly coming out of the db, then resets modified
:param fields: dict, the fields that were passed in
def _populate(self, fields):
"""this runs all the fields through their iget methods to mimic them
freshly coming out ... |
Get all the fields that need to be saved
:param is_udpate: bool, True if update query, False if insert
:returns: dict, key is field_name and val is the field value to be saved
def depopulate(self, is_update):
"""Get all the fields that need to be saved
:param is_udpate: bool, True if ... |
persist the field values of this orm
def insert(self):
"""persist the field values of this orm"""
ret = True
schema = self.schema
fields = self.depopulate(False)
q = self.query
q.set_fields(fields)
pk = q.insert()
if pk:
fields = q.fields
... |
re-persist the updated field values of this orm that has a primary key
def update(self):
"""re-persist the updated field values of this orm that has a primary key"""
ret = True
fields = self.depopulate(True)
q = self.query
q.set_fields(fields)
pk = self.pk
if pk... |
persist the fields in this object into the db, this will update if _id is set, otherwise
it will insert
see also -- .insert(), .update()
def save(self):
"""
persist the fields in this object into the db, this will update if _id is set, otherwise
it will insert
see also... |
delete the object from the db if pk is set
def delete(self):
"""delete the object from the db if pk is set"""
ret = False
q = self.query
pk = self.pk
if pk:
pk_name = self.schema.pk.name
self.query.is_field(pk_name, pk).delete()
setattr(self, ... |
reset field modification tracking
this is handy for when you are loading a new Orm with the results from a query and
you don't want set() to do anything, you can Orm(**fields) and then orm.reset_modified() to
clear all the passed in fields from the modified list
def reset_modified(self):
... |
update the fields of this instance with the values in dict fields
this should rarely be messed with, if you would like to manipulate the
fields you should override _modify()
:param fields: dict, the fields in a dict
:param **fields_kwargs: dict, if you would like to pass the fields as ... |
return a public version of this instance that can be jsonified
Note that this does not return _id, _created, _updated, the reason why is
because lots of times you have a different name for _id (like if it is a
user object, then you might want to call it user_id instead of _id) and I
di... |
Merge 2 EMIR images, averaging the common region.
Parameters
----------
hdu1 : HDUList object
Input image #1.
hdu2 : HDUList object
Input image #2.
debugplot : int
Determines whether intermediate computations and/or plots
are displayed. The valid codes are defined in... |
configure interfaces based on environment variables
by default, when prom is imported, it will look for PROM_DSN, and PROM_DSN_N (where
N is 1 through infinity) in the environment, if it finds them, it will assume they
are dsn urls that prom understands and will configure db connections with them. If you
... |
configure an interface to be used to query a backend
you use this function to configure an Interface using a dsn, then you can get
that interface using the get_interface() method
dsn -- string -- a properly formatted prom dsn, see DsnConnection for how to format the dsn
def configure(dsn, connection_clas... |
don't want to bother with a dsn? Use this method to make an interface available
def set_interface(interface, name=''):
"""
don't want to bother with a dsn? Use this method to make an interface available
"""
global interfaces
if not interface: raise ValueError('interface is empty')
# close dow... |
A context manager which serves this websocket.
:param filter: an async callback which accepts the connection request
and returns a bool, or an explicit Accept/Reject message.
async def open_websocket_server(sock, filter=None): # pylint: disable=W0622
"""
A context manager which serves this websocket.... |
A more low-level form of open_websocket_server.
You are responsible for closing this websocket.
async def create_websocket_server(sock, filter=None): # pylint: disable=W0622
"""
A more low-level form of open_websocket_server.
You are responsible for closing this websocket.
"""
ws = Websocket()... |
fields that aren't magic (eg, aren't _id, _created, _updated)
def normal_fields(self):
"""fields that aren't magic (eg, aren't _id, _created, _updated)"""
return {f:v for f, v in self.fields.items() if not f.startswith('_')} |
The normal required fields (eg, no magic fields like _id are included)
def required_fields(self):
"""The normal required fields (eg, no magic fields like _id are included)"""
return {f:v for f, v in self.normal_fields.items() if v.required} |
the magic fields for the schema
def magic_fields(self):
"""the magic fields for the schema"""
return {f:v for f, v in self.fields.items() if f.startswith('_')} |
add an index to the schema
for the most part, you will use the __getattr__ method of adding indexes for a more fluid interface,
but you can use this if you want to get closer to the bare metal
index_name -- string -- the name of the index
index -- Index() -- an Index instance
def set_... |
return the schema instance if this is reference to another table
def schema(self):
"""return the schema instance if this is reference to another table"""
if not hasattr(self, "_schema"):
ret = None
o = self._type
if isinstance(o, type):
ret = getattr(... |
return the raw value that this property is holding internally for instance
def fval(self, instance):
"""return the raw value that this property is holding internally for instance"""
try:
val = instance.__dict__[self.instance_field_name]
except KeyError as e:
#raise Attri... |
Set the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
{reference}
def set_default_reference(self, method, reference):
"""
Set the default reference for a method.
:arg method: name of a method
:type method: :class:`str... |
Returns the default reference for a method.
:arg method: name of a method
:type method: :class:`str`
:return: reference
:rtype: :class:`Reference <pyxray.descriptor.Reference>` or :class:`str`
def get_default_reference(self, method):
"""
Returns the default reference f... |
Prints all x-ray transitions for an element, with their different
notations and energy.
{element}
:arg file: file for output, default to standard out
def print_element_xray_transitions(self, element, file=sys.stdout, tabulate_kwargs=None):
"""
Prints all x-ray transitions for ... |
return all found modules at modulepath (eg, foo.bar) including modulepath module
def get_modules(modulepath):
"""return all found modules at modulepath (eg, foo.bar) including modulepath module"""
m = importlib.import_module(modulepath)
mpath = m.__file__
ret = set([m])
if "__init__." in mpath.low... |
given a module return all the parent_class subclasses that are found in
that module and any submodules.
:param modulepath: string, a path like foo.bar.che
:param parent_class: object, the class whose children you are looking for
:returns: set, all the found child classes in modulepath of parent_class
... |
pass in an array, when you encounter a ref, call this method again with the array
when something has no more refs, then it gets appended to the array and returns, each
time something gets through the list they are added, but before they are added to the
list it is checked to see if it is already in the list... |
this will return prom.Orm classes found in the given path (classpath or modulepath)
def get_orm_classes(path):
"""this will return prom.Orm classes found in the given path (classpath or modulepath)"""
ret = set()
try:
m = importlib.import_module(path)
except ImportError:
# we have a cl... |
dump all or part of the prom data, currently only works on Postgres databases
basically just a wrapper around `dump backup` https://github.com/Jaymon/dump
def main_dump(paths, directory, dry_run):
"""dump all or part of the prom data, currently only works on Postgres databases
basically just a wrapper ar... |
Restore your database dumped with the dump command
just a wrapper around `dump restore` https://github.com/Jaymon/dump
def main_restore(directory, conn_name):
"""Restore your database dumped with the dump command
just a wrapper around `dump restore` https://github.com/Jaymon/dump
"""
inter = get_... |
return all the fields for the given schema
def _get_fields(self, table_name, **kwargs):
"""return all the fields for the given schema"""
ret = {}
query_str = []
query_args = ['f', table_name]
# I had to brush up on my join knowledge while writing this query
# https://en... |
return all the indexes for the given schema
def _get_indexes(self, schema, **kwargs):
"""return all the indexes for the given schema"""
ret = {}
query_str = []
query_str.append('SELECT')
query_str.append(' tbl.relname AS table_name, i.relname AS index_name, a.attname AS field_n... |
NOTE -- we set the index name using <table_name>_<name> format since indexes have to have
a globally unique name in postgres
http://www.postgresql.org/docs/9.1/static/sql-createindex.html
def _set_index(self, schema, name, fields, **index_options):
"""
NOTE -- we set the index name usi... |
Deal with client authentication
:param request: The refresh access token request
:param auth: Client authentication information
:param kwargs: Extra keyword arguments
:return: dictionary containing client id, client authentication method
and possibly access token.
def clien... |
This is where clients come to get their access tokens
:param request: The request
:param authn: Authentication info, comes from HTTP header
:returns:
def _post_parse_request(self, request, client_id='', **kwargs):
"""
This is where clients come to get their access tokens
... |
Register outputs and metadata.
* ``initial_value`` - used in dynamic calculations
* ``size`` - number of elements per timestep
* ``uncertainty`` - in percent of nominal value
* ``variance`` - dictionary of covariances, diagonal is square of
uncertianties, no units
* ``... |
Classify input frames,
def initial_classification(self, obresult, target_is_sky=False):
"""Classify input frames, """
# lists of targets and sky frames
with obresult.frames[0].open() as baseimg:
# Initial checks
has_bpm_ext = 'BPM' in baseimg
self.logger.deb... |
Read CSU information and slits from header
def read_csu_2(barmodel, hdr):
"""Read CSU information and slits from header"""
conf = CSUConf(barmodel)
conf.conf_f = hdr.get('CSUCONFF', 'UNKNOWN')
# Read CSUPOS and set position in model
# The bars
for idx in conf.bars:
key = "CSUP{}".forma... |
Read CSU information and slits from header
def read_csu_3(barmodel, hdr):
"""Read CSU information and slits from header"""
conf = CSUConf(barmodel)
conf.set_state(hdr)
return conf |
Read CSU information and slits from header
def set_state(self, hdr):
"""Read CSU information and slits from header"""
self.conf_f = hdr.get('CSUCONFF', 'UNKNOWN')
# Read CSUPOS and set position in model
# The bars
for idx in self.bars:
key = "CSUP{}".format(idx)
... |
Recreate slits
def _update_slits(self, hdr):
"""Recreate slits"""
# Slits.
# For the moment we will fuse only reference slits
# clean existing slits
self.slits = {}
mm = []
for idx in self.LBARS:
# References from header
try:
... |
Only sent when not created, since default implementation will
call `self.create` when creating which triggers our signal
already.
def update_or_create(self, *args, **kwargs):
""" Only sent when not created, since default implementation will
call `self.create` when creating w... |
Add a recorded duration.
def update(self, duration):
"""Add a recorded duration."""
if duration >= 0:
self.histogram.update(duration)
self.meter.mark() |
Build the conf of the g5k provider from the vmong5k conf.
def _build_g5k_conf(vmong5k_conf):
"""Build the conf of the g5k provider from the vmong5k conf."""
clusters = [m.cluster for m in vmong5k_conf.machines]
sites = g5k_api_utils.get_clusters_sites(clusters)
site_names = set(sites.values())
if l... |
Copy Django model instance as a dictionary excluding automatically created
fields like an auto-generated sequence as a primary key or an auto-created
many-to-one reverse relation.
:param obj: Django model object
:return: copy of model instance as dictionary
def copy_model_instance(obj):
"""
Co... |
Collects positional and keyword arguments into `data` and applies units.
:return: data
def load_data(self, *args, **kwargs):
"""
Collects positional and keyword arguments into `data` and applies units.
:return: data
"""
# get positional argument names from parameters a... |
Applies units to data when a proxy reader is used. For example if the
data is cached as JSON and retrieved using the
:class:`~simkit.core.data_readers.JSONReader`, then units can be
applied from the original parameter schema.
:param data: Data read by proxy reader.
:return: data... |
Apply units to model.
:return: data
def load_data(self, model_instance, *args, **kwargs):
"""
Apply units to model.
:return: data
"""
model_dict = copy_model_instance(model_instance)
return super(DjangoModelReader, self).load_data(**model_dict) |
Decorator for caching/retrieving api calls request.
Many calls to the API are getter on static parts (e.g site of a given
cluster name won't change). By caching some responses we can avoid
hammering the API server.
def cached(f):
"""Decorator for caching/retrieving api calls request.
Many calls t... |
Gets the reference to the API cient (singleton).
def get_api_client():
"""Gets the reference to the API cient (singleton)."""
with _api_lock:
global _api_client
if not _api_client:
conf_file = os.path.join(os.environ.get("HOME"),
".python-grid500... |
Reload all running or pending jobs of Grid'5000 with a given name.
By default all the sites will be searched for jobs with the name
``job_name``. Using EnOSlib there can be only one job per site with name
``job_name``.
Note that it honors the ``exluded_sites`` attribute of the client so the
scan c... |
Reload all running or pending jobs of Grid'5000 from their ids
Args:
oargrid_jobids (list): list of ``(site, oar_jobid)`` identifying the
jobs on each site
Returns:
The list of python-grid5000 jobs retrieved
def grid_reload_from_ids(oargrid_jobids):
"""Reload all running or pe... |
Destroy all the jobs with a given name.
Args:
job_name (str): the job name
def grid_destroy_from_name(job_name):
"""Destroy all the jobs with a given name.
Args:
job_name (str): the job name
"""
jobs = grid_reload_from_name(job_name)
for job in jobs:
job.delete()
... |
Destroy all the jobs with corresponding ids
Args:
oargrid_jobids (list): the ``(site, oar_job_id)`` list of tuple
identifying the jobs for each site.
def grid_destroy_from_ids(oargrid_jobids):
"""Destroy all the jobs with corresponding ids
Args:
oargrid_jobids (list): the ``(s... |
Submit a job
Args:
job_spec (dict): The job specifiation (see Grid'5000 API reference)
def submit_jobs(job_specs):
"""Submit a job
Args:
job_spec (dict): The job specifiation (see Grid'5000 API reference)
"""
gk = get_api_client()
jobs = []
try:
for site, job_spec ... |
Waits for all the jobs to be runnning.
Args:
jobs(list): list of the python-grid5000 jobs to wait for
Raises:
Exception: if one of the job gets in error state.
def wait_for_jobs(jobs):
"""Waits for all the jobs to be runnning.
Args:
jobs(list): list of the python-grid5000 jo... |
Deploy and wait for the deployment to be finished.
Args:
site(str): the site
nodes(list): list of nodes (str) to depoy
options(dict): option of the deployment (refer to the Grid'5000 API
Specifications)
Returns:
tuple of deployed(list), undeployed(list) nodes.
def ... |
Set the interface of the nodes in a specific vlan.
It is assumed that the same interface name is available on the node.
Args:
site(str): site to consider
nodes(list): nodes to consider
interface(str): the network interface to put in the vlan
vlan_id(str): the id of the vlan
de... |
Get all the corresponding sites of the passed clusters.
Args:
clusters(list): list of string uid of sites (e.g 'rennes')
Return:
dict corresponding to the mapping cluster uid to python-grid5000 site
def clusters_sites_obj(clusters):
"""Get all the corresponding sites of the passed cluster... |
Get all the cluster of all the sites.
Returns:
dict corresponding to the mapping cluster uid to python-grid5000 site
def get_all_clusters_sites():
"""Get all the cluster of all the sites.
Returns:
dict corresponding to the mapping cluster uid to python-grid5000 site
"""
result = {... |
Get all the nodes of a given cluster.
Args:
cluster(string): uid of the cluster (e.g 'rennes')
def get_nodes(cluster):
"""Get all the nodes of a given cluster.
Args:
cluster(string): uid of the cluster (e.g 'rennes')
"""
gk = get_api_client()
site = get_cluster_site(cluster)
... |
Get the network interfaces names corresponding to a criteria.
Note that the cluster is passed (not the individual node names), thus it is
assumed that all nodes in a cluster have the same interface names same
configuration. In addition to ``extra_cond``, only the mountable and
Ehernet interfaces are re... |
Returns for each cluster the available cluster interfaces
Args:
clusters (str): list of the clusters
extra_cond (lambda): extra predicate to filter network card retrieved
from the API. E.g lambda nic: not nic['mounted'] will retrieve all the
usable network cards that are not mounted by defa... |
Check if #nodes can be started on a given cluster.
This is intended to give a good enough approximation.
This can be use to prefiltered possible reservation dates before submitting
them on oar.
def can_start_on_cluster(nodes_status,
nodes,
start,
... |
This returns a common reservation date for all the jobs.
This reservation date is really only a hint and will be supplied to each
oar server. Without this *common* reservation_date, one oar server can
decide to postpone the start of the job while the other are already
running. But this doens't prevent ... |
Break an iterable into lists of a given length::
>>> list(chunked([1, 2, 3, 4, 5, 6, 7], 3))
[[1, 2, 3], [4, 5, 6], [7]]
If the length of ``iterable`` is not evenly divisible by ``n``, the last
returned list will be shorter.
This is useful for splitting up a computation on a large number ... |
Add data to given room's state
def add_data(self, rawdata):
"""Add data to given room's state"""
for data in rawdata:
try:
item = data[0]
if item[0] == 2:
# Flush messages but we got nothing to flush
continue
... |
Register callback that we will have to wait for
def register_callback(self):
"""Register callback that we will have to wait for"""
cid = str(self.__cid)
self.__cid += 1
event = queue.Queue()
self.__callbacks[cid] = event
return cid, event |
Handle Lain being helpful
def _handle_401(self, data):
"""Handle Lain being helpful"""
ex = ConnectionError(
"Can't login to a protected room without a proper password", data
)
self.conn.reraise(ex) |
Handle Lain being helpful
def _handle_429(self, data):
"""Handle Lain being helpful"""
ex = IOError("Too fast", data)
self.conn.reraise(ex) |
Handle lain's callback. Only used with getFileinfo so far
def _handle_callback(self, data):
"""Handle lain's callback. Only used with getFileinfo so far"""
cb_id = data.get("id")
args = data.get("args")
event = self.__callbacks.pop(cb_id, None)
if not event:
return
... |
Handle user count changes
def _handle_userCount(self, data):
"""Handle user count changes"""
self.room.user_count = data
self.conn.enqueue_data("user_count", self.room.user_count) |
Handle user information
def _handle_userInfo(self, data):
"""Handle user information"""
for k, v in data.items():
if k == "nick":
if v == "None":
v = "Volaphile"
setattr(self.room.user, k, v)
self.conn.enqueue_data(k, self... |
Handle keys
def _handle_key(self, data):
"""Handle keys"""
self.room.key = data
self.conn.enqueue_data("key", self.room.key) |
Handle initial config push and config changes
def _handle_config(self, data):
"""Handle initial config push and config changes"""
self.room.config.update(data)
self.conn.enqueue_data("config", data) |
Handle new files being uploaded
def _handle_files(self, data):
"""Handle new files being uploaded"""
initial = data.get("set", False)
files = data["files"]
for f in files:
try:
fobj = File(
self.room,
self.conn,
... |
Handle files being removed
def _handle_delete_file(self, data):
"""Handle files being removed"""
file = self.room.filedict.get(data)
if file:
self.room.filedict = data, None
self.conn.enqueue_data("delete_file", file) |
Handle chat messages
def _handle_chat(self, data):
"""Handle chat messages"""
self.conn.enqueue_data(
"chat", ChatMessage.from_data(self.room, self.conn, data)
) |
Handle configuration changes
def _handle_changed_config(self, change):
"""Handle configuration changes"""
key, value = change.get("key"), change.get("value")
self.room.config.update({key: value})
self.conn.enqueue_data("config", self.room.config) |
Handle user name changes
def _handle_chat_name(self, data):
"""Handle user name changes"""
self.room.user.nick = data
self.conn.enqueue_data("user", self.room.user) |
Auxiliary function to print out progress in loop of slitlets.
Parameters
----------
islitlet : int
Current slitlet number.
islitlet_max : int
Maximum slitlet number.
def islitlet_progress(islitlet, islitlet_max):
"""Auxiliary function to print out progress in loop of slitlets.
... |
Corrector for intensity flat
def get_corrector_f(rinput, meta, ins, datamodel):
"""Corrector for intensity flat"""
from emirdrp.processing.flatfield import FlatFieldCorrector
flat_info = meta['master_flat']
with rinput.master_flat.open() as hdul:
_logger.info('loading intensity flat')
_... |
Log the contents of Recipe Input
def loginfo(method):
"""Log the contents of Recipe Input"""
def loginfo_method(self, rinput):
klass = rinput.__class__
for key in klass.stored():
val = getattr(rinput, key)
if isinstance(val, DataFrame):
self.logger.de... |
Copy or coerce to a Host.
def to_host(self):
"""Copy or coerce to a Host."""
return Host(self.address,
alias=self.alias,
user=self.user,
keyfile=self.keyfile,
port=self.port,
extra=self.extra) |
Returns a dict with table_name keys mapped to the Interface that table exists in
:param *table_names: the tables you are searching for
def get_table_info(*table_names):
"""Returns a dict with table_name keys mapped to the Interface that table exists in
:param *table_names: the tables you are searching fo... |
This will print out valid prom python code for given tables that already exist
in a database.
This is really handy when you want to bootstrap an existing database to work
with prom and don't want to manually create Orm objects for the tables you want
to use, let `generate` do it for you
def main_gener... |
Convert virtual pixel to real pixel
def exvp(pos_x, pos_y):
"""Convert virtual pixel to real pixel"""
pos_x = numpy.asarray(pos_x)
pos_y = numpy.asarray(pos_y)
# convert virtual pixel to real pixel
# convert world coordinate to pixel
center = [1024.5, 1024.5]
cf = EMIR_PLATESCALE_RADS
... |
Verify that all the values in 'first' appear in 'second'.
The values can either be in the form of lists or as space separated
items.
:param first:
:param second:
:return: True/False
def match_sp_sep(first, second):
"""
Verify that all the values in 'first' appear in 'second'.
The value... |
Verify `sector_identifier_uri` is reachable and that it contains
`redirect_uri`s.
:param request: Provider registration request
:return: si_redirects, sector_id
:raises: InvalidSectorIdentifier
def _verify_sector_identifier(self, request):
"""
Verify `sector_identifier... |
Read and analyse the next line of the SExtractor catalog
and return a dictionary {'param1': value, 'param2': value, ...}.
def readline(self):
"""
Read and analyse the next line of the SExtractor catalog
and return a dictionary {'param1': value, 'param2': value, ...}.
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.