INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns a specific resource by resource id. | def get_resource(self, resource_id):
"""
Returns a specific resource by resource id.
"""
# resource_id could be a path such as '/asset/123' so quote
uri = self._get_resource_uri(guid=resource_id)
return self.service._get(uri) |
Create new resources and associated attributes. | def _post_resource(self, body):
"""
Create new resources and associated attributes.
Example:
acs.post_resource([
{
"resourceIdentifier": "masaya",
"parents": [],
"attributes": [
{
... |
Remove a specific resource by its identifier. | def delete_resource(self, resource_id):
"""
Remove a specific resource by its identifier.
"""
# resource_id could be a path such as '/asset/123' so quote
uri = self._get_resource_uri(guid=resource_id)
return self.service._delete(uri) |
Update a resource for the given resource id. The body is not a list but a dictionary of a single resource. | def _put_resource(self, resource_id, body):
"""
Update a resource for the given resource id. The body is not
a list but a dictionary of a single resource.
"""
assert isinstance(body, (dict)), "PUT requires body to be a dict."
# resource_id could be a path such as '/asset... |
Will add the given resource with a given identifier and attribute dictionary. | def add_resource(self, resource_id, attributes, parents=[],
issuer='default'):
"""
Will add the given resource with a given identifier and attribute
dictionary.
example/
add_resource('/asset/12', {'id': 12, 'manufacturer': 'GE'})
"""
# MA... |
Returns the full path that uniquely identifies the subject endpoint. | def _get_subject_uri(self, guid=None):
"""
Returns the full path that uniquely identifies
the subject endpoint.
"""
uri = self.uri + '/v1/subject'
if guid:
uri += '/' + urllib.quote_plus(guid)
return uri |
Returns a specific subject by subject id. | def get_subject(self, subject_id):
"""
Returns a specific subject by subject id.
"""
# subject_id could be a path such as '/user/j12y' so quote
uri = self._get_subject_uri(guid=subject_id)
return self.service._get(uri) |
Create new subjects and associated attributes. | def _post_subject(self, body):
"""
Create new subjects and associated attributes.
Example:
acs.post_subject([
{
"subjectIdentifier": "/role/evangelist",
"parents": [],
"attributes": [
... |
Remove a specific subject by its identifier. | def delete_subject(self, subject_id):
"""
Remove a specific subject by its identifier.
"""
# subject_id could be a path such as '/role/analyst' so quote
uri = self._get_subject_uri(guid=subject_id)
return self.service._delete(uri) |
Update a subject for the given subject id. The body is not a list but a dictionary of a single resource. | def _put_subject(self, subject_id, body):
"""
Update a subject for the given subject id. The body is not
a list but a dictionary of a single resource.
"""
assert isinstance(body, (dict)), "PUT requires body to be dict."
# subject_id could be a path such as '/asset/123' ... |
Will add the given subject with a given identifier and attribute dictionary. | def add_subject(self, subject_id, attributes, parents=[],
issuer='default'):
"""
Will add the given subject with a given identifier and attribute
dictionary.
example/
add_subject('/user/j12y', {'username': 'j12y'})
"""
# MAINT: consider t... |
Tests whether or not the ACS service being monitored is alive. | def _get_monitoring_heartbeat(self):
"""
Tests whether or not the ACS service being monitored is alive.
"""
target = self.uri + '/monitoring/heartbeat'
response = self.session.get(target)
return response |
Will test whether the ACS service is up and alive. | def is_alive(self):
"""
Will test whether the ACS service is up and alive.
"""
response = self.get_monitoring_heartbeat()
if response.status_code == 200 and response.content == 'alive':
return True
return False |
Returns the full path that uniquely identifies the subject endpoint. | def _get_policy_set_uri(self, guid=None):
"""
Returns the full path that uniquely identifies
the subject endpoint.
"""
uri = self.uri + '/v1/policy-set'
if guid:
uri += '/' + urllib.quote_plus(guid)
return uri |
Will create or update a policy set for the given path. | def _put_policy_set(self, policy_set_id, body):
"""
Will create or update a policy set for the given path.
"""
assert isinstance(body, (dict)), "PUT requires body to be a dict."
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._put(uri, body) |
Get a specific policy set by id. | def _get_policy_set(self, policy_set_id):
"""
Get a specific policy set by id.
"""
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._get(uri) |
Delete a specific policy set by id. Method is idempotent. | def delete_policy_set(self, policy_set_id):
"""
Delete a specific policy set by id. Method is idempotent.
"""
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._delete(uri) |
Will create a new policy set to enforce the given policy details. | def add_policy(self, name, action, resource, subject, condition,
policy_set_id=None, effect='PERMIT'):
"""
Will create a new policy set to enforce the given policy details.
The name is just a helpful descriptor for the policy.
The action maps to a HTTP verb.
Polici... |
Evaluate a policy - set against a subject and resource. | def is_allowed(self, subject_id, action, resource_id, policy_sets=[]):
"""
Evaluate a policy-set against a subject and resource.
example/
is_allowed('/user/j12y', 'GET', '/asset/12')
"""
body = {
"action": action,
"subjectIdentifier": subjec... |
Main download function | def download(url, path=None, headers=None, session=None, show_progress=True,
resume=True, auto_retry=True, max_rst_retries=5,
pass_through_opts=None, cainfo=None, user_agent=None, auth=None):
"""Main download function"""
hm = Homura(url, path, headers, session, show_progress, resume,
... |
Fill in the path of the PEM file containing the CA certificate. | def _fill_in_cainfo(self):
"""Fill in the path of the PEM file containing the CA certificate.
The priority is: 1. user provided path, 2. path to the cacert.pem
bundle provided by certifi (if installed), 3. let pycurl use the
system path where libcurl's cacert bundle is assumed to be sto... |
Sending a single cURL request to download | def curl(self):
"""Sending a single cURL request to download"""
c = self._pycurl
# Resume download
if os.path.exists(self.path) and self.resume:
mode = 'ab'
self.downloaded = os.path.getsize(self.path)
c.setopt(pycurl.RESUME_FROM, self.downloaded)
... |
Start downloading handling auto retry download resume and path moving | def start(self):
"""
Start downloading, handling auto retry, download resume and path
moving
"""
if not self.auto_retry:
self.curl()
return
while not self.is_finished:
try:
self.curl()
except pycurl.error as ... |
Move the downloaded file to the authentic path ( identified by effective URL ) | def _move_path(self):
"""
Move the downloaded file to the authentic path (identified by
effective URL)
"""
if is_temp_path(self._path) and self._pycurl is not None:
eurl = self._pycurl.getinfo(pycurl.EFFECTIVE_URL)
er = get_resource_name(eurl)
... |
Create a new instance of the UAA service. Requires a secret password for the admin user account. | def create(self, secret, **kwargs):
"""
Create a new instance of the UAA service. Requires a
secret password for the 'admin' user account.
"""
parameters = {"adminClientSecret": secret}
self.service.create(parameters=parameters)
# Store URI into environment vari... |
Add useful details to the manifest about this service so that it can be used in an application. | def add_to_manifest(self, manifest):
"""
Add useful details to the manifest about this service
so that it can be used in an application.
:param manifest: An predix.admin.app.Manifest object
instance that manages reading/writing manifest config
for a cloud foundry... |
Authenticate into the UAA instance as the admin user. | def authenticate(self):
"""
Authenticate into the UAA instance as the admin user.
"""
# Make sure we've stored uri for use
predix.config.set_env_value(self.use_class, 'uri', self._get_uri())
self.uaac = predix.security.uaa.UserAccountAuthentication()
self.uaac.au... |
Use a cryptograhically - secure Pseudorandom number generator for picking a combination of letters digits and punctuation to be our secret. | def _create_secret(self, length=12):
"""
Use a cryptograhically-secure Pseudorandom number generator for picking
a combination of letters, digits, and punctuation to be our secret.
:param length: how long to make the secret (12 seems ok most of the time)
"""
# Charset w... |
Create a new client for use by applications. | def create_client(self, client_id, client_secret):
"""
Create a new client for use by applications.
"""
assert self.is_admin, "Must authenticate() as admin to create client"
return self.uaac.create_client(client_id, client_secret) |
Add the client credentials to the specified manifest. | def add_client_to_manifest(self, client_id, client_secret, manifest):
"""
Add the client credentials to the specified manifest.
"""
assert self.is_admin, "Must authenticate() as admin to create client"
return self.uaac.add_client_to_manifest(client_id, client_secret,
... |
Returns the URI endpoint for an instance of a UAA service instance from environment inspection. | def _get_uaa_uri(self):
"""
Returns the URI endpoint for an instance of a UAA
service instance from environment inspection.
"""
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
predix_uaa = services['predix-uaa'][0]['cred... |
Returns response of authenticating with the given client and secret. | def _authenticate_client(self, client, secret):
"""
Returns response of authenticating with the given client and
secret.
"""
client_s = str.join(':', [client, secret])
credentials = base64.b64encode(client_s.encode('utf-8')).decode('utf-8')
headers = {
... |
Returns the response of authenticating with the given user and password. | def _authenticate_user(self, user, password):
"""
Returns the response of authenticating with the given
user and password.
"""
headers = self._get_headers()
params = {
'username': user,
'password': password,
'grant_type': 'p... |
For a given client will test whether or not the token has expired. | def is_expired_token(self, client):
"""
For a given client will test whether or not the token
has expired.
This is for testing a client object and does not look up
from client_id. You can use _get_client_from_cache() to
lookup a client from client_id.
"""
... |
If we don t yet have a uaa cache we need to initialize it. As there may be more than one UAA instance we index by issuer and then store any clients users etc. | def _initialize_uaa_cache(self):
"""
If we don't yet have a uaa cache we need to
initialize it. As there may be more than one
UAA instance we index by issuer and then store
any clients, users, etc.
"""
try:
os.makedirs(os.path.dirname(self._cache_path... |
Read cache of UAA client/ user details. | def _read_uaa_cache(self):
"""
Read cache of UAA client/user details.
"""
self._cache_path = os.path.expanduser('~/.predix/uaa.json')
if not os.path.exists(self._cache_path):
return self._initialize_uaa_cache()
with open(self._cache_path, 'r') as data:
... |
For the given client_id return what is cached. | def _get_client_from_cache(self, client_id):
"""
For the given client_id return what is
cached.
"""
data = self._read_uaa_cache()
# Only if we've cached any for this issuer
if self.uri not in data:
return
for client in data[self.uri]:
... |
Cache the client details into a cached file on disk. | def _write_to_uaa_cache(self, new_item):
"""
Cache the client details into a cached file on disk.
"""
data = self._read_uaa_cache()
# Initialize client list if first time
if self.uri not in data:
data[self.uri] = []
# Remove existing client record an... |
Authenticate the given client against UAA. The resulting token will be cached for reuse. | def authenticate(self, client_id, client_secret, use_cache=True):
"""
Authenticate the given client against UAA. The resulting token
will be cached for reuse.
"""
# We will reuse a token for as long as we have one cached
# and it hasn't expired.
if use_cache:
... |
Log currently authenticated user out invalidating any existing tokens. | def logout(self):
"""
Log currently authenticated user out, invalidating any existing tokens.
"""
# Remove token from local cache
# MAINT: need to expire token on server
data = self._read_uaa_cache()
if self.uri in data:
for client in data[self.uri]:
... |
Simple POST request for a given uri path. | def _post(self, uri, data, headers=None):
"""
Simple POST request for a given uri path.
"""
if not headers:
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
logging.debug("BODY=" + str(data))
... |
Returns the bare access token for the authorized client. | def get_token(self):
"""
Returns the bare access token for the authorized client.
"""
if not self.authenticated:
raise ValueError("Must authenticate() as a client first.")
# If token has expired we'll need to refresh and get a new
# client credential
... |
Returns the scopes for the authenticated client. | def get_scopes(self):
"""
Returns the scopes for the authenticated client.
"""
if not self.authenticated:
raise ValueError("Must authenticate() as a client first.")
scope = self.client['scope']
return scope.split() |
Warn that the required scope is not found in the scopes granted to the currently authenticated user. | def assert_has_permission(self, scope_required):
"""
Warn that the required scope is not found in the scopes
granted to the currently authenticated user.
::
# The admin user should have client admin permissions
uaa.assert_has_permission('admin', 'clients.admin')... |
Grant the given client_id permissions for managing clients. | def grant_client_permissions(self, client_id, admin=False, write=False,
read=False, secret=False):
"""
Grant the given client_id permissions for managing clients.
- clients.admin: super user scope to create, modify, delete
- clients.write: scope ot create and modify clients
... |
Returns the clients stored in the instance of UAA. | def get_clients(self):
"""
Returns the clients stored in the instance of UAA.
"""
self.assert_has_permission('clients.read')
uri = self.uri + '/oauth/clients'
headers = self.get_authorization_headers()
response = requests.get(uri, headers=headers)
return ... |
Returns details about a specific client by the client_id. | def get_client(self, client_id):
"""
Returns details about a specific client by the client_id.
"""
self.assert_has_permission('clients.read')
uri = self.uri + '/oauth/clients/' + client_id
headers = self.get_authorization_headers()
response = requests.get(uri, he... |
Will extend the client with additional scopes or authorities. Any existing scopes and authorities will be left as is unless asked to replace entirely. | def update_client_grants(self, client_id, scope=[], authorities=[],
grant_types=[], redirect_uri=[], replace=False):
"""
Will extend the client with additional scopes or
authorities. Any existing scopes and authorities will be left
as is unless asked to replace entirely.
... |
Grant the given client_id permissions for managing users. System for Cross - domain Identity Management ( SCIM ) are required for accessing/ Users and/ Groups endpoints of UAA. | def grant_scim_permissions(self, client_id, read=False, write=False,
create=False, userids=False, zones=False, invite=False,
openid=False):
"""
Grant the given client_id permissions for managing users. System
for Cross-domain Identity Management (SCIM) are required for a... |
Will create a new client for your application use. | def create_client(self, client_id, client_secret, manifest=None,
client_credentials=True, refresh_token=True,
authorization_code=False, redirect_uri=[]):
"""
Will create a new client for your application use.
- client_credentials: allows client to get access token
... |
Add the given client/ secret to the manifest for use in the application. | def add_client_to_manifest(self, client_id, client_secret, manifest):
"""
Add the given client / secret to the manifest for use in
the application.
"""
client_id_key = 'PREDIX_APP_CLIENT_ID'
manifest.add_env_var(client_id_key, client_id)
client_secret_key = 'PRED... |
Creates a new user account with the required details. | def create_user(self, username, password, family_name, given_name, primary_email,
details={}):
"""
Creates a new user account with the required details.
::
create_user('j12y', 'my-secret', 'Delancey', 'Jayson', 'volcano@ge.com')
"""
self.assert_has_perm... |
Delete user with given id. | def delete_user(self, id):
"""
Delete user with given id.
"""
self.assert_has_permission('scim.write')
uri = self.uri + '/Users/%s' % id
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
resp... |
Returns users accounts stored in UAA. See https:// docs. cloudfoundry. org/ api/ uaa/ #list63 | def get_users(self, filter=None, sortBy=None, sortOrder=None,
startIndex=None, count=None):
"""
Returns users accounts stored in UAA.
See https://docs.cloudfoundry.org/api/uaa/#list63
For filtering help, see:
http://www.simplecloud.info/specs/draft-scim-api-01.html#q... |
Returns details for user of the given username. | def get_user_by_username(self, username):
"""
Returns details for user of the given username.
If there is more than one match will only return the first. Use
get_users() for full result set.
"""
results = self.get_users(filter='username eq "%s"' % (username))
if... |
Returns details for user with the given email address. | def get_user_by_email(self, email):
"""
Returns details for user with the given email address.
If there is more than one match will only return the first. Use
get_users() for full result set.
"""
results = self.get_users(filter='email eq "%s"' % (email))
if resu... |
Returns details about the user for the given id. | def get_user(self, id):
"""
Returns details about the user for the given id.
Use get_user_by_email() or get_user_by_username() for help
identifiying the id.
"""
self.assert_has_permission('scim.read')
return self._get(self.uri + '/Users/%s' % (id)) |
Create an instance of the Time Series Service with the typical starting settings. | def create(self):
"""
Create an instance of the Time Series Service with the typical
starting settings.
"""
self.service.create()
predix.config.set_env_value(self.use_class, 'ingest_uri',
self.get_ingest_uri())
predix.config.set_env_value(self.use... |
Grant the given client id all the scopes and authorities needed to work with the timeseries service. | def grant_client(self, client_id, read=True, write=True):
"""
Grant the given client id all the scopes and authorities
needed to work with the timeseries service.
"""
scopes = ['openid']
authorities = ['uaa.resource']
if write:
for zone in self.servic... |
Return the uri used for queries on time series data. | def get_query_uri(self):
"""
Return the uri used for queries on time series data.
"""
# Query URI has extra path we don't want so strip it off here
query_uri = self.service.settings.data['query']['uri']
query_uri = urlparse(query_uri)
return query_uri.scheme + ':/... |
Add useful details to the manifest about this service so that it can be used in an application. | def add_to_manifest(self, manifest):
"""
Add useful details to the manifest about this service
so that it can be used in an application.
:param manifest: An predix.admin.app.Manifest object
instance that manages reading/writing manifest config
for a cloud foundry... |
This method tries to determine the requirements of a particular project by inspecting the possible places that they could be defined. | def find_requirements(path):
"""
This method tries to determine the requirements of a particular project
by inspecting the possible places that they could be defined.
It will attempt, in order:
1) to parse setup.py in the root for an install_requires value
2) to read a requirements.txt file or... |
Returns the GUID for the app instance with the given name. | def get_app_guid(self, app_name):
"""
Returns the GUID for the app instance with
the given name.
"""
summary = self.space.get_space_summary()
for app in summary['apps']:
if app['name'] == app_name:
return app['guid'] |
Delete the given app. | def delete_app(self, app_name):
"""
Delete the given app.
Will fail intentionally if there are any service
bindings. You must delete those first.
"""
if app_name not in self.space.get_apps():
logging.warning("App not found so... succeeded?")
retu... |
Reads in config file of UAA credential information or generates one as a side - effect if not yet initialized. | def _get_service_config(self):
"""
Reads in config file of UAA credential information
or generates one as a side-effect if not yet
initialized.
"""
# Should work for windows, osx, and linux environments
if not os.path.exists(self.config_path):
try:
... |
Will write the config out to disk. | def _write_service_config(self):
"""
Will write the config out to disk.
"""
with open(self.config_path, 'w') as output:
output.write(json.dumps(self.data, sort_keys=True, indent=4)) |
Create an instance of the Blob Store Service with the typical starting settings. | def create(self, **kwargs):
"""
Create an instance of the Blob Store Service with the typical
starting settings.
"""
self.service.create(**kwargs)
predix.config.set_env_value(self.use_class, 'url',
self.service.settings.data['url'])
predix.config.... |
Add useful details to the manifest about this service so that it can be used in an application. | def add_to_manifest(self, manifest):
"""
Add useful details to the manifest about this service
so that it can be used in an application.
:param manifest: An predix.admin.app.Manifest object
instance that manages reading/writing manifest config
for a cloud foundry... |
return a generator for all subscribe messages: return: None | def subscribe(self):
"""
return a generator for all subscribe messages
:return: None
"""
while self.run_subscribe_generator:
if len(self._rx_messages) != 0:
yield self._rx_messages.pop(0)
return |
send acks to the service: param message: EventHub_pb2. Message: return: None | def send_acks(self, message):
"""
send acks to the service
:param message: EventHub_pb2.Message
:return: None
"""
if isinstance(message, EventHub_pb2.Message):
ack = EventHub_pb2.Ack(partition=message.partition, offset=message.offset)
self.grpc_man... |
generate the subscribe stub headers based on the supplied config: return: i | def _generate_subscribe_headers(self):
"""
generate the subscribe stub headers based on the supplied config
:return: i
"""
headers =[]
headers.append(('predix-zone-id', self.eventhub_client.zone_id))
token = self.eventhub_client.service._get_bearer_token()
... |
Returns the raw results of an asset search for a given bounding box. | def _get_assets(self, bbox, size=None, page=None, asset_type=None,
device_type=None, event_type=None, media_type=None):
"""
Returns the raw results of an asset search for a given bounding
box.
"""
uri = self.uri + '/v1/assets/search'
headers = self._get_header... |
Query the assets stored in the intelligent environment for a given bounding box and query. | def get_assets(self, bbox, **kwargs):
"""
Query the assets stored in the intelligent environment for a given
bounding box and query.
Assets can be filtered by type of asset, event, or media available.
- device_type=['DATASIM']
- asset_type=['CAMERA']
... |
Returns raw response for an given asset by its unique id. | def _get_asset(self, asset_uid):
"""
Returns raw response for an given asset by its unique id.
"""
uri = self.uri + '/v2/assets/' + asset_uid
headers = self._get_headers()
return self.service._get(uri, headers=headers) |
Label input grid with hysteresis method. | def label(self, input_grid):
"""
Label input grid with hysteresis method.
Args:
input_grid: 2D array of values.
Returns:
Labeled output grid.
"""
unset = 0
high_labels, num_labels = label(input_grid > self.high_thresh)
region_rank... |
Remove labeled objects that do not meet size threshold criteria. | def size_filter(labeled_grid, min_size):
"""
Remove labeled objects that do not meet size threshold criteria.
Args:
labeled_grid: 2D output from label method.
min_size: minimum size of object in pixels.
Returns:
labeled grid with smaller objects remo... |
Plots a set receiver/ relative operating characteristic ( ROC ) curves from DistributedROC objects. | def roc_curve(roc_objs, obj_labels, colors, markers, filename, figsize=(8, 8),
xlabel="Probability of False Detection",
ylabel="Probability of Detection",
title="ROC Curve", ticks=np.arange(0, 1.1, 0.1), dpi=300,
legend_params=None, bootstrap_sets=None, ci=(2.5, 9... |
Draws a performance diagram from a set of DistributedROC objects. | def performance_diagram(roc_objs, obj_labels, colors, markers, filename, figsize=(8, 8),
xlabel="Success Ratio (1-FAR)",
ylabel="Probability of Detection", ticks=np.arange(0, 1.1, 0.1),
dpi=300, csi_cmap="Blues",
csi_label="... |
Plot reliability curves against a 1: 1 diagonal to determine if probability forecasts are consistent with their observed relative frequency. | def reliability_diagram(rel_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Forecast Probability",
ylabel="Observed Relative Frequency", ticks=np.arange(0, 1.05, 0.05), dpi=300, inset_size=1.5,
title="Reliability Diagram", legend_params=None, bootstra... |
Plot reliability curves against a 1: 1 diagonal to determine if probability forecasts are consistent with their observed relative frequency. Also adds gray areas to show where the climatological probabilities lie and what areas result in a positive Brier Skill Score. | def attributes_diagram(rel_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Forecast Probability",
ylabel="Observed Relative Frequency", ticks=np.arange(0, 1.05, 0.05), dpi=300,
title="Attributes Diagram", legend_params=None, inset_params=None,
... |
Return a string value that the user enters. Raises exception for cancel. | def get_string(self, prompt, default_str=None) -> str:
"""Return a string value that the user enters. Raises exception for cancel."""
accept_event = threading.Event()
value_ref = [None]
def perform():
def accepted(text):
value_ref[0] = text
ac... |
Return a boolean value for accept/ reject. | def __accept_reject(self, prompt, accepted_text, rejected_text, display_rejected):
"""Return a boolean value for accept/reject."""
accept_event = threading.Event()
result_ref = [False]
def perform():
def accepted():
result_ref[0] = True
accept... |
Returns the weight ( w ) using OLS of r * w = gp. _ytr | def compute_weight(self, r, ytr=None, mask=None):
"""Returns the weight (w) using OLS of r * w = gp._ytr """
ytr = self._ytr if ytr is None else ytr
mask = self._mask if mask is None else mask
return compute_weight(r, ytr, mask) |
Test whether the predicted values are finite | def isfinite(self):
"Test whether the predicted values are finite"
if self._multiple_outputs:
if self.hy_test is not None:
r = [(hy.isfinite() and (hyt is None or hyt.isfinite()))
for hy, hyt in zip(self.hy, self.hy_test)]
else:
... |
Parse an arbitrary block of python code to get the value of a named argument from inside a function call | def value_of_named_argument_in_function(argument_name, function_name, search_str,
resolve_varname=False):
""" Parse an arbitrary block of python code to get the value of a named argument
from inside a function call
"""
try:
search_str = unicode(search_... |
Search for a regex in a file | def regex_in_file(regex, filepath, return_match=False):
""" Search for a regex in a file
If return_match is True, return the found object instead of a boolean
"""
file_content = get_file_content(filepath)
re_method = funcy.re_find if return_match else funcy.re_test
return re_method(regex, file_... |
Search for a regex in a file contained within the package directory | def regex_in_package_file(regex, filename, package_name, return_match=False):
""" Search for a regex in a file contained within the package directory
If return_match is True, return the found object instead of a boolean
"""
filepath = package_file_path(filename, package_name)
return regex_in_file(r... |
Test to see if a string is a URL or not defined in this case as a string for which urlparse returns a scheme component | def string_is_url(test_str):
""" Test to see if a string is a URL or not, defined in this case as a string for which
urlparse returns a scheme component
>>> string_is_url('somestring')
False
>>> string_is_url('https://some.domain.org/path')
True
"""
parsed = urlparse.urlparse(test_str)
... |
Begin transaction state for item. | def item_transaction(self, item) -> Transaction:
"""Begin transaction state for item.
A transaction state is exists to prevent writing out to disk, mainly for performance reasons.
All changes to the object are delayed until the transaction state exits.
This method is thread safe.
... |
Insert a new data item into document model. | def insert_data_item(self, before_index, data_item, auto_display: bool = True) -> None:
"""Insert a new data item into document model.
This method is NOT threadsafe.
"""
assert data_item is not None
assert data_item not in self.data_items
assert before_index <= len(self.... |
Remove data item from document model. | def remove_data_item(self, data_item: DataItem.DataItem, *, safe: bool=False) -> typing.Optional[typing.Sequence]:
"""Remove data item from document model.
This method is NOT threadsafe.
"""
# remove data item from any computations
return self.__cascade_delete(data_item, safe=sa... |
Cascade delete an item. | def __cascade_delete_inner(self, master_item, safe: bool=False) -> typing.Optional[typing.Sequence]:
"""Cascade delete an item.
Returns an undelete log that can be used to undo the cascade deletion.
Builds a cascade of items to be deleted and dependencies to be removed when the passed item is ... |
Return the list of data items containing data that directly depends on data in this item. | def get_dependent_items(self, item) -> typing.List:
"""Return the list of data items containing data that directly depends on data in this item."""
with self.__dependency_tree_lock:
return copy.copy(self.__dependency_tree_source_to_target_map.get(weakref.ref(item), list())) |
Return the list of data items containing data that directly depends on data in this item. | def __get_deep_dependent_item_set(self, item, item_set) -> None:
"""Return the list of data items containing data that directly depends on data in this item."""
if not item in item_set:
item_set.add(item)
with self.__dependency_tree_lock:
for dependent in self.get... |
Return the list of data items containing data that directly depends on data in this item. | def get_dependent_data_items(self, data_item: DataItem.DataItem) -> typing.List[DataItem.DataItem]:
"""Return the list of data items containing data that directly depends on data in this item."""
with self.__dependency_tree_lock:
return [data_item for data_item in self.__dependency_tree_sour... |
Return a context object for a document - wide transaction. | def transaction_context(self):
"""Return a context object for a document-wide transaction."""
class DocumentModelTransaction:
def __init__(self, document_model):
self.__document_model = document_model
def __enter__(self):
self.__document_model.per... |
Return a context manager to put the data item in a live state. | def data_item_live(self, data_item):
""" Return a context manager to put the data item in a 'live state'. """
class LiveContextManager:
def __init__(self, manager, object):
self.__manager = manager
self.__object = object
def __enter__(self):
... |
Begins a live state for the data item. | def begin_data_item_live(self, data_item):
"""Begins a live state for the data item.
The live state is propagated to dependent data items.
This method is thread safe. See slow_test_dependent_data_item_removed_while_live_data_item_becomes_unlive.
"""
with self.__live_data_items_... |
Ends a live state for the data item. | def end_data_item_live(self, data_item):
"""Ends a live state for the data item.
The live-ness property is propagated to dependent data items, similar to the transactions.
This method is thread safe.
"""
with self.__live_data_items_lock:
live_count = self.__live_dat... |
Construct a data item reference. | def __construct_data_item_reference(self, hardware_source: HardwareSource.HardwareSource, data_channel: HardwareSource.DataChannel):
"""Construct a data item reference.
Construct a data item reference and assign a data item to it. Update data item session id and session metadata.
Also connect t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.