text stringlengths 18 773k |
|---|
def authenticateUser(self, login, user, properties):
"""
Parameters:
- login
- user
- properties
"""
self.send_authenticateUser(login, user, properties)
return self.recv_authenticateUser() |
def changeUserAuthorizations(self, login, user, authorizations):
"""
Parameters:
- login
- user
- authorizations
"""
self.send_changeUserAuthorizations(login, user, authorizations)
self.recv_changeUserAuthorizations() |
def changeLocalUserPassword(self, login, user, password):
"""
Parameters:
- login
- user
- password
"""
self.send_changeLocalUserPassword(login, user, password)
self.recv_changeLocalUserPassword() |
def createLocalUser(self, login, user, password):
"""
Parameters:
- login
- user
- password
"""
self.send_createLocalUser(login, user, password)
self.recv_createLocalUser() |
def dropLocalUser(self, login, user):
"""
Parameters:
- login
- user
"""
self.send_dropLocalUser(login, user)
self.recv_dropLocalUser() |
def getUserAuthorizations(self, login, user):
"""
Parameters:
- login
- user
"""
self.send_getUserAuthorizations(login, user)
return self.recv_getUserAuthorizations() |
def grantSystemPermission(self, login, user, perm):
"""
Parameters:
- login
- user
- perm
"""
self.send_grantSystemPermission(login, user, perm)
self.recv_grantSystemPermission() |
def grantTablePermission(self, login, user, table, perm):
"""
Parameters:
- login
- user
- table
- perm
"""
self.send_grantTablePermission(login, user, table, perm)
self.recv_grantTablePermission() |
def hasSystemPermission(self, login, user, perm):
"""
Parameters:
- login
- user
- perm
"""
self.send_hasSystemPermission(login, user, perm)
return self.recv_hasSystemPermission() |
def hasTablePermission(self, login, user, table, perm):
"""
Parameters:
- login
- user
- table
- perm
"""
self.send_hasTablePermission(login, user, table, perm)
return self.recv_hasTablePermission() |
def revokeSystemPermission(self, login, user, perm):
"""
Parameters:
- login
- user
- perm
"""
self.send_revokeSystemPermission(login, user, perm)
self.recv_revokeSystemPermission() |
def revokeTablePermission(self, login, user, table, perm):
"""
Parameters:
- login
- user
- table
- perm
"""
self.send_revokeTablePermission(login, user, table, perm)
self.recv_revokeTablePermission() |
def createBatchScanner(self, login, tableName, options):
"""
Parameters:
- login
- tableName
- options
"""
self.send_createBatchScanner(login, tableName, options)
return self.recv_createBatchScanner() |
def createScanner(self, login, tableName, options):
"""
Parameters:
- login
- tableName
- options
"""
self.send_createScanner(login, tableName, options)
return self.recv_createScanner() |
def nextK(self, scanner, k):
"""
Parameters:
- scanner
- k
"""
self.send_nextK(scanner, k)
return self.recv_nextK() |
def updateAndFlush(self, login, tableName, cells):
"""
Parameters:
- login
- tableName
- cells
"""
self.send_updateAndFlush(login, tableName, cells)
self.recv_updateAndFlush() |
def createWriter(self, login, tableName, opts):
"""
Parameters:
- login
- tableName
- opts
"""
self.send_createWriter(login, tableName, opts)
return self.recv_createWriter() |
def getFollowing(self, key, part):
"""
Parameters:
- key
- part
"""
self.send_getFollowing(key, part)
return self.recv_getFollowing() |
def set_relay_on(self):
"""Turn the relay on."""
if not self.get_relay_state():
try:
request = requests.get(
'{}/relay'.format(self.resource), params={'state': '1'},
timeout=self.timeout)
if request.status_code == 200:
... |
def set_relay_off(self):
"""Turn the relay off."""
if self.get_relay_state():
try:
request = requests.get(
'{}/relay'.format(self.resource), params={'state': '0'},
timeout=self.timeout)
if request.status_code == 200:
... |
def get_relay_state(self):
"""Get the relay state."""
self.get_status()
try:
self.state = self.data['relay']
except TypeError:
self.state = False
return bool(self.state) |
def get_consumption(self):
"""Get current power consumption in mWh."""
self.get_status()
try:
self.consumption = self.data['power']
except TypeError:
self.consumption = 0
return self.consumption |
def get_temperature(self):
"""Get current temperature in celsius."""
try:
request = requests.get(
'{}/temp'.format(self.resource), timeout=self.timeout, allow_redirects=False)
self.temperature = request.json()['compensated']
return self.temperature
... |
def eval_fitness(self, chromosome):
"""
Convert a 1-gene chromosome into an integer and calculate its fitness
by checking it against each required factor.
return: fitness value
"""
score = 0
number = self.translator.translate_gene(chromosome.genes[0])
... |
def get_status(self):
"""Get the details from the bulb."""
try:
request = requests.get(
'{}/{}/'.format(self.resource, URI), timeout=self.timeout)
raw_data = request.json()
# Doesn't always work !!!!!
#self._mac = next(iter(self.raw_data))
... |
def get_bulb_state(self):
"""Get the relay state."""
self.get_status()
try:
self.state = self.data['on']
except TypeError:
self.state = False
return bool(self.state) |
def get_power(self):
"""Get current power."""
self.get_status()
try:
self.consumption = self.data['power']
except TypeError:
self.consumption = 0
return self.consumption |
def get_firmware(self):
"""Get the current firmware version."""
self.get_status()
try:
self.firmware = self.data['fw_version']
except TypeError:
self.firmware = 'Unknown'
return self.firmware |
def get_brightness(self):
"""Get current brightness."""
self.get_status()
try:
self.brightness = self.data['color'].split(';')[-1]
except TypeError:
self.brightness = 0
return self.brightness |
def get_transition_time(self):
"""Get the transition time in ms."""
self.get_status()
try:
self.transition_time = self.data['ramp']
except TypeError:
self.transition_time = 0
return self.transition_time |
def get_color(self):
"""Get current color."""
self.get_status()
try:
self.color = self.data['color']
self.mode = self.data['mode']
except TypeError:
self.color = 0
self.mode = ''
return {'color': self.color, 'mode': self.mode} |
def set_color_hsv(self, hue, saturation, value):
"""Turn the bulb on with the given values as HSV."""
try:
data = "action=on&color={};{};{}".format(hue, saturation, value)
request = requests.post(
'{}/{}/{}'.format(self.resource, URI, self._mac),
d... |
def set_rainbow(self, duration):
"""Turn the bulb on and create a rainbow."""
for i in range(0, 359):
self.set_color_hsv(i, 100, 100)
time.sleep(duration/359) |
def set_sunrise(self, duration):
"""Turn the bulb on and create a sunrise."""
self.set_transition_time(duration/100)
for i in range(0, duration):
try:
data = "action=on&color=3;{}".format(i)
request = requests.post(
'{}/{}/{}'.forma... |
def set_flashing(self, duration, hsv1, hsv2):
"""Turn the bulb on, flashing with two colors."""
self.set_transition_time(100)
for step in range(0, int(duration/2)):
self.set_color_hsv(hsv1[0], hsv1[1], hsv1[2])
time.sleep(1)
self.set_color_hsv(hsv2[0], hsv2[1]... |
def set_off(self):
"""Turn the bulb off."""
try:
request = requests.post(
'{}/{}/{}/'.format(self.resource, URI, self._mac),
data={'action': 'off'}, timeout=self.timeout)
if request.status_code == 200:
pass
except requests.e... |
def translate_chromosome(self, chromosome):
"""
Translate all the genes in a chromosome.
chromosome: a ``chromosomes.Chromosome`` instance to translate
return: a list of translation products for the genes in the chromosome
"""
assert isinstance(chromos... |
def translate_gene(self, gene):
"""
Translate a gene with binary DNA into a base-10 floating point real number.
Parses the DNA in this manner:
1. The first bit determines the sign of the integer portion of the result (0=positive, 1=negative)
2. The next ``significand... |
def load_clients(self, path=None, apis=[]):
"""Generate client libraries for the given apis, without starting an
api server"""
if not path:
raise Exception("Missing path to api swagger files")
if type(apis) is not list:
raise Exception("'apis' should be a list o... |
def load_apis(self, path, ignore=[], include_crash_api=False):
"""Load all swagger files found at the given path, except those whose
names are in the 'ignore' list"""
if not path:
raise Exception("Missing path to api swagger files")
if type(ignore) is not list:
... |
def publish_apis(self, path='doc'):
"""Publish all loaded apis on under the uri /<path>/<api-name>, by
redirecting to http://petstore.swagger.io/
"""
assert path
if not self.apis:
raise Exception("You must call .load_apis() before .publish_apis()")
# Infer ... |
def start(self, serve=[]):
"""Load all apis, either as local apis served by the flask app, or as
remote apis to be called from whithin the app's endpoints, then start
the app server"""
# Check arguments
if type(serve) is str:
serve = [serve]
elif type(serve) ... |
def add_error(name=None, code=None, status=None):
"""Create a new Exception class"""
if not name or not status or not code:
raise Exception("Can't create Exception class %s: you must set both name, status and code" % name)
myexception = type(name, (PyMacaronException, ), {"code": code, "status": sta... |
def responsify(error):
"""Take an Error model and return it as a Flask response"""
assert str(type(error).__name__) == 'Error'
if error.error in code_to_class:
e = code_to_class[error.error](error.error_description)
if error.error_id:
e.error_id = error.error_id
if error.... |
def is_error(o):
"""True if o is an instance of a swagger Error model or a flask Response of
an error model"""
if hasattr(o, 'error') and hasattr(o, 'error_description') and hasattr(o, 'status'):
return True
return False |
def format_error(e):
"""Take an exception caught within pymacaron_core and turn it into a
bravado-core Error instance
"""
if isinstance(e, PyMacaronException):
return e.to_model()
if isinstance(e, PyMacaronCoreException) and e.__class__.__name__ == 'ValidationError':
return Validat... |
def raise_error(e):
"""Take a bravado-core Error model and raise it as an exception"""
code = e.error
if code in code_to_class:
raise code_to_class[code](e.error_description)
else:
raise InternalServerError(e.error_description) |
def http_reply(self):
"""Return a Flask reply object describing this error"""
data = {
'status': self.status,
'error': self.code.upper(),
'error_description': str(self)
}
if self.error_caught:
data['error_caught'] = pformat(self.error_caug... |
def to_model(self):
"""Return a bravado-core Error instance"""
e = ApiPool().current_server_api.model.Error(
status=self.status,
error=self.code.upper(),
error_description=str(self),
)
if self.error_id:
e.error_id = self.error_id
if... |
def compute_fitness_cdf(chromosomes, ga):
"""
Return a list of fitness-weighted cumulative probabilities for a set of chromosomes.
chromosomes: chromosomes to use for fitness-based calculations
ga: ``algorithms.BaseGeneticAlgorithm`` used to obtain fitness values using its ``eval_fitness`` method... |
def weighted_choice(seq, cdf):
"""
Select a random element from a sequence, given cumulative probabilities of selection.
See ``compute_fitness_cdf`` function for obtaining cumulative probabilities.
seq: sequence to select from
cdf: sequence with 1 cumulative probability value in [0, 1] f... |
def _list(self, path, dim_key=None, **kwargs):
"""Get a list of metrics."""
url_str = self.base_url + path
if dim_key and dim_key in kwargs:
dim_str = self.get_dimensions_url_string(kwargs[dim_key])
kwargs[dim_key] = dim_str
if kwargs:
url_str += '?%s... |
def mapstr_to_list(mapstr):
""" Convert an ASCII map string with rows to a list of strings, 1 string per row. """
maplist = []
with StringIO(mapstr) as infile:
for row in infile:
maplist.append(row.strip())
return maplist |
def sprinkler_reaches_cell(x, y, sx, sy, r):
"""
Return whether a cell is within the radius of the sprinkler.
x: column index of cell
y: row index of cell
sx: column index of sprinkler
sy: row index of sprinkler
r: sprinkler radius
"""
dx = sx - x
dy = sy - y
return mat... |
def eval_fitness(self, chromosome):
"""
Return the number of plants reached by the sprinkler.
Returns a large penalty for sprinkler locations outside the map.
"""
# convert DNA to represented sprinkler coordinates
sx, sy = self.translator.translate_chromosome(chromosome)... |
def map_sprinkler(self, sx, sy, watered_crop='^', watered_field='_', dry_field=' ', dry_crop='x'):
"""
Return a version of the ASCII map showing reached crop cells.
"""
# convert strings (rows) to lists of characters for easier map editing
maplist = [list(s) for s in self.maplist... |
def index(request, template_name="index.html"):
"""\
The index view, which basically just displays a button and increments
a counter.
"""
if request.GET.get('ic-request'):
counter, created = Counter.objects.get_or_create(pk=1)
counter.value += 1
counter.save()
else:
... |
def get_fitness(self, chromosome):
""" Get the fitness score for a chromosome, using the cached value if available. """
fitness = self.fitness_cache.get(chromosome.dna)
if fitness is None:
fitness = self.eval_fitness(chromosome)
self.fitness_cache[chromosome.dna] = fitne... |
def compete(self, chromosomes):
"""
Simulate competition/survival of the fittest.
The fitness of each chromosome is used to calculate a survival probability
based on how it compares to the overall fitness range of the run and the
fitness range of the current generation. ... |
def reproduce(self, survivors, p_crossover, two_point_crossover=False, target_size=None):
"""
Reproduces the population from a pool of surviving chromosomes
until a target population size is met. Offspring are created
by selecting a survivor. Survivors with higher fitness have a
... |
def mutate(self, chromosomes, p_mutate):
"""
Call every chromosome's ``mutate`` method.
p_mutate: probability of mutation in [0, 1]
"""
assert 0 <= p_mutate <= 1
for chromosome in chromosomes:
chromosome.mutate(p_mutate) |
def run(self, generations, p_mutate, p_crossover, elitist=True, two_point_crossover=False,
refresh_after=None, quit_after=None):
"""
Run a standard genetic algorithm simulation for a set number
of generations (iterations), each consisting of the following
ordered steps:
... |
def create_random(cls, gene_length, n=1, gene_class=BinaryGene):
"""
Create 1 or more chromosomes with randomly generated DNA.
gene_length: int (or sequence of ints) describing gene DNA length
n: number of chromosomes to create (default=1); returns a list if n>1, else a single chromos... |
def dna(self, dna):
"""
Replace this chromosome's DNA with new DNA of equal length,
assigning the new DNA to the chromosome's genes sequentially.
For example, if a chromosome contains these genes...
1. 100100
2. 011011
...and the new DNA... |
def crossover(self, chromosome, point1, point2=None):
"""
Exchange DNA with another chromosome of equal length at one or two common points.
For example, consider chromosomes:
1. 11110000
2. 00001111
If the crossover point is 4, the exchange results... |
def mutate(self, p_mutate):
"""
Check all genes in this chromosome for mutation.
p_mutate: probability for mutation to occur
"""
assert 0 <= p_mutate <= 1
for gene in self.genes:
gene.mutate(p_mutate) |
def copy(self):
""" Return a new instance of this chromosome by copying its genes. """
genes = [g.copy() for g in self.genes]
return type(self)(genes) |
def check_genes(self):
""" Assert that every DNA choice is represented by exactly one gene. """
gene_dna_set = set([g.dna for g in self.genes])
assert gene_dna_set == self.dna_choices_set |
def report_error(title=None, data={}, caught=None, is_fatal=False):
"""Format a crash report and send it somewhere relevant. There are two
types of crashes: fatal crashes (backend errors) or non-fatal ones (just
reporting a glitch, but the api call did not fail)"""
# Don't report errors if NO_ERROR_REP... |
def populate_error_report(data):
"""Add generic stats to the error report"""
# Did pymacaron_core set a call_id and call_path?
call_id, call_path = '', ''
if hasattr(stack.top, 'call_id'):
call_id = stack.top.call_id
if hasattr(stack.top, 'call_path'):
call_path = stack.top.call_pat... |
def generate_crash_handler_decorator(error_decorator=None):
"""Return the crash_handler to pass to pymacaron_core, with optional error decoration"""
def crash_handler(f):
"""Return a decorator that reports failed api calls via the error_reporter,
for use on every server endpoint"""
@wr... |
def create(self, **kwargs):
"""Create a metric."""
url_str = self.base_url
if 'tenant_id' in kwargs:
url_str = url_str + '?tenant_id=%s' % kwargs['tenant_id']
del kwargs['tenant_id']
data = kwargs['jsonbody'] if 'jsonbody' in kwargs else kwargs
body = sel... |
def get_json_results(self, response):
'''
Parses the request result and returns the JSON object. Handles all errors.
'''
try:
# return the proper JSON object, or error code if request didn't go through.
self.most_recent_json = response.json()
json_resu... |
def search_all(self, quota=50, format='json'):
'''
Returns a single list containing up to 'limit' Result objects
Will keep requesting until quota is met
Will also truncate extra results to return exactly the given quota
'''
quota_left = quota
results = []
... |
def format_parameters(params):
'''Reformat parameters into dict of format expected by the API.'''
if not params:
return {}
# expect multiple invocations of --parameters but fall back
# to ; delimited if only one --parameters is specified
if len(params) == 1:
if params[0].find(';') ... |
def delete(self, **kwargs):
"""Delete a specific alarm."""
url_str = self.base_url + '/%s' % kwargs['alarm_id']
resp = self.client.delete(url_str)
return resp |
def history(self, **kwargs):
"""History of a specific alarm."""
url_str = self.base_url + '/%s/state-history' % kwargs['alarm_id']
del kwargs['alarm_id']
if kwargs:
url_str = url_str + '?%s' % parse.urlencode(kwargs, True)
resp = self.client.list(url_str)
retu... |
def history_list(self, **kwargs):
"""History list of alarm state."""
url_str = self.base_url + '/state-history/'
if 'dimensions' in kwargs:
dimstr = self.get_dimensions_url_string(kwargs['dimensions'])
kwargs['dimensions'] = dimstr
if kwargs:
url_str =... |
def do_version():
"""Return version details of the running server api"""
v = ApiPool.ping.model.Version(
name=ApiPool().current_server_name,
version=ApiPool().current_server_api.get_version(),
container=get_container_version(),
)
log.info("/version: " + pprint.pformat(v))
ret... |
def do_metric_create(mc, args):
'''Create metric.'''
fields = {}
fields['name'] = args.name
if args.dimensions:
fields['dimensions'] = utils.format_parameters(args.dimensions)
fields['timestamp'] = args.time
fields['value'] = args.value
if args.value_meta:
fields['value_meta'... |
def do_metric_create_raw(mc, args):
'''Create metric from raw json body.'''
try:
mc.metrics.create(**args.jsonbody)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
print('Successfully created metric') |
def do_metric_name_list(mc, args):
'''List names of metrics.'''
fields = {}
if args.dimensions:
fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offset'] = args.offset
if args.tenant_... |
def do_metric_list(mc, args):
'''List metrics for this tenant.'''
fields = {}
if args.name:
fields['name'] = args.name
if args.dimensions:
fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
if args.limit:
fields['limit'] = args.limit
if args.offset:
... |
def do_dimension_name_list(mc, args):
'''List names of metric dimensions.'''
fields = {}
if args.metric_name:
fields['metric_name'] = args.metric_name
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offset'] = args.offset
if args.tenant_id:
fie... |
def do_dimension_value_list(mc, args):
'''List names of metric dimensions.'''
fields = {}
fields['dimension_name'] = args.dimension_name
if args.metric_name:
fields['metric_name'] = args.metric_name
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offse... |
def do_metric_statistics(mc, args):
'''List measurement statistics for the specified metric.'''
statistic_types = ['AVG', 'MIN', 'MAX', 'COUNT', 'SUM']
statlist = args.statistics.split(',')
for stat in statlist:
if stat.upper() not in statistic_types:
errmsg = ('Invalid type, not one... |
def do_notification_show(mc, args):
'''Describe the notification.'''
fields = {}
fields['notification_id'] = args.id
try:
notification = mc.notifications.get(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.detai... |
def do_notification_list(mc, args):
'''List notifications for this tenant.'''
fields = {}
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offset'] = args.offset
if args.sort_by:
sort_by = args.sort_by.split(',')
for field in sort_by:
fi... |
def do_notification_delete(mc, args):
'''Delete notification.'''
fields = {}
fields['notification_id'] = args.id
try:
mc.notifications.delete(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
... |
def do_notification_update(mc, args):
'''Update notification.'''
fields = {}
fields['notification_id'] = args.id
fields['name'] = args.name
fields['type'] = args.type
fields['address'] = args.address
if not _validate_notification_period(args.period, args.type.upper()):
return
fi... |
def do_alarm_definition_create(mc, args):
'''Create an alarm definition.'''
fields = {}
fields['name'] = args.name
if args.description:
fields['description'] = args.description
fields['expression'] = args.expression
if args.alarm_actions:
fields['alarm_actions'] = args.alarm_acti... |
def do_alarm_definition_list(mc, args):
'''List alarm definitions for this tenant.'''
fields = {}
if args.name:
fields['name'] = args.name
if args.dimensions:
fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
if args.severity:
if not _validate_severity(arg... |
def do_alarm_definition_delete(mc, args):
'''Delete the alarm definition.'''
fields = {}
fields['alarm_id'] = args.id
try:
mc.alarm_definitions.delete(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
... |
def do_alarm_definition_update(mc, args):
'''Update the alarm definition.'''
fields = {}
fields['alarm_id'] = args.id
fields['name'] = args.name
fields['description'] = args.description
fields['expression'] = args.expression
fields['alarm_actions'] = _arg_split_patch_update(args.alarm_action... |
def do_alarm_definition_patch(mc, args):
'''Patch the alarm definition.'''
fields = {}
fields['alarm_id'] = args.id
if args.name:
fields['name'] = args.name
if args.description:
fields['description'] = args.description
if args.expression:
fields['expression'] = args.expre... |
def do_alarm_list(mc, args):
'''List alarms for this tenant.'''
fields = {}
if args.alarm_definition_id:
fields['alarm_definition_id'] = args.alarm_definition_id
if args.metric_name:
fields['metric_name'] = args.metric_name
if args.metric_dimensions:
fields['metric_dimensions... |
def do_alarm_show(mc, args):
'''Describe the alarm.'''
fields = {}
fields['alarm_id'] = args.id
try:
alarm = mc.alarms.get(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
if args.json... |
def do_alarm_update(mc, args):
'''Update the alarm state.'''
fields = {}
fields['alarm_id'] = args.id
if args.state.upper() not in state_types:
errmsg = ('Invalid state, not one of [' +
', '.join(state_types) + ']')
print(errmsg)
return
field... |
def do_alarm_delete(mc, args):
'''Delete the alarm.'''
fields = {}
fields['alarm_id'] = args.id
try:
mc.alarms.delete(**fields)
except (osc_exc.ClientException, k_exc.HttpError) as he:
raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
else:
print('Successful... |
def do_alarm_count(mc, args):
'''Count alarms.'''
fields = {}
if args.alarm_definition_id:
fields['alarm_definition_id'] = args.alarm_definition_id
if args.metric_name:
fields['metric_name'] = args.metric_name
if args.metric_dimensions:
fields['metric_dimensions'] = utils.for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.