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 unflatten_dct(obj):
""" Undoes the work of flatten_dict @param {Object} obj 1-D object in the form returned by flattenObj @returns {Object} The original :par... |
def reduce_func(accum, key_string_and_value):
key_string = key_string_and_value[0]
value = key_string_and_value[1]
item_key_path = key_string_to_lens_path(key_string)
# All but the last segment gives us the item container len
container_key_path = init(item_key_path)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change_view(self, request, object_id, form_url='', extra_context=None):
""" Override change view to add extra context enabling moderate tool. """ |
context = {
'has_moderate_tool': True
}
if extra_context:
context.update(extra_context)
return super(AdminModeratorMixin, self).change_view(
request=request,
object_id=object_id,
form_url=form_url,
extra_context=con... |
<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_urls(self):
""" Add aditional moderate url. """ |
from django.conf.urls import url
urls = super(AdminModeratorMixin, self).get_urls()
info = self.model._meta.app_label, self.model._meta.model_name
return [
url(r'^(.+)/moderate/$',
self.admin_site.admin_view(self.moderate_view),
name='%s_%s_mo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def operating_system():
"""Return a string identifying the operating system the application is running on. :rtype: str """ |
if platform.system() == 'Darwin':
return 'OS X Version %s' % platform.mac_ver()[0]
distribution = ' '.join(platform.linux_distribution()).strip()
os_platform = platform.platform(True, True)
if distribution:
os_platform += ' (%s)' % distribution
return os_platform |
<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):
"""Daemonize if the process is not already running.""" |
if self._is_already_running():
LOGGER.error('Is already running')
sys.exit(1)
try:
self._daemonize()
self.controller.start()
except Exception as error:
sys.stderr.write('\nERROR: Startup of %s Failed\n.' %
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gid(self):
"""Return the group id that the daemon will run with :rtype: int """ |
if not self._gid:
if self.controller.config.daemon.group:
self._gid = grp.getgrnam(self.config.daemon.group).gr_gid
else:
self._gid = os.getgid()
return self._gid |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uid(self):
"""Return the user id that the process will run as :rtype: int """ |
if not self._uid:
if self.config.daemon.user:
self._uid = pwd.getpwnam(self.config.daemon.user).pw_uid
else:
self._uid = os.getuid()
return self._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_exception_log_path():
"""Return the normalized path for the connection log, raising an exception if it can not written to. :return: str """ |
app = sys.argv[0].split('/')[-1]
for exception_log in ['/var/log/%s.errors' % app,
'/var/tmp/%s.errors' % app,
'/tmp/%s.errors' % app]:
if os.access(path.dirname(exception_log), os.W_OK):
return exception_log
... |
<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_pidfile_path(self):
"""Return the normalized path for the pidfile, raising an exception if it can not written to. :return: str :raises: ValueError :rais... |
if self.config.daemon.pidfile:
pidfile = path.abspath(self.config.daemon.pidfile)
if not os.access(path.dirname(pidfile), os.W_OK):
raise ValueError('Cannot write to specified pid file path'
' %s' % pidfile)
return pidfile
... |
<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_already_running(self):
"""Check to see if the process is running, first looking for a pidfile, then shelling out in either case, removing a pidfile if it... |
# Look for the pidfile, if exists determine if the process is alive
pidfile = self._get_pidfile_path()
if os.path.exists(pidfile):
pid = open(pidfile).read().strip()
try:
os.kill(int(pid), 0)
sys.stderr.write('Process already running as pi... |
<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_pidfile(self):
"""Remove the pid file from the filesystem""" |
LOGGER.debug('Removing pidfile: %s', self.pidfile_path)
try:
os.unlink(self.pidfile_path)
except OSError:
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 _write_pidfile(self):
"""Write the pid file out with the process number in the pid file""" |
LOGGER.debug('Writing pidfile: %s', self.pidfile_path)
with open(self.pidfile_path, "w") as handle:
handle.write(str(os.getpid())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_camel_case(snake_case_string):
""" Convert a string from snake case to camel case. For example, "some_var" would become "someVar". :param snake_case_strin... |
parts = snake_case_string.lstrip('_').split('_')
return parts[0] + ''.join([i.title() for i in parts[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 to_capitalized_camel_case(snake_case_string):
""" Convert a string from snake case to camel case with the first letter capitalized. For example, "some_var" w... |
parts = snake_case_string.split('_')
return ''.join([i.title() for i in parts]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_snake_case(camel_case_string):
""" Convert a string from camel case to snake case. From example, "someVar" would become "some_var". :param camel_case_stri... |
first_pass = _first_camel_case_regex.sub(r'\1_\2', camel_case_string)
return _second_camel_case_regex.sub(r'\1_\2', first_pass).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 keys_to_snake_case(camel_case_dict):
""" Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on each of the k... |
return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items()) |
<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_functions(awsclient):
"""List the deployed lambda functions and print configuration. :return: exit_code """ |
client_lambda = awsclient.get_client('lambda')
response = client_lambda.list_functions()
for function in response['Functions']:
log.info(function['FunctionName'])
log.info('\t' 'Memory: ' + str(function['MemorySize']))
log.info('\t' 'Timeout: ' + str(function['Timeout']))
lo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy_lambda(awsclient, function_name, role, handler_filename, handler_function, folders, description, timeout, memory, subnet_ids=None, security_groups=None... |
# TODO: the signature of this function is too big, clean this up
# also consolidate create, update, config and add waiters!
if lambda_exists(awsclient, function_name):
function_version = _update_lambda(awsclient, function_name,
handler_filename,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bundle_lambda(zipfile):
"""Write zipfile contents to file. :param zipfile: :return: exit_code """ |
# TODO have 'bundle.zip' as default config
if not zipfile:
return 1
with open('bundle.zip', 'wb') as zfile:
zfile.write(zipfile)
log.info('Finished - a bundle.zip is waiting for you...')
return 0 |
<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_metrics(awsclient, name):
"""Print out cloudformation metrics for a lambda function. :param awsclient :param name: name of the lambda function :return: e... |
metrics = ['Duration', 'Errors', 'Invocations', 'Throttles']
client_cw = awsclient.get_client('cloudwatch')
for metric in metrics:
response = client_cw.get_metric_statistics(
Namespace='AWS/Lambda',
MetricName=metric,
Dimensions=[
{
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rollback(awsclient, function_name, alias_name=ALIAS_NAME, version=None):
"""Rollback a lambda function to a given version. :param awsclient: :param function_... |
if version:
log.info('rolling back to version {}'.format(version))
else:
log.info('rolling back to previous version')
version = _get_previous_version(awsclient, function_name, alias_name)
if version == '0':
log.error('unable to find previous version of lambda functio... |
<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_lambda(awsclient, function_name, events=None, delete_logs=False):
"""Delete a lambda function. :param awsclient: :param function_name: :param events: ... |
if events is not None:
unwire(awsclient, events, function_name, alias_name=ALIAS_NAME)
client_lambda = awsclient.get_client('lambda')
response = client_lambda.delete_function(FunctionName=function_name)
if delete_logs:
log_group_name = '/aws/lambda/%s' % function_name
delete_log... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _stop_ec2_instances(awsclient, ec2_instances, wait=True):
"""Helper to stop ec2 instances. By default it waits for instances to stop. :param awsclient: :para... |
if len(ec2_instances) == 0:
return
client_ec2 = awsclient.get_client('ec2')
# get running instances
running_instances = all_pages(
client_ec2.describe_instance_status,
{
'InstanceIds': ec2_instances,
'Filters': [{
'Name': 'instance-state-... |
<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_ec2_instances(awsclient, ec2_instances, wait=True):
"""Helper to start ec2 instances :param awsclient: :param ec2_instances: :param wait: waits for in... |
if len(ec2_instances) == 0:
return
client_ec2 = awsclient.get_client('ec2')
# get stopped instances
stopped_instances = all_pages(
client_ec2.describe_instance_status,
{
'InstanceIds': ec2_instances,
'Filters': [{
'Name': 'instance-state-... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _filter_db_instances_by_status(awsclient, db_instances, status_list):
"""helper to select dbinstances. :param awsclient: :param db_instances: :param status_l... |
client_rds = awsclient.get_client('rds')
db_instances_with_status = []
for db in db_instances:
response = client_rds.describe_db_instances(
DBInstanceIdentifier=db
)
for entry in response.get('DBInstances', []):
if entry['DBInstanceStatus'] in status_list:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop_stack(awsclient, stack_name, use_suspend=False):
"""Stop an existing stack on AWS cloud. :param awsclient: :param stack_name: :param use_suspend: use su... |
exit_code = 0
# check for DisableStop
#disable_stop = conf.get('deployment', {}).get('DisableStop', False)
#if disable_stop:
# log.warn('\'DisableStop\' is set - nothing to do!')
#else:
if not stack_exists(awsclient, stack_name):
log.warn('Stack \'%s\' not deployed - nothing to ... |
<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_autoscaling_min_max(template, parameters, asg_name):
"""Helper to extract the configured MinSize, MaxSize attributes from the template. :param template:... |
params = {e['ParameterKey']: e['ParameterValue'] for e in parameters}
asg = template.get('Resources', {}).get(asg_name, None)
if asg:
assert asg['Type'] == 'AWS::AutoScaling::AutoScalingGroup'
min = asg.get('Properties', {}).get('MinSize', None)
max = asg.get('Properties', {}).get('... |
<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_cluster_desired_count(template, parameters, service_name):
"""Helper to extract the configured desiredCount attribute from the template. :param ... |
params = {e['ParameterKey']: e['ParameterValue'] for e in parameters}
service = template.get('Resources', {}).get(service_name, None)
if service:
assert service['Type'] == 'AWS::ECS::Service'
cluster = service.get('Properties', {}).get('Cluster', None)
desired_count = service.get('P... |
<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_stack(awsclient, stack_name, use_suspend=False):
"""Start an existing stack on AWS cloud. :param awsclient: :param stack_name: :param use_suspend: use ... |
exit_code = 0
# check for DisableStop
#disable_stop = conf.get('deployment', {}).get('DisableStop', False)
#if disable_stop:
# log.warn('\'DisableStop\' is set - nothing to do!')
#else:
if not stack_exists(awsclient, stack_name):
log.warn('Stack \'%s\' not deployed - nothing to ... |
<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_running(self):
"""Property method that returns a bool specifying if the process is currently running. This will return true if the state is active, idle o... |
return self._state in [self.STATE_ACTIVE,
self.STATE_IDLE,
self.STATE_INITIALIZING] |
<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_signal(self, signum):
"""Invoked whenever a signal is added to the stack. :param int signum: The signal that was added """ |
if signum == signal.SIGTERM:
LOGGER.info('Received SIGTERM, initiating shutdown')
self.stop()
elif signum == signal.SIGHUP:
LOGGER.info('Received SIGHUP')
if self.config.reload():
LOGGER.info('Configuration reloaded')
loggi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""The core method for starting the application. Will setup logging, toggle the runtime state flag, block on loop, then call shutdown. Redefine th... |
LOGGER.info('%s v%s started', self.APPNAME, self.VERSION)
self.setup()
while not any([self.is_stopping, self.is_stopped]):
self.set_state(self.STATE_SLEEPING)
try:
signum = self.pending_signals.get(True, self.wake_interval)
except queue.Empty:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Override to implement shutdown steps.""" |
LOGGER.info('Attempting to stop the process')
self.set_state(self.STATE_STOP_REQUESTED)
# Call shutdown for classes to add shutdown steps
self.shutdown()
# Wait for the current run to finish
while self.is_running and self.is_waiting_to_stop:
LOGGER.info('Wa... |
<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_default_arguments(parser):
"""Add the default arguments to the parser. :param argparse.ArgumentParser parser: The argument parser """ |
parser.add_argument('-c', '--config', action='store', dest='config',
help='Path to the configuration file')
parser.add_argument('-f', '--foreground', action='store_true', dest='foreground',
help='Run the application interactively') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(pif, fp, **kwargs):
""" Convert a single Physical Information Object, or a list of such objects, into a JSON-encoded text file. :param pif: Object or li... |
return json.dump(pif, fp, cls=PifEncoder, **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 load(fp, class_=None, **kwargs):
""" Convert content in a JSON-encoded text file to a Physical Information Object or a list of such objects. :param fp: File-... |
return loado(json.load(fp, **kwargs), class_=class_) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loads(s, class_=None, **kwargs):
""" Convert content in a JSON-encoded string to a Physical Information Object or a list of such objects. :param s: String to... |
return loado(json.loads(s, **kwargs), class_=class_) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loado(obj, class_=None):
""" Convert a dictionary or a list of dictionaries into a single Physical Information Object or a list of such objects. :param obj: ... |
if isinstance(obj, list):
return [_dict_to_pio(i, class_=class_) for i in obj]
elif isinstance(obj, dict):
return _dict_to_pio(obj, class_=class_)
else:
raise ValueError('expecting list or dictionary as outermost structure') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dict_to_pio(d, class_=None):
""" Convert a single dictionary object to a Physical Information Object. :param d: Dictionary to convert. :param class_: Subcla... |
d = keys_to_snake_case(d)
if class_:
return class_(**d)
if 'category' not in d:
raise ValueError('Dictionary does not contains a category field: ' + ', '.join(d.keys()))
elif d['category'] == 'system':
return System(**d)
elif d['category'] == 'system.chemical':
retur... |
<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_command(arguments):
"""Utility function to extract command from docopt arguments. :param arguments: :return: command """ |
cmds = list(filter(lambda k: not (k.startswith('-') or
k.startswith('<')) and arguments[k],
arguments.keys()))
if len(cmds) != 1:
raise Exception('invalid command line!')
return cmds[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch(cls, arguments, **kwargs):
"""Dispatch arguments parsed by docopt to the cmd with matching spec. :param arguments: :param kwargs: :return: exit_code... |
# first match wins
# spec: all '-' elements must match, all others are False;
# '<sth>' elements are converted to call args on order of
# appearance
#
# kwargs are provided to dispatch call and used in func call
for spec, func in cls._specs:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_representation(self, i):
""" Return the proper representation for the given integer """ |
if self.number_representation == 'unsigned':
return i
elif self.number_representation == 'signed':
if i & (1 << self.interpreter._bit_width - 1):
return -((~i + 1) & (2**self.interpreter._bit_width - 1))
else:
return i
elif sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def magic_generate_random(self, line):
""" Set the generate random flag, unset registers and memory will return a random value. Usage: Call the magic by itself o... |
line = line.strip().lower()
if not line or line == 'true':
self.interpreter.generate_random = True
elif line == 'false':
self.interpreter.generate_random = False
else:
stream_content = {'name': 'stderr', 'text': "unknwon value '{}'".format(line)}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def magic_postpone_execution(self, line):
""" Postpone execution of instructions until explicitly run Usage: Call this magic with `true` or nothing to postpone e... |
line = line.strip().lower()
if not line or line == 'true':
self.interpreter.postpone_execution = True
elif line == 'false':
self.interpreter.postpone_execution = False
else:
stream_content = {'name': 'stderr', 'text': "unknwon value '{}'".format(line)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def magic_register(self, line):
""" Print out the current value of a register Usage: Pass in the register, or a list of registers separated by spaces A list of r... |
message = ""
for reg in [i.strip() for i in line.replace(',', '').split()]:
if '-' in reg:
# We have a range (Rn-Rk)
r1, r2 = reg.split('-')
# TODO do we want to allow just numbers?
n1 = re.search(self.interpreter.REGISTER_REGE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def magic_memory(self, line):
""" Print out the current value of memory Usage: Pass in the byte of memory to read, separated by spaced A list of memory contents ... |
# TODO add support for directives
message = ""
for address in [i.strip() for i in line.replace(',', '').split()]:
if '-' in address:
# We have a range (n-k)
m1, m2 = address.split('-')
n1 = re.search(self.interpreter.IMMEDIATE_NUMBER, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def magic_run(self, line):
""" Run the current program Usage: Call with a numbe rto run that many steps, or call with no arguments to run to the end of the curre... |
i = float('inf')
if line.strip():
i = int(line)
try:
with warnings.catch_warnings(record=True) as w:
self.interpreter.run(i)
for warning_message in w:
# TODO should this be stdout or stderr
stream_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 magic_help(self, line):
""" Print out the help for magics Usage: Call help with no arguments to list all magics, or call it with a magic to print out it's he... |
line = line.strip()
if not line:
for magic in self.magics:
stream_content = {'name': 'stdout', 'text': "%{}\n".format(magic)}
self.send_response(self.iopub_socket, 'stream', stream_content)
elif line in self.magics:
# its a magic
... |
<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_apis(awsclient):
"""List APIs in account.""" |
client_api = awsclient.get_client('apigateway')
apis = client_api.get_rest_apis()['items']
for api in apis:
print(json2table(api)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy_api(awsclient, api_name, api_description, stage_name, api_key, lambdas, cache_cluster_enabled, cache_cluster_size, method_settings=None):
"""Deploy AP... |
if not _api_exists(awsclient, api_name):
if os.path.isfile(SWAGGER_FILE):
# this does an import from swagger file
# the next step does not make sense since there is a check in
# _import_from_swagger for if api is existent!
# _create_api(api_name=api_name, api... |
<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_api(awsclient, api_name):
"""Delete the API. :param api_name: """ |
_sleep()
client_api = awsclient.get_client('apigateway')
print('deleting api: %s' % api_name)
api = _api_by_name(awsclient, api_name)
if api is not None:
print(json2table(api))
response = client_api.delete_rest_api(
restApiId=api['id']
)
print(json2ta... |
<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_api_key(awsclient, api_name, api_key_name):
"""Create a new API key as reference for api.conf. :param api_name: :param api_key_name: :return: api_key ... |
_sleep()
client_api = awsclient.get_client('apigateway')
print('create api key: %s' % api_key_name)
response = client_api.create_api_key(
name=api_key_name,
description='Created for ' + api_name,
enabled=True
)
#print(json2table(response))
print('Add this api 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 delete_api_key(awsclient, api_key):
"""Remove API key. :param api_key: """ |
_sleep()
client_api = awsclient.get_client('apigateway')
print('delete api key: %s' % api_key)
response = client_api.delete_api_key(
apiKey=api_key
)
print(json2table(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 list_api_keys(awsclient):
"""Print the defined API keys. """ |
_sleep()
client_api = awsclient.get_client('apigateway')
print('listing api keys')
response = client_api.get_api_keys()['items']
for item in response:
print(json2table(item)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deploy_custom_domain(awsclient, api_name, api_target_stage, api_base_path, domain_name, route_53_record, cert_name, cert_arn, hosted_zone_id, ensure_cname):
... |
api_base_path = _basepath_to_string_if_null(api_base_path)
api = _api_by_name(awsclient, api_name)
if not api:
print("Api %s does not exist, aborting..." % api_name)
# exit(1)
return 1
domain = _custom_domain_name_exists(awsclient, domain_name)
if not domain:
resp... |
<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_lambdas(awsclient, config, add_arn=False):
"""Get the list of lambda functions. :param config: :param add_arn: :return: list containing lambda entries ""... |
if 'lambda' in config:
client_lambda = awsclient.get_client('lambda')
lambda_entries = config['lambda'].get('entries', [])
lmbdas = []
for lambda_entry in lambda_entries:
lmbda = {
'name': lambda_entry.get('name', None),
'alias': lambda_en... |
<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_stage(awsclient, api_id, stage_name, method_settings):
"""Helper to apply method_settings to stage :param awsclient: :param api_id: :param stage_name... |
# settings docs in response: https://botocore.readthedocs.io/en/latest/reference/services/apigateway.html#APIGateway.Client.update_stage
client_api = awsclient.get_client('apigateway')
operations = _convert_method_settings_into_operations(method_settings)
if operations:
print('update method set... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _convert_method_settings_into_operations(method_settings=None):
"""Helper to handle the conversion of method_settings to operations :param method_settings: :... |
# operations docs here: https://tools.ietf.org/html/rfc6902#section-4
operations = []
if method_settings:
for method in method_settings.keys():
for key, value in method_settings[method].items():
if isinstance(value, bool):
if 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 generate_settings():
""" This command is run when ``default_path`` doesn't exist, or ``init`` is run and returns a string representing the default data to pu... |
conf_file = os.path.join(os.path.dirname(base_settings.__file__),
'example', 'conf.py')
conf_template = open(conf_file).read()
default_url = 'http://salmon.example.com'
site_url = raw_input("What will be the URL for Salmon? [{0}]".format(
default_url))
site_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 configure_app(**kwargs):
"""Builds up the settings using the same method as logan""" |
sys_args = sys.argv
args, command, command_args = parse_args(sys_args[1:])
parser = OptionParser()
parser.add_option('--config', metavar='CONFIG')
(options, logan_args) = parser.parse_args(args)
config_path = options.config
logan_configure(config_path=config_path, **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 _reset_changes(self):
"""Stores current values for comparison later""" |
self._original = {}
if self.last_updated is not None:
self._original['last_updated'] = self.last_updated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def whisper_filename(self):
"""Build a file path to the Whisper database""" |
source_name = self.source_id and self.source.name or ''
return get_valid_filename("{0}__{1}.wsp".format(source_name,
self.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_value_display(self):
"""Human friendly value output""" |
if self.display_as == 'percentage':
return '{0}%'.format(self.latest_value)
if self.display_as == 'boolean':
return bool(self.latest_value)
if self.display_as == 'byte':
return defaultfilters.filesizeformat(self.latest_value)
if self.display_as == '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 time_between_updates(self):
"""Time between current `last_updated` and previous `last_updated`""" |
if 'last_updated' not in self._original:
return 0
last_update = self._original['last_updated']
this_update = self.last_updated
return this_update - last_update |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_counter_conversion(self):
"""Update latest value to the diff between it and the previous value""" |
if self.is_counter:
if self._previous_counter_value is None:
prev_value = self.latest_value
else:
prev_value = self._previous_counter_value
self._previous_counter_value = self.latest_value
self.latest_value = self.latest_value - pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace_variable(self, variable):
"""Substitute variables with numeric values""" |
if variable == 'x':
return self.value
if variable == 't':
return self.timedelta
raise ValueError("Invalid variable %s", variable) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def result(self):
"""Evaluate expression and return result""" |
# Module(body=[Expr(value=...)])
return self.eval_(ast.parse(self.expr).body[0].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 email_login(request, *, email, **kwargs):
""" Given a request, an email and optionally some additional data, ensure that a user with the email address exists... |
_u, created = auth.get_user_model()._default_manager.get_or_create(email=email)
user = auth.authenticate(request, email=email)
if user and user.is_active: # The is_active check is possibly redundant.
auth.login(request, user)
return user, created
return None, 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 dashboard(request):
"""Shows the latest results for each source""" |
sources = (models.Source.objects.all().prefetch_related('metric_set')
.order_by('name'))
metrics = SortedDict([(src, src.metric_set.all()) for src in sources])
no_source_metrics = models.Metric.objects.filter(source__isnull=True)
if no_source_metrics:
m... |
<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 the Whisper file on disk""" |
if not os.path.exists(settings.SALMON_WHISPER_DB_PATH):
os.makedirs(settings.SALMON_WHISPER_DB_PATH)
archives = [whisper.parseRetentionDef(retentionDef)
for retentionDef in settings.ARCHIVES.split(",")]
whisper.create(self.path, archives,
x... |
<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(self, datapoints):
""" This method store in the datapoints in the current database. :datapoints: is a list of tupple with the epoch timestamp and val... |
if len(datapoints) == 1:
timestamp, value = datapoints[0]
whisper.update(self.path, value, timestamp)
else:
whisper.update_many(self.path, datapoints) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self, from_time, until_time=None):
""" This method fetch data from the database according to the period given fetch(path, fromTime, untilTime=None) fro... |
until_time = until_time or datetime.now()
time_info, values = whisper.fetch(self.path,
from_time.strftime('%s'),
until_time.strftime('%s'))
# build up a list of (timestamp, value)
start_time, end_time, 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 CMN(self, params):
""" CMN Ra, Rb Add the two registers and set the NZCV flags The result is discarded Ra and Rb must be low registers """ |
Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)
self.check_arguments(low_registers=(Ra, Rb))
# CMN Ra, Rb
def CMN_func():
self.set_NZCV_flags(self.register[Ra], self.register[Rb],
self.register[Ra] + self.registe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MULS(self, params):
""" MULS Ra, Rb, Ra Multiply Rb and Ra together and store the result in Ra. Set the NZ flags. Ra and Rb must be low registers The first a... |
Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_COMMA_SEPARATED, params)
self.check_arguments(low_registers=(Ra, Rb, Rc))
if Ra != Rc:
raise iarm.exceptions.RuleError("Third parameter {} is not the same as the first parameter {}".format(Rc, Ra))
# MULS Ra, Rb, ... |
<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(template, service_name, environment='dev'):
"""Adds SERVICE_NAME, SERVICE_ENVIRONMENT, and DEFAULT_TAGS to the template :param template: :param se... |
template.SERVICE_NAME = os.getenv('SERVICE_NAME', service_name)
template.SERVICE_ENVIRONMENT = os.getenv('ENV', environment).lower()
template.DEFAULT_TAGS = troposphere.Tags(**{
'service-name': template.SERVICE_NAME,
'environment': template.SERVICE_ENVIRONMENT
})
template.add_versio... |
<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_dist(dist_name, lookup_dirs=None):
"""Get dist for installed version of dist_name avoiding pkg_resources cache """ |
# note: based on pip/utils/__init__.py, get_installed_version(...)
# Create a requirement that we'll look for inside of setuptools.
req = pkg_resources.Requirement.parse(dist_name)
# We want to avoid having this cached, so we need to construct a new
# working set each time.
if lookup_dirs is ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_hooks(path):
"""Load hook module and register signals. :param path: Absolute or relative path to module. :return: module """ |
module = imp.load_source(os.path.splitext(os.path.basename(path))[0], path)
if not check_hook_mechanism_is_intact(module):
# no hooks - do nothing
log.debug('No valid hook configuration: \'%s\'. Not using hooks!', path)
else:
if check_register_present(module):
# register... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(doc, tool, dispatch_only=None):
"""gcdt tools parametrized main function to initiate gcdt lifecycle. :param doc: docopt string :param tool: gcdt tool (g... |
# Use signal handler to throw exception which can be caught to allow
# graceful exit.
# here: https://stackoverflow.com/questions/26414704/how-does-a-python-process-exit-gracefully-after-receiving-sigterm-while-waiting
signal.signal(signal.SIGTERM, signal_handler) # Jenkins
signal.signal(signal.SI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MOV(self, params):
""" MOV Rx, Ry MOV PC, Ry Move the value of Ry into Rx or PC """ |
Rx, Ry = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)
self.check_arguments(any_registers=(Rx, Ry))
def MOV_func():
self.register[Rx] = self.register[Ry]
return MOV_func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MRS(self, params):
""" MRS Rj, Rspecial Copy the value of Rspecial to Rj Rspecial can be APSR, IPSR, or EPSR """ |
Rj, Rspecial = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)
self.check_arguments(LR_or_general_purpose_registers=(Rj,), special_registers=(Rspecial,))
def MRS_func():
# TODO add combination registers IEPSR, IAPSR, and EAPSR
# TODO needs to use 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 MSR(self, params):
""" MSR Rspecial, Rj Copy the value of Rj to Rspecial Rspecial can be APSR, IPSR, or EPSR """ |
Rspecial, Rj = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)
self.check_arguments(LR_or_general_purpose_registers=(Rj,), special_registers=(Rspecial,))
def MSR_func():
# TODO add combination registers IEPSR, IAPSR, and EAPSR
# http://infocenter.ar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MVNS(self, params):
""" MVNS Ra, Rb Negate the value in Rb and store it in Ra Ra and Rb must be a low register """ |
Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)
self.check_arguments(low_registers=(Ra, Rb))
def MVNS_func():
self.register[Ra] = ~self.register[Rb]
self.set_NZ_flags(self.register[Ra])
return MVNS_func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def REV(self, params):
""" REV Ra, Rb Reverse the byte order in register Rb and store the result in Ra """ |
Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)
self.check_arguments(low_registers=(Ra, Rb))
def REV_func():
self.register[Ra] = ((self.register[Rb] & 0xFF000000) >> 24) | \
((self.register[Rb] & 0x00FF0000) >> 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 REV16(self, params):
""" REV16 Ra, Rb Reverse the byte order of the half words in register Rb and store the result in Ra """ |
Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)
self.check_arguments(low_registers=(Ra, Rb))
def REV16_func():
self.register[Ra] = ((self.register[Rb] & 0xFF00FF00) >> 8) | \
((self.register[Rb] & 0x00FF00FF) << 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 SXTB(self, params):
""" STXB Ra, Rb Sign extend the byte in Rb and store the result in Ra """ |
Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params)
self.check_arguments(low_registers=(Ra, Rb))
def SXTB_func():
if self.register[Rb] & (1 << 7):
self.register[Ra] = 0xFFFFFF00 + (self.register[Rb] & 0xFF)
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 SXTH(self, params):
""" STXH Ra, Rb Sign extend the half word in Rb and store the result in Ra """ |
Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params)
self.check_arguments(low_registers=(Ra, Rb))
def SXTH_func():
if self.register[Rb] & (1 << 15):
self.register[Ra] = 0xFFFF0000 + (self.register[Rb] & 0xFFFF)
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 UXTB(self, params):
""" UTXB Ra, Rb Zero extend the byte in Rb and store the result in Ra """ |
Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params)
self.check_arguments(low_registers=(Ra, Rb))
def UXTB_func():
self.register[Ra] = (self.register[Rb] & 0xFF)
return UXTB_func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def UXTH(self, params):
""" UTXH Ra, Rb Zero extend the half word in Rb and store the result in Ra """ |
Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params)
self.check_arguments(low_registers=(Ra, Rb))
def UXTH_func():
self.register[Ra] = (self.register[Rb] & 0xFFFF)
return UXTH_func |
<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_event_source_obj(awsclient, evt_source):
""" Given awsclient, event_source dictionary item create an event_source object of the appropriate event type t... |
event_source_map = {
'dynamodb': event_source.dynamodb_stream.DynamoDBStreamEventSource,
'kinesis': event_source.kinesis.KinesisEventSource,
's3': event_source.s3.S3EventSource,
'sns': event_source.sns.SNSEventSource,
'events': event_source.cloudwatch.CloudWatchEventSource,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unwire(awsclient, events, lambda_name, alias_name=ALIAS_NAME):
"""Unwire a list of event from an AWS Lambda function. 'events' is a list of dictionaries, whe... |
if not lambda_exists(awsclient, lambda_name):
log.error(colored.red('The function you try to wire up doesn\'t ' +
'exist... Bailing out...'))
return 1
client_lambda = awsclient.get_client('lambda')
lambda_function = client_lambda.get_function(FunctionName=lambda_n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wire_deprecated(awsclient, function_name, s3_event_sources=None, time_event_sources=None, alias_name=ALIAS_NAME):
"""Deprecated! Please use wire! :param awsc... |
if not lambda_exists(awsclient, function_name):
log.error(colored.red('The function you try to wire up doesn\'t ' +
'exist... Bailing out...'))
return 1
client_lambda = awsclient.get_client('lambda')
lambda_function = client_lambda.get_function(FunctionName=functio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unwire_deprecated(awsclient, function_name, s3_event_sources=None, time_event_sources=None, alias_name=ALIAS_NAME):
"""Deprecated! Please use unwire! :param ... |
if not lambda_exists(awsclient, function_name):
log.error(colored.red('The function you try to wire up doesn\'t ' +
'exist... Bailing out...'))
return 1
client_lambda = awsclient.get_client('lambda')
lambda_function = client_lambda.get_function(FunctionName=functi... |
<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_add_s3_event_source(awsclient, arn, event, bucket, prefix, suffix):
"""Use only prefix OR suffix :param arn: :param event: :param bucket: :param pref... |
json_data = {
'LambdaFunctionConfigurations': [{
'LambdaFunctionArn': arn,
'Id': str(uuid.uuid1()),
'Events': [event]
}]
}
filter_rules = build_filter_rules(prefix, suffix)
json_data['LambdaFunctionConfigurations'][0].update({
'Filter': {
... |
<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_eigen(hint=None):
r'''
Try to find the Eigen library. If successful the include directory is returned.
'''
# search with pkgconfig
# ---------------------
try:
import pkgconfig
if pkgconfig.installed('eigen3','>3.0.0'):
return pkgconfig.parse('eigen3')['include_dirs'][0]
except:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_and_format_logs_params(start, end, tail):
"""Helper to read the params for the logs command""" |
def _decode_duration_type(duration_type):
durations = {'m': 'minutes', 'h': 'hours', 'd': 'days', 'w': 'weeks'}
return durations[duration_type]
if not start:
if tail:
start_dt = maya.now().subtract(seconds=300).datetime(naive=True)
else:
start_dt = maya.... |
<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_to_s3(awsclient, bucket, key, filename):
"""Upload a file to AWS S3 bucket. :param awsclient: :param bucket: :param key: :param filename: :return... |
client_s3 = awsclient.get_client('s3')
transfer = S3Transfer(client_s3)
# Upload /tmp/myfile to s3://bucket/key and print upload progress.
transfer.upload_file(filename, bucket, key)
response = client_s3.head_object(Bucket=bucket, Key=key)
etag = response.get('ETag')
version_id = response.g... |
<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_file_from_s3(awsclient, bucket, key):
"""Remove a file from an AWS S3 bucket. :param awsclient: :param bucket: :param key: :return: """ |
client_s3 = awsclient.get_client('s3')
response = client_s3.delete_object(Bucket=bucket, Key=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 ls(awsclient, bucket, prefix=None):
"""List bucket contents :param awsclient: :param bucket: :param prefix: :return: """ |
# this works until 1000 keys!
params = {'Bucket': bucket}
if prefix:
params['Prefix'] = prefix
client_s3 = awsclient.get_client('s3')
objects = client_s3.list_objects_v2(**params)
if objects['KeyCount'] > 0:
keys = [k['Key'] for k in objects['Contents']]
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 TST(self, params):
""" TST Ra, Rb AND Ra and Rb together and update the NZ flag. The result is not set The equivalent of `Ra & Rc` Ra and Rb must be low regi... |
Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)
self.check_arguments(low_registers=(Ra, Rb))
def TST_func():
result = self.register[Ra] & self.register[Rb]
self.set_NZ_flags(result)
return TST_func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_to_mail(template, context, **kwargs):
""" Renders a mail and returns the resulting ``EmailMultiAlternatives`` instance * ``template``: The base name o... |
lines = iter(
line.rstrip()
for line in render_to_string("%s.txt" % template, context).splitlines()
)
subject = ""
try:
while True:
line = next(lines)
if line:
subject = line
break
except StopIteration: # if lines is ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.