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 from_raw(raw):
"""Test if raw packets are valid for initialization of Position.""" |
if not isinstance(raw, bytes):
raise PyVLXException("Position::raw_must_be_bytes")
if len(raw) != 2:
raise PyVLXException("Position::raw_must_be_two_bytes")
if raw != Position.from_int(Position.CURRENT_POSITION) and \
raw != Position.from_int(Position.UNK... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_percent(position_percent):
"""Create raw value out of percent position.""" |
if not isinstance(position_percent, int):
raise PyVLXException("Position::position_percent_has_to_be_int")
if position_percent < 0:
raise PyVLXException("Position::position_percent_has_to_be_positive")
if position_percent > 100:
raise PyVLXException("Position... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def product(self):
"""Return product as human readable string.""" |
if self.product_group == 14 and self.product_type == 3:
return "KLF 200"
return "Unknown Product: {}:{}".format(self.product_group, self.product_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def main(loop):
"""Log packets from Bus.""" |
# Setting debug
PYVLXLOG.setLevel(logging.DEBUG)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)
PYVLXLOG.addHandler(stream_handler)
# Connecting to KLF 200
pyvlx = PyVLX('pyvlx.yaml', loop=loop)
await pyvlx.load_scenes()
await pyvlx.load_nodes()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def rename(self, name):
"""Change name of node.""" |
set_node_name = SetNodeName(pyvlx=self.pyvlx, node_id=self.node_id, name=name)
await set_node_name.do_api_call()
if not set_node_name.success:
raise PyVLXException("Unable to rename node")
self.name = name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def set_position(self, position, wait_for_completion=True):
"""Set window to desired position. Parameters: * position: Position object containing the targe... |
command_send = CommandSend(
pyvlx=self.pyvlx,
wait_for_completion=wait_for_completion,
node_id=self.node_id,
parameter=position)
await command_send.do_api_call()
if not command_send.success:
raise PyVLXException("Unable to send command... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def open(self, wait_for_completion=True):
"""Open window. Parameters: * wait_for_completion: If set, function will return after device has reached target p... |
await self.set_position(
position=Position(position_percent=0),
wait_for_completion=wait_for_completion) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def close(self, wait_for_completion=True):
"""Close window. Parameters: * wait_for_completion: If set, function will return after device has reached target... |
await self.set_position(
position=Position(position_percent=100),
wait_for_completion=wait_for_completion) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def stop(self, wait_for_completion=True):
"""Stop window. Parameters: * wait_for_completion: If set, function will return after device has reached target p... |
await self.set_position(
position=CurrentPosition(),
wait_for_completion=wait_for_completion) |
<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_sampleset(model):
"""Return sampleset of a model or `None` if undefined. Model could be a real model or evaluated sampleset.""" |
if isinstance(model, Model):
if hasattr(model, 'sampleset'):
w = model.sampleset()
else:
w = None
else:
w = model # Already a sampleset
return w |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _shift_wavelengths(model1, model2):
"""One of the models is either ``RedshiftScaleFactor`` or ``Scale``. Possible combos:: RedshiftScaleFactor | Model Scale ... |
if isinstance(model1, _models.RedshiftScaleFactor):
val = _get_sampleset(model2)
if val is None:
w = val
else:
w = model1.inverse(val)
elif isinstance(model1, _models.Scale):
w = _get_sampleset(model2)
else:
w = _get_sampleset(model1)
retu... |
<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_waveset(model):
"""Get optimal wavelengths for sampling a given model. Parameters model : `~astropy.modeling.Model` Model. Returns ------- waveset : arra... |
if not isinstance(model, Model):
raise SynphotError('{0} is not a model.'.format(model))
if isinstance(model, _CompoundModel):
waveset = model._tree.evaluate(WAVESET_OPERATORS, getter=None)
else:
waveset = _get_sampleset(model)
return waveset |
<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_meta(model):
"""Return metadata of a model. Model could be a real model or evaluated metadata.""" |
if isinstance(model, Model):
w = model.meta
else:
w = model # Already metadata
return w |
<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_metadata(model):
"""Get metadata for a given model. Parameters model : `~astropy.modeling.Model` Model. Returns ------- metadata : dict Metadata for the ... |
if not isinstance(model, Model):
raise SynphotError('{0} is not a model.'.format(model))
if isinstance(model, _CompoundModel):
metadata = model._tree.evaluate(METADATA_OPERATORS, getter=None)
else:
metadata = deepcopy(model.meta)
return metadata |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lambda_max(self):
"""Peak wavelength in Angstrom when the curve is expressed as power density.""" |
return ((const.b_wien.value / self.temperature) * u.m).to(u.AA).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 _calc_sampleset(w1, w2, step, minimal):
"""Calculate sampleset for each model.""" |
if minimal:
arr = [w1 - step, w1, w2, w2 + step]
else:
arr = np.arange(w1 - step, w2 + step + step, step)
return arr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(self, x, *args):
"""One dimensional constant flux model function. Parameters x : number or ndarray Wavelengths in Angstrom. Returns ------- y : numb... |
a = (self.amplitude * np.ones_like(x)) * self._flux_unit
y = units.convert_flux(x, a, units.PHOTLAM)
return y.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 _process_neg_flux(self, x, y):
"""Remove negative flux.""" |
if self._keep_neg: # Nothing to do
return y
old_y = None
if np.isscalar(y): # pragma: no cover
if y < 0:
n_neg = 1
old_x = x
old_y = y
y = 0
else:
x = np.asarray(x) # In case input ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(x, amplitude, mean, stddev):
""" GaussianAbsorption1D model function. """ |
return 1.0 - Gaussian1D.evaluate(x, amplitude, mean, stddev) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit_deriv(x, amplitude, mean, stddev):
""" GaussianAbsorption1D model function derivatives. """ |
import operator
return list(map(
operator.neg, Gaussian1D.fit_deriv(x, amplitude, mean, stddev))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(self, x, *args):
"""Return flux in PHOTLAM. Assume input wavelength is in Angstrom.""" |
xx = x / self.x_0
y = (self.amplitude * xx ** (-self.alpha)) * self._flux_unit
flux = units.convert_flux(x, y, units.PHOTLAM)
return flux.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_payment_request(self, cart, request):
""" From the given request, add a snippet to the page. """ |
try:
self.charge(cart, request)
thank_you_url = OrderModel.objects.get_latest_url()
js_expression = 'window.location.href="{}";'.format(thank_you_url)
return js_expression
except (KeyError, stripe.error.StripeError) as err:
raise ValidationErr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refund_payment(self):
""" Refund the payment using Stripe's refunding API. """ |
Money = MoneyMaker(self.currency)
filter_kwargs = {
'transaction_id__startswith': 'ch_',
'payment_method': StripePayment.namespace,
}
for payment in self.orderpayment_set.filter(**filter_kwargs):
refund = stripe.Refund.create(charge=payment.transactio... |
<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_in_progress(self):
""" Creating this service is handled asynchronously so this method will simply check if the create is in progress. If it is not in... |
instance = self.service.service.get_instance(self.service.name)
if (instance['last_operation']['state'] == 'in progress' and
instance['last_operation']['type'] == 'create'):
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 create(self, max_wait=180, **kwargs):
""" Create an instance of the Predix Cache Service with they typical starting settings. :param max_wait: service is cre... |
# Will need to wait for the service to be provisioned before can add
# service keys and get env details.
self.service.create(async=True, create_keys=False)
while self._create_in_progress() and max_wait > 0:
time.sleep(1)
max_wait -= 1
# Now get the servi... |
<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_uri(self):
""" Will return the uri for an existing instance. """ |
if not self.service.exists():
logging.warning("Service does not yet exist.")
return self.service.settings.data['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_zone_id(self):
""" Will return the zone id for an existing instance. """ |
if not self.service.exists():
logging.warning("Service does not yet exist.")
return self.service.settings.data['zone']['http-header-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 create(self):
""" Create an instance of the Access Control Service with the typical starting settings. """ |
self.service.create()
# Set environment variables for immediate use
predix.config.set_env_value(self.use_class, 'uri', self._get_uri())
predix.config.set_env_value(self.use_class, 'zone_id',
self._get_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 grant_client(self, client_id):
""" Grant the given client id all the scopes and authorities needed to work with the access control service. """ |
zone = self.service.settings.data['zone']['oauth-scope']
scopes = ['openid', zone,
'acs.policies.read', 'acs.attributes.read',
'acs.policies.write', 'acs.attributes.write']
authorities = ['uaa.resource', zone,
'acs.policies.read', 'acs.pol... |
<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, path):
""" Generic GET with headers """ |
uri = self.config.get_target() + path
headers = self._get_headers()
logging.debug("URI=GET " + str(uri))
logging.debug("HEADERS=" + str(headers))
response = self.session.get(uri, headers=headers)
if response.status_code == 200:
return response.json()
... |
<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, path, data):
""" Generic POST with headers """ |
uri = self.config.get_target() + path
headers = self._post_headers()
logging.debug("URI=POST " + str(uri))
logging.debug("HEADERS=" + str(headers))
logging.debug("BODY=" + str(data))
response = self.session.post(uri, headers=headers,
data=json.dumps(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 delete(self, path, data=None, params=None):
""" Generic DELETE with headers """ |
uri = self.config.get_target() + path
headers = {
'Authorization': self.config.get_access_token()
}
logging.debug("URI=DELETE " + str(uri))
logging.debug("HEADERS=" + str(headers))
response = self.session.delete(
uri, headers=headers, 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 get_orgs(self):
""" Returns a flat list of the names for the organizations user belongs. """ |
orgs = []
for resource in self._get_orgs()['resources']:
orgs.append(resource['entity']['name'])
return orgs |
<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_apps(self):
""" Returns a flat list of the names for the apps in the organization. """ |
apps = []
for resource in self._get_apps()['resources']:
apps.append(resource['entity']['name'])
return 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 add_user(self, user_name, role='user'):
""" Calls CF's associate user with org. Valid roles include `user`, `auditor`, `manager`,`billing_manager` """ |
role_uri = self._get_role_uri(role=role)
return self.api.put(path=role_uri, data={'username': user_name}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_user(self, user_name, role):
""" Calls CF's remove user with org """ |
role_uri = self._get_role_uri(role=role)
return self.api.delete(path=role_uri, data={'username': user_name}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_publisher_ws(self):
""" Create a new web socket connection with proper headers. """ |
logging.debug("Initializing new web socket connection.")
url = ('wss://%s/v1/stream/messages/' % self.eventhub_client.host)
headers = self._generate_publish_headers()
logging.debug("URL=" + str(url))
logging.debug("HEADERS=" + str(headers))
websocket.enableTrace(Fals... |
<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):
""" Create an instance of the Parking Planning Service with the typical starting settings. """ |
self.service.create()
os.environ[self.__module__ + '.uri'] = self.service.settings.data['url']
os.environ[self.__module__ + '.zone_id'] = self.get_predix_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 read_manifest(self, encrypted=None):
""" Read an existing manifest. """ |
with open(self.manifest_path, 'r') as input_file:
self.manifest = yaml.safe_load(input_file)
if 'env' not in self.manifest:
self.manifest['env'] = {}
if 'services' not in self.manifest:
self.manifest['services'] = []
# If 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_manifest(self):
""" Create a new manifest and write it to disk. """ |
self.manifest = {}
self.manifest['applications'] = [{'name': self.app_name}]
self.manifest['services'] = []
self.manifest['env'] = {
'PREDIXPY_VERSION': str(predix.version),
}
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 _get_encrypted_manifest(self):
""" Returns contents of the manifest where environment variables that are secret will be encrypted without modifying the exist... |
key = predix.config.get_crypt_key(self.manifest_key)
f = Fernet(key)
manifest = copy.deepcopy(self.manifest)
for var in self.manifest['env'].keys():
value = str(self.manifest['env'][var])
manifest['env'][var] = f.encrypt(bytes(value, 'utf-8')).decode('utf-8')
... |
<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_manifest(self, manifest_path=None, encrypted=None):
""" Write manifest to disk. :param manifest_path: write to a different location :param encrypted: w... |
manifest_path = manifest_path or self.manifest_path
self.manifest['env']['PREDIXPY_VERSION'] = str(predix.version)
with open(manifest_path, 'w') as output_file:
if encrypted or self.encrypted:
self.manifest['env']['PREDIXPY_ENCRYPTED'] = self.manifest_key
... |
<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_service(self, service_name):
""" Add the given service to the manifest. """ |
if service_name not in self.manifest['services']:
self.manifest['services'].append(service_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_os_environ(self):
""" Will load any environment variables found in the manifest file into the current process for use by applications. When apps run in c... |
for key in self.manifest['env'].keys():
os.environ[key] = str(self.manifest['env'][key]) |
<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_id(self):
""" Return the client id that should have all the needed scopes and authorities for the services in this manifest. """ |
self._client_id = predix.config.get_env_value(predix.app.Manifest, 'client_id')
return self._client_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_client_secret(self):
""" Return the client secret that should correspond with the client id. """ |
self._client_secret = predix.config.get_env_value(predix.app.Manifest, 'client_secret')
return self._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 get_timeseries(self, *args, **kwargs):
""" Returns an instance of the Time Series Service. """ |
import predix.data.timeseries
ts = predix.data.timeseries.TimeSeries(*args, **kwargs)
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 get_asset(self):
""" Returns an instance of the Asset Service. """ |
import predix.data.asset
asset = predix.data.asset.Asset()
return asset |
<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(self):
""" Returns an insstance of the UAA Service. """ |
import predix.security.uaa
uaa = predix.security.uaa.UserAccountAuthentication()
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 get_acs(self):
""" Returns an instance of the Asset Control Service. """ |
import predix.security.acs
acs = predix.security.acs.AccessControl()
return acs |
<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_weather(self):
""" Returns an instance of the Weather Service. """ |
import predix.data.weather
weather = predix.data.weather.WeatherForecast()
return weather |
<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_weather_forecast_days(self, latitude, longitude, days=1, frequency=1, reading_type=None):
""" Return the weather forecast for a given location. :: result... |
params = {}
# Can get data from NWS1 or NWS3 representing 1-hr and 3-hr
# intervals.
if frequency not in [1, 3]:
raise ValueError("Reading frequency must be 1 or 3")
params['days'] = days
params['source'] = 'NWS' + str(frequency)
params['latitude'] ... |
<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_weather_forecast(self, latitude, longitude, start, end, frequency=1, reading_type=None):
""" Return the weather forecast for a given location for specifi... |
params = {}
# Can get data from NWS1 or NWS3 representing 1-hr and 3-hr
# intervals.
if frequency not in [1, 3]:
raise ValueError("Reading frequency must be 1 or 3")
params['source'] = 'NWS' + str(frequency)
params['latitude'] = latitude
params['lon... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_name(self, space, service_name, plan_name):
""" Can generate a name based on the space, service name and plan. """ |
return str.join('-', [space, service_name, plan_name]).lower() |
<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_config_path(self):
""" Return a sensible configuration path for caching config settings. """ |
org = self.service.space.org.name
space = self.service.space.name
name = self.name
return "~/.predix/%s/%s/%s.json" % (org, space, name) |
<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_service(self, parameters={}, **kwargs):
""" Create a Cloud Foundry service that has custom parameters. """ |
logging.debug("_create_service()")
logging.debug(str.join(',', [self.service_name, self.plan_name,
self.name, str(parameters)]))
return self.service.create_service(self.service_name, self.plan_name,
self.name, parameters, **kwargs) |
<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_service(self, service_only=False):
""" Delete a Cloud Foundry service and any associations. """ |
logging.debug('_delete_service()')
return self.service.delete_service(self.service_name) |
<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_or_create_service_key(self):
""" Get a service key or create one if needed. """ |
keys = self.service._get_service_keys(self.name)
for key in keys['resources']:
if key['entity']['name'] == self.service_name:
return self.service.get_service_key(self.name,
self.service_name)
self.service.create_service_key(self.name, self.se... |
<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):
""" Will get configuration for the service from a service key. """ |
key = self._get_or_create_service_key()
config = {}
config['service_key'] = [{'name': self.name}]
config.update(key['entity']['credentials'])
return config |
<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, parameters={}, create_keys=True, **kwargs):
""" Create the service. """ |
# Create the service
cs = self._create_service(parameters=parameters, **kwargs)
# Create the service key to get config details and
# store in local cache file.
if create_keys:
cfg = parameters
cfg.update(self._get_service_config())
self.setti... |
<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_or_create_uaa(self, uaa):
""" Returns a valid UAA instance for performing administrative functions on services. """ |
if isinstance(uaa, predix.admin.uaa.UserAccountAuthentication):
return uaa
logging.debug("Initializing a new UAA")
return predix.admin.uaa.UserAccountAuthentication() |
<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, publish=False, subscribe=False, publish_protocol=None, publish_topics=None, subscribe_topics=None, scope_prefix='predix-event-hu... |
scopes = ['openid']
authorities = ['uaa.resource']
zone_id = self.get_zone_id()
# always must be part of base user scope
scopes.append('%s.zones.%s.user' % (scope_prefix, zone_id))
authorities.append('%s.zones.%s.user' % (scope_prefix, zone_id))
if publish_topi... |
<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_eventhub_host(self):
""" returns the publish grpc endpoint for ingestion. """ |
for protocol in self.service.settings.data['publish']['protocol_details']:
if protocol['protocol'] == 'grpc':
return protocol['uri'][0:protocol['uri'].index(':')] |
<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_host(self):
""" Returns the host address for an instance of Blob Store service from environment inspection. """ |
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
host = services['predix-blobstore'][0]['credentials']['host']
else:
host = predix.config.get_env_value(self, 'host')
# Protocol may not always be included in host setting
... |
<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_access_key_id(self):
""" Returns the access key for an instance of Blob Store service from environment inspection. """ |
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
return services['predix-blobstore'][0]['credentials']['access_key_id']
else:
return predix.config.get_env_value(self, 'access_key_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 list_objects(self, bucket_name=None, **kwargs):
""" This method is primarily for illustration and just calls the boto3 client implementation of list_objects ... |
if not bucket_name: bucket_name = self.bucket_name
return self.client.list_objects(Bucket=bucket_name, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_file(self, src_filepath, dest_filename=None, bucket_name=None, **kwargs):
""" This method is primarily for illustration and just calls the boto3 clien... |
if not bucket_name: bucket_name = self.bucket_name
if not dest_filename: dest_filename = src_filepath
return self.client.upload_file(src_filepath, bucket_name,
dest_filename, **kwargs) |
<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_cloud_foundry_config(self):
""" Reads the local cf CLI cache stored in the users home directory. """ |
config = os.path.expanduser(self.config_file)
if not os.path.exists(config):
raise CloudFoundryLoginError('You must run `cf login` to authenticate')
with open(config, "r") as data:
return json.load(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_organization_guid(self):
""" Returns the GUID for the organization currently targeted. """ |
if 'PREDIX_ORGANIZATION_GUID' in os.environ:
return os.environ['PREDIX_ORGANIZATION_GUID']
else:
info = self._get_organization_info()
for key in ('Guid', 'GUID'):
if key in info.keys():
return info[key]
raise ValueError... |
<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_space_guid(self):
""" Returns the GUID for the space currently targeted. Can be set by environment variable with PREDIX_SPACE_GUID. Can be determined by ... |
if 'PREDIX_SPACE_GUID' in os.environ:
return os.environ['PREDIX_SPACE_GUID']
else:
info = self._get_space_info()
for key in ('Guid', 'GUID'):
if key in info.keys():
return info[key]
raise ValueError('Unable to determine... |
<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_crypt_key(key_path):
""" Get the user's PredixPy manifest key. Generate and store one if not yet generated. """ |
key_path = os.path.expanduser(key_path)
if os.path.exists(key_path):
with open(key_path, 'r') as data:
key = data.read()
else:
key = Fernet.generate_key()
with open(key_path, 'w') as output:
output.write(key)
return key |
<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_env_key(obj, key=None):
""" Return environment variable key to use for lookups within a namespace represented by the package name. For example, any varia... |
return str.join('_', [obj.__module__.replace('.','_').upper(),
key.upper()]) |
<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_env_value(obj, attribute):
""" Returns the environment variable value for the attribute of the given object. For example `get_env_value(predix.security.u... |
varname = get_env_key(obj, attribute)
var = os.environ.get(varname)
if not var:
raise ValueError("%s must be set in your environment." % varname)
return var |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_env_value(obj, attribute, value):
""" Set the environment variable value for the attribute of the given object. will set the environment variable PREDIX_... |
varname = get_env_key(obj, attribute)
os.environ[varname] = value
return varname |
<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_instance_guid(self, service_name):
""" Returns the GUID for the service instance with the given name. """ |
summary = self.space.get_space_summary()
for service in summary['services']:
if service['name'] == service_name:
return service['guid']
raise ValueError("No service with name '%s' found." % (service_name)) |
<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_bindings(self, service_name):
""" Return the service bindings for the service instance. """ |
instance = self.get_instance(service_name)
return self.api.get(instance['service_bindings_url']) |
<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_service_bindings(self, service_name):
""" Remove service bindings to applications. """ |
instance = self.get_instance(service_name)
return self.api.delete(instance['service_bindings_url']) |
<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_keys(self, service_name):
""" Return the service keys for the given service. """ |
guid = self.get_instance_guid(service_name)
uri = "/v2/service_instances/%s/service_keys" % (guid)
return self.api.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 get_service_keys(self, service_name):
""" Returns a flat list of the names of the service keys for the given service. """ |
keys = []
for key in self._get_service_keys(service_name)['resources']:
keys.append(key['entity']['name'])
return keys |
<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_key(self, service_name, key_name):
""" Returns the service key details. Similar to `cf service-key`. """ |
for key in self._get_service_keys(service_name)['resources']:
if key_name == key['entity']['name']:
guid = key['metadata']['guid']
uri = "/v2/service_keys/%s" % (guid)
return self.api.get(uri)
return None |
<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_service_key(self, service_name, key_name):
""" Create a service key for the given service. """ |
if self.has_key(service_name, key_name):
logging.warning("Reusing existing service key %s" % (key_name))
return self.get_service_key(service_name, key_name)
body = {
'service_instance_guid': self.get_instance_guid(service_name),
'name': key_name
... |
<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_service_key(self, service_name, key_name):
""" Delete a service key for the given service. """ |
key = self.get_service_key(service_name, key_name)
logging.info("Deleting service key %s for service %s" % (key, service_name))
return self.api.delete(key['metadata']['url']) |
<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_instance(self, service_name):
""" Retrieves a service instance with the given name. """ |
for resource in self.space._get_instances():
if resource['entity']['name'] == service_name:
return resource['entity'] |
<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_plan_for_service(self, service_name):
""" Return the service plans available for a given service. """ |
services = self.get_services()
for service in services['resources']:
if service['entity']['label'] == service_name:
response = self.api.get(service['entity']['service_plans_url'])
return response['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 create_service(self, service_type, plan_name, service_name, params, async=False, **kwargs):
""" Create a service instance. """ |
if self.space.has_service_with_name(service_name):
logging.warning("Service already exists with that name.")
return self.get_instance(service_name)
if self.space.has_service_of_type(service_type):
logging.warning("Service type already exists.")
guid = 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_query_uri(self):
""" Returns the URI endpoint for performing queries of a Predix Time Series instance from environment inspection. """ |
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
predix_timeseries = services['predix-timeseries'][0]['credentials']
return predix_timeseries['query']['uri'].partition('/v1')[0]
else:
return predix.config.get_env_value(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_query_zone_id(self):
""" Returns the ZoneId for performing queries of a Predix Time Series instance from environment inspection. """ |
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
predix_timeseries = services['predix-timeseries'][0]['credentials']
return predix_timeseries['query']['zone-http-header-value']
else:
return predix.config.get_env_value(se... |
<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_datapoints(self, params):
""" Will make a direct REST call with the given json body payload to get datapoints. """ |
url = self.query_uri + '/v1/datapoints'
return self.service._get(url, 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 get_values(self, *args, **kwargs):
""" Convenience method that for simple single tag queries will return just the values to be iterated on. """ |
if isinstance(args[0], list):
raise ValueError("Can only get_values() for a single tag.")
response = self.get_datapoints(*args, **kwargs)
for value in response['tags'][0]['results'][0]['values']:
yield [datetime.datetime.utcfromtimestamp(value[0]/1000),
... |
<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_datapoints(self, tags, start=None, end=None, order=None, limit=None, qualities=None, attributes=None, measurement=None, aggregations=None, post=False):
"... |
params = {}
# Documentation says start is required for GET but not POST, but
# seems to be required all the time, so using sensible default.
if not start:
start = '1w-ago'
logging.warning("Defaulting query for data with start date %s" % (start))
# 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 _create_connection(self):
""" Create a new websocket connection with proper headers. """ |
logging.debug("Initializing new websocket connection.")
headers = {
'Authorization': self.service._get_bearer_token(),
'Predix-Zone-Id': self.ingest_zone_id,
'Content-Type': 'application/json',
}
url = self.ingest_uri
logging.debug("URL=" + 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_websocket(self, reuse=True):
""" Reuse existing connection or create a new connection. """ |
# Check if still connected
if self.ws and reuse:
if self.ws.connected:
return self.ws
logging.debug("Stale connection, reconnecting.")
self.ws = self._create_connection()
return self.ws |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _send_to_timeseries(self, message):
""" Establish or reuse socket connection and send the given message to the timeseries service. """ |
logging.debug("MESSAGE=" + str(message))
result = None
try:
ws = self._get_websocket()
ws.send(json.dumps(message))
result = ws.recv()
except (websocket.WebSocketConnectionClosedException, Exception) as e:
logging.debug("Connection failed... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, statement, *args, **kwargs):
""" This convenience method will execute the query passed in as is. For more complex functionality you may want to... |
with self.engine.connect() as conn:
s = sqlalchemy.sql.text(statement)
return conn.execute(s, **kwargs) |
<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_temp_space():
""" Create a new temporary cloud foundry space for a project. """ |
# Truncating uuid to just take final 12 characters since space name
# is used to name services and there is a 50 character limit on instance
# names.
# MAINT: hacky with possible collisions
unique_name = str(uuid.uuid4()).split('-')[-1]
admin = predix.admin.cf.spaces.Space()
res = admin.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 _get_spaces(self):
""" Get the marketplace services. """ |
guid = self.api.config.get_organization_guid()
uri = '/v2/organizations/%s/spaces' % (guid)
return self.api.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 target(self):
""" Target the current space for any forthcoming Cloud Foundry operations. """ |
# MAINT: I don't like this, but will deal later
os.environ['PREDIX_SPACE_GUID'] = self.guid
os.environ['PREDIX_SPACE_NAME'] = self.name
os.environ['PREDIX_ORGANIZATION_GUID'] = self.org.guid
os.environ['PREDIX_ORGANIZATION_NAME'] = self.org.name |
<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_spaces(self):
""" Return a flat list of the names for spaces in the organization. """ |
self.spaces = []
for resource in self._get_spaces()['resources']:
self.spaces.append(resource['entity']['name'])
return self.spaces |
<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_space(self, space_name, add_users=True):
""" Create a new space with the given name in the current target organization. """ |
body = {
'name': space_name,
'organization_guid': self.api.config.get_organization_guid()
}
# MAINT: may need to do this more generally later
if add_users:
space_users = []
org_users = self.org.get_users()
for org_user in org_... |
<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_space(self, name=None, guid=None):
""" Delete the current space, or a space with the given name or guid. """ |
if not guid:
if name:
spaces = self._get_spaces()
for space in spaces['resources']:
if space['entity']['name'] == name:
guid = space['metadata']['guid']
break
if not guid:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.