INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
The core method for starting the application. Will setup logging toggle the runtime state flag block on loop then call shutdown.
def run(self): """The core method for starting the application. Will setup logging, toggle the runtime state flag, block on loop, then call shutdown. Redefine this method if you intend to use an IO Loop or some other long running process. """ LOGGER.info('%s v%s started...
Important:
def start(self): """Important: Do not extend this method, rather redefine Controller.run """ for signum in [signal.SIGHUP, signal.SIGTERM, signal.SIGUSR1, signal.SIGUSR2]: signal.signal(signum, self._on_signal) self.run()
Set the runtime state of the Controller. Use the internal constants to ensure proper state values:
def set_state(self, state): """Set the runtime state of the Controller. Use the internal constants to ensure proper state values: - :attr:`Controller.STATE_INITIALIZING` - :attr:`Controller.STATE_ACTIVE` - :attr:`Controller.STATE_IDLE` - :attr:`Controller.STATE_SLEEPING`...
Override to implement shutdown steps.
def stop(self): """Override to implement shutdown steps.""" LOGGER.info('Attempting to stop the process') self.set_state(self.STATE_STOP_REQUESTED) # Call shutdown for classes to add shutdown steps self.shutdown() # Wait for the current run to finish while self....
parse timestamp.: param ts: timestamp in ISO8601 format: return: tbd!!!
def parse_ts(ts): """ parse timestamp. :param ts: timestamp in ISO8601 format :return: tbd!!! """ # ISO8601 = '%Y-%m-%dT%H:%M:%SZ' # ISO8601_MS = '%Y-%m-%dT%H:%M:%S.%fZ' # RFC1123 = '%a, %d %b %Y %H:%M:%S %Z' dt = maya.parse(ts.strip()) return dt.datetime(naive=True)
Read environment from ENV and mangle it to a ( lower case ) representation Note: gcdt. servicediscovery get_outputs_for_stack (( awsclient stack_name ) is used in many cloudformation. py templates!
def get_outputs_for_stack(awsclient, stack_name): """ Read environment from ENV and mangle it to a (lower case) representation Note: gcdt.servicediscovery get_outputs_for_stack((awsclient, stack_name) is used in many cloudformation.py templates! :param awsclient: :param stack_name: :return:...
DEPRECATED!!! return the latest version of our base AMI we can t use tags for this so we have only the name as resource note: this functionality is deprecated since this only works for old baseami.
def get_base_ami(awsclient, owners): """ DEPRECATED!!! return the latest version of our base AMI we can't use tags for this, so we have only the name as resource note: this functionality is deprecated since this only works for "old" baseami. """ client_ec2 = awsclient.get_client('ec2') ...
Add the default arguments to the parser.
def _add_default_arguments(parser): """Add the default arguments to the parser. :param argparse.ArgumentParser parser: The argument parser """ parser.add_argument('-c', '--config', action='store', dest='config', help='Path to the configuration file') parser.add_argument('-f...
Ensures that the val is the default str () type for python2 or 3
def _str(val): """ Ensures that the val is the default str() type for python2 or 3 """ if str == bytes: if isinstance(val, str): return val else: return str(val) else: if isinstance(val, str): return val else: return str...
Use requests. Request and requests. PreparedRequest to produce the body ( and boundary value ) of a multipart/ form - data ; POST request as detailed in https:// www. mediawiki. org/ wiki/ API: Edit#Large_texts
def _prepare_long_request(self, url, api_query): """ Use requests.Request and requests.PreparedRequest to produce the body (and boundary value) of a multipart/form-data; POST request as detailed in https://www.mediawiki.org/wiki/API:Edit#Large_texts """ partlist = [] ...
e. g. { action: query meta: userinfo }. format = json not required function returns a python dict that resembles the api s json response
def request(self, api_query, url=None): """ e.g. {'action': 'query', 'meta': 'userinfo'}. format=json not required function returns a python dict that resembles the api's json response """ api_query['format'] = 'json' if url is not None: api_url = url + "/api....
Convert a single Physical Information Object or a list of such objects into a JSON - encoded text file.
def dump(pif, fp, **kwargs): """ Convert a single Physical Information Object, or a list of such objects, into a JSON-encoded text file. :param pif: Object or list of objects to serialize. :param fp: File-like object supporting .write() method to write the serialized object(s) to. :param kwargs: An...
Convert content in a JSON - encoded text file to a Physical Information Object or a list of such objects.
def load(fp, class_=None, **kwargs): """ Convert content in a JSON-encoded text file to a Physical Information Object or a list of such objects. :param fp: File-like object supporting .read() method to deserialize from. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :param ...
Convert content in a JSON - encoded string to a Physical Information Object or a list of such objects.
def loads(s, class_=None, **kwargs): """ Convert content in a JSON-encoded string to a Physical Information Object or a list of such objects. :param s: String to deserialize. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :param kwargs: Any options available to json.loads()...
Convert a dictionary or a list of dictionaries into a single Physical Information Object or a list of such objects.
def loado(obj, class_=None): """ Convert a dictionary or a list of dictionaries into a single Physical Information Object or a list of such objects. :param obj: Dictionary or list to convert to Physical Information Objects. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :re...
Convert a single dictionary object to a Physical Information Object.
def _dict_to_pio(d, class_=None): """ Convert a single dictionary object to a Physical Information Object. :param d: Dictionary to convert. :param class_: Subclass of :class:`.Pio` to produce, if not unambiguous :return: Single object derived from :class:`.Pio`. """ d = keys_to_snake_case(d...
Utility function to extract command from docopt arguments.
def get_command(arguments): """Utility function to extract command from docopt arguments. :param arguments: :return: command """ cmds = list(filter(lambda k: not (k.startswith('-') or k.startswith('<')) and arguments[k], arguments.keys())) if l...
Dispatch arguments parsed by docopt to the cmd with matching spec.
def dispatch(cls, arguments, **kwargs): """Dispatch arguments parsed by docopt to the cmd with matching spec. :param arguments: :param kwargs: :return: exit_code """ # first match wins # spec: all '-' elements must match, all others are False; # '<s...
Retrieves an attribute from an existing stack: param parameter: The output parameter which should be retrieved: param as_reference: Is the parameter a reference ( Default ) or a string: return: Value of parameter to retrieve
def get_att(self, parameter, as_reference=True): """Retrieves an attribute from an existing stack :param parameter: The output parameter which should be retrieved :param as_reference: Is the parameter a reference (Default) or a string :return: Value of parameter to retrieve """ ...
if key_filters in self. _config: filters_spec = { Key: { FilterRules: [] } } # I do not think this is a useful structure: for filter in self. _config [ key_filters ]: if type in filter and value in filter and filter [ type ] in ( prefix suffix ): rule = { Name: filter [ type ]. capitalize () Value: filter [ value ] } f...
def _get_notification_spec(self, lambda_arn): lambda_name = base.get_lambda_name(lambda_arn) notification_spec = { 'Id': self._make_notification_id(lambda_name), 'Events': [e for e in self._config['events']], 'LambdaFunctionArn': lambda_arn } # Add S3...
Return the proper representation for the given integer
def convert_representation(self, i): """ Return the proper representation for the given integer """ if self.number_representation == 'unsigned': return i elif self.number_representation == 'signed': if i & (1 << self.interpreter._bit_width - 1): ...
Set the generate random flag unset registers and memory will return a random value.
def magic_generate_random(self, line): """ Set the generate random flag, unset registers and memory will return a random value. Usage: Call the magic by itself or with `true` to have registers and memory return a random value if they are unset and read from, much like how real h...
Postpone execution of instructions until explicitly run
def magic_postpone_execution(self, line): """ Postpone execution of instructions until explicitly run Usage: Call this magic with `true` or nothing to postpone execution, or call with `false` to execute each instruction when evaluated. This defaults to True. Not...
Print out the current value of a register
def magic_register(self, line): """ Print out the current value of a register Usage: Pass in the register, or a list of registers separated by spaces A list of registeres can be entered by separating them by a hyphen `%reg R1` or `%reg R0 R5 R6` ...
Print out the current value of memory
def magic_memory(self, line): """ Print out the current value of memory Usage: Pass in the byte of memory to read, separated by spaced A list of memory contents can be entered by separating them by a hyphen `%mem 4 5` or `%mem 8-12` """ #...
Run the current program
def magic_run(self, line): """ Run the current program Usage: Call with a numbe rto run that many steps, or call with no arguments to run to the end of the current program `%run` or `%run 1` """ i = float('inf') if line.strip(): ...
Print out the help for magics
def magic_help(self, line): """ Print out the help for magics Usage: Call help with no arguments to list all magics, or call it with a magic to print out it's help info. `%help` or `%help run """ line = line.strip() if not line: ...
Export the API design as swagger file.: param api_name:: param stage_name:: param api_description:: param lambdas:: param custom_hostname:: param custom_base_path:
def export_to_swagger(awsclient, api_name, stage_name, api_description, lambdas, custom_hostname=False, custom_base_path=False): """Export the API design as swagger file. :param api_name: :param stage_name: :param api_description: :param lambdas: :param custom_hos...
List APIs in account.
def list_apis(awsclient): """List APIs in account.""" client_api = awsclient.get_client('apigateway') apis = client_api.get_rest_apis()['items'] for api in apis: print(json2table(api))
Deploy API Gateway to AWS cloud.
def deploy_api(awsclient, api_name, api_description, stage_name, api_key, lambdas, cache_cluster_enabled, cache_cluster_size, method_settings=None): """Deploy API Gateway to AWS cloud. :param awsclient: :param api_name: :param api_description: :param stage_name: :param api_key: ...
Delete the API.
def delete_api(awsclient, api_name): """Delete the API. :param api_name: """ _sleep() client_api = awsclient.get_client('apigateway') print('deleting api: %s' % api_name) api = _api_by_name(awsclient, api_name) if api is not None: print(json2table(api)) response = cli...
Create a new API key as reference for api. conf.
def create_api_key(awsclient, api_name, api_key_name): """Create a new API key as reference for api.conf. :param api_name: :param api_key_name: :return: api_key """ _sleep() client_api = awsclient.get_client('apigateway') print('create api key: %s' % api_key_name) response = client...
Remove API key.
def delete_api_key(awsclient, api_key): """Remove API key. :param api_key: """ _sleep() client_api = awsclient.get_client('apigateway') print('delete api key: %s' % api_key) response = client_api.delete_api_key( apiKey=api_key ) print(json2table(response))
Print the defined API keys.
def list_api_keys(awsclient): """Print the defined API keys. """ _sleep() client_api = awsclient.get_client('apigateway') print('listing api keys') response = client_api.get_api_keys()['items'] for item in response: print(json2table(item))
Add custom domain to your API.
def deploy_custom_domain(awsclient, api_name, api_target_stage, api_base_path, domain_name, route_53_record, cert_name, cert_arn, hosted_zone_id, ensure_cname): """Add custom domain to your API. :param api_name: :param api_target_stage: :param api_base_...
Get the list of lambda functions.
def get_lambdas(awsclient, config, add_arn=False): """Get the list of lambda functions. :param config: :param add_arn: :return: list containing lambda entries """ if 'lambda' in config: client_lambda = awsclient.get_client('lambda') lambda_entries = config['lambda'].get('entries...
Helper to apply method_settings to stage
def _update_stage(awsclient, api_id, stage_name, method_settings): """Helper to apply method_settings to stage :param awsclient: :param api_id: :param stage_name: :param method_settings: :return: """ # settings docs in response: https://botocore.readthedocs.io/en/latest/reference/servic...
Helper to handle the conversion of method_settings to operations
def _convert_method_settings_into_operations(method_settings=None): """Helper to handle the conversion of method_settings to operations :param method_settings: :return: list of operations """ # operations docs here: https://tools.ietf.org/html/rfc6902#section-4 operations = [] if method_set...
This command is run when default_path doesn t exist or init is run and returns a string representing the default data to put into their settings file.
def generate_settings(): """ This command is run when ``default_path`` doesn't exist, or ``init`` is run and returns a string representing the default data to put into their settings file. """ conf_file = os.path.join(os.path.dirname(base_settings.__file__), 'example...
Builds up the settings using the same method as logan
def configure_app(**kwargs): """Builds up the settings using the same method as logan""" sys_args = sys.argv args, command, command_args = parse_args(sys_args[1:]) parser = OptionParser() parser.add_option('--config', metavar='CONFIG') (options, logan_args) = parser.parse_args(args) config_p...
Stores current values for comparison later
def _reset_changes(self): """Stores current values for comparison later""" self._original = {} if self.last_updated is not None: self._original['last_updated'] = self.last_updated
Build a file path to the Whisper database
def whisper_filename(self): """Build a file path to the Whisper database""" source_name = self.source_id and self.source.name or '' return get_valid_filename("{0}__{1}.wsp".format(source_name, self.name))
Human friendly value output
def get_value_display(self): """Human friendly value output""" if self.display_as == 'percentage': return '{0}%'.format(self.latest_value) if self.display_as == 'boolean': return bool(self.latest_value) if self.display_as == 'byte': return defaultfilte...
Time between current last_updated and previous last_updated
def time_between_updates(self): """Time between current `last_updated` and previous `last_updated`""" if 'last_updated' not in self._original: return 0 last_update = self._original['last_updated'] this_update = self.last_updated return this_update - last_update
Apply the transformation ( if it exists ) to the latest_value
def do_transform(self): """Apply the transformation (if it exists) to the latest_value""" if not self.transform: return try: self.latest_value = utils.Transform( expr=self.transform, value=self.latest_value, timedelta=self.time_between_upda...
Update latest value to the diff between it and the previous value
def do_counter_conversion(self): """Update latest value to the diff between it and the previous value""" if self.is_counter: if self._previous_counter_value is None: prev_value = self.latest_value else: prev_value = self._previous_counter_value ...
Relay source group signals to the appropriate spec strategy.
def source_group_receiver(self, sender, source, signal, **kwargs): """ Relay source group signals to the appropriate spec strategy. """ from imagekit.cachefiles import ImageCacheFile source_group = sender # Ignore signals from unregistered groups. if source_gro...
Substitute variables with numeric values
def replace_variable(self, variable): """Substitute variables with numeric values""" if variable == 'x': return self.value if variable == 't': return self.timedelta raise ValueError("Invalid variable %s", variable)
Evaluate expression and return result
def result(self): """Evaluate expression and return result""" # Module(body=[Expr(value=...)]) return self.eval_(ast.parse(self.expr).body[0].value)
获取用户信息: param user_alias: 用户ID: return:
def get_people(self, user_alias=None): """ 获取用户信息 :param user_alias: 用户ID :return: """ user_alias = user_alias or self.api.user_alias content = self.api.req(API_PEOPLE_HOME % user_alias).content xml = self.api.to_xml(re.sub(b'<br />', b'\n', cont...
Given a request an email and optionally some additional data ensure that a user with the email address exists and authenticate & login them right away if the user is active.
def email_login(request, *, email, **kwargs): """ Given a request, an email and optionally some additional data, ensure that a user with the email address exists, and authenticate & login them right away if the user is active. Returns a tuple consisting of ``(user, created)`` upon success or ``(Non...
Shows the latest results for each source
def dashboard(request): """Shows the latest results for each source""" sources = (models.Source.objects.all().prefetch_related('metric_set') .order_by('name')) metrics = SortedDict([(src, src.metric_set.all()) for src in sources]) no_source_metrics = models.Metr...
Create the Whisper file on disk
def _create(self): """Create the Whisper file on disk""" if not os.path.exists(settings.SALMON_WHISPER_DB_PATH): os.makedirs(settings.SALMON_WHISPER_DB_PATH) archives = [whisper.parseRetentionDef(retentionDef) for retentionDef in settings.ARCHIVES.split(",")] ...
This method store in the datapoints in the current database.
def _update(self, datapoints): """ This method store in the datapoints in the current database. :datapoints: is a list of tupple with the epoch timestamp and value [(1368977629,10)] """ if len(datapoints) == 1: timestamp, value = datapoints[0] ...
This method fetch data from the database according to the period given
def fetch(self, from_time, until_time=None): """ This method fetch data from the database according to the period given fetch(path, fromTime, untilTime=None) fromTime is an datetime untilTime is also an datetime, but defaults to now. Returns a tuple of (timeInf...
构建带翻页的列表: param results: 已获取的数据列表: param xml: 原始页面xml: return: { results: list count: int next_start: int|None } 如果count与results长度不同,则有更多 如果next_start不为None,则可以到下一页
def build_list_result(results, xml): """ 构建带翻页的列表 :param results: 已获取的数据列表 :param xml: 原始页面xml :return: {'results': list, 'count': int, 'next_start': int|None} 如果count与results长度不同,则有更多 如果next_start不为None,则可以到下一页 """ xml_count = xml.xpath('//div[@class="paginator"...
ADCS [ Ra ] Rb Rc
def ADCS(self, params): """ ADCS [Ra,] Rb, Rc Add Rb and Rc + the carry bit and store the result in Ra Ra, Rb, and Rc must be low registers if Ra is omitted, then it is assumed to be Rb """ # This instruction allows for an optional destination register # ...
ADD [ Rx ] Ry [ Rz PC ] ADD [ Rx ] [ SP PC ] #imm10_4 ADD [ SP ] SP #imm9_4
def ADD(self, params): """ ADD [Rx,] Ry, [Rz, PC] ADD [Rx,] [SP, PC], #imm10_4 ADD [SP,] SP, #imm9_4 Add Ry and Rz and store the result in Rx Rx, Ry, and Rz can be any register If Rx is omitted, then it is assumed to be Ry """ # This instruction a...
CMN Ra Rb
def CMN(self, params): """ CMN Ra, Rb Add the two registers and set the NZCV flags The result is discarded Ra and Rb must be low registers """ Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) self.check_arguments(low_registers...
CMP Rm Rn CMP Rm #imm8
def CMP(self, params): """ CMP Rm, Rn CMP Rm, #imm8 Subtract Rn or imm8 from Rm, set the NZCV flags, and discard the result Rm and Rn can be R0-R14 """ Rm, Rn = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) if self.is_register(Rn): ...
MULS Ra Rb Ra
def MULS(self, params): """ MULS Ra, Rb, Ra Multiply Rb and Ra together and store the result in Ra. Set the NZ flags. Ra and Rb must be low registers The first and last operand must be the same register """ Ra, Rb, Rc = self.get_three_parameters(self.THRE...
RSBS [ Ra ] Rb #0
def RSBS(self, params): """ RSBS [Ra,] Rb, #0 Subtract Rb from zero (0 - Rb) and store the result in Ra Set the NZCV flags Ra and Rb must be low registers if Ra is omitted, then it is assumed to be Rb """ # This instruction allows for an optional destinat...
SUB [ SP ] SP #imm9_4
def SUB(self, params): """ SUB [SP,] SP, #imm9_4 Subtract an immediate from the Stack Pointer The first SP is optional """ # This instruction allows for an optional destination register # If it is omitted, then it is assumed to be Rb # As defined in http:...
SUBS [ Ra ] Rb Rc SUBS [ Ra ] Rb #imm3 SUBS [ Ra ] Ra #imm8
def SUBS(self, params): """ SUBS [Ra,] Rb, Rc SUBS [Ra,] Rb, #imm3 SUBS [Ra,] Ra, #imm8 Subtract Rc or an immediate from Rb and store the result in Ra Ra, Rb, and Rc must be low registers If Ra is omitted, then it is assumed to be Rb """ # This in...
Adds SERVICE_NAME SERVICE_ENVIRONMENT and DEFAULT_TAGS to the template
def initialize(template, service_name, environment='dev'): """Adds SERVICE_NAME, SERVICE_ENVIRONMENT, and DEFAULT_TAGS to the template :param template: :param service_name: :param environment: :return: """ template.SERVICE_NAME = os.getenv('SERVICE_NAME', service_name) template.SERVICE_...
Get dist for installed version of dist_name avoiding pkg_resources cache
def get_dist(dist_name, lookup_dirs=None): """Get dist for installed version of dist_name avoiding pkg_resources cache """ # note: based on pip/utils/__init__.py, get_installed_version(...) # Create a requirement that we'll look for inside of setuptools. req = pkg_resources.Requirement.parse(dist_n...
Get the package version information ( = SetuptoolsVersion ) which is comparable. note: we use the pip list_command implementation for this
def get_package_versions(package): """Get the package version information (=SetuptoolsVersion) which is comparable. note: we use the pip list_command implementation for this :param package: name of the package :return: installed version, latest available version """ list_command = ListComma...
Load hook module and register signals.
def _load_hooks(path): """Load hook module and register signals. :param path: Absolute or relative path to module. :return: module """ module = imp.load_source(os.path.splitext(os.path.basename(path))[0], path) if not check_hook_mechanism_is_intact(module): # no hooks - do nothing ...
Tool lifecycle which provides hooks into the different stages of the command execution. See signals for hook details.
def lifecycle(awsclient, env, tool, command, arguments): """Tool lifecycle which provides hooks into the different stages of the command execution. See signals for hook details. """ log.debug('### init') load_plugins() context = get_context(awsclient, env, tool, command, arguments) # every t...
gcdt tools parametrized main function to initiate gcdt lifecycle.
def main(doc, tool, dispatch_only=None): """gcdt tools parametrized main function to initiate gcdt lifecycle. :param doc: docopt string :param tool: gcdt tool (gcdt, kumo, tenkai, ramuda, yugen) :param dispatch_only: list of commands which do not use gcdt lifecycle :return: exit_code """ # ...
MOV Rx Ry MOV PC Ry
def MOV(self, params): """ MOV Rx, Ry MOV PC, Ry Move the value of Ry into Rx or PC """ Rx, Ry = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) self.check_arguments(any_registers=(Rx, Ry)) def MOV_func(): self.register[R...
MOVS Ra Rb MOVS Ra #imm8
def MOVS(self, params): """ MOVS Ra, Rb MOVS Ra, #imm8 Move the value of Rb or imm8 into Ra Ra and Rb must be low registers """ Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) if self.is_immediate(Rb): self.check_...
MRS Rj Rspecial
def MRS(self, params): """ MRS Rj, Rspecial Copy the value of Rspecial to Rj Rspecial can be APSR, IPSR, or EPSR """ Rj, Rspecial = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) self.check_arguments(LR_or_general_purpose_registers=(Rj,), sp...
MSR Rspecial Rj
def MSR(self, params): """ MSR Rspecial, Rj Copy the value of Rj to Rspecial Rspecial can be APSR, IPSR, or EPSR """ Rspecial, Rj = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) self.check_arguments(LR_or_general_purpose_registers=(Rj,), sp...
MVNS Ra Rb
def MVNS(self, params): """ MVNS Ra, Rb Negate the value in Rb and store it in Ra Ra and Rb must be a low register """ Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) self.check_arguments(low_registers=(Ra, Rb)) def MVNS_fun...
REV Ra Rb
def REV(self, params): """ REV Ra, Rb Reverse the byte order in register Rb and store the result in Ra """ Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) self.check_arguments(low_registers=(Ra, Rb)) def REV_func(): self...
REV16 Ra Rb
def REV16(self, params): """ REV16 Ra, Rb Reverse the byte order of the half words in register Rb and store the result in Ra """ Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) self.check_arguments(low_registers=(Ra, Rb)) def REV16_...
REVSH
def REVSH(self, params): """ REVSH Reverse the byte order in the lower half word in Rb and store the result in Ra. If the result of the result is signed, then sign extend """ Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params) ...
STXB Ra Rb
def SXTB(self, params): """ STXB Ra, Rb Sign extend the byte in Rb and store the result in Ra """ Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params) self.check_arguments(low_registers=(Ra, Rb)) def SXTB_func(): i...
STXH Ra Rb
def SXTH(self, params): """ STXH Ra, Rb Sign extend the half word in Rb and store the result in Ra """ Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params) self.check_arguments(low_registers=(Ra, Rb)) def SXTH_func(): ...
UTXB Ra Rb
def UXTB(self, params): """ UTXB Ra, Rb Zero extend the byte in Rb and store the result in Ra """ Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params) self.check_arguments(low_registers=(Ra, Rb)) def UXTB_func(): s...
UTXH Ra Rb
def UXTH(self, params): """ UTXH Ra, Rb Zero extend the half word in Rb and store the result in Ra """ Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params) self.check_arguments(low_registers=(Ra, Rb)) def UXTH_func(): ...
Get type of event e. g. s3 events kinesis...
def _get_event_type(evt_source): """Get type of event e.g. 's3', 'events', 'kinesis',... :param evt_source: :return: """ if 'schedule' in evt_source: return 'events' elif 'pattern' in evt_source: return 'events' elif 'log_group_name_prefix' in evt_source: return 'clo...
Given awsclient event_source dictionary item create an event_source object of the appropriate event type to schedule this event and return the object.
def _get_event_source_obj(awsclient, evt_source): """ Given awsclient, event_source dictionary item create an event_source object of the appropriate event type to schedule this event, and return the object. """ event_source_map = { 'dynamodb': event_source.dynamodb_stream.DynamoDBStreamE...
Given an event_source dictionary create the object and add the event source.
def _add_event_source(awsclient, evt_source, lambda_arn): """ Given an event_source dictionary, create the object and add the event source. """ event_source_obj = _get_event_source_obj(awsclient, evt_source) # (where zappa goes like remove, add) # we go with update and add like this: if eve...
Given an event_source dictionary create the object and remove the event source.
def _remove_event_source(awsclient, evt_source, lambda_arn): """ Given an event_source dictionary, create the object and remove the event source. """ event_source_obj = _get_event_source_obj(awsclient, evt_source) if event_source_obj.exists(lambda_arn): event_source_obj.remove(lambda_arn)
Given an event_source dictionary create the object and get the event source status.
def _get_event_source_status(awsclient, evt_source, lambda_arn): """ Given an event_source dictionary, create the object and get the event source status. """ event_source_obj = _get_event_source_obj(awsclient, evt_source) return event_source_obj.status(lambda_arn)
Unwire a list of event from an AWS Lambda function.
def unwire(awsclient, events, lambda_name, alias_name=ALIAS_NAME): """Unwire a list of event from an AWS Lambda function. 'events' is a list of dictionaries, where the dict must contains the 'schedule' of the event as string, and an optional 'name' and 'description'. :param awsclient: :param event...
Deprecated! Please use wire!
def wire_deprecated(awsclient, function_name, s3_event_sources=None, time_event_sources=None, alias_name=ALIAS_NAME): """Deprecated! Please use wire! :param awsclient: :param function_name: :param s3_event_sources: dictionary :param time_event_sources: :...
Deprecated! Please use unwire!
def unwire_deprecated(awsclient, function_name, s3_event_sources=None, time_event_sources=None, alias_name=ALIAS_NAME): """Deprecated! Please use unwire! :param awsclient: :param function_name: :param s3_event_sources: dictionary :param time_event_sources: :param alias_nam...
Use only prefix OR suffix
def _lambda_add_s3_event_source(awsclient, arn, event, bucket, prefix, suffix): """Use only prefix OR suffix :param arn: :param event: :param bucket: :param prefix: :param suffix: :return: """ json_data = { 'LambdaFunctionConfigurations': [{ ...
r Try to find the Eigen library. If successful the include directory is returned.
def find_eigen(hint=None): r''' Try to find the Eigen library. If successful the include directory is returned. ''' # search with pkgconfig # --------------------- try: import pkgconfig if pkgconfig.installed('eigen3','>3.0.0'): return pkgconfig.parse('eigen3')['include_dirs'][0] except: ...
Helper to read the params for the logs command
def check_and_format_logs_params(start, end, tail): """Helper to read the params for the logs command""" def _decode_duration_type(duration_type): durations = {'m': 'minutes', 'h': 'hours', 'd': 'days', 'w': 'weeks'} return durations[duration_type] if not start: if tail: ...
Upload a file to AWS S3 bucket.
def upload_file_to_s3(awsclient, bucket, key, filename): """Upload a file to AWS S3 bucket. :param awsclient: :param bucket: :param key: :param filename: :return: """ client_s3 = awsclient.get_client('s3') transfer = S3Transfer(client_s3) # Upload /tmp/myfile to s3://bucket/key ...
Remove a file from an AWS S3 bucket.
def remove_file_from_s3(awsclient, bucket, key): """Remove a file from an AWS S3 bucket. :param awsclient: :param bucket: :param key: :return: """ client_s3 = awsclient.get_client('s3') response = client_s3.delete_object(Bucket=bucket, Key=key)
List bucket contents
def ls(awsclient, bucket, prefix=None): """List bucket contents :param awsclient: :param bucket: :param prefix: :return: """ # this works until 1000 keys! params = {'Bucket': bucket} if prefix: params['Prefix'] = prefix client_s3 = awsclient.get_client('s3') objects ...
ORRS [ Ra ] Ra Rb
def ORRS(self, params): """ ORRS [Ra,] Ra, Rb OR Ra and Rb together and store the result in Ra The equivalent of `Ra = Ra | Rc` Updates NZ flags Ra and Rb must be low registers The first register is optional """ # This instruction allows for an op...
TST Ra Rb
def TST(self, params): """ TST Ra, Rb AND Ra and Rb together and update the NZ flag. The result is not set The equivalent of `Ra & Rc` Ra and Rb must be low registers """ Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) self.c...
Renders a mail and returns the resulting EmailMultiAlternatives instance
def render_to_mail(template, context, **kwargs): """ Renders a mail and returns the resulting ``EmailMultiAlternatives`` instance * ``template``: The base name of the text and HTML (optional) version of the mail. * ``context``: The context used to render the mail. This context instance ...
Returns the confirmation URL
def get_confirmation_url(email, request, name="email_registration_confirm", **kwargs): """ Returns the confirmation URL """ return request.build_absolute_uri( reverse(name, kwargs={"code": get_confirmation_code(email, request, **kwargs)}) )