Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _construct_body_s3_dict(self): if isinstance(self.definition_uri, dict): if not self.definition_uri.get("Bucket", None) or not self.definition_uri.get("Key", None): # DefinitionUri is a dictionary but does not contain Bucket o...
[ "Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property.\n\n :returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition\n :rtype: dict\n " ]
Please provide a description of the function:def _construct_deployment(self, rest_api): deployment = ApiGatewayDeployment(self.logical_id + 'Deployment', attributes=self.passthrough_resource_attributes) deployment.RestApiId = rest_api.get_runtime_attr('...
[ "Constructs and returns the ApiGateway Deployment.\n\n :param model.apigateway.ApiGatewayRestApi rest_api: the RestApi for this Deployment\n :returns: the Deployment to which this SAM Api corresponds\n :rtype: model.apigateway.ApiGatewayDeployment\n " ]
Please provide a description of the function:def _construct_stage(self, deployment, swagger): # If StageName is some intrinsic function, then don't prefix the Stage's logical ID # This will NOT create duplicates because we allow only ONE stage per API resource stage_name_prefix = self....
[ "Constructs and returns the ApiGateway Stage.\n\n :param model.apigateway.ApiGatewayDeployment deployment: the Deployment for this Stage\n :returns: the Stage to which this SAM Api corresponds\n :rtype: model.apigateway.ApiGatewayStage\n " ]
Please provide a description of the function:def to_cloudformation(self): rest_api = self._construct_rest_api() deployment = self._construct_deployment(rest_api) swagger = None if rest_api.Body is not None: swagger = rest_api.Body elif rest_api.BodyS3Locati...
[ "Generates CloudFormation resources from a SAM API resource\n\n :returns: a tuple containing the RestApi, Deployment, and Stage for an empty Api.\n :rtype: tuple\n " ]
Please provide a description of the function:def _add_cors(self): INVALID_ERROR = "Invalid value for 'Cors' property" if not self.cors: return if self.cors and not self.definition_body: raise InvalidResourceException(self.logical_id, ...
[ "\n Add CORS configuration to the Swagger file, if necessary\n " ]
Please provide a description of the function:def _add_auth(self): if not self.auth: return if self.auth and not self.definition_body: raise InvalidResourceException(self.logical_id, "Auth works only with inline Swagger specifi...
[ "\n Add Auth configuration to the Swagger file, if necessary\n " ]
Please provide a description of the function:def _add_gateway_responses(self): if not self.gateway_responses: return if self.gateway_responses and not self.definition_body: raise InvalidResourceException( self.logical_id, "GatewayResponses works only wi...
[ "\n Add Gateway Response configuration to the Swagger file, if necessary\n " ]
Please provide a description of the function:def _get_permission(self, authorizer_name, authorizer_lambda_function_arn): rest_api = ApiGatewayRestApi(self.logical_id, depends_on=self.depends_on, attributes=self.resource_attributes) api_id = rest_api.get_runtime_attr('rest_api_id') part...
[ "Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function.\n\n :returns: the permission resource\n :rtype: model.lambda_.LambdaPermission\n " ]
Please provide a description of the function:def _set_endpoint_configuration(self, rest_api, value): rest_api.EndpointConfiguration = {"Types": [value]} rest_api.Parameters = {"endpointConfigurationTypes": value}
[ "\n Sets endpoint configuration property of AWS::ApiGateway::RestApi resource\n :param rest_api: RestApi resource\n :param string/dict value: Value to be set\n " ]
Please provide a description of the function:def retry(time_unit, multiplier, backoff_coefficient, max_delay, max_attempts, expiration_duration, enable_jitter): def deco_retry(task_to_try): @wraps(task_to_try) def retry_impl(*args, **kwargs): total_wait_time = 0 have_tr...
[ "\n The retry function will keep retrying `task_to_try` until either:\n (1) it returns None, then retry() finishes\n (2) `max_attempts` is reached, then retry() raises an exception.\n (3) if retrying one more time will cause total wait time to go above: `expiration_duration`, then\n retry() raises an...
Please provide a description of the function:def to_cloudformation(self, **kwargs): resources = [] intrinsics_resolver = kwargs["intrinsics_resolver"] if self.DeadLetterQueue: self._validate_dlq() lambda_function = self._construct_lambda_function() resource...
[ "Returns the Lambda function, role, and event resources to which this SAM Function corresponds.\n\n :param dict kwargs: already-converted resources that may need to be modified when converting this \\\n macro to pure CloudFormation\n :returns: a list of vanilla CloudFormation Resources, to whic...
Please provide a description of the function:def _get_resolved_alias_name(self, property_name, original_alias_value, intrinsics_resolver): # Try to resolve. resolved_alias_name = intrinsics_resolver.resolve_parameter_refs(original_alias_value) if not isinstance(resolved_alias_name, st...
[ "\n Alias names can be supplied as an intrinsic function. This method tries to extract alias name from a reference\n to a parameter. If it cannot completely resolve (ie. if a complex intrinsic function was used), then this\n method raises an exception. If alias name is just a plain string, it w...
Please provide a description of the function:def _construct_lambda_function(self): lambda_function = LambdaFunction(self.logical_id, depends_on=self.depends_on, attributes=self.resource_attributes) if self.FunctionName: lambda_function.Funct...
[ "Constructs and returns the Lambda function.\n\n :returns: a list containing the Lambda function and execution role resources\n :rtype: list\n " ]
Please provide a description of the function:def _construct_role(self, managed_policy_map): execution_role = IAMRole(self.logical_id + 'Role', attributes=self.get_passthrough_resource_attributes()) execution_role.AssumeRolePolicyDocument = IAMRolePolicies.lambda_assume_role_policy() ma...
[ "Constructs a Lambda execution role based on this SAM function's Policies property.\n\n :returns: the generated IAM Role\n :rtype: model.iam.IAMRole\n " ]
Please provide a description of the function:def _validate_dlq(self): # Validate required logical ids valid_dlq_types = str(list(self.dead_letter_queue_policy_actions.keys())) if not self.DeadLetterQueue.get('Type') or not self.DeadLetterQueue.get('TargetArn'): raise Invalid...
[ "Validates whether the DeadLetterQueue LogicalId is validation\n :raise: InvalidResourceException\n " ]
Please provide a description of the function:def _generate_event_resources(self, lambda_function, execution_role, event_resources, lambda_alias=None): resources = [] if self.Events: for logical_id, event_dict in self.Events.items(): try: eventsour...
[ "Generates and returns the resources associated with this function's events.\n\n :param model.lambda_.LambdaFunction lambda_function: generated Lambda function\n :param iam.IAMRole execution_role: generated Lambda execution role\n :param implicit_api: Global Implicit API resource where the impl...
Please provide a description of the function:def _construct_version(self, function, intrinsics_resolver): code_dict = function.Code if not code_dict: raise ValueError("Lambda function code must be a valid non-empty dictionary") if not intrinsics_resolver: raise ...
[ "Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes.\n Old versions will not be deleted without a direct reference from the CloudFormation template.\n\n :param model.lambda_.LambdaFunction function: Lambda function object that is being connected to a ...
Please provide a description of the function:def _construct_alias(self, name, function, version): if not name: raise InvalidResourceException(self.logical_id, "Alias name is required to create an alias") logical_id = "{id}Alias{suffix}".format(id=function.logical_id, suffix=name) ...
[ "Constructs a Lambda Alias for the given function and pointing to the given version\n\n :param string name: Name of the alias\n :param model.lambda_.LambdaFunction function: Lambda function object to associate the alias with\n :param model.lambda_.LambdaVersion version: Lambda version object to...
Please provide a description of the function:def to_cloudformation(self, **kwargs): resources = [] api_generator = ApiGenerator(self.logical_id, self.CacheClusterEnabled, self.CacheClusterSize, ...
[ "Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds.\n\n :param dict kwargs: already-converted resources that may need to be modified when converting this \\\n macro to pure CloudFormation\n :returns: a list of vanilla CloudFormation Resources, to which thi...
Please provide a description of the function:def _construct_nested_stack(self): nested_stack = NestedStack(self.logical_id, depends_on=self.depends_on, attributes=self.get_passthrough_resource_attributes()) nested_stack.Parameters = self.Parameters nes...
[ "Constructs a AWS::CloudFormation::Stack resource\n " ]
Please provide a description of the function:def _get_application_tags(self): application_tags = {} if isinstance(self.Location, dict): if (self.APPLICATION_ID_KEY in self.Location.keys() and self.Location[self.APPLICATION_ID_KEY] is not None): ap...
[ "Adds tags to the stack if this resource is using the serverless app repo\n " ]
Please provide a description of the function:def to_cloudformation(self, **kwargs): resources = [] # Append any CFN resources: intrinsics_resolver = kwargs["intrinsics_resolver"] resources.append(self._construct_lambda_layer(intrinsics_resolver)) return resources
[ "Returns the Lambda layer to which this SAM Layer corresponds.\n\n :param dict kwargs: already-converted resources that may need to be modified when converting this \\\n macro to pure CloudFormation\n :returns: a list of vanilla CloudFormation Resources, to which this Function expands\n ...
Please provide a description of the function:def _construct_lambda_layer(self, intrinsics_resolver): # Resolve intrinsics if applicable: self.LayerName = self._resolve_string_parameter(intrinsics_resolver, self.LayerName, 'LayerName') self.LicenseInfo = self._resolve_string_parameter(in...
[ "Constructs and returns the Lambda function.\n\n :returns: a list containing the Lambda function and execution role resources\n :rtype: list\n " ]
Please provide a description of the function:def _get_retention_policy_value(self): if self.RetentionPolicy is None or self.RetentionPolicy.lower() == self.RETAIN.lower(): return self.RETAIN elif self.RetentionPolicy.lower() == self.DELETE.lower(): return self.DELETE ...
[ "\n Sets the deletion policy on this resource. The default is 'Retain'.\n\n :return: value for the DeletionPolicy attribute.\n " ]
Please provide a description of the function:def order_flowers(intent_request): flower_type = get_slots(intent_request)["FlowerType"] date = get_slots(intent_request)["PickupDate"] time = get_slots(intent_request)["PickupTime"] source = intent_request['invocationSource'] if source == 'DialogC...
[ "\n Performs dialog management and fulfillment for ordering flowers.\n Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action\n in slot validation and re-prompting.\n " ]
Please provide a description of the function:def dispatch(intent_request): logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot's intent handlers if...
[ "\n Called when the user specifies an intent for this bot.\n " ]
Please provide a description of the function:def _construct_permission(self, function, source_arn=None, source_account=None, suffix="", event_source_token=None): lambda_permission = LambdaPermission(self.logical_id + 'Permission' + suffix, attributes=functio...
[ "Constructs the Lambda Permission resource allowing the source service to invoke the function this event\n source triggers.\n\n :returns: the permission resource\n :rtype: model.lambda_.LambdaPermission\n " ]
Please provide a description of the function:def to_cloudformation(self, **kwargs): function = kwargs.get('function') if not function: raise TypeError("Missing required keyword argument: function") resources = [] events_rule = EventsRule(self.logical_id) r...
[ "Returns the CloudWatch Events Rule and Lambda Permission to which this Schedule event source corresponds.\n\n :param dict kwargs: no existing resources need to be modified\n :returns: a list of vanilla CloudFormation Resources, to which this pull event expands\n :rtype: list\n " ]
Please provide a description of the function:def _construct_target(self, function): target = { 'Arn': function.get_runtime_attr("arn"), 'Id': self.logical_id + 'LambdaTarget' } if self.Input is not None: target['Input'] = self.Input i...
[ "Constructs the Target property for the CloudWatch Events Rule.\n\n :returns: the Target property\n :rtype: dict\n " ]
Please provide a description of the function:def to_cloudformation(self, **kwargs): function = kwargs.get('function') if not function: raise TypeError("Missing required keyword argument: function") if 'bucket' not in kwargs or kwargs['bucket'] is None: raise Ty...
[ "Returns the Lambda Permission resource allowing S3 to invoke the function this event source triggers.\n\n :param dict kwargs: S3 bucket resource\n :returns: a list of vanilla CloudFormation Resources, to which this S3 event expands\n :rtype: list\n " ]
Please provide a description of the function:def _depend_on_lambda_permissions(self, bucket, permission): depends_on = bucket.get("DependsOn", []) # DependsOn can be either a list of strings or a scalar string if isinstance(depends_on, string_types): depends_on = [depends_...
[ "\n Make the S3 bucket depends on Lambda Permissions resource because when S3 adds a Notification Configuration,\n it will check whether it has permissions to access Lambda. This will fail if the Lambda::Permissions is not\n already applied for this bucket to invoke the Lambda.\n\n :para...
Please provide a description of the function:def _depend_on_lambda_permissions_using_tag(self, bucket, permission): properties = bucket.get('Properties', None) if properties is None: properties = {} bucket['Properties'] = properties tags = properties.get('Tags', ...
[ "\n Since conditional DependsOn is not supported this undocumented way of\n implicitely making dependency through tags is used.\n\n See https://stackoverflow.com/questions/34607476/cloudformation-apply-condition-on-dependson\n\n It is done by using Ref wrapped in a conditional Fn::If. U...
Please provide a description of the function:def to_cloudformation(self, **kwargs): function = kwargs.get('function') if not function: raise TypeError("Missing required keyword argument: function") return [self._construct_permission(function, source_arn=self.Topic), ...
[ "Returns the Lambda Permission resource allowing SNS to invoke the function this event source triggers.\n\n :param dict kwargs: no existing resources need to be modified\n :returns: a list of vanilla CloudFormation Resources, to which this SNS event expands\n :rtype: list\n " ]
Please provide a description of the function:def resources_to_link(self, resources): rest_api_id = self.RestApiId if isinstance(rest_api_id, dict) and "Ref" in rest_api_id: rest_api_id = rest_api_id["Ref"] # If RestApiId is a resource in the same template, then we try find...
[ "\n If this API Event Source refers to an explicit API resource, resolve the reference and grab\n necessary data from the explicit API\n " ]
Please provide a description of the function:def to_cloudformation(self, **kwargs): resources = [] function = kwargs.get('function') if not function: raise TypeError("Missing required keyword argument: function") if self.Method is not None: # Convert t...
[ "If the Api event source has a RestApi property, then simply return the Lambda Permission resource allowing\n API Gateway to call the function. If no RestApi is provided, then additionally inject the path, method, and the\n x-amazon-apigateway-integration into the Swagger body for a provided implicit ...
Please provide a description of the function:def _add_swagger_integration(self, api, function): swagger_body = api.get("DefinitionBody") if swagger_body is None: return function_arn = function.get_runtime_attr('arn') partition = ArnGenerator.get_partition_name() ...
[ "Adds the path and method for this Api event source to the Swagger body for the provided RestApi.\n\n :param model.apigateway.ApiGatewayRestApi rest_api: the RestApi to which the path and method should be added.\n " ]
Please provide a description of the function:def resolve_parameter_refs(self, input): return self._traverse(input, self.parameters, self._try_resolve_parameter_refs)
[ "\n Resolves references to parameters within the given dictionary recursively. Other intrinsic functions such as\n !GetAtt, !Sub or !Ref to non-parameters will be left untouched.\n\n Result is a dictionary where parameter values are inlined. Don't pass this dictionary directly into\n tra...
Please provide a description of the function:def resolve_sam_resource_refs(self, input, supported_resource_refs): return self._traverse(input, supported_resource_refs, self._try_resolve_sam_resource_refs)
[ "\n Customers can provide a reference to a \"derived\" SAM resource such as Alias of a Function or Stage of an API\n resource. This method recursively walks the tree, converting all derived references to the real resource name,\n if it is present.\n\n Example:\n {\"Ref\": \"My...
Please provide a description of the function:def resolve_sam_resource_id_refs(self, input, supported_resource_id_refs): return self._traverse(input, supported_resource_id_refs, self._try_resolve_sam_resource_id_refs)
[ "\n Some SAM resources have their logical ids mutated from the original id that the customer writes in the\n template. This method recursively walks the tree and updates these logical ids from the old value\n to the new value that is generated by SAM.\n\n Example:\n {\"Ref\": ...
Please provide a description of the function:def _traverse(self, input, resolution_data, resolver_method): # There is data to help with resolution. Skip the traversal altogether if len(resolution_data) == 0: return input # # Traversal Algorithm: # #...
[ "\n Driver method that performs the actual traversal of input and calls the appropriate `resolver_method` when\n to perform the resolution.\n\n :param input: Any primitive type (dict, array, string etc) whose value might contain an intrinsic function\n :param resolution_data: Data that ...
Please provide a description of the function:def _traverse_dict(self, input_dict, resolution_data, resolver_method): for key, value in input_dict.items(): input_dict[key] = self._traverse(value, resolution_data, resolver_method) return input_dict
[ "\n Traverse a dictionary to resolve intrinsic functions on every value\n\n :param input_dict: Input dictionary to traverse\n :param resolution_data: Data that the `resolver_method` needs to operate\n :param resolver_method: Method that can actually resolve an intrinsic function, if it d...
Please provide a description of the function:def _traverse_list(self, input_list, resolution_data, resolver_method): for index, value in enumerate(input_list): input_list[index] = self._traverse(value, resolution_data, resolver_method) return input_list
[ "\n Traverse a list to resolve intrinsic functions on every element\n\n :param input_list: List of input\n :param resolution_data: Data that the `resolver_method` needs to operate\n :param resolver_method: Method that can actually resolve an intrinsic function, if it detects one\n ...
Please provide a description of the function:def _try_resolve_parameter_refs(self, input, parameters): if not self._is_intrinsic_dict(input): return input function_type = list(input.keys())[0] return self.supported_intrinsics[function_type].resolve_parameter_refs(input, par...
[ "\n Try to resolve parameter references on the given input object. The object could be of any type.\n If the input is not in the format used by intrinsics (ie. dictionary with one key), input is returned\n unmodified. If the single key in dictionary is one of the supported intrinsic function ty...
Please provide a description of the function:def _try_resolve_sam_resource_refs(self, input, supported_resource_refs): if not self._is_intrinsic_dict(input): return input function_type = list(input.keys())[0] return self.supported_intrinsics[function_type].resolve_resource_...
[ "\n Try to resolve SAM resource references on the given template. If the given object looks like one of the\n supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original input\n unmodified.\n\n :param dict input: Dictionary that may represent...
Please provide a description of the function:def _try_resolve_sam_resource_id_refs(self, input, supported_resource_id_refs): if not self._is_intrinsic_dict(input): return input function_type = list(input.keys())[0] return self.supported_intrinsics[function_type].resolve_res...
[ "\n Try to resolve SAM resource id references on the given template. If the given object looks like one of the\n supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original input\n unmodified.\n\n :param dict input: Dictionary that may repres...
Please provide a description of the function:def _is_intrinsic_dict(self, input): # All intrinsic functions are dictionaries with just one key return isinstance(input, dict) \ and len(input) == 1 \ and list(input.keys())[0] in self.supported_intrinsics
[ "\n Can the input represent an intrinsic function in it?\n\n :param input: Object to be checked\n :return: True, if the input contains a supported intrinsic function. False otherwise\n " ]
Please provide a description of the function:def to_cloudformation(self, **kwargs): function = kwargs.get('function') if not function: raise TypeError("Missing required keyword argument: function") source_arn = self.get_source_arn() permission = self._construct_per...
[ "Returns the CloudWatch Logs Subscription Filter and Lambda Permission to which this CloudWatch Logs event source\n corresponds.\n\n :param dict kwargs: no existing resources need to be modified\n :returns: a list of vanilla CloudFormation Resources, to which this push event expands\n :r...
Please provide a description of the function:def convert(self, template_name, parameter_values): if not self.has(template_name): raise TemplateNotFoundException(template_name) template = self.get(template_name) return template.to_statement(parameter_values)
[ "\n Converts the given template to IAM-ready policy statement by substituting template parameters with the given\n values.\n\n :param template_name: Name of the template\n :param parameter_values: Values for all parameters of the template\n :return dict: Dictionary containing poli...
Please provide a description of the function:def _is_valid_templates_dict(policy_templates_dict, schema=None): if not schema: schema = PolicyTemplatesProcessor._read_schema() try: jsonschema.validate(policy_templates_dict, schema) except ValidationError as ex: ...
[ "\n Is this a valid policy template dictionary\n\n :param dict policy_templates_dict: Data to be validated\n :param dict schema: Optional, dictionary containing JSON Schema representing policy template\n :return: True, if it is valid.\n :raises ValueError: If the template dictiona...
Please provide a description of the function:def render_chart_to_file(self, template_name: str, chart: Any, path: str): tpl = self.env.get_template(template_name) html = tpl.render(chart=self.generate_js_link(chart)) write_utf8_html_file(path, self._reg_replace(html))
[ "\n Render a chart or page to local html files.\n\n :param chart: A Chart or Page object\n :param path: The destination file which the html code write to\n :param template_name: The name of template file.\n " ]
Please provide a description of the function:def decode_base64(data: str) -> bytes: missing_padding = len(data) % 4 if missing_padding != 0: data += "=" * (4 - missing_padding) return base64.decodebytes(data.encode("utf-8"))
[ "Decode base64, padding being optional.\n\n :param data: Base64 data as an ASCII byte string\n :returns: The decoded byte string.\n " ]
Please provide a description of the function:def _set_collapse_interval(data, interval): if interval <= 0: return data if data and isinstance(data, list): for d in data: children = d.get("children", None) if children and interval > ...
[ "\r\n 间隔折叠节点,当节点过多时可以解决节点显示过杂间隔。\r\n\r\n :param data: 节点数据\r\n :param interval: 指定间隔\r\n " ]
Please provide a description of the function:def parse_pin(name_str): if len(name_str) < 1: raise ValueError("Expecting pin name to be at least 4 charcters.") if name_str[0] != 'P': raise ValueError("Expecting pin name to start with P") pin_str = name_str[1:].split('/')[0] if not pi...
[ "Parses a string and returns a pin-num." ]
Please provide a description of the function:def ptr(self): if self.fn_num is None: return self.func return '{:s}{:d}'.format(self.func, self.fn_num)
[ "Returns the numbered function (i.e. USART6) for this AF." ]
Please provide a description of the function:def print(self): if self.supported: print(' AF', end='') else: print(' //', end='') fn_num = self.fn_num if fn_num is None: fn_num = 0 print('({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}...
[ "Prints the C representation of this AF." ]
Please provide a description of the function:def run_loop(leds=all_leds): print('Loop started.\nPress Ctrl+C to break out of the loop.') while 1: try: if switch(): [led.on() for led in leds] else: [led.off() for led in leds] except OSE...
[ "\n Start the loop.\n\n :param `leds`: Which LEDs to light up upon switch press.\n :type `leds`: sequence of LED objects\n " ]
Please provide a description of the function:def find_c_file(obj_file, vpath): c_file = None relative_c_file = os.path.splitext(obj_file)[0] + ".c" relative_c_file = relative_c_file.lstrip('/\\') for p in vpath: possible_c_file = os.path.join(p, relative_c_file) if os.path.exists(po...
[ " Search vpaths for the c file that matches the provided object_file.\n\n :param str obj_file: object file to find the matching c file for\n :param List[str] vpath: List of base paths, similar to gcc vpath\n :return: str path to c file or None\n " ]
Please provide a description of the function:def find_module_registrations(c_file): global pattern if c_file is None: # No c file to match the object file, skip return set() with io.open(c_file, encoding='utf-8') as c_file_obj: return set(re.findall(pattern, c_file_obj.read())...
[ " Find any MP_REGISTER_MODULE definitions in the provided c file.\n\n :param str c_file: path to c file to check\n :return: List[(module_name, obj_module, enabled_define)]\n " ]
Please provide a description of the function:def generate_module_table_header(modules): # Print header file for all external modules. mod_defs = [] print("// Automatically generated by makemoduledefs.py.\n") for module_name, obj_module, enabled_define in modules: mod_def = "MODULE_DEF_{}"....
[ " Generate header with module table entries for builtin modules.\n\n :param List[(module_name, obj_module, enabled_define)] modules: module defs\n :return: None\n " ]
Please provide a description of the function:def readfiles(): tests = list(filter(lambda x: x.endswith('.py'), os.listdir(TESTPATH))) tests.sort() files = [] for test in tests: text = open(TESTPATH + test, 'r').read() try: class_, desc, cause, workaround, code = [x.rst...
[ " Reads test files " ]
Please provide a description of the function:def uimports(code): for uimport in UIMPORTLIST: uimport = bytes(uimport, 'utf8') code = code.replace(uimport, b'u' + uimport) return code
[ " converts CPython module names into MicroPython equivalents " ]
Please provide a description of the function:def indent(block, spaces): new_block = '' for line in block.split('\n'): new_block += spaces + line + '\n' return new_block
[ " indents paragraphs of text for rst formatting " ]
Please provide a description of the function:def gen_table(contents): xlengths = [] ylengths = [] for column in contents: col_len = 0 for entry in column: lines = entry.split('\n') for line in lines: col_len = max(len(line) + 2, col_len) x...
[ " creates a table given any set of columns " ]
Please provide a description of the function:def gen_rst(results): # make sure the destination directory exists try: os.mkdir(DOCPATH) except OSError as e: if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR: raise toctree = [] class_ = [] for output in ...
[ " creates restructured text documents to display tests " ]
Please provide a description of the function:def main(): # set search path so that test scripts find the test modules (and no other ones) os.environ['PYTHONPATH'] = TESTPATH os.environ['MICROPYPATH'] = TESTPATH files = readfiles() results = run_tests(files) gen_rst(results)
[ " Main function " ]
Please provide a description of the function:def init(): global __dev, __cfg_descr devices = get_dfu_devices(idVendor=__VID, idProduct=__PID) if not devices: raise ValueError('No DFU device found') if len(devices) > 1: raise ValueError("Multiple DFU devices found") __dev = devic...
[ "Initializes the found DFU device so that we can program it." ]
Please provide a description of the function:def page_erase(addr): if __verbose: print("Erasing page: 0x%x..." % (addr)) # Send DNLOAD with first byte=0x41 and page address buf = struct.pack("<BI", 0x41, addr) __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT) ...
[ "Erases a single page." ]
Please provide a description of the function:def set_address(addr): # Send DNLOAD with first byte=0x21 and page address buf = struct.pack("<BI", 0x21, addr) __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, buf, __TIMEOUT) # Execute last command if get_status() != __DFU_STATE_DFU_DOW...
[ "Sets the address for the next operation." ]
Please provide a description of the function:def write_memory(addr, buf, progress=None, progress_addr=0, progress_size=0): xfer_count = 0 xfer_bytes = 0 xfer_total = len(buf) xfer_base = addr while xfer_bytes < xfer_total: if __verbose and xfer_count % 512 == 0: print ("Ad...
[ "Writes a buffer into memory. This routine assumes that memory has\n already been erased.\n " ]
Please provide a description of the function:def write_page(buf, xfer_offset): xfer_base = 0x08000000 # Set mem write address set_address(xfer_base+xfer_offset) # Send DNLOAD with fw data __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, buf, __TIMEOUT) # Execute last command ...
[ "Writes a single page. This routine assumes that memory has already\n been erased.\n " ]
Please provide a description of the function:def exit_dfu(): # set jump address set_address(0x08000000) # Send DNLOAD with 0 length to exit DFU __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, None, __TIMEOUT) try: # Execute last command if ...
[ "Exit DFU mode, and start running the program." ]
Please provide a description of the function:def consume(fmt, data, names): size = struct.calcsize(fmt) return named(struct.unpack(fmt, data[:size]), names), data[size:]
[ "Parses the struct defined by `fmt` from `data`, stores the parsed fields\n into a named tuple using `names`. Returns the named tuple, and the data\n with the struct stripped off." ]
Please provide a description of the function:def read_dfu_file(filename): print("File: {}".format(filename)) with open(filename, 'rb') as fin: data = fin.read() crc = compute_crc(data[:-4]) elements = [] # Decode the DFU Prefix # # <5sBIB # < little endian # 5s ...
[ "Reads a DFU file, and parses the individual elements from the file.\n Returns an array of elements. Each element is a dictionary with the\n following keys:\n num - The element index\n address - The address that the element data should be written to.\n size - The size of the elemen...
Please provide a description of the function:def get_dfu_devices(*args, **kwargs): # convert to list for compatibility with newer pyusb return list(usb.core.find(*args, find_all=True, custom_match=FilterDFU(), **kwargs))
[ "Returns a list of USB device which are currently in DFU mode.\n Additional filters (like idProduct and idVendor) can be passed in to\n refine the search.\n " ]
Please provide a description of the function:def get_memory_layout(device): cfg = device[0] intf = cfg[(0, 0)] mem_layout_str = get_string(device, intf.iInterface) mem_layout = mem_layout_str.split('/') result = [] for mem_layout_index in range(1, len(mem_layout), 2): addr = int(mem...
[ "Returns an array which identifies the memory layout. Each entry\n of the array will contain a dictionary with the following keys:\n addr - Address of this memory segment\n last_addr - Last address contained within the memory segment.\n size - size of the segment, in bytes\n ...
Please provide a description of the function:def list_dfu_devices(*args, **kwargs): devices = get_dfu_devices(*args, **kwargs) if not devices: print("No DFU capable devices found") return for device in devices: print("Bus {} Device {:03d}: ID {:04x}:{:04x}" .format...
[ "Prints a lits of devices detected in DFU mode." ]
Please provide a description of the function:def write_elements(elements, mass_erase_used, progress=None): mem_layout = get_memory_layout(__dev) for elem in elements: addr = elem['addr'] size = elem['size'] data = elem['data'] elem_size = size elem_addr = addr ...
[ "Writes the indicated elements into the target memory,\n erasing as needed.\n " ]
Please provide a description of the function:def cli_progress(addr, offset, size): width = 25 done = offset * width // size print("\r0x{:08x} {:7d} [{}{}] {:3d}% " .format(addr, size, '=' * done, ' ' * (width - done), offset * 100 // size), end="") try: sys.stdou...
[ "Prints a progress report suitable for use on the command line." ]
Please provide a description of the function:def main(): global __verbose # Parse CMD args parser = argparse.ArgumentParser(description='DFU Python Util') #parser.add_argument("path", help="file path") parser.add_argument( "-l", "--list", help="list available DFU devices", ...
[ "Test program for verifying this files functionality." ]
Please provide a description of the function:def parse_port_pin(name_str): if len(name_str) < 3: raise ValueError("Expecting pin name to be at least 3 charcters.") if name_str[0] != 'P': raise ValueError("Expecting pin name to start with P") if name_str[1] < 'A' or name_str[1] > 'K': ...
[ "Parses a string and returns a (port-num, pin-num) tuple." ]
Please provide a description of the function:def print(self): cond_var = None if self.supported: cond_var = conditional_var('{}{}'.format(self.func, self.fn_num)) print_conditional_if(cond_var) print(' AF', end='') else: print(' //', en...
[ "Prints the C representation of this AF." ]
Please provide a description of the function:def parse_port_pin(name_str): if len(name_str) < 3: raise ValueError("Expecting pin name to be at least 3 characters") if name_str[:2] != 'GP': raise ValueError("Expecting pin name to start with GP") if not name_str[2:].isdigit(): rai...
[ "Parses a string and returns a (port, gpio_bit) tuple." ]
Please provide a description of the function:def run_node(cls, node, # type: NodeProto inputs, # type: Any device='CPU', # type: Text outputs_info=None, # type: Optional[Sequence[Tuple[numpy.dtype, Tuple[int, ...]]]] **kwargs # ty...
[]
Please provide a description of the function:def load_external_data_for_tensor(tensor, base_dir): # type: (TensorProto, Text) -> None if tensor.HasField("raw_data"): # already loaded return info = ExternalDataInfo(tensor) file_location = _sanitize_path(info.location) external_data_file_pa...
[ "\n Load data from an external file for tensor.\n\n @params\n tensor: a TensorProto object.\n base_dir: directory that contains the external data.\n " ]
Please provide a description of the function:def load_external_data_for_model(model, base_dir): # type: (ModelProto, Text) -> None for tensor in _get_all_tensors(model): if uses_external_data(tensor): load_external_data_for_tensor(tensor, base_dir)
[ "\n Loads external tensors into model\n\n @params\n model: ModelProto to load external data to\n base_dir: directory that contains external data\n " ]
Please provide a description of the function:def convert_model_to_external_data(model, all_tensors_to_one_file=True, location=None): # type: (ModelProto, bool, Optional[Text]) -> None if all_tensors_to_one_file: file_name = Text(uuid.uuid1()) if location: file_name = location ...
[ "\n call to set all tensors as external data. save_model saves all the tensors data as external data after calling this function.\n @params\n model: ModelProto to be converted.\n all_tensors_to_one_file: If true, save all tensors to one external file specified by location.\n ...
Please provide a description of the function:def convert_model_from_external_data(model): # type: (ModelProto) -> None for tensor in _get_all_tensors(model): if uses_external_data(tensor): if not tensor.HasField("raw_data"): raise ValueError("raw_data field doesn't exist.")...
[ "\n call to set all tensors data as embedded data. save_model saves all the tensors data as embedded data after calling this function.\n @params\n model: ModelProto to be converted.\n " ]
Please provide a description of the function:def save_external_data(tensor, base_path): # type: (TensorProto, Text) -> None info = ExternalDataInfo(tensor) external_data_file_path = os.path.join(base_path, info.location) # Retrieve the tensor's data from raw_data or load external file if not tens...
[ "\n Write tensor data to an external file according to information in the `external_data` field.\n\n @params\n tensor: Tensor object to be serialized\n base_path: System path of a folder where tensor data is to be stored\n " ]
Please provide a description of the function:def _get_attribute_tensors(onnx_model_proto): # type: (ModelProto) -> Iterable[TensorProto] for node in onnx_model_proto.graph.node: for attribute in node.attribute: if attribute.HasField("t"): yield attribute.t for t...
[ "Create an iterator of tensors from node attributes of an ONNX model." ]
Please provide a description of the function:def remove_external_data_field(tensor, field_key): # type: (TensorProto, Text) -> None for (i, field) in enumerate(tensor.external_data): if field.key == field_key: del tensor.external_data[i]
[ "\n Remove a field from a Tensor's external_data key-value store.\n\n Modifies tensor object in place.\n\n @params\n tensor: Tensor object from which value will be removed\n field_key: The key of the field to be removed\n " ]
Please provide a description of the function:def write_external_data_tensors(model, filepath): # type: (ModelProto, Text) -> ModelProto for tensor in _get_all_tensors(model): if uses_external_data(tensor): save_external_data(tensor, filepath) tensor.ClearField(str('raw_data')) ...
[ "\n Write external data of all tensors to files on disk.\n\n Note: This function also strips basepath information from all tensors' external_data fields.\n\n @params\n model: Model object which is the source of tensors to serialize.\n filepath: System path to the directory which should be treated as ...
Please provide a description of the function:def _import(self, path, name): # type: (Text, Text) -> Text imp = path.replace('/', '.') self.imports[imp].add(name) return name
[ "Imports a stdlib path and returns a handle to it\n eg. self._import(\"typing\", \"Optional\") -> \"Optional\"\n " ]
Please provide a description of the function:def _import_message(self, type_name): # type: (d.FieldDescriptorProto) -> Text name = cast(Text, type_name) if name[0] == '.' and name[1].isupper() and name[2].islower(): # Message defined in this file return name[1:]...
[ "Import a referenced message and return a handle" ]
Please provide a description of the function:def run(self): onnx_script = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools/mypy-onnx.py")) returncode = subprocess.call([sys.executable, onnx_script]) sys.exit(returncode)
[ "Run command." ]
Please provide a description of the function:def make_node( op_type, # type: Text inputs, # type: Sequence[Text] outputs, # type: Sequence[Text] name=None, # type: Optional[Text] doc_string=None, # type: Optional[Text] domain=None, # type: Optional[Text] **k...
[ "Construct a NodeProto.\n\n Arguments:\n op_type (string): The name of the operator to construct\n inputs (list of string): list of input names\n outputs (list of string): list of output names\n name (string, default None): optional unique identifier for NodeProto\n doc_string ...
Please provide a description of the function:def make_operatorsetid( domain, # type: Text version, # type: int ): # type: (...) -> OperatorSetIdProto operatorsetid = OperatorSetIdProto() operatorsetid.domain = domain operatorsetid.version = version return operatorsetid
[ "Construct an OperatorSetIdProto.\n\n Arguments:\n domain (string): The domain of the operator set id\n version (integer): Version of operator set id\n " ]
Please provide a description of the function:def _to_bytes_or_false(val): # type: (Union[Text, bytes]) -> Union[bytes, bool] if isinstance(val, bytes): return val else: try: return val.encode('utf-8') except AttributeError: return False
[ "An internal graph to convert the input to a bytes or to False.\n\n The criteria for conversion is as follows and should be python 2 and 3\n compatible:\n - If val is py2 str or py3 bytes: return bytes\n - If val is py2 unicode or py3 str: return val.decode('utf-8')\n - Otherwise, return False\n "...
Please provide a description of the function:def make_attribute( key, # type: Text value, # type: Any doc_string=None # type: Optional[Text] ): # type: (...) -> AttributeProto attr = AttributeProto() attr.name = key if doc_string: attr.doc_string = doc_string is...
[ "Makes an AttributeProto based on the value type." ]
Please provide a description of the function:def make_tensor_value_info( name, # type: Text elem_type, # type: int shape, # type: Optional[Sequence[Union[Text, int]]] doc_string="", # type: Text shape_denotation=None, # type: Optional[List[Text]] ): # type: (...) -> ValueIn...
[ "Makes a ValueInfoProto based on the data type and shape." ]
Please provide a description of the function:def strip_doc_string(proto): # type: (google.protobuf.message.Message) -> None assert isinstance(proto, google.protobuf.message.Message) for descriptor in proto.DESCRIPTOR.fields: if descriptor.name == 'doc_string': proto.ClearField(descript...
[ "\n Empties `doc_string` field on any nested protobuf messages\n " ]