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 transform (list, pattern, indices = [1]): """ Matches all elements of 'list' agains the 'pattern' and returns a list of the elements indicated by indices of ...
result = [] for e in list: m = re.match (pattern, e) if m: for i in indices: result.append (m.group (i)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace(s, pattern, replacement): """Replaces occurrences of a match string in a given string and returns the new string. The match string can be a regex exp...
# the replacement string may contain invalid backreferences (like \1 or \g) # which will cause python's regex to blow up. Since this should emulate # the jam version exactly and the jam version didn't support # backreferences, this version shouldn't either. re.sub # allows replacement to be a calla...
<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_list(items, match, replacement): """Replaces occurrences of a match string in a given list of strings and returns a list of new strings. The match st...
return [replace(item, match, replacement) for item in 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 create(dataset, num_topics=10, initial_topics=None, alpha=None, beta=.1, num_iterations=10, num_burnin=5, associations=None, verbose=False, print_interval=10,...
dataset = _check_input(dataset) _check_categorical_option_type("method", method, ['auto', 'cgs', 'alias']) if method == 'cgs' or method == 'auto': model_name = 'cgs_topic_model' else: model_name = 'alias_topic_model' # If associations are provided, check they are in the proper for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perplexity(test_data, predictions, topics, vocabulary): """ Compute the perplexity of a set of test documents given a set of predicted topics. Let theta be t...
test_data = _check_input(test_data) assert isinstance(predictions, _SArray), \ "Predictions must be an SArray of vector type." assert predictions.dtype == _array.array, \ "Predictions must be probabilities. Try using m.predict() with " + \ "output_type='probability'." opts = {'...
<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_topics(self, topic_ids=None, num_words=5, cdf_cutoff=1.0, output_type='topic_probabilities'): """ Get the words associated with a given topic. The score ...
_check_categorical_option_type('output_type', output_type, ['topic_probabilities', 'topic_words']) if topic_ids is None: topic_ids = list(range(self._get('num_topics'))) assert isinstance(topic_ids, list), \ "The provided topic_ids is not a 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 predict(self, dataset, output_type='assignment', num_burnin=None): """ Use the model to predict topics for each document. The provided `dataset` should be an...
dataset = _check_input(dataset) if num_burnin is None: num_burnin = self.num_burnin opts = {'model': self.__proxy__, 'data': dataset, 'num_burnin': num_burnin} response = _turicreate.extensions._text.topicmodel_predict(opts) preds = ...
<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, train_data, test_data=None, metric='perplexity'): """ Estimate the model's ability to predict new data. Imagine you have a corpus of books. On...
train_data = _check_input(train_data) if test_data is None: test_data = train_data else: test_data = _check_input(test_data) predictions = self.predict(train_data, output_type='probability') topics = self.topics ret = {} ret['perplexity...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _raise_error_if_not_drawing_classifier_input_sframe( dataset, feature, target): """ Performs some sanity checks on the SFrame provided as input to `turicreat...
from turicreate.toolkits._internal_utils import _raise_error_if_not_sframe _raise_error_if_not_sframe(dataset) if feature not in dataset.column_names(): raise _ToolkitError("Feature column '%s' does not exist" % feature) if target not in dataset.column_names(): raise _ToolkitError("Targ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _predict_with_probabilities(self, input_dataset, batch_size=None, verbose=True): """ Predict with probabilities. The core prediction part that both `evaluate...
from .._mxnet import _mxnet_utils import mxnet as _mx from ._sframe_loader import SFrameClassifierIter as _SFrameClassifierIter is_stroke_input = (input_dataset[self.feature].dtype != _tc.Image) dataset = _extensions._drawing_classifier_prepare_data( input_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 predict(self, data, output_type='class', batch_size=None, verbose=True): """ Predict on an SFrame or SArray of drawings, or on a single drawing. Parameters d...
_tkutl._check_categorical_option_type("output_type", output_type, ["probability", "class", "probability_vector"]) if isinstance(data, _tc.SArray): predicted = self._predict_with_probabilities( _tc.SFrame({ self.feature: 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 _BOW_FEATURE_EXTRACTOR(sf, target=None): """ Return an SFrame containing a bag of words representation of each column. """
if isinstance(sf, dict): out = _tc.SArray([sf]).unpack('') elif isinstance(sf, _tc.SFrame): out = sf.__copy__() else: raise ValueError("Unrecognized input to feature extractor.") for f in _get_str_columns(out): if target != f: out[f] = _tc.text_analytics.coun...
<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_str_columns(sf): """ Returns a list of names of columns that are string type. """
return [name for name in sf.column_names() if sf[name].dtype == str]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict(self, dataset, output_type='class'): """ Return predictions for ``dataset``, using the trained model. Parameters dataset : SFrame dataset of new obse...
m = self.__proxy__['classifier'] target = self.__proxy__['target'] f = _BOW_FEATURE_EXTRACTOR return m.predict(f(dataset, target), output_type=output_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classify(self, dataset): """ Return a classification, for each example in the ``dataset``, using the trained model. The output SFrame contains predictions as...
m = self.__proxy__['classifier'] target = self.__proxy__['target'] f = _BOW_FEATURE_EXTRACTOR return m.classify(f(dataset, target))
<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_base_svm_regression_spec(model): """ Takes an SVM regression model produces a starting spec using the parts. that are shared between all SVMs. """
if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') spec = _Model_pb2.Model() spec.specificationVersion = SPECIFICATION_VERSION svm = spec.supportVectorRegressor _set_kernel(model, svm) svm.rho = -model.intercept_[0] for i ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _VerifyExtensionHandle(message, extension_handle): """Verify that the given extension handle is valid."""
if not isinstance(extension_handle, _FieldDescriptor): raise KeyError('HasExtension() expects an extension handle, got: %s' % extension_handle) if not extension_handle.is_extension: raise KeyError('"%s" is not an extension.' % extension_handle.full_name) if not extension_handle.cont...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _AddEnumValues(descriptor, cls): """Sets class-level attributes for all enum fields defined in this message. Also exporting a class-level object that can nam...
for enum_type in descriptor.enum_types: setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type)) for enum_value in enum_type.values: setattr(cls, enum_value.name, enum_value.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 _DefaultValueConstructorForField(field): """Returns a function which returns a default value for a field. Args: field: FieldDescriptor object for this field....
if _IsMapField(field): return _GetInitializeDefaultForMap(field) if field.label == _FieldDescriptor.LABEL_REPEATED: if field.has_default_value and field.default_value != []: raise ValueError('Repeated field default value not empty list: %s' % ( field.default_value)) if field.cpp_type ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReraiseTypeErrorWithFieldName(message_name, field_name): """Re-raise the currently-handled TypeError with the field name added."""
exc = sys.exc_info()[1] if len(exc.args) == 1 and type(exc) is TypeError: # simple TypeError; add field name to exception message exc = TypeError('%s for field %s.%s' % (str(exc), message_name, field_name)) # re-raise possibly-amended exception with original traceback: six.reraise(type(exc), exc, sys....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _GetFieldByName(message_descriptor, field_name): """Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in...
try: return message_descriptor.fields_by_name[field_name] except KeyError: raise ValueError('Protocol message %s has no "%s" field.' % (message_descriptor.name, field_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 _AddPropertiesForNonRepeatedScalarField(field, cls): """Adds a public property for a nonrepeated, scalar protocol message field. Clients can use this propert...
proto_field_name = field.name property_name = _PropertyName(proto_field_name) type_checker = type_checkers.GetTypeChecker(field) default_value = field.default_value valid_values = set() is_proto3 = field.containing_type.syntax == "proto3" def getter(self): # TODO(protobuf-team): This may be broken 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 _InternalUnpackAny(msg): """Unpacks Any message and returns the unpacked message. This internal method is different from public Any Unpack method which takes...
# TODO(amauryfa): Don't use the factory of generated messages. # To make Any work with custom factories, use the message factory of the # parent message. # pylint: disable=g-import-not-at-top from google.protobuf import symbol_database factory = symbol_database.Default() type_url = msg.type_url if no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _BytesForNonRepeatedElement(value, field_number, field_type): """Returns the number of bytes needed to serialize a non-repeated element. The returned byte co...
try: fn = type_checkers.TYPE_TO_BYTE_SIZE_FN[field_type] return fn(field_number, value) except KeyError: raise message_mod.EncodeError('Unrecognized field type: %d' % field_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _AddIsInitializedMethod(message_descriptor, cls): """Adds the IsInitialized and FindInitializationError methods to the protocol message class."""
required_fields = [field for field in message_descriptor.fields if field.label == _FieldDescriptor.LABEL_REQUIRED] def IsInitialized(self, errors=None): """Checks if all required fields of a message are set. Args: errors: A list which, if provided, will be populated wit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _AddMessageMethods(message_descriptor, cls): """Adds implementations of all Message methods to cls."""
_AddListFieldsMethod(message_descriptor, cls) _AddHasFieldMethod(message_descriptor, cls) _AddClearFieldMethod(message_descriptor, cls) if message_descriptor.is_extendable: _AddClearExtensionMethod(cls) _AddHasExtensionMethod(cls) _AddEqualsMethod(message_descriptor, cls) _AddStrMethod(message_desc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _AddPrivateHelperMethods(message_descriptor, cls): """Adds implementation of private helper methods to cls."""
def Modified(self): """Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change. """ # Note: Some callers check _cached_byte_size_dirty before calling # _Modified() as an extra optimization. So, if this method is ever # changed such...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Modified(self): """Also updates the state of the containing oneof in the parent message."""
try: self._parent_message_weakref._UpdateOneofState(self._field) super(_OneofListener, self).Modified() except ReferenceError: 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 Name(self, number): """Returns a string containing the name of an enum value."""
if number in self._enum_type.values_by_number: return self._enum_type.values_by_number[number].name raise ValueError('Enum %s has no name defined for value %d' % ( self._enum_type.name, 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 Value(self, name): """Returns the value coresponding to the given enum name."""
if name in self._enum_type.values_by_name: return self._enum_type.values_by_name[name].number raise ValueError('Enum %s has no value defined for name %s' % ( self._enum_type.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: def _load_tcmps_lib(): """ Load global singleton of tcmps lib handler. This function is used not used at the top level, so that the shared library is loaded lazi...
global _g_TCMPS_LIB if _g_TCMPS_LIB is None: # This library requires macOS 10.14 or above if _mac_ver() < (10, 14): return None # The symbols defined in libtcmps are now exposed directly by # libunity_shared. Eventually the object_detector and # activity_cla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mps_device_name(): """ Returns name of MPS device that will be used, else None. """
lib = _load_tcmps_lib() if lib is None: return None n = 256 c_name = (_ctypes.c_char * n)() ret = lib.TCMPSMetalDeviceName(_ctypes.byref(c_name), _ctypes.c_int32(n)) if ret == 0: return _decode_bytes_to_native_string(c_name.value) else: 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 mps_device_memory_limit(): """ Returns the memory size in bytes that can be effectively allocated on the MPS device that will be used, or None if no suitable...
lib = _load_tcmps_lib() if lib is None: return None c_size = _ctypes.c_uint64() ret = lib.TCMPSMetalDeviceMemoryLimit(_ctypes.byref(c_size)) return c_size.value if ret == 0 else 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 shape(self): """Copy the shape from TCMPS as a new numpy ndarray."""
# Create C variables that will serve as out parameters for TCMPS. shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr dim = _ctypes.c_size_t() # size_t dim # Obtain pointer into memory owned by the C++ object self.handle. status_code = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def asnumpy(self): """Copy the data from TCMPS into a new numpy ndarray"""
# Create C variables that will serve as out parameters for TCMPS. data_ptr = _ctypes.POINTER(_ctypes.c_float)() # float* data_ptr shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr dim = _ctypes.c_size_t() # size_t dim # Obtain poin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def route_sns_task(event, context): """ Gets SNS Message, deserialises the message, imports the function, calls the function with args """
record = event['Records'][0] message = json.loads( record['Sns']['Message'] ) return run_message(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def task(*args, **kwargs): """Async task decorator so that running Args: func (function): the function to be wrapped Further requirements: func must be an indep...
func = None if len(args) == 1 and callable(args[0]): func = args[0] if not kwargs: # Default Values service = 'lambda' lambda_function_name_arg = None aws_region_arg = None else: # Arguments were passed service = kwargs.get('service', 'lambda') lambd...
<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_func_task_path(func): """ Format the modular task path for a function via inspection. """
module_path = inspect.getmodule(func).__name__ task_path = '{module_path}.{func_name}'.format( module_path=module_path, func_name=func.__name__ ) return task_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 get_async_response(response_id): """ Get the response from the async table """
response = DYNAMODB_CLIENT.get_item( TableName=ASYNC_RESPONSE_TABLE, Key={'id': {'S': str(response_id)}} ) if 'Item' not in response: return None return { 'status': response['Item']['async_status']['S'], 'response': json.loads(response['Item']['async_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 send(self, task_path, args, kwargs): """ Create the message object and pass it to the actual sender. """
message = { 'task_path': task_path, 'capture_response': self.capture_response, 'response_id': self.response_id, 'args': args, 'kwargs': kwargs } self._send(message) return 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 _send(self, message): """ Given a message, directly invoke the lamdba function for this task. """
message['command'] = 'zappa.asynchronous.route_lambda_task' payload = json.dumps(message).encode('utf-8') if len(payload) > LAMBDA_ASYNC_PAYLOAD_LIMIT: # pragma: no cover raise AsyncException("Payload too large for async Lambda call") self.response = self.client.invoke( ...
<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(self, message): """ Given a message, publish to this topic. """
message['command'] = 'zappa.asynchronous.route_sns_task' payload = json.dumps(message).encode('utf-8') if len(payload) > LAMBDA_ASYNC_PAYLOAD_LIMIT: # pragma: no cover raise AsyncException("Payload too large for SNS") self.response = self.client.publish( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_s3_url(url): """ Parses S3 URL. Returns bucket (domain) and file (full path). """
bucket = '' path = '' if url: result = urlparse(url) bucket = result.netloc path = result.path.strip('/') return bucket, 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 string_to_timestamp(timestring): """ Accepts a str, returns an int timestamp. """
ts = None # Uses an extended version of Go's duration string. try: delta = durationpy.from_str(timestring); past = datetime.datetime.utcnow() - delta ts = calendar.timegm(past.timetuple()) return ts except Exception as e: pass if ts: 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 detect_django_settings(): """ Automatically try to discover Django settings files, return them as relative module paths. """
matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.filter(filenames, '*settings.py'): full = os.path.join(root, filename) if 'site-packages' in full: continue full = os.path.join(root, filename) pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_flask_apps(): """ Automatically try to discover Flask apps files, return them as relative module paths. """
matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.filter(filenames, '*.py'): full = os.path.join(root, filename) if 'site-packages' in full: continue full = os.path.join(root, filename) with io....
<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_new_version_available(this_version): """ Checks if a newer version of Zappa is available. Returns True is updateable, else False. """
import requests pypi_url = 'https://pypi.python.org/pypi/Zappa/json' resp = requests.get(pypi_url, timeout=1.5) top_version = resp.json()['info']['version'] return this_version != top_version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def conflicts_with_a_neighbouring_module(directory_path): """ Checks if a directory lies in the same directory as a .py file with the same name. """
parent_dir_path, current_dir_name = os.path.split(os.path.normpath(directory_path)) neighbours = os.listdir(parent_dir_path) conflicting_neighbour_filename = current_dir_name+'.py' return conflicting_neighbour_filename in neighbours
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def common_log(environ, response, response_time=None): """ Given the WSGI environ and the response, log this event in Common Log Format. """
logger = logging.getLogger() if response_time: formatter = ApacheFormatter(with_response_time=True) try: log_entry = formatter(response.status_code, environ, len(response.content), rt_us=response_time) except TypeError: # Upstr...
<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_remote_settings(self, remote_bucket, remote_file): """ Attempt to read a file from s3 containing a flat json object. Adds each key->value pair as enviro...
if not self.session: boto_session = boto3.Session() else: boto_session = self.session s3 = boto_session.resource('s3') try: remote_env_object = s3.Object(remote_bucket, remote_file).get() except Exception as e: # pragma: no cover ...
<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_function(app_function, event, context): """ Given a function and event context, detect signature and execute, returning any result. """
# getargspec does not support python 3 method with type hints # Related issue: https://github.com/Miserlou/Zappa/issues/1452 if hasattr(inspect, "getfullargspec"): # Python 3 args, varargs, keywords, defaults, _, _, _ = inspect.getfullargspec(app_function) else: # Python 2...
<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_function_for_aws_event(self, record): """ Get the associated function to execute for a triggered AWS event Support S3, SNS, DynamoDB, kinesis and SQS eve...
if 's3' in record: if ':' in record['s3']['configurationId']: return record['s3']['configurationId'].split(':')[-1] arn = None if 'Sns' in record: try: message = json.loads(record['Sns']['Message']) if message.get('command...
<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_function_from_bot_intent_trigger(self, event): """ For the given event build ARN and return the configured function """
intent = event.get('currentIntent') if intent: intent = intent.get('name') if intent: return self.settings.AWS_BOT_EVENT_MAPPING.get( "{}:{}".format(intent, event.get('invocationSource')) )
<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_function_for_cognito_trigger(self, trigger): """ Get the associated function to execute for a cognito trigger """
print("get_function_for_cognito_trigger", self.settings.COGNITO_TRIGGER_MAPPING, trigger, self.settings.COGNITO_TRIGGER_MAPPING.get(trigger)) return self.settings.COGNITO_TRIGGER_MAPPING.get(trigger)
<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_handler(event, context): print("Client token: " + event['authorizationToken']) print("Method ARN: " + event['methodArn']) """validate the incoming tok...
"""and produce the principal user identifier associated with the token""" """this could be accomplished in a number of ways:""" """1. Call out to OAuth provider""" """2. Decode a JWT token inline""" """3. Lookup in a self-managed DB""" principalId = "user|a1b2c3d4" """you can send a 401 U...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _addMethod(self, effect, verb, resource, conditions): """Adds a method to the internal lists of allowed or denied methods. Each object in the internal list c...
if verb != "*" and not hasattr(HttpVerb, verb): raise NameError("Invalid HTTP verb " + verb + ". Allowed verbs in HttpVerb class") resourcePattern = re.compile(self.pathRegex) if not resourcePattern.match(resource): raise NameError("Invalid resource path: " + resource + ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def boto_client(self, service, *args, **kwargs): """A wrapper to apply configuration options to boto clients"""
return self.boto_session.client(service, *args, **self.configure_boto_session_method_kwargs(service, 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 boto_resource(self, service, *args, **kwargs): """A wrapper to apply configuration options to boto resources"""
return self.boto_session.resource(service, *args, **self.configure_boto_session_method_kwargs(service, 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 cache_param(self, value): '''Returns a troposphere Ref to a value cached as a parameter.''' if value not in self.cf_parameters: keyname = chr(ord('A') + len(self.cf_parameters)) param = self.cf_template.add_parameter(troposphere.Parameter( keyname, Type="Stri...
<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_deps_list(self, pkg_name, installed_distros=None): """ For a given package, returns a list of required packages. Recursive. """
# https://github.com/Miserlou/Zappa/issues/1478. Using `pkg_resources` # instead of `pip` is the recommended approach. The usage is nearly # identical. import pkg_resources deps = [] if not installed_distros: installed_distros = pkg_resources.WorkingSet() ...
<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_handler_venv(self): """ Takes the installed zappa and brings it into a fresh virtualenv-like folder. All dependencies are then downloaded. """
import subprocess # We will need the currenv venv to pull Zappa from current_venv = self.get_current_venv() # Make a new folder for the handler packages ve_path = os.path.join(os.getcwd(), 'handler_venv') if os.sys.platform == 'win32': current_site_package...
<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_current_venv(): """ Returns the path to the current virtualenv """
if 'VIRTUAL_ENV' in os.environ: venv = os.environ['VIRTUAL_ENV'] elif os.path.exists('.python-version'): # pragma: no cover try: subprocess.check_output(['pyenv', 'help'], stderr=subprocess.STDOUT) except OSError: print("This director...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_lambda_package(self, package_name, path): """ Extracts the lambda package into a given path. Assumes the package exists in lambda packages. """
lambda_package = lambda_packages[package_name][self.runtime] # Trash the local version to help with package space saving shutil.rmtree(os.path.join(path, package_name), ignore_errors=True) tar = tarfile.open(lambda_package['path'], mode="r:gz") for member in tar.getmembers(): ...
<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_installed_packages(site_packages, site_packages_64): """ Returns a dict of installed packages that Zappa cares about. """
import pkg_resources package_to_keep = [] if os.path.isdir(site_packages): package_to_keep += os.listdir(site_packages) if os.path.isdir(site_packages_64): package_to_keep += os.listdir(site_packages_64) package_to_keep = [x.lower() for x in package_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 have_correct_lambda_package_version(self, package_name, package_version): """ Checks if a given package version binary should be copied over from lambda pack...
lambda_package_details = lambda_packages.get(package_name, {}).get(self.runtime) if lambda_package_details is None: return False # Binaries can be compiled for different package versions # Related: https://github.com/Miserlou/Zappa/issues/800 if package_version != ...
<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_cached_manylinux_wheel(self, package_name, package_version, disable_progress=False): """ Gets the locally stored version of a manylinux wheel. If one doe...
cached_wheels_dir = os.path.join(tempfile.gettempdir(), 'cached_wheels') if not os.path.isdir(cached_wheels_dir): os.makedirs(cached_wheels_dir) wheel_file = '{0!s}-{1!s}-{2!s}'.format(package_name, package_version, self.manylinux_wheel_file_suffix) wheel_path = os.path.joi...
<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_manylinux_wheel_url(self, package_name, package_version): """ For a given package name, returns a link to the download URL, else returns None. Related: h...
cached_pypi_info_dir = os.path.join(tempfile.gettempdir(), 'cached_pypi_info') if not os.path.isdir(cached_pypi_info_dir): os.makedirs(cached_pypi_info_dir) # Even though the metadata is for the package, we save it in a # filename that includes the package's version. This he...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_on_s3(self, src_file_name, dst_file_name, bucket_name): """ Copies src file to destination within a bucket. """
try: self.s3_client.head_bucket(Bucket=bucket_name) except botocore.exceptions.ClientError as e: # pragma: no cover # If a client error is thrown, then check that it was a 404 error. # If it was a 404 error, then the bucket does not exist. error_code = i...
<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_from_s3(self, file_name, bucket_name): """ Given a file name and a bucket, remove it from S3. There's no reason to keep the file hosted on S3 once its...
try: self.s3_client.head_bucket(Bucket=bucket_name) except botocore.exceptions.ClientError as e: # pragma: no cover # If a client error is thrown, then check that it was a 404 error. # If it was a 404 error, then the bucket does not exist. error_code = i...
<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_lambda_configuration( self, lambda_arn, function_name, handler, description='Zappa Deployment', timeout=30, memory_size=512, publish=True, vpc_config=N...
print("Updating Lambda function configuration..") if not vpc_config: vpc_config = {} if not self.credentials_arn: self.get_credentials_arn() if not aws_kms_key_arn: aws_kms_key_arn = '' if not aws_environment_variables: aws_enviro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invoke_lambda_function( self, function_name, payload, invocation_type='Event', log_type='Tail', client_context=None, qualifier=None ): """ Directly invoke a ...
return self.lambda_client.invoke( FunctionName=function_name, InvocationType=invocation_type, LogType=log_type, Payload=payload )
<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_lambda_function_version(self, function_name, versions_back=1, publish=True): """ Rollback the lambda function code 'versions_back' number of revisio...
response = self.lambda_client.list_versions_by_function(FunctionName=function_name) # Take into account $LATEST if len(response['Versions']) < versions_back + 1: print("We do not have {} revisions. Aborting".format(str(versions_back))) return False revisions = ...
<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_lambda_function(self, function_name): """ Returns the lambda function ARN, given a name This requires the "lambda:GetFunction" role. """
response = self.lambda_client.get_function( FunctionName=function_name) return response['Configuration']['FunctionArn']
<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_lambda_function_versions(self, function_name): """ Simply returns the versions available for a Lambda function, given a function name. """
try: response = self.lambda_client.list_versions_by_function( FunctionName=function_name ) return response.get('Versions', []) except Exception: return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_api_gateway_routes( self, lambda_arn, api_name=None, api_key_required=False, authorization_type='NONE', authorizer=None, cors_options=None, description...
restapi = troposphere.apigateway.RestApi('Api') restapi.Name = api_name or lambda_arn.split(':')[-1] if not description: description = 'Created automatically by Zappa.' restapi.Description = description endpoint_configuration = [] if endpoint_configuration is None e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_authorizer(self, restapi, uri, authorizer): """ Create Authorizer for API gateway """
authorizer_type = authorizer.get("type", "TOKEN").upper() identity_validation_expression = authorizer.get('validation_expression', None) authorizer_resource = troposphere.apigateway.Authorizer("Authorizer") authorizer_resource.RestApiId = troposphere.Ref(restapi) authorizer_res...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy_api_gateway( self, api_id, stage_name, stage_description="", description="", cache_cluster_enabled=False, cache_cluster_size='0.5', variables=None, clo...
print("Deploying API Gateway..") self.apigateway_client.create_deployment( restApiId=api_id, stageName=stage_name, stageDescription=stage_description, description=description, cacheClusterEnabled=cache_cluster_enabled, cacheCluste...
<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_binary_support(self, api_id, cors=False): """ Remove binary support """
response = self.apigateway_client.get_rest_api( restApiId=api_id ) if "binaryMediaTypes" in response and "*/*" in response["binaryMediaTypes"]: self.apigateway_client.update_rest_api( restApiId=api_id, patchOperations=[ ...
<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_api_compression(self, api_id, min_compression_size): """ Add Rest API compression """
self.apigateway_client.update_rest_api( restApiId=api_id, patchOperations=[ { 'op': 'replace', 'path': '/minimumCompressionSize', 'value': str(min_compression_size) } ] )
<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_api_keys(self, api_id, stage_name): """ Generator that allows to iterate per API keys associated to an api_id and a stage_name. """
response = self.apigateway_client.get_api_keys(limit=500) stage_key = '{}/{}'.format(api_id, stage_name) for api_key in response.get('items'): if stage_key in api_key.get('stageKeys'): yield api_key.get('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 create_api_key(self, api_id, stage_name): """ Create new API key and link it with an api_id and a stage_name """
response = self.apigateway_client.create_api_key( name='{}_{}'.format(stage_name, api_id), description='Api Key for {}'.format(api_id), enabled=True, stageKeys=[ { 'restApiId': '{}'.format(api_id), 'stageNam...
<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_api_key(self, api_id, stage_name): """ Remove a generated API key for api_id and stage_name """
response = self.apigateway_client.get_api_keys( limit=1, nameQuery='{}_{}'.format(stage_name, api_id) ) for api_key in response.get('items'): self.apigateway_client.delete_api_key( apiKey="{}".format(api_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 add_api_stage_to_api_key(self, api_key, api_id, stage_name): """ Add api stage to Api key """
self.apigateway_client.update_api_key( apiKey=api_key, patchOperations=[ { 'op': 'add', 'path': '/stages', 'value': '{}/{}'.format(api_id, stage_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_patch_op(self, keypath, value, op='replace'): """ Return an object that describes a change of configuration on the given staging. Setting will be applied...
if isinstance(value, bool): value = str(value).lower() return {'op': op, 'path': '/*/*/{}'.format(keypath), 'value': 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_rest_apis(self, project_name): """ Generator that allows to iterate per every available apis. """
all_apis = self.apigateway_client.get_rest_apis( limit=500 ) for api in all_apis['items']: if api['name'] != project_name: continue yield 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 undeploy_api_gateway(self, lambda_name, domain_name=None, base_path=None): """ Delete a deployed REST API Gateway. """
print("Deleting API Gateway..") api_id = self.get_api_id(lambda_name) if domain_name: # XXX - Remove Route53 smartly here? # XXX - This doesn't raise, but doesn't work either. try: self.apigateway_client.delete_base_path_mapping( ...
<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_config( self, project_name, stage_name, cloudwatch_log_level, cloudwatch_data_trace, cloudwatch_metrics_enabled ): """ Update CloudWatch metrics...
if cloudwatch_log_level not in self.cloudwatch_log_levels: cloudwatch_log_level = 'OFF' for api in self.get_rest_apis(project_name): self.apigateway_client.update_stage( restApiId=api['id'], stageName=stage_name, patchOperations=[...
<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_stack(self, name, wait=False): """ Delete the CF stack managed by Zappa. """
try: stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0] except: # pragma: no cover print('No Zappa stack named {0}'.format(name)) return False tags = {x['Key']:x['Value'] for x in stack['Tags']} if tags.get('ZappaProject') == 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_stack_template( self, lambda_arn, lambda_name, api_key_required, iam_authorization, authorizer, cors_options=None, description=None, endpoint_configura...
auth_type = "NONE" if iam_authorization and authorizer: logger.warn("Both IAM Authorization and Authorizer are specified, this is not possible. " "Setting Auth method to IAM Authorization") authorizer = None auth_type = "AWS_IAM" elif...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stack_outputs(self, name): """ Given a name, describes CloudFront stacks and returns dict of the stack Outputs , else returns an empty dict. """
try: stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0] return {x['OutputKey']: x['OutputValue'] for x in stack['Outputs']} except botocore.client.ClientError: return {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_api_url(self, lambda_name, stage_name): """ Given a lambda_name and stage_name, return a valid API URL. """
api_id = self.get_api_id(lambda_name) if api_id: return "https://{}.execute-api.{}.amazonaws.com/{}".format(api_id, self.boto_session.region_name, stage_name) else: 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 get_api_id(self, lambda_name): """ Given a lambda_name, return the API id. """
try: response = self.cf_client.describe_stack_resource(StackName=lambda_name, LogicalResourceId='Api') return response['StackResourceDetail'].get('PhysicalResourceId', None) except: # pragma: no cover try:...
<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_domain_name(self, domain_name, certificate_name, certificate_body=None, certificate_private_key=None, certificate_chain=None, certificate_arn=None, lam...
# This is a Let's Encrypt or custom certificate if not certificate_arn: agw_response = self.apigateway_client.create_domain_name( domainName=domain_name, certificateName=certificate_name, certificateBody=certificate_body, cert...
<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_route53_records(self, domain_name, dns_name): """ Updates Route53 Records following GW domain creation """
zone_id = self.get_hosted_zone_id_for_domain(domain_name) is_apex = self.route53.get_hosted_zone(Id=zone_id)['HostedZone']['Name'][:-1] == domain_name if is_apex: record_set = { 'Name': domain_name, 'Type': 'A', 'AliasTarget': { ...
<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_domain_name(self, domain_name, certificate_name=None, certificate_body=None, certificate_private_key=None, certificate_chain=None, certificate_arn=None...
print("Updating domain name!") certificate_name = certificate_name + str(time.time()) api_gateway_domain = self.apigateway_client.get_domain_name(domainName=domain_name) if not certificate_arn\ and certificate_body and certificate_private_key and certificate_chain: ...
<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_domain_base_path_mapping(self, domain_name, lambda_name, stage, base_path): """ Update domain base path mapping on API Gateway if it was changed """
api_id = self.get_api_id(lambda_name) if not api_id: print("Warning! Can't update base path mapping!") return base_path_mappings = self.apigateway_client.get_base_path_mappings(domainName=domain_name) found = False for base_path_mapping in base_path_mappi...
<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_all_zones(self): """Same behaviour of list_host_zones, but transparently handling pagination."""
zones = {'HostedZones': []} new_zones = self.route53.list_hosted_zones(MaxItems='100') while new_zones['IsTruncated']: zones['HostedZones'] += new_zones['HostedZones'] new_zones = self.route53.list_hosted_zones(Marker=new_zones['NextMarker'], MaxItems='100') zo...
<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_domain_name(self, domain_name, route53=True): """ Scan our hosted zones for the record of a given name. Returns the record entry, else None. """
# Make sure api gateway domain is present try: self.apigateway_client.get_domain_name(domainName=domain_name) except Exception: return None if not route53: return True try: zones = self.get_all_zones() for zone in zon...
<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_credentials_arn(self): """ Given our role name, get and set the credentials_arn. """
role = self.iam.Role(self.role_name) self.credentials_arn = role.arn return role, self.credentials_arn
<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_iam_roles(self): """ Create and defines the IAM roles and policies necessary for Zappa. If the IAM role already exists, it will be updated if necessar...
attach_policy_obj = json.loads(self.attach_policy) assume_policy_obj = json.loads(self.assume_policy) if self.extra_permissions: for permission in self.extra_permissions: attach_policy_obj['Statement'].append(dict(permission)) self.attach_policy = json.d...