text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_services(self): """ Returns a flat list of the service names available from the marketplace for this space. """
services = [] for resource in self._get_services()['resources']: services.append(resource['entity']['label']) return services
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_instances(self, page_number=None): """ Returns the service instances activated in this space. """
instances = [] uri = '/v2/spaces/%s/service_instances' % self.guid json_response = self.api.get(uri) instances += json_response['resources'] while json_response['next_url'] is not None: json_response = self.api.get(json_response['next_url']) instances += ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_instances(self): """ Returns a flat list of the names of services created in this space. """
services = [] for resource in self._get_instances(): services.append(resource['entity']['name']) return services
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_service_of_type(self, service_type): """ Tests whether a service instance exists for the given service. """
summary = self.get_space_summary() for instance in summary['services']: if 'service_plan' in instance: if service_type == instance['service_plan']['service']['label']: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def purge(self): """ Remove all services and apps from the space. Will leave the space itself, call delete_space() if you want to remove that too. Similar to `cf...
logging.warning("Purging all services from space %s" % (self.name)) service = predix.admin.cf.services.Service() for service_name in self.get_instances(): service.purge(service_name) apps = predix.admin.cf.apps.App() for app_name in self.get_apps():...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, max_wait=300, allocated_storage=None, encryption_at_rest=None, restore_to_time=None, **kwargs): """ Create an instance of the PostgreSQL service...
# MAINT: Add these if there is demand for it and validated if allocated_storage or encryption_at_rest or restore_to_time: raise NotImplementedError() # Will need to wait for the service to be provisioned before can add # service keys and get env details. self.ser...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, asset, timeseries, client_id, client_secret, ui_client_id=None, ui_client_secret=None): """ Create an instance of the Analytics Framework Servic...
assert isinstance(asset, predix.admin.asset.Asset), \ "Require an existing predix.admin.asset.Asset instance" assert isinstance(timeseries, predix.admin.timeseries.TimeSeries), \ "Require an existing predix.admin.timeseries.TimeSeries instance" parameters = { ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_to_manifest(self, manifest): """ Add to the manifest to make sure it is bound to the application. """
manifest.add_service(self.service.name) manifest.write_manifest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_zone_id(self): """ Returns the Predix Zone Id for the service that is a required header in service calls. """
if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) predix_asset = services['predix-asset'][0]['credentials'] return predix_asset['zone']['http-header-value'] else: return predix.config.get_env_value(self, 'zone_id')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_collections(self): """ Returns a flat list of the names of collections in the asset service. .. ['wind-turbines', 'jet-engines'] """
collections = [] for result in self._get_collections(): collections.append(result['collection']) return collections
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_collection(self, collection, filter=None, fields=None, page_size=None): """ Returns a specific collection from the asset service with the given collectio...
params = {} if filter: params['filter'] = filter if fields: params['fields'] = fields if page_size: params['pageSize'] = page_size uri = self.uri + '/v1' + collection return self.service._get(uri, params=params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_guid(self, collection=None): """ Returns a new guid for use in posting a new asset to a collection. """
guid = str(uuid.uuid4()) if collection: return str.join('/', [collection, guid]) else: return guid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_collection(self, collection, body): """ Creates a new collection. This is mostly just transport layer and passes collection and body along. It presumes ...
assert isinstance(body, (list)), "POST requires body to be a list" assert collection.startswith('/'), "Collections must start with /" uri = self.uri + '/v1' + collection return self.service._post(uri, body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put_collection(self, collection, body): """ Updates an existing collection. The collection being updated *is* expected to include the id. """
uri = self.uri + '/v1' + collection return self.service._put(uri, body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_collection(self, collection): """ Deletes an existing collection. The collection being updated *is* expected to include the id. """
uri = str.join('/', [self.uri, collection]) return self.service._delete(uri)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_collection(self, collection, changes): """ Will make specific updates to a record based on JSON Patch documentation. https://tools.ietf.org/html/rfc690...
uri = str.join('/', [self.uri, collection]) return self.service._patch(uri, changes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, collection): """ Save an asset collection to the service. """
assert isinstance(collection, predix.data.asset.AssetCollection), "Expected AssetCollection" collection.validate() self.put_collection(collection.uri, collection.__dict__)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_manifest_from_space(self): """ Populate a manifest file generated from details from the cloud foundry space environment. """
space = predix.admin.cf.spaces.Space() summary = space.get_space_summary() for instance in summary['services']: service_type = instance['service_plan']['service']['label'] name = instance['name'] if service_type in self.supported: service = s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lock_to_org_space(self): """ Lock the manifest to the current organization and space regardless of Cloud Foundry target. """
self.add_env_var('PREDIX_ORGANIZATION_GUID', self.space.org.guid) self.add_env_var('PREDIX_ORGANIZATION_NAME', self.space.org.name) self.add_env_var('PREDIX_SPACE_GUID', self.space.guid) self.add_env_var('PREDIX_SPACE_NAME', self.space.name) self.write_manifest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_uaa(self, admin_secret, **kwargs): """ Creates an instance of UAA Service. :param admin_secret: The secret password for administering the service such...
uaa = predix.admin.uaa.UserAccountAuthentication(**kwargs) if not uaa.exists(): uaa.create(admin_secret, **kwargs) uaa.add_to_manifest(self) return uaa
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_client(self, client_id=None, client_secret=None, uaa=None): """ Create a client and add it to the manifest. :param client_id: The client id used to au...
if not uaa: uaa = predix.admin.uaa.UserAccountAuthentication() # Client id and secret can be generated if not provided as arguments if not client_id: client_id = uaa._create_id() if not client_secret: client_secret = uaa._create_secret() u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_timeseries(self, **kwargs): """ Creates an instance of the Time Series Service. """
ts = predix.admin.timeseries.TimeSeries(**kwargs) ts.create() client_id = self.get_client_id() if client_id: ts.grant_client(client_id) ts.add_to_manifest(self) return ts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_blobstore(self, **kwargs): """ Creates an instance of the BlobStore Service. """
blobstore = predix.admin.blobstore.BlobStore(**kwargs) blobstore.create() blobstore.add_to_manifest(self) return blobstore
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_logstash(self, **kwargs): """ Creates an instance of the Logging Service. """
logstash = predix.admin.logstash.Logging(**kwargs) logstash.create() logstash.add_to_manifest(self) logging.info('Install Kibana-Me-Logs application by following GitHub instructions') logging.info('git clone https://github.com/cloudfoundry-community/kibana-me-logs.git') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_cache(self, **kwargs): """ Creates an instance of the Cache Service. """
cache = predix.admin.cache.Cache(**kwargs) cache.create(**kwargs) cache.add_to_manifest(self) return cache
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_service_marketplace(self, available=True, unavailable=False, deprecated=False): """ Returns a list of service names. Can return all services, just those ...
supported = set(self.supported.keys()) all_services = set(self.space.get_services()) results = set() if available: results.update(supported) if unavailable: results.update(all_services.difference(supported)) if deprecated: results.up...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _auto_authenticate(self): """ If we are in an app context we can authenticate immediately. """
client_id = predix.config.get_env_value(predix.app.Manifest, 'client_id') client_secret = predix.config.get_env_value(predix.app.Manifest, 'client_secret') if client_id and client_secret: logging.info("Automatically authenticated as %s" % (client_id)) self.uaa.authentic...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get(self, uri, params=None, headers=None): """ Simple GET request for a given path. """
if not headers: headers = self._get_headers() logging.debug("URI=" + str(uri)) logging.debug("HEADERS=" + str(headers)) response = self.session.get(uri, headers=headers, params=params) logging.debug("STATUS=" + str(response.status_code)) if response.status_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post(self, uri, data): """ Simple POST request for a given path. """
headers = self._get_headers() logging.debug("URI=" + str(uri)) logging.debug("BODY=" + json.dumps(data)) response = self.session.post(uri, headers=headers, data=json.dumps(data)) if response.status_code in [200, 204]: try: return res...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _put(self, uri, data): """ Simple PUT operation for a given path. """
headers = self._get_headers() logging.debug("URI=" + str(uri)) logging.debug("BODY=" + json.dumps(data)) response = self.session.put(uri, headers=headers, data=json.dumps(data)) if response.status_code in [201, 204]: return data else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _delete(self, uri): """ Simple DELETE operation for a given path. """
headers = self._get_headers() response = self.session.delete(uri, headers=headers) # Will return a 204 on successful delete if response.status_code == 204: return response else: logging.error(response.content) response.raise_for_status()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _patch(self, uri, data): """ Simple PATCH operation for a given path. The body is expected to list operations to perform to update the data. Operations inclu...
headers = self._get_headers() response = self.session.patch(uri, headers=headers, data=json.dumps(data)) # Will return a 204 on successful patch if response.status_code == 204: return response else: logging.error(response.content) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_resource_uri(self, guid=None): """ Returns the full path that uniquely identifies the resource endpoint. """
uri = self.uri + '/v1/resource' if guid: uri += '/' + urllib.quote_plus(guid) return uri
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post_resource(self, body): """ Create new resources and associated attributes. Example: acs.post_resource([ { "resourceIdentifier": "masaya", "parents": [],...
assert isinstance(body, (list)), "POST for requires body to be a list" uri = self._get_resource_uri() return self.service._post(uri, body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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/123' so quote uri = self._get_resource_uri(guid=resource_id) return self.service._put(uri, body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_resource(self, resource_id, attributes, parents=[], issuer='default'): """ Will add the given resource with a given identifier and attribute dictionary. ...
# MAINT: consider test to avoid adding duplicate resource id assert isinstance(attributes, (dict)), "attributes expected to be dict" attrs = [] for key in attributes.keys(): attrs.append({ 'issuer': issuer, 'name': key, 'value...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post_subject(self, body): """ Create new subjects and associated attributes. Example: acs.post_subject([ { "subjectIdentifier": "/role/evangelist", "parents...
assert isinstance(body, (list)), "POST requires body to be a list" uri = self._get_subject_uri() return self.service._post(uri, body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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' so quote uri = self._get_subject_uri(guid=subject_id) return self.service._put(uri, body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_subject(self, subject_id, attributes, parents=[], issuer='default'): """ Will add the given subject with a given identifier and attribute dictionary. exa...
# MAINT: consider test to avoid adding duplicate subject id assert isinstance(attributes, (dict)), "attributes expected to be dict" attrs = [] for key in attributes.keys(): attrs.append({ 'issuer': issuer, 'name': key, 'value'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 poli...
# If not given a policy set id will generate one if not policy_set_id: policy_set_id = str(uuid.uuid4()) # Only a few operations / actions are supported in policy definitions if action not in ['GET', 'PUT', 'POST', 'DELETE']: raise ValueError("Invalid action") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'...
body = { "action": action, "subjectIdentifier": subject_id, "resourceIdentifier": resource_id, } if policy_sets: body['policySetsEvaluationOrder'] = policy_sets # Will return a 200 with decision uri = self.uri + '/v1/policy-evalu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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,...
hm = Homura(url, path, headers, session, show_progress, resume, auto_retry, max_rst_retries, pass_through_opts, cainfo, user_agent, auth) hm.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 b...
if self.cainfo: cainfo = self.cainfo else: try: cainfo = certifi.where() except AttributeError: cainfo = None if cainfo: self._pycurl.setopt(pycurl.CAINFO, cainfo)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) else: mode = 'wb' with open(self.path, mode) as...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 e: # transfer closed with n bytes remaining to read if e.args[0] == pycurl.E_PARTIAL_FILE: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 variable predix.config.set_env_value(self.use_class, 'uri', self._get_uri()) # Once we create it login self.authenticate()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.authenticate('admin', self._get_admin_secret(), use_cache=False) self.is_admin = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_secret(self, length=12): """ Use a cryptograhically-secure Pseudorandom number generator for picking a combination of letters, digits, and punctuatio...
# Charset will have 64 +- characters charset = string.digits + string.ascii_letters + '+-' return "".join(random.SystemRandom().choice(charset) for _ in range(length))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, manifest)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]['credentials'] return predix_uaa['uri'] else: return predix.config.get_env_value(self, 'uri')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = { 'Content-Type': 'application/x-www-form-urlencoded', 'Cache-Control': 'no-cache', 'Authorization': 'Basic ' + credentials ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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': 'password', } uri = self.uri + '/oauth/token' logging.debug("URI=" + str(uri)) logging.debug("HEADERS=" + str(headers))...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
if 'expires' not in client: return True expires = dateutil.parser.parse(client['expires']) if expires < datetime.datetime.now(): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
try: os.makedirs(os.path.dirname(self._cache_path)) except OSError as exc: if exc.errno != errno.EEXIST: raise data = {} data[self.uri] = [] return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]: if client['id'] == client_id: return client
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 and any expired tokens for client in data[self.uri]: if new_item['id'] == client['id']: dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: client = self._get_client_from_cache(client_id) if (client) and (not self.is_expired_token(client)): self.authenticated = True self.client = c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]: if client['id'] == self.client['id']: data[self.uri].remove(client) with open...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)) response = self.session.post(uri, headers=headers, data=json.dumps(data)) logging.deb...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 if self.is_expired_token(self.client): logging.info("client token expired, will need to refresh t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assert_has_permission(self, scope_required): """ Warn that the required scope is not found in the scopes granted to the currently authenticated user. :: # Th...
if not self.authenticated: raise ValueError("Must first authenticate()") if scope_required not in self.get_scopes(): logging.warning("Authenticated as %s" % (self.client['id'])) logging.warning("Have scopes: %s" % (str.join(',', self.get_scopes()))) logg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grant_client_permissions(self, client_id, admin=False, write=False, read=False, secret=False): """ Grant the given client_id permissions for managing clients...
self.assert_has_permission('clients.admin') perms = [] if admin: perms.append('clients.admin') if write or admin: perms.append('clients.write') if read or admin: perms.append('clients.read') if secret or admin: perms.ap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 response.json()['resources']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, headers=headers) if response.status_code == 200: return response.json() else: # Not ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_client_grants(self, client_id, scope=[], authorities=[], grant_types=[], redirect_uri=[], replace=False): """ Will extend the client with additional s...
self.assert_has_permission('clients.write') client = self.get_client(client_id) if not client: raise ValueError("Must first create client: '%s'" % (client_id)) if replace: changes = { 'client_id': client_id, 'scope': scope, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_client(self, client_id, client_secret, manifest=None, client_credentials=True, refresh_token=True, authorization_code=False, redirect_uri=[]): """ Wil...
self.assert_has_permission('clients.admin') if authorization_code and not redirect_uri: raise ValueError("Must provide a redirect_uri for clients used with authorization_code") # Check if client already exists client = self.get_client(client_id) if client: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_user(self, username, password, family_name, given_name, primary_email, details={}): """ Creates a new user account with the required details. :: creat...
self.assert_has_permission('scim.write') data = { 'userName': username, 'password': password, 'name': { 'familyName': family_name, 'givenName': given_name, }, 'emails': [{ 'value': primary_e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)) response = self.session.delete(uri, headers=headers) logging.debug("STATUS=" + st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
results = self.get_users(filter='username eq "%s"' % (username)) if results['totalResults'] == 0: logging.warning("Found no matches for given username.") return elif results['totalResults'] > 1: logging.warning("Found %s matches for username %s" % ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ge...
results = self.get_users(filter='email eq "%s"' % (email)) if results['totalResults'] == 0: logging.warning("Found no matches for given email.") return elif results['totalResults'] > 1: logging.warning("Found %s matches for email %s" % (result...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.service.settings.data['ingest']['zone-token-scopes']: scopes.append(zone) authorities.append(zone) if read: for zone in self.service.settings.data['que...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 + '://' + query_uri.netloc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_requirements(path): """ This method tries to determine the requirements of a particular project by inspecting the possible places that they could be def...
requirements = [] setup_py = os.path.join(path, 'setup.py') if os.path.exists(setup_py) and os.path.isfile(setup_py): try: requirements = from_setup_py(setup_py) requirements.sort() return requirements except CouldNotParseRequirements: pass ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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?") return True guid = self.get_app_guid(app_name) self.api.delete("/v2/apps/%s" % (guid))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: os.makedirs(os.path.dirname(self.config_path)) except OSError as exc: if exc.errno != errno.EEXIST: raise return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.set_env_value(self.use_class, 'access_key_id', self.service.settings.data['access_key_id']) predix.config.set_env_value(self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 s...
uri = self.uri + '/v1/assets/search' headers = self._get_headers() params = { 'bbox': bbox, } # Query parameters params['q'] = [] if device_type: if isinstance(device_type, str): device_type = [device_type] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ty...
response = self._get_assets(bbox, **kwargs) # Remove broken HATEOAS _links but identify asset uid first assets = [] for asset in response['_embedded']['assets']: asset_url = asset['_links']['self'] uid = asset_url['href'].split('/')[-1] asset['uid'] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_ranking = np.argsort(maximum(input_grid, high_labels, index=np.arange(1, num_labels + 1)))[::-1] output_grid = np.zeros(input_grid.shape, dtype=int) stack = [] for rank in region_ranking: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. mi...
out_grid = np.zeros(labeled_grid.shape, dtype=int) slices = find_objects(labeled_grid) j = 1 for i, s in enumerate(slices): box = labeled_grid[s] size = np.count_nonzero(box.ravel() == (i + 1)) if size >= min_size and box.shape[0] > 1 and box.shape[1]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 accept_event.set() def rejected(): accept_event.set() self.__message_column.remove_all() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
try: search_str = unicode(search_str) except NameError: pass readline = StringIO(search_str).readline try: token_generator = tokenize.generate_tokens(readline) tokens = [SimplifiedToken(toknum, tokval) for toknum, tokval, _, _, _ in token_generator] except tokenize.T...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_m...
filepath = package_file_path(filename, package_name) return regex_in_file(regex, filepath, return_match=return_match)