text stringlengths 81 112k |
|---|
Makes a combined condition using Fn::Or. Since Fn::Or only accepts up to 10 conditions,
this method optionally creates multiple conditions. These conditions are named based on
the condition_name parameter that is passed into the method.
:param list conditions_list: list of conditions
:param string cond... |
Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single
key that is the name of the intrinsics.
:param input: Input value to check if it is an intrinsic
:return: True, if yes
def is_instrinsic(input):
"""
Checks if the given input is an intrins... |
Validates that the input dictionary contains only one key and is of the given intrinsic_name
:param input_dict: Input dictionary representing the intrinsic function
:return: True if it matches expected structure, False otherwise
def can_handle(self, input_dict):
"""
Validates that the ... |
Splits a resource reference of structure "LogicalId.Property" and returns the "LogicalId" and "Property"
separately.
:param string ref_value: Input reference value which *may* contain the structure "LogicalId.Property"
:return string, string: Returns two values - logical_id, property. If the in... |
Resolves references that are present in the parameters and returns the value. If it is not in parameters,
this method simply returns the input unchanged.
:param input_dict: Dictionary representing the Ref function. Must contain only one key and it should be "Ref".
Ex: {Ref: "foo"}
... |
Resolves references to some property of a resource. These are runtime properties which can't be converted
to a value here. Instead we output another reference that will more actually resolve to the value when
executed via CloudFormation
Example:
{"Ref": "LogicalId.Property"} => {"Re... |
Updates references to the old logical id of a resource to the new (generated) logical id.
Example:
{"Ref": "MyLayer"} => {"Ref": "MyLayerABC123"}
:param dict input_dict: Dictionary representing the Ref function to be resolved.
:param dict supported_resource_id_refs: Dictionary that... |
Substitute references found within the string of `Fn::Sub` intrinsic function
:param input_dict: Dictionary representing the Fn::Sub function. Must contain only one key and it should be
`Fn::Sub`. Ex: {"Fn::Sub": ...}
:param parameters: Dictionary of parameter values for substitution
... |
Resolves reference to some property of a resource. Inside string to be substituted, there could be either a
"Ref" or a "GetAtt" usage of this property. They have to be handled differently.
Ref usages are directly converted to a Ref on the resolved value. GetAtt usages are split under the assumption
... |
Resolves reference to some property of a resource. Inside string to be substituted, there could be either a
"Ref" or a "GetAtt" usage of this property. They have to be handled differently.
Ref usages are directly converted to a Ref on the resolved value. GetAtt usages are split under the assumption
... |
Handles resolving replacements in the Sub action based on the handler that is passed as an input.
:param input_dict: Dictionary to be resolved
:param supported_values: One of several different objects that contain the supported values that
need to be changed. See each method above for speci... |
Generic method to handle value to Fn::Sub key. We are interested in parsing the ${} syntaxes inside
the string portion of the value.
:param sub_value: Value of the Sub function
:param handler_method: Method to be called on every occurrence of `${LogicalId}` structure within the string.
... |
Substitute references within a string that is using ${key} syntax by calling the `handler_method` on every
occurrence of this structure. The value returned by this method directly replaces the reference structure.
Ex:
text = "${key1}-hello-${key2}
def handler_method(full_ref, re... |
Resolve resource references within a GetAtt dict.
Example:
{ "Fn::GetAtt": ["LogicalId.Property", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]}
Theoretically, only the first element of the array can contain reference to SAM resources. The second element
is name of an... |
Resolve resource references within a GetAtt dict.
Example:
{ "Fn::GetAtt": ["LogicalId", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]}
Theoretically, only the first element of the array can contain reference to SAM resources. The second element
is name of an attribut... |
Resolves the function and returns the updated dictionary
:param input_dict: Dictionary to be resolved
:param key: Name of this intrinsic.
:param resolved_value: Resolved or updated value for this action.
:param remaining: Remaining sections for the GetAtt action.
def _get_resolved_dict... |
Recursively resolves "Fn::FindInMap"references that are present in the mappings and returns the value.
If it is not in mappings, this method simply returns the input unchanged.
:param input_dict: Dictionary representing the FindInMap function. Must contain only one key and it
... |
Process a RDS enhenced monitoring DATA_MESSAGE,
coming from CLOUDWATCH LOGS
def lambda_handler(event, context):
''' Process a RDS enhenced monitoring DATA_MESSAGE,
coming from CLOUDWATCH LOGS
'''
# event is a dict containing a base64 string gzipped
event = json.loads(gzip.GzipFile(fileo... |
Constructs and returns the ApiGateway RestApi.
:returns: the RestApi to which this SAM Api corresponds
:rtype: model.apigateway.ApiGatewayRestApi
def _construct_rest_api(self):
"""Constructs and returns the ApiGateway RestApi.
:returns: the RestApi to which this SAM Api corresponds
... |
Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property.
:returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition
:rtype: dict
def _construct_body_s3_dict(self):
"""Constructs the RestApi's `BodyS3Location prop... |
Constructs and returns the ApiGateway Deployment.
:param model.apigateway.ApiGatewayRestApi rest_api: the RestApi for this Deployment
:returns: the Deployment to which this SAM Api corresponds
:rtype: model.apigateway.ApiGatewayDeployment
def _construct_deployment(self, rest_api):
"""C... |
Constructs and returns the ApiGateway Stage.
:param model.apigateway.ApiGatewayDeployment deployment: the Deployment for this Stage
:returns: the Stage to which this SAM Api corresponds
:rtype: model.apigateway.ApiGatewayStage
def _construct_stage(self, deployment, swagger):
"""Constru... |
Generates CloudFormation resources from a SAM API resource
:returns: a tuple containing the RestApi, Deployment, and Stage for an empty Api.
:rtype: tuple
def to_cloudformation(self):
"""Generates CloudFormation resources from a SAM API resource
:returns: a tuple containing the RestAp... |
Add CORS configuration to the Swagger file, if necessary
def _add_cors(self):
"""
Add CORS configuration to the Swagger file, if necessary
"""
INVALID_ERROR = "Invalid value for 'Cors' property"
if not self.cors:
return
if self.cors and not self.definition... |
Add Auth configuration to the Swagger file, if necessary
def _add_auth(self):
"""
Add Auth configuration to the Swagger file, if necessary
"""
if not self.auth:
return
if self.auth and not self.definition_body:
raise InvalidResourceException(self.logica... |
Add Gateway Response configuration to the Swagger file, if necessary
def _add_gateway_responses(self):
"""
Add Gateway Response configuration to the Swagger file, if necessary
"""
if not self.gateway_responses:
return
if self.gateway_responses and not self.definiti... |
Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function.
:returns: the permission resource
:rtype: model.lambda_.LambdaPermission
def _get_permission(self, authorizer_name, authorizer_lambda_function_arn):
"""Constructs and returns the Lambda Permis... |
Sets endpoint configuration property of AWS::ApiGateway::RestApi resource
:param rest_api: RestApi resource
:param string/dict value: Value to be set
def _set_endpoint_configuration(self, rest_api, value):
"""
Sets endpoint configuration property of AWS::ApiGateway::RestApi resource
... |
The retry function will keep retrying `task_to_try` until either:
(1) it returns None, then retry() finishes
(2) `max_attempts` is reached, then retry() raises an exception.
(3) if retrying one more time will cause total wait time to go above: `expiration_duration`, then
retry() raises an exception
... |
Returns the Lambda function, role, and event resources to which this SAM Function corresponds.
:param dict kwargs: already-converted resources that may need to be modified when converting this \
macro to pure CloudFormation
:returns: a list of vanilla CloudFormation Resources, to which this Fun... |
Alias names can be supplied as an intrinsic function. This method tries to extract alias name from a reference
to a parameter. If it cannot completely resolve (ie. if a complex intrinsic function was used), then this
method raises an exception. If alias name is just a plain string, it will return as is
... |
Constructs and returns the Lambda function.
:returns: a list containing the Lambda function and execution role resources
:rtype: list
def _construct_lambda_function(self):
"""Constructs and returns the Lambda function.
:returns: a list containing the Lambda function and execution role... |
Constructs a Lambda execution role based on this SAM function's Policies property.
:returns: the generated IAM Role
:rtype: model.iam.IAMRole
def _construct_role(self, managed_policy_map):
"""Constructs a Lambda execution role based on this SAM function's Policies property.
:returns: ... |
Validates whether the DeadLetterQueue LogicalId is validation
:raise: InvalidResourceException
def _validate_dlq(self):
"""Validates whether the DeadLetterQueue LogicalId is validation
:raise: InvalidResourceException
"""
# Validate required logical ids
valid_dlq_types =... |
Generates and returns the resources associated with this function's events.
:param model.lambda_.LambdaFunction lambda_function: generated Lambda function
:param iam.IAMRole execution_role: generated Lambda execution role
:param implicit_api: Global Implicit API resource where the implicit APIs... |
Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes.
Old versions will not be deleted without a direct reference from the CloudFormation template.
:param model.lambda_.LambdaFunction function: Lambda function object that is being connected to a version
... |
Constructs a Lambda Alias for the given function and pointing to the given version
:param string name: Name of the alias
:param model.lambda_.LambdaFunction function: Lambda function object to associate the alias with
:param model.lambda_.LambdaVersion version: Lambda version object to associat... |
Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds.
:param dict kwargs: already-converted resources that may need to be modified when converting this \
macro to pure CloudFormation
:returns: a list of vanilla CloudFormation Resources, to which this Function... |
Constructs a AWS::CloudFormation::Stack resource
def _construct_nested_stack(self):
"""Constructs a AWS::CloudFormation::Stack resource
"""
nested_stack = NestedStack(self.logical_id, depends_on=self.depends_on,
attributes=self.get_passthrough_resource_attribu... |
Adds tags to the stack if this resource is using the serverless app repo
def _get_application_tags(self):
"""Adds tags to the stack if this resource is using the serverless app repo
"""
application_tags = {}
if isinstance(self.Location, dict):
if (self.APPLICATION_ID_KEY in ... |
Returns the Lambda layer to which this SAM Layer corresponds.
:param dict kwargs: already-converted resources that may need to be modified when converting this \
macro to pure CloudFormation
:returns: a list of vanilla CloudFormation Resources, to which this Function expands
:rtype: lis... |
Constructs and returns the Lambda function.
:returns: a list containing the Lambda function and execution role resources
:rtype: list
def _construct_lambda_layer(self, intrinsics_resolver):
"""Constructs and returns the Lambda function.
:returns: a list containing the Lambda function ... |
Sets the deletion policy on this resource. The default is 'Retain'.
:return: value for the DeletionPolicy attribute.
def _get_retention_policy_value(self):
"""
Sets the deletion policy on this resource. The default is 'Retain'.
:return: value for the DeletionPolicy attribute.
... |
Performs dialog management and fulfillment for ordering flowers.
Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action
in slot validation and re-prompting.
def order_flowers(intent_request):
"""
Performs dialog management and fulfillment for ordering... |
Called when the user specifies an intent for this bot.
def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))
intent_name = intent_requ... |
Constructs the Lambda Permission resource allowing the source service to invoke the function this event
source triggers.
:returns: the permission resource
:rtype: model.lambda_.LambdaPermission
def _construct_permission(self, function, source_arn=None, source_account=None, suffix="", event_sou... |
Returns the CloudWatch Events Rule and Lambda Permission to which this Schedule event source corresponds.
:param dict kwargs: no existing resources need to be modified
:returns: a list of vanilla CloudFormation Resources, to which this pull event expands
:rtype: list
def to_cloudformation(self... |
Constructs the Target property for the CloudWatch Events Rule.
:returns: the Target property
:rtype: dict
def _construct_target(self, function):
"""Constructs the Target property for the CloudWatch Events Rule.
:returns: the Target property
:rtype: dict
"""
tar... |
Returns the Lambda Permission resource allowing S3 to invoke the function this event source triggers.
:param dict kwargs: S3 bucket resource
:returns: a list of vanilla CloudFormation Resources, to which this S3 event expands
:rtype: list
def to_cloudformation(self, **kwargs):
"""Retur... |
Make the S3 bucket depends on Lambda Permissions resource because when S3 adds a Notification Configuration,
it will check whether it has permissions to access Lambda. This will fail if the Lambda::Permissions is not
already applied for this bucket to invoke the Lambda.
:param dict bucket: Dict... |
Since conditional DependsOn is not supported this undocumented way of
implicitely making dependency through tags is used.
See https://stackoverflow.com/questions/34607476/cloudformation-apply-condition-on-dependson
It is done by using Ref wrapped in a conditional Fn::If. Using Ref implies a
... |
Returns the Lambda Permission resource allowing SNS to invoke the function this event source triggers.
:param dict kwargs: no existing resources need to be modified
:returns: a list of vanilla CloudFormation Resources, to which this SNS event expands
:rtype: list
def to_cloudformation(self, **... |
If this API Event Source refers to an explicit API resource, resolve the reference and grab
necessary data from the explicit API
def resources_to_link(self, resources):
"""
If this API Event Source refers to an explicit API resource, resolve the reference and grab
necessary data from th... |
If the Api event source has a RestApi property, then simply return the Lambda Permission resource allowing
API Gateway to call the function. If no RestApi is provided, then additionally inject the path, method, and the
x-amazon-apigateway-integration into the Swagger body for a provided implicit API.
... |
Adds the path and method for this Api event source to the Swagger body for the provided RestApi.
:param model.apigateway.ApiGatewayRestApi rest_api: the RestApi to which the path and method should be added.
def _add_swagger_integration(self, api, function):
"""Adds the path and method for this Api eve... |
Resolves references to parameters within the given dictionary recursively. Other intrinsic functions such as
!GetAtt, !Sub or !Ref to non-parameters will be left untouched.
Result is a dictionary where parameter values are inlined. Don't pass this dictionary directly into
transform's output bec... |
Customers can provide a reference to a "derived" SAM resource such as Alias of a Function or Stage of an API
resource. This method recursively walks the tree, converting all derived references to the real resource name,
if it is present.
Example:
{"Ref": "MyFunction.Alias"} -> {"Ref... |
Some SAM resources have their logical ids mutated from the original id that the customer writes in the
template. This method recursively walks the tree and updates these logical ids from the old value
to the new value that is generated by SAM.
Example:
{"Ref": "MyLayer"} -> {"Ref": ... |
Driver method that performs the actual traversal of input and calls the appropriate `resolver_method` when
to perform the resolution.
:param input: Any primitive type (dict, array, string etc) whose value might contain an intrinsic function
:param resolution_data: Data that will help with reso... |
Traverse a dictionary to resolve intrinsic functions on every value
:param input_dict: Input dictionary to traverse
:param resolution_data: Data that the `resolver_method` needs to operate
:param resolver_method: Method that can actually resolve an intrinsic function, if it detects one
... |
Traverse a list to resolve intrinsic functions on every element
:param input_list: List of input
:param resolution_data: Data that the `resolver_method` needs to operate
:param resolver_method: Method that can actually resolve an intrinsic function, if it detects one
:return: Modified l... |
Try to resolve parameter references on the given input object. The object could be of any type.
If the input is not in the format used by intrinsics (ie. dictionary with one key), input is returned
unmodified. If the single key in dictionary is one of the supported intrinsic function types,
go a... |
Try to resolve SAM resource references on the given template. If the given object looks like one of the
supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original input
unmodified.
:param dict input: Dictionary that may represent an intrinsic funct... |
Try to resolve SAM resource id references on the given template. If the given object looks like one of the
supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original input
unmodified.
:param dict input: Dictionary that may represent an intrinsic fu... |
Can the input represent an intrinsic function in it?
:param input: Object to be checked
:return: True, if the input contains a supported intrinsic function. False otherwise
def _is_intrinsic_dict(self, input):
"""
Can the input represent an intrinsic function in it?
:param in... |
Returns the CloudWatch Logs Subscription Filter and Lambda Permission to which this CloudWatch Logs event source
corresponds.
:param dict kwargs: no existing resources need to be modified
:returns: a list of vanilla CloudFormation Resources, to which this push event expands
:rtype: list... |
Converts the given template to IAM-ready policy statement by substituting template parameters with the given
values.
:param template_name: Name of the template
:param parameter_values: Values for all parameters of the template
:return dict: Dictionary containing policy statement
... |
Is this a valid policy template dictionary
:param dict policy_templates_dict: Data to be validated
:param dict schema: Optional, dictionary containing JSON Schema representing policy template
:return: True, if it is valid.
:raises ValueError: If the template dictionary doesn't match up ... |
Render a chart or page to local html files.
:param chart: A Chart or Page object
:param path: The destination file which the html code write to
:param template_name: The name of template file.
def render_chart_to_file(self, template_name: str, chart: Any, path: str):
"""
Render... |
Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
def decode_base64(data: str) -> bytes:
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
... |
间隔折叠节点,当节点过多时可以解决节点显示过杂间隔。
:param data: 节点数据
:param interval: 指定间隔
def _set_collapse_interval(data, interval):
"""
间隔折叠节点,当节点过多时可以解决节点显示过杂间隔。
:param data: 节点数据
:param interval: 指定间隔
"""
if interval <= 0:
return data
if da... |
Parses a string and returns a pin-num.
def parse_pin(name_str):
"""Parses a string and returns a pin-num."""
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 = n... |
Returns the numbered function (i.e. USART6) for this AF.
def ptr(self):
"""Returns the numbered function (i.e. USART6) for this AF."""
if self.fn_num is None:
return self.func
return '{:s}{:d}'.format(self.func, self.fn_num) |
Prints the C representation of this AF.
def print(self):
"""Prints the C representation of this AF."""
if self.supported:
print(' AF', end='')
else:
print(' //', end='')
fn_num = self.fn_num
if fn_num is None:
fn_num = 0
print('({:2... |
Start the loop.
:param `leds`: Which LEDs to light up upon switch press.
:type `leds`: sequence of LED objects
def run_loop(leds=all_leds):
"""
Start the loop.
:param `leds`: Which LEDs to light up upon switch press.
:type `leds`: sequence of LED objects
"""
print('Loop started.\nPres... |
Search vpaths for the c file that matches the provided object_file.
:param str obj_file: object file to find the matching c file for
:param List[str] vpath: List of base paths, similar to gcc vpath
:return: str path to c file or None
def find_c_file(obj_file, vpath):
""" Search vpaths for the c file t... |
Find any MP_REGISTER_MODULE definitions in the provided c file.
:param str c_file: path to c file to check
:return: List[(module_name, obj_module, enabled_define)]
def find_module_registrations(c_file):
""" Find any MP_REGISTER_MODULE definitions in the provided c file.
:param str c_file: path to c f... |
Generate header with module table entries for builtin modules.
:param List[(module_name, obj_module, enabled_define)] modules: module defs
:return: None
def generate_module_table_header(modules):
""" Generate header with module table entries for builtin modules.
:param List[(module_name, obj_module, ... |
Reads test files
def readfiles():
""" Reads test files """
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.rstrip... |
converts CPython module names into MicroPython equivalents
def uimports(code):
""" converts CPython module names into MicroPython equivalents """
for uimport in UIMPORTLIST:
uimport = bytes(uimport, 'utf8')
code = code.replace(uimport, b'u' + uimport)
return code |
indents paragraphs of text for rst formatting
def indent(block, spaces):
""" indents paragraphs of text for rst formatting """
new_block = ''
for line in block.split('\n'):
new_block += spaces + line + '\n'
return new_block |
creates a table given any set of columns
def gen_table(contents):
""" creates a table given any set of columns """
xlengths = []
ylengths = []
for column in contents:
col_len = 0
for entry in column:
lines = entry.split('\n')
for line in lines:
co... |
creates restructured text documents to display tests
def gen_rst(results):
""" creates restructured text documents to display tests """
# 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:
... |
Main function
def main():
""" Main function """
# 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) |
Initializes the found DFU device so that we can program it.
def init():
"""Initializes the found DFU device so that we can program it."""
global __dev, __cfg_descr
devices = get_dfu_devices(idVendor=__VID, idProduct=__PID)
if not devices:
raise ValueError('No DFU device found')
if len(devic... |
Performs a MASS erase (i.e. erases the entire device.
def mass_erase():
"""Performs a MASS erase (i.e. erases the entire device."""
# Send DNLOAD with first byte=0x41
__dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE,
"\x41", __TIMEOUT)
# Execute last command
if ge... |
Erases a single page.
def page_erase(addr):
"""Erases a single page."""
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)... |
Sets the address for the next operation.
def set_address(addr):
"""Sets the address for the next operation."""
# 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... |
Writes a buffer into memory. This routine assumes that memory has
already been erased.
def write_memory(addr, buf, progress=None, progress_addr=0, progress_size=0):
"""Writes a buffer into memory. This routine assumes that memory has
already been erased.
"""
xfer_count = 0
xfer_bytes = 0
x... |
Writes a single page. This routine assumes that memory has already
been erased.
def write_page(buf, xfer_offset):
"""Writes a single page. This routine assumes that memory has already
been erased.
"""
xfer_base = 0x08000000
# Set mem write address
set_address(xfer_base+xfer_offset)
#... |
Exit DFU mode, and start running the program.
def exit_dfu():
"""Exit DFU mode, and start running the program."""
# 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)... |
Parses the struct defined by `fmt` from `data`, stores the parsed fields
into a named tuple using `names`. Returns the named tuple, and the data
with the struct stripped off.
def consume(fmt, data, names):
"""Parses the struct defined by `fmt` from `data`, stores the parsed fields
into a named tuple us... |
Reads a DFU file, and parses the individual elements from the file.
Returns an array of elements. Each element is a dictionary with the
following keys:
num - The element index
address - The address that the element data should be written to.
size - The size of the element ddata.
... |
Returns a list of USB device which are currently in DFU mode.
Additional filters (like idProduct and idVendor) can be passed in to
refine the search.
def get_dfu_devices(*args, **kwargs):
"""Returns a list of USB device which are currently in DFU mode.
Additional filters (like idProduct and idVendor) c... |
Returns an array which identifies the memory layout. Each entry
of the array will contain a dictionary with the following keys:
addr - Address of this memory segment
last_addr - Last address contained within the memory segment.
size - size of the segment, in bytes
num... |
Prints a lits of devices detected in DFU mode.
def list_dfu_devices(*args, **kwargs):
"""Prints a lits of devices detected in DFU mode."""
devices = get_dfu_devices(*args, **kwargs)
if not devices:
print("No DFU capable devices found")
return
for device in devices:
print("Bus {}... |
Writes the indicated elements into the target memory,
erasing as needed.
def write_elements(elements, mass_erase_used, progress=None):
"""Writes the indicated elements into the target memory,
erasing as needed.
"""
mem_layout = get_memory_layout(__dev)
for elem in elements:
addr = elem... |
Prints a progress report suitable for use on the command line.
def cli_progress(addr, offset, size):
"""Prints a progress report suitable for use on the command line."""
width = 25
done = offset * width // size
print("\r0x{:08x} {:7d} [{}{}] {:3d}% "
.format(addr, size, '=' * done, ' ' * (wid... |
Test program for verifying this files functionality.
def main():
"""Test program for verifying this files functionality."""
global __verbose
# Parse CMD args
parser = argparse.ArgumentParser(description='DFU Python Util')
#parser.add_argument("path", help="file path")
parser.add_argument(
... |
Parses a string and returns a (port-num, pin-num) tuple.
def parse_port_pin(name_str):
"""Parses a string and returns a (port-num, pin-num) tuple."""
if len(name_str) < 3:
raise ValueError("Expecting pin name to be at least 3 charcters.")
if name_str[0] != 'P':
raise ValueError("Expecting p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.