INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Creates a new price record | def add_price(self, price: PriceModel):
""" Creates a new price record """
# assert isinstance(price, PriceModel)
if not price:
raise ValueError("Cannot add price. The received model is null!")
mapper = mappers.PriceMapper()
entity = mapper.map_model(price)
... |
Adds the price | def add_price_entity(self, price: dal.Price):
""" Adds the price """
from decimal import Decimal
# check if the price already exists in db.
repo = self.get_price_repository()
existing = (
repo.query
.filter(dal.Price.namespace == price.namespace)
... |
Download and save price online | def download_price(self, symbol: str, currency: str, agent: str) -> PriceModel:
""" Download and save price online """
price = self.__download_price(symbol, currency, agent)
self.save()
return price |
Downloads all the prices that are listed in the Security table. Accepts filter arguments: currency agent symbol namespace. | def download_prices(self, **kwargs):
""" Downloads all the prices that are listed in the Security table.
Accepts filter arguments: currency, agent, symbol, namespace.
"""
currency: str = kwargs.get('currency', None)
if currency:
currency = currency.upper()
age... |
Incomplete | def import_prices(self, file_path: str, currency_symbol: str):
""" Incomplete """
from .csv import CsvParser
assert isinstance(file_path, str)
assert isinstance(currency_symbol, str)
self.logger.debug(f"Importing {file_path}")
parser = CsvParser()
prices = parse... |
Returns the current db session | def session(self):
""" Returns the current db session """
if not self.__session:
self.__session = dal.get_default_session()
return self.__session |
Fetches all the prices for the given arguments | def get_prices(self, date: str, currency: str) -> List[PriceModel]:
""" Fetches all the prices for the given arguments """
from .repositories import PriceRepository
session = self.session
repo = PriceRepository(session)
query = repo.query
if date:
query = que... |
Returns the latest price on the date | def get_prices_on(self, on_date: str, namespace: str, symbol: str):
""" Returns the latest price on the date """
repo = self.get_price_repository()
query = (
repo.query.filter(dal.Price.namespace == namespace)
.filter(dal.Price.symbol == symbol)
.filter(dal.Pr... |
Price repository | def get_price_repository(self):
""" Price repository """
from .repositories import PriceRepository
if not self.price_repo:
self.price_repo = PriceRepository(self.session)
return self.price_repo |
Security repository | def get_security_repository(self):
""" Security repository """
from .repositories import SecurityRepository
if not self.security_repo:
self.security_repo = SecurityRepository(self.session)
return self.security_repo |
Prune historical prices for all symbols leaving only the latest. Returns the number of items removed. | def prune_all(self) -> int:
"""
Prune historical prices for all symbols, leaving only the latest.
Returns the number of items removed.
"""
from .repositories import PriceRepository
# get all symbols that have prices
repo = PriceRepository()
items = repo.q... |
Delete all but the latest available price for the given symbol. Returns the number of items removed. | def prune(self, symbol: SecuritySymbol):
"""
Delete all but the latest available price for the given symbol.
Returns the number of items removed.
"""
from .repositories import PriceRepository
assert isinstance(symbol, SecuritySymbol)
self.logger.debug(f"pruning ... |
Save changes | def save(self):
""" Save changes """
if self.__session:
self.session.commit()
else:
self.logger.warning("Save called but no session open.") |
Downloads and parses the price | def __download_price(self, symbol: str, currency: str, agent: str):
""" Downloads and parses the price """
from finance_quote_python import Quote
assert isinstance(symbol, str)
assert isinstance(currency, str)
assert isinstance(agent, str)
if not symbol:
ret... |
Fetches the securities that match the given filters | def __get_securities(self, currency: str, agent: str, symbol: str,
namespace: str) -> List[dal.Security]:
""" Fetches the securities that match the given filters """
repo = self.get_security_repository()
query = repo.query
if currency is not None:
qu... |
Return partial of original function call | def partial(self):
"""Return partial of original function call"""
ba = self.data["bound_args"]
return state_partial(self.data["func"], *ba.args[1:], **ba.kwargs) |
Replace child nodes on original function call with their partials | def update_child_calls(self):
"""Replace child nodes on original function call with their partials"""
for node in filter(lambda n: len(n.arg_name), self.child_list):
self.data["bound_args"].arguments[node.arg_name] = node.partial()
self.updated = True |
Descend depth first into all child nodes | def descend(self, include_me=True):
"""Descend depth first into all child nodes"""
if include_me:
yield self
for child in self.child_list:
yield child
yield from child.descend() |
Decorator for multi to remove nodes for original test functions from root node | def multi_dec(f):
"""Decorator for multi to remove nodes for original test functions from root node"""
@wraps(f)
def wrapper(*args, **kwargs):
args = (
args[0] if len(args) == 1 and isinstance(args[0], (list, tuple)) else args
)
for arg in args:
if isinstance... |
Verify that a part that is zoomed in on has equal length. | def has_equal_part_len(state, name, unequal_msg):
"""Verify that a part that is zoomed in on has equal length.
Typically used in the context of ``check_function_def()``
Arguments:
name (str): name of the part for which to check the length to the corresponding part in the solution.
unequal_... |
Test whether abstract syntax trees match between the student and solution code. | def has_equal_ast(state, incorrect_msg=None, code=None, exact=True, append=None):
"""Test whether abstract syntax trees match between the student and solution code.
``has_equal_ast()`` can be used in two ways:
* As a robust version of ``has_code()``. By setting ``code``, you can look for the AST represent... |
Test the student code. | def has_code(state, text, pattern=True, not_typed_msg=None):
"""Test the student code.
Tests if the student typed a (pattern of) text. It is advised to use ``has_equal_ast()`` instead of ``has_code()``,
as it is more robust to small syntactical differences that don't change the code's behavior.
Args:
... |
Checks whether student imported a package or function correctly. | def has_import(
state,
name,
same_as=False,
not_imported_msg="Did you import `{{pkg}}`?",
incorrect_as_msg="Did you import `{{pkg}}` as `{{alias}}`?",
):
"""Checks whether student imported a package or function correctly.
Python features many ways to import packages.
All of these differ... |
Search student output for a pattern. | def has_output(state, text, pattern=True, no_output_msg=None):
"""Search student output for a pattern.
Among the student and solution process, the student submission and solution code as a string,
the ``Ex()`` state also contains the output that a student generated with his or her submission.
With ``h... |
Check if the right printouts happened. | def has_printout(
state, index, not_printed_msg=None, pre_code=None, name=None, copy=False
):
"""Check if the right printouts happened.
``has_printout()`` will look for the printout in the solution code that you specified with ``index`` (0 in this case), rerun the ``print()`` call in
the solution proce... |
Check whether the submission did not generate a runtime error. | def has_no_error(
state,
incorrect_msg="Have a look at the console: your code contains an error. Fix it and try again!",
):
"""Check whether the submission did not generate a runtime error.
If all SCTs for an exercise pass, before marking the submission as correct pythonwhat will automatically check wh... |
Test multiple choice exercise. | def has_chosen(state, correct, msgs):
"""Test multiple choice exercise.
Test for a MultipleChoiceExercise. The correct answer (as an integer) and feedback messages
are passed to this function.
Args:
correct (int): the index of the correct answer (should be an instruction). Starts at 1.
... |
Check whether a particular function is called. | def check_function(
state,
name,
index=0,
missing_msg=None,
params_not_matched_msg=None,
expand_msg=None,
signature=True,
):
"""Check whether a particular function is called.
``check_function()`` is typically followed by:
- ``check_args()`` to check whether the arguments we... |
Decorator to ( optionally ) run function in a process. | def process_task(f):
"""Decorator to (optionally) run function in a process."""
sig = inspect.signature(f)
@wraps(f)
def wrapper(*args, **kwargs):
# get bound arguments for call
ba = sig.bind_partial(*args, **kwargs)
# when process is specified, remove from args and use to execu... |
Get a value from process return tuple of value res if succesful | def getResultFromProcess(res, tempname, process):
"""Get a value from process, return tuple of value, res if succesful"""
if not isinstance(res, (UndefinedValue, Exception)):
value = getRepresentation(tempname, process)
return value, res
else:
return res, str(res) |
Creates code to assign name ( or tuple of names ) node from expr | def assign_from_ast(node, expr):
"""
Creates code to assign name (or tuple of names) node from expr
This is useful for recreating destructuring assignment behavior, like
a, *b = [1,2,3].
"""
if isinstance(expr, str):
expr = ast.Name(id=expr, ctx=ast.Load())
mod = ast.Module([ast.Ass... |
Override the solution code with something arbitrary. | def override(state, solution):
"""Override the solution code with something arbitrary.
There might be cases in which you want to temporarily override the solution code
so you can allow for alternative ways of solving an exercise.
When you use ``override()`` in an SCT chain, the remainder of that SCT ch... |
Update context values for student and solution environments. When has_equal_x () is used after this the context values ( in for loops and function definitions for example ) will have the values specified through his function. It is the function equivalent of the context_vals argument of the has_equal_x () functions. | def set_context(state, *args, **kwargs):
"""Update context values for student and solution environments.
When ``has_equal_x()`` is used after this, the context values (in ``for`` loops and function definitions, for example)
will have the values specified through his function. It is the function equival... |
Update/ set environemnt variables for student and solution environments. | def set_env(state, **kwargs):
"""Update/set environemnt variables for student and solution environments.
When ``has_equal_x()`` is used after this, the variables specified through this function will
be available in the student and solution process. Note that you will not see these variables
in the stud... |
Check object existence ( and equality ) | def check_object(
state, index, missing_msg=None, expand_msg=None, typestr="variable"
):
"""Check object existence (and equality)
Check whether an object is defined in the student's process, and zoom in on its value in both
student and solution process to inspect quality (with has_equal_value().
I... |
Check whether an object is an instance of a certain class. | def is_instance(state, inst, not_instance_msg=None):
"""Check whether an object is an instance of a certain class.
``is_instance()`` can currently only be used when chained from ``check_object()``, the function that is
used to 'zoom in' on the object of interest.
Args:
inst (class): The class ... |
Check whether a DataFrame was defined and it is the right type check_df () is a combo of check_object () and is_instance () that checks whether the specified object exists and whether the specified object is pandas DataFrame. | def check_df(
state, index, missing_msg=None, not_instance_msg=None, expand_msg=None
):
"""Check whether a DataFrame was defined and it is the right type
``check_df()`` is a combo of ``check_object()`` and ``is_instance()`` that checks whether the specified object exists
and whether the specified o... |
Check whether an object ( dict DataFrame etc ) has a key. | def check_keys(state, key, missing_msg=None, expand_msg=None):
"""Check whether an object (dict, DataFrame, etc) has a key.
``check_keys()`` can currently only be used when chained from ``check_object()``, the function that is
used to 'zoom in' on the object of interest.
Args:
key (str): Name ... |
Return copy of instance omitting entries that are EMPTY | def defined_items(self):
"""Return copy of instance, omitting entries that are EMPTY"""
return self.__class__(
[(k, v) for k, v in self.items() if v is not self.EMPTY], is_empty=False
) |
Dive into nested tree. | def to_child(self, append_message="", node_name="", **kwargs):
"""Dive into nested tree.
Set the current state as a state with a subtree of this syntax tree as
student tree and solution tree. This is necessary when testing if statements or
for loops for example.
"""
base... |
getter for Parser outputs | def _getx(self, Parser, ext_attr, tree):
"""getter for Parser outputs"""
# return cached output if possible
cache_key = Parser.__name__ + str(hash(tree))
if self._parser_cache.get(cache_key):
p = self._parser_cache[cache_key]
else:
# otherwise, run parser ... |
When dispatched on loops has_context the target vars are the attribute _target_vars. | def has_context_loop(state, incorrect_msg, exact_names):
"""When dispatched on loops, has_context the target vars are the attribute _target_vars.
Note: This is to allow people to call has_context on a node (e.g. for_loop) rather than
one of its attributes (e.g. body). Purely for convenience.
"""
... |
When dispatched on with statements has_context loops over each context manager. | def has_context_with(state, incorrect_msg, exact_names):
"""When dispatched on with statements, has_context loops over each context manager.
Note: This is to allow people to call has_context on the with statement, rather than
having to manually loop over each context manager.
e.g. Ex().che... |
Return child state with name part as its ast tree | def check_part(state, name, part_msg, missing_msg=None, expand_msg=None):
"""Return child state with name part as its ast tree"""
if missing_msg is None:
missing_msg = "Are you sure you defined the {{part}}? "
if expand_msg is None:
expand_msg = "Did you correctly specify the {{part}}? "
... |
Return child state with indexed name part as its ast tree. | def check_part_index(state, name, index, part_msg, missing_msg=None, expand_msg=None):
"""Return child state with indexed name part as its ast tree.
``index`` can be:
- an integer, in which case the student/solution_parts are indexed by position.
- a string, in which case the student/solution_parts ar... |
Check whether a function argument is specified. | def check_args(state, name, missing_msg=None):
"""Check whether a function argument is specified.
This function can follow ``check_function()`` in an SCT chain and verifies whether an argument is specified.
If you want to go on and check whether the argument was correctly specified, you can can continue ch... |
When checking a function definition of lambda function prepare has_equal_x for checking the call of a user - defined function. | def check_call(state, callstr, argstr=None, expand_msg=None):
"""When checking a function definition of lambda function,
prepare has_equal_x for checking the call of a user-defined function.
Args:
callstr (str): call string that specifies how the function should be called, e.g. `f(1, a = 2)`.
... |
Does this compiler support OpenMP parallelization? | def detect_openmp():
"""Does this compiler support OpenMP parallelization?"""
compiler = new_compiler()
print("Checking for OpenMP support... ")
hasopenmp = hasfunction(compiler, 'omp_get_num_threads()')
needs_gomp = hasopenmp
if not hasopenmp:
compiler.add_library('gomp')
hasopenmp = hasfunction(compiler, 'om... |
zs = np. linspace ( 0. 1. 1000 ) rp = 0. 1 wrapped = wrapper ( _quadratic_ld. _quadratic_ld zs rp 0. 1 0. 3 1 ) t = timeit. timeit ( wrapped number = 10000 ) print ( time: t ) | def make_plots():
import matplotlib.pyplot as plt
"""zs = np.linspace(0., 1., 1000)
rp = 0.1
wrapped = wrapper(_quadratic_ld._quadratic_ld, zs, rp, 0.1, 0.3, 1)
t = timeit.timeit(wrapped,number=10000)
print("time:", t)"""
"""zs = np.linspace(0., 1., 1000)
rp = 0.1
u = [0., 0.7, 0.0, -0.3]
f = _nonlinear_ld._n... |
Calculate a model light curve. | def light_curve(self, params):
"""
Calculate a model light curve.
:param params: Transit parameters
:type params: A `TransitParams` instance
:return: Relative flux
:rtype: ndarray
:Example:
>>> flux = m.light_curve(params)
"""
#recalculates rsky and fac if necessary
if params.t0 != self.t0 or... |
Return the time of periastron passage ( calculated using params. t0 ). | def get_t_periastron(self, params):
"""
Return the time of periastron passage (calculated using `params.t0`).
"""
phase = self._get_phase(params, "primary")
return params.t0 - params.per*phase |
Return the time of secondary eclipse center ( calculated using params. t0 ). | def get_t_secondary(self, params):
"""
Return the time of secondary eclipse center (calculated using `params.t0`).
"""
phase = self._get_phase(params, "primary")
phase2 = self._get_phase(params, "secondary")
return params.t0 + params.per*(phase2-phase) |
Return the time of primary transit center ( calculated using params. t_secondary ). | def get_t_conjunction(self, params):
"""
Return the time of primary transit center (calculated using `params.t_secondary`).
"""
phase = self._get_phase(params, "primary")
phase2 = self._get_phase(params, "secondary")
return params.t_secondary + params.per*(phase-phase2) |
Return the true anomaly at each time | def get_true_anomaly(self):
"""
Return the true anomaly at each time
"""
self.f = _rsky._getf(self.t_supersample, self.t0, self.per, self.a,
self.inc*pi/180., self.ecc, self.w*pi/180.,
self.transittype, self.nthreads)
return self.f |
Does this compiler support OpenMP parallelization? | def detect():
"""Does this compiler support OpenMP parallelization?"""
compiler = new_compiler()
hasopenmp = hasfunction(compiler, 'omp_get_num_threads()')
needs_gomp = hasopenmp
if not hasopenmp:
compiler.add_library('gomp')
hasopenmp = hasfunction(compiler, 'omp_get_num_threads()')
needs_gomp = hasopenmp
re... |
Validate the username/ password data against ldap directory | def validate_ldap(self):
logging.debug('Validating LDAPLoginForm against LDAP')
'Validate the username/password data against ldap directory'
ldap_mgr = current_app.ldap3_login_manager
username = self.username.data
password = self.password.data
result = ldap_mgr.authentic... |
Validates the form by calling validate on each field passing any extra Form. validate_<fieldname > validators to the field validator. | def validate(self, *args, **kwargs):
"""
Validates the form by calling `validate` on each field, passing any
extra `Form.validate_<fieldname>` validators to the field validator.
also calls `validate_ldap`
"""
valid = FlaskForm.validate(self, *args, **kwargs)
if ... |
Configures this extension with the given app. This registers an teardown_appcontext call and attaches this LDAP3LoginManager to it as app. ldap3_login_manager. | def init_app(self, app):
'''
Configures this extension with the given app. This registers an
``teardown_appcontext`` call, and attaches this ``LDAP3LoginManager``
to it as ``app.ldap3_login_manager``.
Args:
app (flask.Flask): The flask app to initialise with
... |
Configures this extension with a given configuration dictionary. This allows use of this extension without a flask app. | def init_config(self, config):
'''
Configures this extension with a given configuration dictionary.
This allows use of this extension without a flask app.
Args:
config (dict): A dictionary with configuration keys
'''
self.config.update(config)
self.... |
Add an additional server to the server pool and return the freshly created server. | def add_server(self, hostname, port, use_ssl, tls_ctx=None):
"""
Add an additional server to the server pool and return the
freshly created server.
Args:
hostname (str): Hostname of the server
port (int): Port of the server
use_ssl (bool): True if SSL... |
Add a connection to the appcontext so it can be freed/ unbound at a later time if an exception occured and it was not freed. | def _contextualise_connection(self, connection):
"""
Add a connection to the appcontext so it can be freed/unbound at
a later time if an exception occured and it was not freed.
Args:
connection (ldap3.Connection): Connection to add to the appcontext
"""
ctx... |
Remove a connection from the appcontext. | def _decontextualise_connection(self, connection):
"""
Remove a connection from the appcontext.
Args:
connection (ldap3.Connection): connection to remove from the
appcontext
"""
ctx = stack.top
if ctx is not None and connection in ctx.ldap3_... |
Cleanup after a request. Close any open connections. | def teardown(self, exception):
"""
Cleanup after a request. Close any open connections.
"""
ctx = stack.top
if ctx is not None:
if hasattr(ctx, 'ldap3_manager_connections'):
for connection in ctx.ldap3_manager_connections:
self.des... |
An abstracted authentication method. Decides whether to perform a direct bind or a search bind based upon the login attribute configured in the config. | def authenticate(self, username, password):
"""
An abstracted authentication method. Decides whether to perform a
direct bind or a search bind based upon the login attribute configured
in the config.
Args:
username (str): Username of the user to bind
pass... |
Performs a direct bind however using direct credentials. Can be used if interfacing with an Active Directory domain controller which authenticates using username@domain. com directly. | def authenticate_direct_credentials(self, username, password):
"""
Performs a direct bind, however using direct credentials. Can be used
if interfacing with an Active Directory domain controller which
authenticates using username@domain.com directly.
Performing this kind of look... |
Performs a direct bind. We can do this since the RDN is the same as the login attribute. Hence we just string together a dn to find this user with. | def authenticate_direct_bind(self, username, password):
"""
Performs a direct bind. We can do this since the RDN is the same
as the login attribute. Hence we just string together a dn to find
this user with.
Args:
username (str): Username of the user to bind (the fie... |
Performs a search bind to authenticate a user. This is required when a the login attribute is not the same as the RDN since we cannot string together their DN on the fly instead we have to find it in the LDAP then attempt to bind with their credentials. | def authenticate_search_bind(self, username, password):
"""
Performs a search bind to authenticate a user. This is
required when a the login attribute is not the same
as the RDN, since we cannot string together their DN on
the fly, instead we have to find it in the LDAP, then att... |
Gets a list of groups a user at dn is a member of | def get_user_groups(self, dn, group_search_dn=None, _connection=None):
"""
Gets a list of groups a user at dn is a member of
Args:
dn (str): The dn of the user to find memberships for.
_connection (ldap3.Connection): A connection object to use when
search... |
Gets info about a user specified at dn. | def get_user_info(self, dn, _connection=None):
"""
Gets info about a user specified at dn.
Args:
dn (str): The dn of the user to find
_connection (ldap3.Connection): A connection object to use when
searching. If not given, a temporary connection will be
... |
Gets info about a user at a specified username by searching the Users DN. Username attribute is the same as specified as LDAP_USER_LOGIN_ATTR. | def get_user_info_for_username(self, username, _connection=None):
"""
Gets info about a user at a specified username by searching the
Users DN. Username attribute is the same as specified as
LDAP_USER_LOGIN_ATTR.
Args:
username (str): Username of the user to search ... |
Gets an object at the specified dn and returns it. | def get_object(self, dn, filter, attributes, _connection=None):
"""
Gets an object at the specified dn and returns it.
Args:
dn (str): The dn of the object to find.
filter (str): The LDAP syntax search filter.
attributes (list): A list of LDAP attributes to g... |
Convenience property for externally accessing an authenticated connection to the server. This connection is automatically handled by the appcontext so you do not have to perform an unbind. | def connection(self):
"""
Convenience property for externally accessing an authenticated
connection to the server. This connection is automatically
handled by the appcontext, so you do not have to perform an unbind.
Returns:
ldap3.Connection: A bound ldap3.Connection... |
Make a connection to the LDAP Directory. | def make_connection(self, bind_user=None, bind_password=None, **kwargs):
"""
Make a connection to the LDAP Directory.
Args:
bind_user (str): User to bind with. If `None`, AUTH_ANONYMOUS is
used, otherwise authentication specified with
config['LDAP_BIN... |
Make a connection. | def _make_connection(self, bind_user=None, bind_password=None,
contextualise=True, **kwargs):
"""
Make a connection.
Args:
bind_user (str): User to bind with. If `None`, AUTH_ANONYMOUS is
used, otherwise authentication specified with
... |
Destroys a connection. Removes the connection from the appcontext and unbinds it. | def destroy_connection(self, connection):
"""
Destroys a connection. Removes the connection from the appcontext, and
unbinds it.
Args:
connection (ldap3.Connection): The connnection to destroy
"""
log.debug("Destroying connection at <{0}>".format(hex(id(con... |
Returns: str: A DN with the DN Base appended to the end. | def compiled_sub_dn(self, prepend):
"""
Returns:
str: A DN with the DN Base appended to the end.
Args:
prepend (str): The dn to prepend to the base.
"""
prepend = prepend.strip()
if prepend == '':
return self.config.get('LDAP_BASE_DN')... |
query a s3 endpoint for an image based on a string | def search(self, query=None, args=None):
'''query a s3 endpoint for an image based on a string
EXAMPLE QUERIES:
[empty] list all container collections
vsoch/dinosaur look for containers with name vsoch/dinosaur
'''
if query is not None:
return self._container_se... |
a show all search that doesn t require a query Parameters ========== quiet: if quiet is True we only are using the function to return rows of results. | def search_all(self, quiet=False):
'''a "show all" search that doesn't require a query
Parameters
==========
quiet: if quiet is True, we only are using the function to return
rows of results.
'''
results = []
for obj in self.bucket.objects.all():
subsr... |
search for a specific container. If across collections is False the query is parsed as a full container name and a specific container is returned. If across_collections is True the container is searched for across collections. If across collections is True details are not shown | def container_search(self, query, across_collections=False):
'''search for a specific container. If across collections is False,
the query is parsed as a full container name and a specific container
is returned. If across_collections is True, the container is searched
for across collections. If across c... |
query a Singularity registry for a list of images. If query is None collections are listed. | def search(self, query=None, args=None):
'''query a Singularity registry for a list of images.
If query is None, collections are listed.
EXAMPLE QUERIES:
[empty] list all collections in registry
vsoch do a general search for the expression "vsoch"
vsoch/ ... |
collection search will list all containers for a specific collection. We assume query is the name of a collection | def collection_search(self, query):
'''collection search will list all containers for a specific
collection. We assume query is the name of a collection'''
query = query.lower().strip('/')
url = '%s/collection/%s' %(self.base, query)
result = self._get(url)
if len(result) == 0:
bot.inf... |
search across labels | def label_search(self, key=None, value=None):
'''search across labels'''
if key is not None:
key = key.lower()
if value is not None:
value = value.lower()
show_details = True
if key is None and value is None:
url = '%s/labels/search' % (self.base)
show_details = Fa... |
search for a specific container. If across collections is False the query is parsed as a full container name and a specific container is returned. If across_collections is True the container is searched for across collections. If across collections is True details are not shown | def container_search(self, query, across_collections=False):
'''search for a specific container. If across collections is False,
the query is parsed as a full container name and a specific container
is returned. If across_collections is True, the container is searched
for across collections. If across c... |
query a GitLab artifacts folder for a list of images. If query is None collections are listed. | def search(self, query=None, args=None):
'''query a GitLab artifacts folder for a list of images.
If query is None, collections are listed.
'''
if query is None:
bot.exit('You must include a collection query, <collection>/<repo>')
# or default to listing (searching) all things.
retur... |
a show all search that doesn t require a query the user is shown URLs to | def search_all(self, collection, job_id=None):
'''a "show all" search that doesn't require a query
the user is shown URLs to
'''
results = [['job_id', 'browser']]
url = "%s/projects/%s/jobs" %(self.api_base,
quote_plus(collection.strip('/')))
response =... |
ensure that the client name is included in a list of tags. This is important for matching builders to the correct client. We exit on fail. Parameters ========== tags: a list of tags to look for client name in | def _client_tagged(self, tags):
'''ensure that the client name is included in a list of tags. This is
important for matching builders to the correct client. We exit
on fail.
Parameters
==========
tags: a list of tags to look for client name in
... |
a function for the client to announce him or herself depending on the level specified. If you want your client to have additional announced things here then implement the class _speak for your client. | def speak(self):
'''
a function for the client to announce him or herself, depending
on the level specified. If you want your client to have additional
announced things here, then implement the class `_speak` for your
client.
'''
if self.quiet is Fals... |
the client will announce itself given that a command is not in a particular predefined list. | def announce(self, command=None):
'''the client will announce itself given that a command is not in a
particular predefined list.
'''
if command is not None:
if command not in ['get'] and self.quiet is False:
self.speak() |
The user is required to have an application secrets file in his or her environment. The client exists with error if the variable isn t found. | def _update_secrets(self):
'''The user is required to have an application secrets file in his
or her environment. The client exists with error
if the variable isn't found.
'''
env = 'SREGISTRY_GOOGLE_DRIVE_CREDENTIALS'
self._secrets = self._get_and_update_setting(e... |
get service client for the google drive API: param version: version to use ( default is v3 ) | def _get_service(self, version='v3'):
'''get service client for the google drive API
:param version: version to use (default is v3)
'''
invalid = True
# The user hasn't disabled cache of credentials
if self._credential_cache is not None:
storage = Storage(sel... |
dummy add simple returns an object that mimics a database entry so the calling function ( in push or pull ) can interact with it equally. Most variables ( other than image_path ) are not used. | def add(self, image_path=None,
image_uri=None,
image_name=None,
url=None,
metadata=None,
save=True,
copy=False):
'''dummy add simple returns an object that mimics a database entry, so the
calling function (in push or pull) ... |
query a Singularity registry for a list of images. If query is None collections are listed. | def search(self, query=None, **kwargs):
'''query a Singularity registry for a list of images.
If query is None, collections are listed.
EXAMPLE QUERIES:
[empty] list all collections in singularity hub
vsoch do a general search for collection "vsoch"
vsoch/dinosaur ... |
a show all search that doesn t require a query | def list_all(self, **kwargs):
'''a "show all" search that doesn't require a query'''
quiet=False
if "quiet" in kwargs:
quiet = kwargs['quiet']
bot.spinner.start()
url = '%s/collections/' %self.base
results = self._paginate_get(url)
bot.spinner.stop()
if len(results) == 0:
... |
collection search will list all containers for a specific collection. We assume query is the name of a collection | def search_collection(self, query):
'''collection search will list all containers for a specific
collection. We assume query is the name of a collection'''
query = query.lower().strip('/')
q = parse_image_name(remove_uri(query), defaults=False)
# Workaround for now - the Singularity Hub search... |
pull an image from gitlab. The image is found based on the uri that should correspond to a gitlab repository and then the branch job name artifact folder and tag of the container. The minimum that we need are the job id collection and job name. Eg: | def pull(self, images, file_name=None, save=True, **kwargs):
'''pull an image from gitlab. The image is found based on the
uri that should correspond to a gitlab repository, and then
the branch, job name, artifact folder, and tag of the container.
The minimum that we need are the job id, colle... |
run will send a list of tasks a tuple with arguments through a function. the arguments should be ordered correctly.: param func: the function to run with multiprocessing. pool: param tasks: a list of tasks each a tuple of arguments to process: param func2: filter function to run result from func through ( optional ) | def run(self, func, tasks, func2=None):
'''run will send a list of tasks,
a tuple with arguments, through a function.
the arguments should be ordered correctly.
:param func: the function to run with multiprocessing.pool
:param tasks: a list of tasks, each a tuple
... |
get_cache will return the user s cache for singularity.: param subfolder: a subfolder in the cache base to retrieve specifically | def get_cache(subfolder=None, quiet=False):
'''get_cache will return the user's cache for singularity.
:param subfolder: a subfolder in the cache base to retrieve, specifically
'''
DISABLE_CACHE = convert2boolean(getenv("SINGULARITY_DISABLE_CACHE",
default=Fal... |
push an image to Google Cloud Storage meaning uploading it path: should correspond to an absolte image path ( or derive it ) name: should be the complete uri that the user has requested to push. tag: should correspond with an image tag. This is provided to mirror Docker | def push(self, path, name, tag=None):
'''push an image to Google Cloud Storage, meaning uploading it
path: should correspond to an absolte image path (or derive it)
name: should be the complete uri that the user has requested to push.
tag: should correspond with an image tag. This is provided to mi... |
upload a file from a source to a destination. The client is expected to have a bucket ( self. _bucket ) that is created when instantiated. This would be the method to do the same using the storage client but not easily done for resumable | def upload(self, source,
destination,
bucket,
chunk_size = 2 * 1024 * 1024,
metadata=None,
keep_private=True):
'''upload a file from a source to a destination. The client is expected
to have a bucket (self._bucket) that ... |
update headers with a token & other fields | def update_headers(self,fields=None):
'''update headers with a token & other fields
'''
do_reset = True
if hasattr(self, 'headers'):
if self.headers is not None:
do_reset = False
if do_reset is True:
self._reset_headers()
if fields is not None:
for key,value... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.