text stringlengths 81 112k |
|---|
sets to all wrapped processors
def set_parameters(self, **args):
"""sets to all wrapped processors"""
not_used = set()
not_given = set()
for p in self.processors:
nu, ng = p.set_parameters(**args)
not_used = not_used.union(nu)
not_given = not_given.un... |
Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child class.
def render(self, filename):
"""Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child cla... |
Prints in standard output report about animation rendering. Namely, it prints seconds spent, number of
frames and step size that is used in functional animation.
def report(self):
"""Prints in standard output report about animation rendering. Namely, it prints seconds spent, number of
frames an... |
Add *address* to the subscribing list for *topics*.
It topics is None we will subscibe to already specified topics.
def add(self, address, topics=None):
"""Add *address* to the subscribing list for *topics*.
It topics is None we will subscibe to already specified topics.
"""
w... |
Remove *address* from the subscribing list for *topics*.
def remove(self, address):
"""Remove *address* from the subscribing list for *topics*.
"""
with self._lock:
try:
subscriber = self.addr_sub[address]
except KeyError:
return False
... |
Updating with a set of addresses.
def update(self, addresses):
"""Updating with a set of addresses.
"""
if isinstance(addresses, six.string_types):
addresses = [addresses, ]
s0_, s1_ = set(self.addresses), set(addresses)
sr_, sa_ = s0_.difference(s1_), s1_.difference... |
Specify a *callback* in the same stream (thread) as the main receive
loop. The callback will be called with the received messages from the
specified subscription.
Good for operations, which is required to be done in the same thread as
the main recieve loop (e.q operations on the underly... |
Same as above, but with a PULL socket.
(e.g good for pushed 'inproc' messages from another thread).
def add_hook_pull(self, address, callback):
"""Same as above, but with a PULL socket.
(e.g good for pushed 'inproc' messages from another thread).
"""
LOGGER.info("Subscriber addi... |
Generic hook. The passed socket has to be "receive only".
def _add_hook(self, socket, callback):
"""Generic hook. The passed socket has to be "receive only".
"""
self._hooks.append(socket)
self._hooks_cb[socket] = callback
if self.poller:
self.poller.register(socket,... |
Receive, optionally with *timeout* in seconds.
def recv(self, timeout=None):
"""Receive, optionally with *timeout* in seconds.
"""
if timeout:
timeout *= 1000.
for sub in list(self.subscribers) + self._hooks:
self.poller.register(sub, POLLIN)
self._loop ... |
Close the subscriber: stop it and close the local subscribers.
def close(self):
"""Close the subscriber: stop it and close the local subscribers.
"""
self.stop()
for sub in list(self.subscribers) + self._hooks:
try:
sub.setsockopt(LINGER, 1)
s... |
Add the magick to the topics if missing.
def _magickfy_topics(topics):
"""Add the magick to the topics if missing.
"""
# If topic does not start with messages._MAGICK (pytroll:/), it will be
# prepended.
if topics is None:
return None
if isinstance(topics, si... |
Start the subscriber.
def start(self):
"""Start the subscriber.
"""
def _get_addr_loop(service, timeout):
"""Try to get the address of *service* until for *timeout* seconds.
"""
then = datetime.now() + timedelta(seconds=timeout)
while datetime.now... |
handle the message *msg*.
def handle_msg(self, msg):
"""handle the message *msg*.
"""
addr_ = msg.data["URI"]
status = msg.data.get('status', True)
if status:
service = msg.data.get('service')
for service in self.services:
if not service o... |
*classify the transients selected from the transient selection query in the settings file or passed in via the CL or other code*
**Return:**
- ``crossmatches`` -- list of dictionaries of crossmatched associated sources
- ``classifications`` -- the classifications assigned to the transie... |
use the transient query in the settings file to generate a list of transients to corssmatch and classify
**Return:**
- ``transientsMetadataList``
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
... |
update the NED stream within the catalogues database at the locations of the transients
**Key Arguments:**
- ``transientsMetadataList`` -- the list of transient metadata lifted from the database.
.. todo ::
- update key arguments values and definitions with defaults
... |
iterate through the transient locations to see if we have recent local NED coverage of that area already
**Key Arguments:**
- ``coordinateList`` -- set of coordinate to check for previous queries
**Return:**
- ``updatedCoordinateList`` -- coordinate list with previous queries r... |
run the transients through the crossmatch algorithm in the settings file
**Key Arguments:**
- ``transientsMetadataListIndex`` -- the list of transient metadata lifted from the database.
- ``colMaps`` -- dictionary of dictionaries with the name of the database-view (e.g. `tcs_view_agn_m... |
update transient database with classifications and crossmatch results
**Key Arguments:**
- ``crossmatches`` -- the crossmatches and associations resulting from the catlaogue crossmatches
- ``classifications`` -- the classifications assigned to the transients post-crossmatches (dictionar... |
*rank the classifications returned from the catalogue crossmatcher, annotate the results with a classification rank-number (most likely = 1) and a rank-score (weight of classification)*
**Key Arguments:**
- ``crossmatchArrayIndex`` -- the index of list of unranked crossmatch classifications
... |
*print the classification and crossmatch results for a single transient object to stdout*
**Key Arguments:**
- ``crossmatches`` -- the unranked crossmatch classifications
- ``classifications`` -- the classifications assigned to the transients post-crossmatches (dictionary of rank ordere... |
*match the coordinate list against itself with the parameters of the NED search queries to minimise duplicated NED queries*
**Key Arguments:**
- ``coordinateList`` -- the original coordinateList.
**Return:**
- ``updatedCoordinateList`` -- the coordinate list with duplicated sea... |
*add a detialed classification annotation to each classification in the sherlock_classifications table*
**Key Arguments:**
# -
**Return:**
- None
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usage
... |
*update classification annotations and summaries*
**Key Arguments:**
- ``updatePeakMagnitudes`` -- update the peak magnitudes in the annotations to give absolute magnitudes. Default *True*
**Return:**
- None
**Usage:**
.. todo::
- add ... |
*update peak magnitudes*
**Key Arguments:**
# -
**Return:**
- None
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usage
- write a command-line tool for this method
- upd... |
*create the sherlock helper tables if they don't yet exist*
**Key Arguments:**
# -
**Return:**
- None
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usage
- write a command-line tool fo... |
Delete an analysis log from the database.
def check(context: click.Context, family: str):
"""Delete an analysis log from the database."""
analysis_obj = context.obj['store'].analyses(family=family).first()
if analysis_obj is None:
LOG.error('no analysis found')
context.abort()
config_p... |
Name a FASTQ file following MIP conventions.
def name_file(lane: int, flowcell: str, sample: str, read: int,
undetermined: bool=False, date: dt.datetime=None, index: str=None) -> str:
"""Name a FASTQ file following MIP conventions."""
flowcell = f"{flowcell}-undetermined" if undetermi... |
Link FASTQ files for a sample.
def link(self, family: str, sample: str, analysis_type: str, files: List[str]):
"""Link FASTQ files for a sample."""
root_dir = Path(self.families_dir) / family / analysis_type / sample / 'fastq'
root_dir.mkdir(parents=True, exist_ok=True)
for fastq_data i... |
*Get the root path for this python package - used in unit testing code*
def getpackagepath():
"""
*Get the root path for this python package - used in unit testing code*
"""
moduleDirectory = os.path.dirname(__file__)
packagePath = os.path.dirname(__file__) + "/../"
return packagePath |
Non-object interface for sending multicast messages.
def mcast_sender(mcgroup=MC_GROUP):
"""Non-object interface for sending multicast messages.
"""
sock = socket(AF_INET, SOCK_DGRAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
if _is_broadcast_group(mcgroup):
group = '<broadcast>'
... |
Open a UDP socket, bind it to a port and select a multicast group.
def mcast_receiver(port, mcgroup=MC_GROUP):
"""Open a UDP socket, bind it to a port and select a multicast group.
"""
if _is_broadcast_group(mcgroup):
group = None
else:
group = mcgroup
# Create a socket
sock =... |
Close the receiver.
def close(self):
"""Close the receiver.
"""
self.socket.setsockopt(SOL_SOCKET, SO_LINGER,
struct.pack('ii', 1, 1))
self.socket.close() |
Convenience decorator to associate HTTP status codes with :class:`.ApiError` subclasses.
:param http_code: (int) HTTP status code.
:return: wrapper function.
def api_exception(http_code):
"""Convenience decorator to associate HTTP status codes with :class:`.ApiError` subclasses.
:param http_code: (in... |
Delete temporary logs for the current family.
def _delete_temp_logs(self, family_name: str):
"""Delete temporary logs for the current family."""
for temp_log in self.store.analyses(family=family_name, temp=True):
log.debug(f"delete temporary log: {temp_log.id} - {temp_log.status}")
... |
Parse information about a run.
def parse(cls, config_data: dict, sampleinfo_data: dict, sacct_jobs: List[dict],
jobs: int) -> dict:
"""Parse information about a run."""
analysis_types = [sample['type'] for sample in config_data['samples']]
run_data = {
'user': config_d... |
Parse out info from Sacct log.
def _parse_sacct(sacct_jobs: List[dict], jobs_count: int=None):
"""Parse out info from Sacct log."""
failed_jobs = sacct_api.filter_jobs(sacct_jobs, failed=True)
completed_jobs = [job for job in sacct_jobs if job['is_completed']]
last_job_end = completed_j... |
Determine the overall analysis type.
def _get_analysis_type(analysis_types: List[str]) -> str:
"""Determine the overall analysis type."""
types_set = set(analysis_types)
return types_set.pop() if len(types_set) == 1 else 'wgs' |
Build a new Analysis object.
def build(self, run_data: dict) -> models.Analysis:
"""Build a new Analysis object."""
existing_run = self.store.find_analysis(family=run_data['family'],
started_at=run_data['started_at'],
... |
return default value
def get_default_value(self):
""" return default value """
default = self.default_value
if isinstance(default, collections.Callable):
default = default()
return default |
Initialize execution context for a Compiled construct.
def _init_compiled(cls, dialect, connection, dbapi_connection,
compiled, parameters):
"""Initialize execution context for a Compiled construct."""
self = cls.__new__(cls)
self.root_connection = connection
sel... |
Utility function to return a list of sentences.
@param text The text that must be split in to sentences.
def split_sentences(text):
"""
Utility function to return a list of sentences.
@param text The text that must be split in to sentences.
"""
sentence_delimiters = re.compile(u'[.!?,;:\t\\\\"\... |
Decorator that makes standard Django admin actions compatible.
def takes_instance_or_queryset(func):
"""Decorator that makes standard Django admin actions compatible."""
@wraps(func)
def decorated_function(self, request, queryset):
# func follows the prototype documented at:
# https://docs.... |
Prepend `get_urls` with our own patterns.
def get_urls(self):
"""Prepend `get_urls` with our own patterns."""
urls = super(BaseDjangoObjectActions, self).get_urls()
return self._get_action_urls() + urls |
Get the url patterns that route each action to a view.
def _get_action_urls(self):
"""Get the url patterns that route each action to a view."""
actions = {}
model_name = self.model._meta.model_name
# e.g.: polls_poll
base_url_name = '%s_%s' % (self.model._meta.app_label, model_... |
Represents the tool as a dict with extra meta.
def _get_tool_dict(self, tool_name):
"""Represents the tool as a dict with extra meta."""
tool = getattr(self, tool_name)
standard_attrs, custom_attrs = self._get_button_attrs(tool)
return dict(
name=tool_name,
label... |
Get the HTML attributes associated with a tool.
There are some standard attributes (class and title) that the template
will always want. Any number of additional attributes can be specified
and passed on. This is kinda awkward and due for a refactor for
readability.
def _get_button_att... |
Add a question mark.
def question_mark(self, request, obj):
"""Add a question mark."""
obj.question = obj.question + '?'
obj.save() |
Builds an html link.
:param href: link for the anchor element
:param text: text for the anchor element
:param attrs: other attribute kwargs
>>> build_link('xyz.com', 'hello', 'big')
u'<a href="xyz.com" class="big">hello</a>'
>>> build_link('xyz.com', 'hello', 'big', 'fa fa-times')
u'<a hre... |
Builds an html element.
:param tag: the html tag to build ('a', 'div', 'img', etc)
:param icon_class: the class to apply to an icon element. This only
applies to elements that allow a closing tag.
:param cls: the css class to apply to the tag. This can also be passed
in as a kwarg as "cla... |
Serialize a migration session state to yaml using nicer formatting
Args:
raw: object to serialize
Returns: string (of yaml)
Specifically, this forces the "output" member of state step dicts (e.g.
state[0]['output']) to use block formatting. For example, rather than this:
- migration: [app... |
Add migrations to be applied.
Args:
migrations: a list of migrations to add of the form [(app, migration_name), ...]
Raises:
MigrationSessionError if called on a closed MigrationSession
def add_migrations(self, migrations):
"""
Add migrations to be applied.
... |
Output a list of unapplied migrations in the form [['migration1', migration2'], ...].
This implementation is mostly copied from the Django 'showmigrations' mgmt command.
https://github.com/django/django/blob/stable/1.8.x/django/core/management/commands/showmigrations.py
This should only be call... |
Extract the most recent migrations from the relevant apps.
If no migrations have been performed, return 'zero' as the most recent migration for the app.
This should only be called from list_migrations().
def _get_current_migration_state(self, loader, apps):
"""
Extract the most recent ... |
Returns a tuple of unapplied, current
"Unapplied" is a list of unapplied migrations. "Current" is a list of the current migration
states for apps with unapplied migrations.
Both are tuples of the form (app, migration_name).
def list_migrations(self):
"""
Returns a tuple of una... |
Args:
output: str, output of "manage.py migrate"
Returns (succeeded: list(tuple), failed: tuple or None)
Both tuples are of the form (app, migration)
def _parse_migrate_output(self, output):
"""
Args:
output: str, output of "manage.py migrate"
Returns (su... |
If a migration is supplied, runs that migration and appends to state.
If run_all==True, runs all migrations.
Raises a ValueError if neither "migration" nor "run_all" are provided.
def __apply(self, migration=None, run_all=False):
"""
If a migration is supplied, runs that migration and a... |
Applies all migrations that have been added.
Note that some migrations depend on others, so you might end up
running more than one.
def apply(self):
"""
Applies all migrations that have been added.
Note that some migrations depend on others, so you might end up
running m... |
Applies all Django model migrations at once, recording the result.
def apply_all(self):
"""
Applies all Django model migrations at once, recording the result.
"""
if self.__closed:
raise MigrationSessionError("Can't apply applied session")
if self._to_apply:
... |
Send an email from a template.
:param to_email: the email address to send the email to
:param from_email: the email address the email will be from
:param subject: the subject of the email
:param markdown_template: the markdown syntax template to use for the
email. If provided, this will generat... |
Send many emails from single template. Each email address listed in the
``to_emails`` will receive an separate email.
:param to_emails: list of email address to send the email to
:param from_email: the email address the email will be from
:param subject: the subject of the email
:param markdown_te... |
Find all the possible interpretations given a set of symbols
def all_models(self, alphabet: _Alphabet) -> Set[PLInterpretation]:
"""Find all the possible interpretations given a set of symbols"""
all_possible_interpretations = alphabet.powerset().symbols
all_models = set()
for i in all... |
Find models of min size (i.e. the less number of proposition to True).
Very trivial (and inefficient) algorithm: BRUTE FORCE on all the possible interpretations.
def minimal_models(self, alphabet: _Alphabet) -> Set[PLInterpretation]:
"""Find models of min size (i.e. the less number of proposition to Tr... |
Make sure token is added.
def save(self, *args, **kwargs):
"""Make sure token is added."""
self.save_prep(instance_or_instances=self)
return super(AbstractTokenModel, self).save(*args, **kwargs) |
Preprocess the object before the object is saved. This
automatically gets called when the save method gets called.
def save_prep(cls, instance_or_instances):
"""Preprocess the object before the object is saved. This
automatically gets called when the save method gets called.
"""
... |
recursively find commutative binary operator
among child formulas and pop up them at the same level
def _popup(self):
"""recursively find commutative binary operator
among child formulas and pop up them at the same level"""
res = ()
for child in self.formulas:
if typ... |
Gets the absolute url for the content object.
def get_content_object_url(self):
"""Gets the absolute url for the content object."""
if (self.content_object and
hasattr(self.content_object, 'get_absolute_url')):
return self.content_object.get_absolute_url()
return None |
r'[a-zA-Z_][a-zA-Z_0-9]*
def t_ATOM(self, t):
r'[a-zA-Z_][a-zA-Z_0-9]*'
t.type = LDLfLexer.reserved.get(t.value, 'ATOM') # Check for reserved words
return t |
temp_formula : temp_formula EQUIVALENCE temp_formula
| temp_formula IMPLIES temp_formula
| temp_formula OR temp_formula
| temp_formula AND temp_formula
| BOXLSEPARATOR path BOXRSEPARATOR temp_formula
... |
path : path UNION path
| path SEQ path
| path STAR
| temp_formula TEST
| propositional
def p_path(self, p):
"""path : path UNION path
| path SEQ path
| path STAR
| temp_formula TEST
|... |
propositional : propositional EQUIVALENCE propositional
| propositional IMPLIES propositional
| propositional OR propositional
| propositional AND propositional
| NOT propositional
| FALSE
... |
priorities are (primary domain and aliases are treated the same):
exact redirect match > exact alias match > pattern redirect match > pattern alias match
:param current_url: the url that is being called
:param config: redirect configuration for this url
:param want_https: whether redirects should go... |
Given a context, this invokes the attached callback (if it exists)
in the right way.
def invoke(self, ctx):
"""Given a context, this invokes the attached callback (if it exists)
in the right way.
"""
if self.callback is not None:
loop = asyncio.get_event_loop()
... |
Returns the help option object.
def get_help_option(self, ctx):
"""Returns the help option object."""
help_options = self.get_help_option_names(ctx)
if not help_options or not self.add_help_option:
return
def show_help(ctx, param, value):
import abot.bot
... |
Gets the class for the widget.
def get_widget_css_class(self, attrs):
"""Gets the class for the widget."""
size_class = 'size-{0}'.format(self.num_inputs)
if 'class' in attrs:
attrs['class'] += ' {0}'.format(size_class)
else:
attrs['class'] = size_class |
r'[a-zA-Z_][a-zA-Z_0-9]*
def t_ATOM(self, t):
r'[a-zA-Z_][a-zA-Z_0-9]*'
t.type = PLLexer.reserved.get(t.value, 'ATOM') # Check for reserved words
return t |
formula : ATOM
| TRUE
| FALSE
def p_formula_atom(self, p):
"""formula : ATOM
| TRUE
| FALSE"""
if p[1]==Symbols.TRUE.value:
p[0] = PLTrue()
elif p[1]==Symbols.FALSE.value:
p[0] = PLFalse()
... |
Gets a single object based on kwargs or None if one is not found.
:param prefetch_related: list or tuple of fields to prefetch for an
object. This takes precedence over select_related.
Example:
>> get_or_none(prefetch_related=['some_field',
... ... |
Gets by a instance instance r raises a 404 is one isn't found.
def get_by_id_or_404(self, id, **kwargs):
"""Gets by a instance instance r raises a 404 is one isn't found."""
obj = self.get_by_id(id=id, **kwargs)
if obj:
return obj
raise Http404 |
Insert many object at once.
def bulk_create(self, objs, *args, **kwargs):
"""Insert many object at once."""
if hasattr(self.model, 'save_prep'):
# Method from AbstractBaseModel. If the model class doesn't
# subclass AbstractBaseModel, then don't call this.
self.model... |
Delete objects by ids.
:param ids: list of objects ids to delete.
:return: True if objects were deleted. Otherwise, return False if no
objects were found or the delete was not successful.
def delete_by_ids(self, ids):
"""Delete objects by ids.
:param ids: list of obje... |
Checks to see if a slug is available. If the slug is already being used
this method returns False. Otherwise, return True.
def is_slug_available(self, slug, **kwargs):
"""Checks to see if a slug is available. If the slug is already being used
this method returns False. Otherwise, return True.... |
Gets the next available slug.
:param slug: the slug to slugify
:param kwargs: additional filter criteria to check for when looking for
a unique slug.
Example:
if the value "my-slug" is already taken, this method will append "-n"
to the end of the slug until the nex... |
Gets the next available token.
:param length: length of the token
:param kwargs: additional filter criteria to check for when looking for
a unique token.
def get_next_token(self, length=15, **kwargs):
"""Gets the next available token.
:param length: length of the token
... |
Gets a list of available tokens.
:param count: the number of tokens to return.
:param token_length: the length of the tokens. The higher the number
the easier it will be to return a list. If token_length == 1
there's a strong probability that the enough tokens will exist in
... |
Create a generic object.
:param content_object: the content object to create a new object for.
def create_generic(self, content_object=None, **kwargs):
"""Create a generic object.
:param content_object: the content object to create a new object for.
"""
if content_object:
... |
Filter by a generic object.
:param content_object: the content object to filter on.
def filter_generic(self, content_object=None, **kwargs):
"""Filter by a generic object.
:param content_object: the content object to filter on.
"""
if content_object:
kwargs['conten... |
Gets or creates a generic object. This is a wrapper for
get_or_create(...) when you need to get or create a generic object.
:param obj: the object to get or create
:param kwargs: any other kwargs that the model accepts.
def get_or_create_generic(self, content_object=None, **kwargs):
"... |
Gets all object by a specific model.
def get_by_model(self, model):
"""Gets all object by a specific model."""
content_type = ContentType.objects.get_for_model(model)
return self.filter(content_type=content_type) |
Does the same thing as getattr.
getattr(obj, attr, '')
def attr(obj, attr):
"""
Does the same thing as getattr.
getattr(obj, attr, '')
"""
if not obj or not hasattr(obj, attr):
return ''
return getattr(obj, attr, '') |
Make an object iterable.
>>> make_iterable(obj='hello')
('hello',)
>>> make_iterable(obj=None)
()
def make_iterable(obj):
"""Make an object iterable.
>>> make_iterable(obj='hello')
('hello',)
>>> make_iterable(obj=None)
()
"""
if not obj:
return tuple()
if isi... |
Add the 'data' to the form args so you can validate the form
data on a get request.
def get_form_kwargs(self):
"""Add the 'data' to the form args so you can validate the form
data on a get request.
"""
kwargs = super(ApiFormView, self).get_form_kwargs()
kwargs['data'] = ... |
This will return the request with form errors as well as any
additional context.
def form_invalid(self, form, context=None, **kwargs):
"""This will return the request with form errors as well as any
additional context.
"""
if not context:
context = {}
contex... |
Boolean indicating of the value is a valid hex value.
def is_valid_hex(value):
"""Boolean indicating of the value is a valid hex value."""
if not value:
return False
regex = re.compile(HEX_COLOR_REGEX)
return bool(regex.match(value)) |
Checks whether the value is a valid rgb or rgba color string.
Valid colors consist of:
- rgb(255, 255, 255)
- rgba(23, 34, 45, .5)
def is_valid_rgb_color(value):
"""Checks whether the value is a valid rgb or rgba color string.
Valid colors consist of:
- rgb(255, 255, 255)
- rgba(23, 34,... |
Validates that a password is as least 7 characters long and has at least
1 digit and 1 letter.
def validate_password_strength(value):
"""Validates that a password is as least 7 characters long and has at least
1 digit and 1 letter.
"""
min_length = 7
if len(value) < min_length:
raise V... |
Class decorator for creating a class with a metaclass.
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
return metaclass... |
Validates that the input can be converted to a list of decimals.
def clean(self, value):
"""Validates that the input can be converted to a list of decimals."""
if not value:
return None
# if any value exists, then add "0" as a placeholder to the remaining
# values.
... |
Validates that the input can be converted to a list of decimals.
def to_python(self, value):
"""Validates that the input can be converted to a list of decimals."""
if not value:
return None
if isinstance(value, list):
for index, position_val in enumerate(value):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.