text stringlengths 81 112k |
|---|
Check whether the outputs of the pipeline are present in all sessions
in the project repository and were generated with matching provenance.
Return an 2D boolean array (subjects: rows, visits: cols) with the
sessions to process marked True.
Parameters
----------
pipeline... |
'Dialates' a to_process/to_protect array to include all subject and/or
visits if the pipeline contains any joins over the corresponding
iterators.
Parameters
----------
array : np.array[M, N]
The array to potentially dialate
iterators : set[str]
T... |
Intercept calls to get template and return our own node-specific
template
def _get_args(self, node, keywords):
"""
Intercept calls to get template and return our own node-specific
template
"""
args = super(ArcanaSlurmGraphPlugin, self)._get_args(
node, keywor... |
Returns the wall time in the format required for the sbatch script
def wall_time_str(self, wall_time):
"""
Returns the wall time in the format required for the sbatch script
"""
days = int(wall_time // 1440)
hours = int((wall_time - days * 1440) // 60)
minutes = int(math... |
Retrieve panel information from ElkM1
def sync(self):
"""Retrieve panel information from ElkM1"""
self._elk.add_handler('VN', self._vn_handler)
self._elk.add_handler('XK', self._xk_handler)
self._elk.add_handler('RP', self._rp_handler)
self._elk.add_handler('IE', self._elk.call_... |
(Helper) Set thermostat
def set(self, element_to_set, value):
"""(Helper) Set thermostat"""
self._elk.send(ts_encode(self.index, value, element_to_set)) |
Duplicate the datum and rename it
def renamed(self, name):
"""
Duplicate the datum and rename it
"""
duplicate = copy(self)
duplicate._name = name
return duplicate |
Compares the version with another
Parameters
----------
other : Version
The version to compare to
def compare(self, other):
"""
Compares the version with another
Parameters
----------
other : Version
The version to compare to
... |
Splits a typical version string (e.g. <MAJOR>.<MINOR>.<MICRO>)
into a tuple that can be sorted properly. Ignores all leading
and trailing characters by using a regex search (instead of match) so
as to pick the version string out of a block of text.
Parameters
----------
... |
A single version can also be interpreted as an open range (i.e. no
maximum version)
def within(self, version):
"""
A single version can also be interpreted as an open range (i.e. no
maximum version)
"""
if not isinstance(version, Version):
version = type(self... |
Returns either a single requirement version or a requirement version
range depending on whether two arguments are supplied or one
Parameters
----------
version : str | Version
Either a version of the requirement, or the first version in a
range of acceptable vers... |
Open a connection to the database.
If a connection appears to be open already, transactions are committed
and it is closed before proceeding. After establishing the connection,
the searchIndex table is prepared (and dropped if it already exists).
def open(self):
'''Open a connection to... |
Insert an entry into the Zeal database.
Args:
name: A string representing the name of the entry.
entry_type: A string representing the entry type.
filename: A string representing the filename of the documentation
for the entry.
Raises:
Ru... |
A simple wrapper of Django's serializer with defaults
for JSON and natural keys.
Note: use_natural_primary_keys is False as once
a pk is set, it should not be changed throughout the
distributed data.
def serialize(objects=None):
"""A simple wrapper of Django's serializer with defaults
for JSON... |
Returns the Fileset(s) or Field(s) associated with the provided spec
name(s), generating derived filesets as required. Multiple names in a
list can be provided, to allow their workflows to be combined into a
single workflow.
Parameters
----------
name : str | List[str]
... |
Checks whether the given switch matches the value provided
Parameters
----------
name : str
The name of the parameter to retrieve
value : str | None
The value(s) of the switch to match if a non-boolean switch
def branch(self, name, values=None): # @UnusedVariab... |
Convenient method for raising exception if a pipeline doesn't
handle a particular switch value
Parameters
----------
name : str
Name of the switch
value : str
Value of the switch which hasn't been handled
def unhandled_branch(self, name):
"""
... |
Saves a graph of the workflow to generate the requested spec_name
Parameters
----------
spec_name : str
Name of the spec to generate the graph for
fname : str
The filename for the saved graph
style : str
The style of the graph, can be one of c... |
Returns either the input corresponding to a fileset or field
field spec or a spec or parameter that has either
been passed to the study as an input or can be derived.
Parameters
----------
name : Str | BaseData | Parameter
A parameter, fileset or field or name of one... |
Returns an input selector or derived spec bound to the study, i.e.
where the repository tree is checked for existing outputs
Parameters
----------
name : Str
A name of a fileset or field
def bound_spec(self, name):
"""
Returns an input selector or derived sp... |
Return the fileset_spec, i.e. the template of the fileset expected to
be supplied or generated corresponding to the fileset_spec name.
Parameters
----------
name : Str
Name of the fileset_spec to return
def data_spec(cls, name):
"""
Return the fileset_spec, ... |
Runs the Study's repository source node for each of the inputs
of the study, thereby caching any data required from remote
repositorys. Useful when launching many parallel jobs that will
all try to concurrently access the remote repository, and probably
lead to timeout errors.
def cache... |
Checks to see whether the corresponding data spec was provided an
explicit input, as opposed to derivatives or missing optional inputs
Parameters
----------
spec_name : str
Name of a data spec
def provided(self, spec_name, default_okay=True):
"""
Checks to s... |
Returns the frequency corresponding to the given iterators
def freq_from_iterators(cls, iterators):
"""
Returns the frequency corresponding to the given iterators
"""
return {
set(it): f for f, it in cls.FREQUENCIES.items()}[set(iterators)] |
Extracts provenance information from the study for storage alongside
generated derivatives. Typically for reference purposes only as only
the pipeline workflow, inputs and outputs are checked by default when
determining which sessions require reprocessing.
Returns
-------
... |
(Helper) Arm system at specified level (away, vacation, etc)
def arm(self, level, code):
"""(Helper) Arm system at specified level (away, vacation, etc)"""
self._elk.send(al_encode(level, self._index, code)) |
Display a message on all of the keypads in this area.
def display_message(self, clear, beep, timeout, line1, line2):
"""Display a message on all of the keypads in this area."""
self._elk.send(
dm_encode(self._index, clear, beep, timeout, line1, line2)
) |
Retrieve areas from ElkM1
def sync(self):
"""Retrieve areas from ElkM1"""
self.elk.send(as_encode())
self.get_descriptions(TextDescriptions.AREA.value) |
(Helper) Set light to specified level
def level(self, level, time=0):
"""(Helper) Set light to specified level"""
if level <= 0:
self._elk.send(pf_encode(self._index))
elif level >= 98:
self._elk.send(pn_encode(self._index))
else:
self._elk.send(pc_en... |
Retrieve lights from ElkM1
def sync(self):
"""Retrieve lights from ElkM1"""
for i in range(4):
self.elk.send(ps_encode(i))
self.get_descriptions(TextDescriptions.LIGHT.value) |
Returns the latest modification time of all files/subdirectories in a
directory
def dir_modtime(dpath):
"""
Returns the latest modification time of all files/subdirectories in a
directory
"""
return max(os.path.getmtime(d) for d, _, _ in os.walk(dpath)) |
A extension splitter that checks for compound extensions such as
'file.nii.gz'
Parameters
----------
filename : str
A filename to split into base and extension
Returns
-------
base : str
The base part of the string, i.e. 'file' of 'file.nii.gz'
ext : str
The ext... |
Tries to convert to int, float and then gives up and assumes the value
is of type string. Useful when excepting values that may be string
representations of numerical values
def parse_single_value(value):
"""
Tries to convert to int, float and then gives up and assumes the value
is of type string. ... |
Checks whether all the provided items are containers (i.e of class list,
dict, tuple, etc...)
def iscontainer(*items):
"""
Checks whether all the provided items are containers (i.e of class list,
dict, tuple, etc...)
"""
return all(isinstance(i, Iterable) and not isinstance(i, basestring)
... |
Finds where two objects differ, iterating down into nested containers
(i.e. dicts, lists and tuples) They can be nested containers
any combination of primary dtypes, str, int, float, dict and lists
Parameters
----------
first : dict | list | tuple | str | int | float
The first object to com... |
Returns a generator of deserialized objects.
Wraps django deserialize with defaults for JSON
and natural keys.
See https://docs.djangoproject.com/en/2.1/topics/serialization/
def deserialize(json_text=None):
"""Returns a generator of deserialized objects.
Wraps django deserialize with defaults f... |
Create token when a user is created (from rest_framework).
def create_auth_token(sender, instance, raw, created, **kwargs):
"""Create token when a user is created (from rest_framework).
"""
if not raw:
if created:
sender.objects.create(user=instance) |
Part of the serialize transaction process that ensures m2m are
serialized correctly.
Skip those not registered.
def serialize_m2m_on_save(sender, action, instance, using, **kwargs):
""" Part of the serialize transaction process that ensures m2m are
serialized correctly.
Skip those not registered.... |
Serialize the model instance as an OutgoingTransaction.
Skip those not registered.
def serialize_on_save(sender, instance, raw, created, using, **kwargs):
""" Serialize the model instance as an OutgoingTransaction.
Skip those not registered.
"""
if not raw:
if "historical" not in instance... |
Serialize the history instance as an OutgoingTransaction.
Skip those not registered.
def serialize_history_on_post_create(history_instance, using, **kwargs):
""" Serialize the history instance as an OutgoingTransaction.
Skip those not registered.
"""
try:
wrapped_instance = site_offline_m... |
Creates a serialized OutgoingTransaction when
a model instance is deleted.
Skip those not registered.
def serialize_on_post_delete(sender, instance, using, **kwargs):
"""Creates a serialized OutgoingTransaction when
a model instance is deleted.
Skip those not registered.
"""
try:
... |
(Helper) Set custom value.
def set(self, value):
"""(Helper) Set custom value."""
self._elk.send(cw_encode(self._index, value, self.value_format)) |
Retrieve custom values from ElkM1
def sync(self):
"""Retrieve custom values from ElkM1"""
self.elk.send(cp_encode())
self.get_descriptions(TextDescriptions.SETTING.value) |
Iterates through all files in the set
def paths(self):
"""Iterates through all files in the set"""
if self.format is None:
raise ArcanaFileFormatError(
"Cannot get paths of fileset ({}) that hasn't had its format "
"set".format(self))
if self.format.d... |
Detects the format of the fileset from a list of possible
candidates. If multiple candidates match the potential files, e.g.
NiFTI-X (see dcm2niix) and NiFTI, then the first matching candidate is
selected.
If a 'format_name' was specified when the fileset was
created then that i... |
Test the equality of the fileset contents with another fileset. If the
fileset's format implements a 'contents_equal' method than that is used
to determine the equality, otherwise a straight comparison of the
checksums is used.
Parameters
----------
other : Fileset
... |
Returns a copy of the AcquiredSpec bound to the given study
Parameters
----------
study : Study
A study to bind the fileset spec to (should happen in the
study __init__)
def bind(self, study, **kwargs): # @UnusedVariable
"""
Returns a copy of the Acquir... |
Returns a copy of the Spec bound to the given study
Parameters
----------
study : Study
A study to bind the fileset spec to (should happen in the
study __init__)
def bind(self, study, **kwargs): # @UnusedVariable
"""
Returns a copy of the Spec bound to ... |
Returns the relevant nodes for the spec's frequency
def nodes(self, tree):
"""
Returns the relevant nodes for the spec's frequency
"""
# Run the match against the tree
if self.frequency == 'per_session':
nodes = []
for subject in tree.subjects:
... |
Whether the spec (only valid for derived specs) can be derived
given the inputs and switches provided to the study
def derivable(self):
"""
Whether the spec (only valid for derived specs) can be derived
given the inputs and switches provided to the study
"""
try:
... |
Re-establish connection to all instances
def reconnect_all(self):
"""
Re-establish connection to all instances
"""
for role in self.Instances.keys():
for connection in self.Instances[role]:
connection.reconnect() |
Add instance to the setup
@param role: instance's role
@type role: str
@param instance: host parameters we would like to establish connection
to
@type instance: dict
@param username: user name for creating ssh connection
@type username: str
... |
Setup from yaml config
@param yamlfile: path to yaml config file
@type yamlfile: str
@param output_shell: write output from this connection to standard
output
@type output_shell: bool
def setup_from_yamlfile(self, yamlfile, output_shell=False):
"""... |
helper function to iterate over a process stdout
and report error messages when done
def process_iter(proc, cmd=""):
"""
helper function to iterate over a process stdout
and report error messages when done
"""
try:
for l in proc.stdout:
yield l
finally:
if proc.p... |
just grab the header from a given file
def header(fname, sep="\t"):
"""
just grab the header from a given file
"""
fh = iter(nopen(fname))
h = tokens(next(fh), sep)
h[0] = h[0].lstrip("#")
return h |
r"""
for each row in the file `fname` generate dicts If `header` is True
or lists if `header` is False. The dict keys are drawn from the first
line.
If `header` is a list of names, those will be used as the dict keys.
If `header` is 'ordered', the function will yield ordered dicts.
If `header` i... |
check that all b files have been modified more recently than a
def is_newer_b(a, bfiles):
"""
check that all b files have been modified more recently than a
"""
if isinstance(bfiles, basestring):
bfiles = [bfiles]
if not op.exists(a): return False
if not all(op.exists(b) for b in bfile... |
Expect a list of expressions
@param connection: Connection to the host
@type connection: L{Connection}
@param regexp_list: regular expressions and associated return values
@type regexp_list: list of (regexp, return value)
@param timeout: timeout for performing expect operation... |
Expect one expression
@param connection: Connection to the host
@type connection: L{Connection}
@param strexp: string to convert to expression (.*string.*)
@type strexp: str
@param timeout: timeout for performing expect operation
@type timeout: int
@return: Tr... |
Match against an expression
@param connection: Connection to the host
@type connection: L{Connection}
@param regexp: compiled regular expression
@type regexp: L{SRE_Pattern}
@param grouplist: list of groups to return
@type group: list of int
@param timeout: ti... |
Enter a command and wait for something to happen (enter + expect
combined)
@param connection: connection to the host
@type connection: L{Connection}
@param command: command to execute
@type command: str
@param strexp: string to convert to expression (.*string.*)
... |
Run command and expect specified return valud
@param connection: connection to the host
@type connection: L{Connection}
@param command: command to execute
@type command: str
@param expected_status: expected return value
@type expected_status: int
@param timeou... |
Retrieve areas from ElkM1
def sync(self):
"""Retrieve areas from ElkM1"""
self.elk.send(ka_encode())
self.get_descriptions(TextDescriptions.KEYPAD.value) |
Yield tags matching the tag criterion from a soup.
There is no need to override this if you are satisfied with finding
tags that match match_criterion.
Args:
soup: A BeautifulSoup to search through.
Yields:
BeautifulSoup Tags that match the criterion.
def find... |
Extract and return a representative "name" from a tag.
Override as necessary. get_name's output can be controlled through
keyword arguments that are provided when initializing a
TagProcessor. For instance, a member of a class or namespace can have
its parent scope included in the name b... |
Extract and return a documentation filename from a tag.
Override as necessary, though this default implementation probably
covers all the cases of interest.
Args:
tag: A BeautifulSoup Tag that satisfies match_criterion.
Returns:
A string that would be appropria... |
Override. Determine if a tag has the desired name and kind attribute
value.
Args:
tag: A BeautifulSoup Tag.
Returns:
True if tag has the desired name and kind, otherwise False.
def match_criterion(self, tag):
'''Override. Determine if a tag has the desired name... |
Override. Extract a representative "name" from a function tag.
get_name's output can be controlled through keyword arguments that are
provided when initializing a functionTagProcessor. For instance,
function arguments and return types can be included by passing
include_function_signatur... |
Override that returns u'Method' for class/struct methods.
Override as necessary.
Args:
tag: A BeautifulSoup Tag for a function.
Returns:
If this is a class/struct method, returns u'Method', otherwise
returns the value from the inherited implementation of
... |
create a multiprocessing pool that responds to interrupts.
def pool(n=None, dummy=False):
"""
create a multiprocessing pool that responds to interrupts.
"""
if dummy:
from multiprocessing.dummy import Pool
else:
from multiprocessing import Pool
if n is None:
import mult... |
parallel map of a function to an iterable
if each item in iterable is itself an iterable, then
automatically call f(*item) instead of f(item)
Arguments:
f: function
iterable: any iterable where each item is sent to f
n: number of cpus (default is number on machine)
dummy: use dummy ... |
Callbacks when attribute of element changes
def _call_callbacks(self):
"""Callbacks when attribute of element changes"""
for callback in self._callbacks:
callback(self, self._changeset)
self._changeset = {} |
If attribute value has changed then set it and call the callbacks
def setattr(self, attr, new_value, close_the_changeset=True):
"""If attribute value has changed then set it and call the callbacks"""
existing_value = getattr(self, attr, None)
if existing_value != new_value:
setattr(... |
Return a default name for based on class and index of element
def default_name(self, separator='-'):
"""Return a default name for based on class and index of element"""
return self.__class__.__name__ + '{}{:03d}'.format(
separator, self._index+1) |
Package up the public attributes as a dict.
def as_dict(self):
"""Package up the public attributes as a dict."""
attrs = vars(self)
return {key: attrs[key] for key in attrs if not key.startswith('_')} |
Gets the descriptions for specified type.
When complete the callback is called with a list of descriptions
def get_descriptions(self, description_type):
"""
Gets the descriptions for specified type.
When complete the callback is called with a list of descriptions
"""
(de... |
(:class:`str`) The canonical url of the page.
def page_url(self) -> str:
"""(:class:`str`) The canonical url of the page."""
url = self.attributes['canonicalurl']
assert isinstance(url, str)
return url |
r"""(:class:`~typing.Optional`\ [:class:`str`]) The image url.
It may be :const:`None` if it's not an image.
def image_url(self) -> Optional[str]:
r"""(:class:`~typing.Optional`\ [:class:`str`]) The image url.
It may be :const:`None` if it's not an image.
"""
images = self.attr... |
r"""(:class:`~typing.Optional`\ [:class:`~typing.Tuple`\ [:class:`int`,
:class:`int`]]) The (width, height) pair of the image.
It may be :const:`None` if it's not an image.
def image_resolution(self) -> Optional[Tuple[int, int]]:
r"""(:class:`~typing.Optional`\ [:class:`~typing.Tuple`\ [:class:... |
r"""(:class:`~typing.Optional`\ [:class:`int`]) The size of the image
in bytes. It may be :const:`None` if it's not an image.
def image_size(self) -> Optional[int]:
r"""(:class:`~typing.Optional`\ [:class:`int`]) The size of the image
in bytes. It may be :const:`None` if it's not an image.
... |
Determine the normalized locale code string.
>>> normalize_locale_code('ko-kr')
'ko_KR'
>>> normalize_locale_code('zh_TW')
'zh_Hant_TW'
>>> normalize_locale_code(Locale.parse('en_US'))
'en_US'
def normalize_locale_code(locale: Union[Locale, str]) -> str:
"""Determine the normalized locale ... |
Get a Wikidata entity by its :class:`~.entity.EntityId`.
:param entity_id: The :attr:`~.entity.Entity.id` of
the :class:`~.entity.Entity` to find.
:type eneity_id: :class:`~.entity.EntityId`
:param load: Eager loading on :const:`True`.
Lazy loading... |
r"""Guess :class:`~.entity.EntityType` from the given
:class:`~.entity.EntityId`. It could return :const:`None` when it
fails to guess.
.. note::
It always fails to guess when :attr:`entity_type_guess`
is configued to :const:`False`.
:return: The guessed :class:... |
Decode the given ``datavalue`` using the configured
:attr:`datavalue_decoder`.
.. versionadded:: 0.3.0
def decode_datavalue(self,
datatype: str,
datavalue: Mapping[str, object]) -> object:
"""Decode the given ``datavalue`` using the configured
... |
r"""Create or update a cache.
:param key: A key string to create or update.
:type key: :const:`CacheKey`
:param value: A value to cache. :const:`None` to remove cache.
:type value: :class:`~typing.Optional`\ [:const:`CacheValue`]
def set(self, key: CacheKey, value: Optional[CacheValue... |
r"""Return all values associated to the given ``key`` property
in sequence.
:param key: The property entity.
:type key: :class:`Entity`
:return: A sequence of all values associated to the given ``key``
property. It can be empty if nothing is associated to
... |
(:class:`EntityType`) The type of entity, :attr:`~EntityType.item`
or :attr:`~EntityType.property`.
.. versionadded:: 0.2.0
def type(self) -> EntityType:
"""(:class:`EntityType`) The type of entity, :attr:`~EntityType.item`
or :attr:`~EntityType.property`.
.. versionadded:: 0.... |
Create the user-role association table so that
it correctly references your own UserMixin subclass.
def make_user_role_table(table_name='user', id_column_name='id'):
"""
Create the user-role association table so that
it correctly references your own UserMixin subclass.
"""
return ... |
Takes an ability (a string name of either a role or an ability) and returns the function if the user has that ability
def user_has(ability, get_user=import_user):
"""
Takes an ability (a string name of either a role or an ability) and returns the function if the user has that ability
"""
def wrapper(fu... |
Takes an role (a string name of either a role or an ability) and returns the function if the user has that role
def user_is(role, get_user=import_user):
"""
Takes an role (a string name of either a role or an ability) and returns the function if the user has that role
"""
def wrapper(func):
@wr... |
Handles generating a 'combo' file for the given path. This is similar to
what happens when we upload to S3. Processors are applied, and we get
the value that we would if we were serving from S3. This is a good way
to make sure combo files work as intended before rolling out
to production.
def combo_ser... |
Given a URL path, massage it into a key we can perform a lookup on the
MEDIASYNC['JOINED'] dict with.
This mostly involves figuring into account the CSS_PATH and JS_PATH
settings, if they have been set.
def _form_key_str(path):
"""
Given a URL path, massage it into a key we can perform a looku... |
Calculate the key to check the MEDIASYNC['JOINED'] dict for, perform the
lookup, and return the matching key string if a match is found. If no
match is found, return None instead.
def _find_combo_match(path):
"""
Calculate the key to check the MEDIASYNC['JOINED'] dict for, perform the
lookup, and r... |
Given a request for a media asset, this view does the necessary wrangling
to get the correct thing delivered to the user. This can also emulate the
combo behavior seen when SERVE_REMOTE == False and EMULATE_COMBO == True.
def static_serve(request, path, client):
"""
Given a request for a media asset, t... |
Create a HTTP server and start it.
:param int port_number: the port number to bind the server to
:param int number_of_procs: number of processes to pass to
Tornado's ``httpserver.HTTPServer.start``.
If the application's ``debug`` setting is ``True``, then we are
going to ru... |
Create the server and run the IOLoop.
:param int port_number: the port number to bind the server to
:param int number_of_procs: number of processes to pass to
Tornado's ``httpserver.HTTPServer.start``.
If the application's ``debug`` setting is ``True``, then we are
going to... |
Sets 'short_description' attribute (this attribute is in exports to generate header name).
def short_description(description):
"""
Sets 'short_description' attribute (this attribute is in exports to generate header name).
"""
def decorator(func):
if isinstance(func, property):
func ... |
Adds configuration parameters from a Python module.
def add_module(self, module):
'''
Adds configuration parameters from a Python module.
'''
for key, value in module.__dict__.iteritems():
if key[0:2] != '__':
self.__setattr__(attr=key, value=value) |
Redirects the user to the login page, passing the given 'next' page
def redirect_to_login(next, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Redirects the user to the login page, passing the given 'next' page
"""
resolved_url = reverse('IS:login')
login_url_parts = list(urlparse(resolved_url))
... |
If customer is not authorized he should not get information that object is exists.
Therefore 403 is returned if object was not found or is redirected to the login page.
If custmer is authorized and object was not found is returned 404.
If object was found and user is not authorized is returned 4... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.