code stringlengths 1 18.2k |
|---|
def LDR(self, params): """ LDR Ra, [PC, #imm10_4] LDR Ra, label LDR Ra, =equate LDR Ra, [Rb, Rc] LDR Ra, [Rb, #imm7_4] LDR Ra, [SP, #imm10_4] Load a word from memory into Ra Ra, Rb, and Rc must be low registers """ # TODO definition for PC is Ra <- M[PC + Imm10_4], Imm10_4 = PC - label, need to figure this one out |
try: Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) except iarm.exceptions.ParsingError: Ra, label_name = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) if label_name.startswith('='): # This is a pseudoinstructions label_name = label_name[1:] # TODO add check tha... |
be decompiled self.check_arguments(low_registers=(Ra,)) if label_name in self.labels: label_value = self.labels[label_name] elif label_name in self.equates: label_value = self.equates[label_name] else: try: label_value = int(self.convert_to_integer(label_name)) except ValueError: warnings.warn(iarm.exceptions.LabelDoes... |
are word aligned raise iarm.exceptions.IarmError("Memory access not word aligned; Immediate: {}".format(int(label_value))) elif label_name.startswith('[') and label_name.endswith(']'): # TODO improve this Rb = label_name[1:-1] if Rb == 'SP' or Rb == 'R13': self.check_arguments(low_registers=(Ra,)) else: self.check_argu... |
(self.memory[self.register[Rb] + i] << (8 * i)) return LDR_func else: self.check_arguments(low_registers=(Ra,), label_exists=(label_name,)) try: label_value = self.labels[label_name] if label_value >= 1024: raise iarm.exceptions.IarmError("Label {} has value {} and is greater than 1020".format(label_name, label_value))... |
raise an exception now, # But we're avoiding that elsewhere, might as well avoid it here too pass def LDR_func(): nonlocal label_value # Since we can get a label that didn't exist in the creation step, We need to check it here # TODO is there a way for label_value to not exist? if label_value is None: # Try to get it a... |
label_name in self.labels: label_value = self.labels[label_name] elif label_name in self.equates: label_value = self.equates[label_name] # If it is still None, then it never got allocated if label_value is None: raise iarm.exceptions.IarmError("label `{}` does not exist. Was space allocated?".format(label_name)) # It d... |
except ValueError: # TODO Can we even get to this path now? self.register[Ra] = self.labels[label_name] return LDR_func if self.is_immediate(Rc): if Rb == 'SP' or Rb == 'R15': self.check_arguments(low_registers=(Ra,), imm10_4=(Rc,)) else: self.check_arguments(low_registers=(Ra, Rb), imm7_4=(Rc,)) def LDR_func(): # TODO... |
i in range(4): self.register[Ra] |= (self.memory[self.register[Rb] + self.convert_to_integer(Rc[1:]) + i] << (8 * i)) else: self.check_arguments(low_registers=(Ra, Rb, Rc)) def LDR_func(): # TODO does memory read up? if (self.register[Rb] + self.register[Rc]) % 4 != 0: raise iarm.exceptions.HardFault( "Memory access no... |
i)) return LDR_func |
def LDRB(self, params): """ LDRB Ra, [Rb, Rc] LDRB Ra, [Rb, #imm5] Load a byte from memory into Ra Ra, Rb, and Rc must be low registers """ try: Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) except iarm.exceptions.ParsingError: # LDRB Rn, [Rk] translates to an offset of zero Ra, Rb ... |
self.memory[self.register[Rb] + self.convert_to_integer(Rc[1:])] else: self.check_arguments(low_registers=(Ra, Rb, Rc)) def LDRB_func(): self.register[Ra] = self.memory[self.register[Rb] + self.register[Rc]] return LDRB_func |
def LDRH(self, params): """ LDRH Ra, [Rb, Rc] LDRH Ra, [Rb, #imm6_2] Load a half word from memory into Ra Ra, Rb, and Rc must be low registers """ try: Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) except iarm.exceptions.ParsingError: # LDRB Rn, [Rk] translates to an offset of zero ... |
TODO does memory read up? if (self.register[Rb]) % 2 != 0: raise iarm.exceptions.HardFault( "Memory access not half word aligned; Register: {} Immediate: {}".format(self.register[Rb], self.convert_to_integer( Rc[1:]))) self.register[Ra] = 0 for i in range(2): self.register[Ra] |= (self.memory[self.register[Rb] + self.c... |
iarm.exceptions.HardFault( "Memory access not half word aligned; Register: {} Immediate: {}".format(self.register[Rb], self.register[Rc])) self.register[Ra] = 0 for i in range(2): self.register[Ra] |= (self.memory[self.register[Rb] + self.register[Rc] + i] << (8 * i)) return LDRH_func |
def LDRSB(self, params): """ LDRSB Ra, [Rb, Rc] Load a byte from memory, sign extend, and put into Ra Ra, Rb, and Rc must be low registers """ # TODO LDRSB cant use immediates Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) self.check_arguments(low_registers=(Ra, Rb, Rc)) def LDRSB_fu... |
7): self.register[Ra] |= (0xFFFFFF << 8) return LDRSB_func |
def LDRSH(self, params): """ LDRSH Ra, [Rb, Rc] Load a half word from memory, sign extend, and put into Ra Ra, Rb, and Rc must be low registers """ # TODO LDRSH cant use immediates Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) self.check_arguments(low_registers=(Ra, Rb, Rc)) def LDR... |
not half word aligned\nR{}: {}\nR{}: {}".format(Rb, self.register[Rb], Rc, self.register[Rc])) self.register[Ra] = 0 for i in range(2): self.register[Ra] |= (self.memory[self.register[Rb] + self.register[Rc] + i] << (8 * i)) if self.register[Ra] & (1 << 15): self.register[Ra] |= (0xFFFF << 16) return LDRSH_func |
def POP(self, params): """ POP {RPopList} Pop from the stack into the list of registers List must contain only low registers or PC """ # TODO verify pop order # TODO pop list is comma separate, right? # TODO what registeres are allowed to POP to? Low Registers and PC # TODO need to support ranges, ie {R2, R5-R7} # TODO... |
the list, not POP RPopList = self.get_one_parameter(r'\s*{(.*)}(.*)', params).split(',') RPopList.reverse() RPopList = [i.strip() for i in RPopList] def POP_func(): for register in RPopList: # Get 4 bytes value = 0 for i in range(4): # TODO use memory width instead of constants value |= self.memory[self.register['SP'] ... |
def PUSH(self, params): """ PUSH {RPushList} Push to the stack from a list of registers List must contain only low registers or LR """ # TODO what registers are allowed to PUSH to? Low registers and LR # TODO PUSH should reverse the list, not POP RPushList = self.get_one_parameter(r'\s*{(.*)}(.*)', params).split(',') R... |
register exists? probably not def PUSH_func(): for register in RPushList: self.register['SP'] -= 4 for i in range(4): # TODO is this the same as with POP? self.memory[self.register['SP'] + i] = ((self.register[register] >> (8 * i)) & 0xFF) return PUSH_func |
def STM(self, params): """ STM Ra!, {RLoList} Store multiple registers into memory """ # TODO what registers can be stored? Ra, RLoList = self.get_two_parameters(r'\s*([^\s,]*)!,\s*{(.*)}(.*)', params).split(',') RLoList = RLoList.split(',') RLoList = [i.strip() for i in RLoList] self.check_arguments(low_registers=[Ra]... |
return STM_func |
def STR(self, params): """ STR Ra, [Rb, Rc] STR Ra, [Rb, #imm7_4] STR Ra, [SP, #imm10_4] Store Ra into memory as a word Ra, Rb, and Rc must be low registers """ Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) if self.is_immediate(Rc): if Rb == 'SP' or Rb == 'FP': self.check_arguments(... |
i] = ((self.register[Ra] >> (8 * i)) & 0xFF) else: self.check_arguments(low_registers=(Ra, Rb, Rc)) def STR_func(): for i in range(4): self.memory[self.register[Rb] + self.register[Rc] + i] = ((self.register[Ra] >> (8 * i)) & 0xFF) return STR_func |
def STRB(self, params): """ STRB Ra, [Rb, Rc] STRB Ra, [Rb, #imm5] Store Ra into memory as a byte Ra, Rb, and Rc must be low registers """ Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) if self.is_immediate(Rc): self.check_arguments(low_registers=(Ra, Rb), imm5=(Rc,)) def STRB_func()... |
def STRH(self, params): """ STRH Ra, [Rb, Rc] STRH Ra, [Rb, #imm6_2] Store Ra into memory as a half word Ra, Rb, and Rc must be low registers """ Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) if self.is_immediate(Rc): self.check_arguments(low_registers=(Ra, Rb), imm5=(Rc,)) def STRH... |
STRH_func(): for i in range(2): self.memory[self.register[Rb] + self.register[Rc] + i] = ((self.register[Ra] >> (8 * i)) & 0xFF) return STRH_func |
def _stop_ec2_instances(awsclient, ec2_instances, wait=True): """Helper to stop ec2 instances. By default it waits for instances to stop. :param awsclient: :param ec2_instances: :param wait: waits for instances to stop :return: """ if len(ec2_instances) == 0: return client_ec2 = awsclient.get_client('ec2') # get runnin... |
r.get('InstanceStatuses', [])], ) if running_instances: log.info('Stopping EC2 instances: %s', running_instances) client_ec2.stop_instances(InstanceIds=running_instances) if wait: # wait for instances to stop waiter_inst_stopped = client_ec2.get_waiter('instance_stopped') waiter_inst_stopped.wait(InstanceIds=running_in... |
def _start_ec2_instances(awsclient, ec2_instances, wait=True): """Helper to start ec2 instances :param awsclient: :param ec2_instances: :param wait: waits for instances to start :return: """ if len(ec2_instances) == 0: return client_ec2 = awsclient.get_client('ec2') # get stopped instances stopped_instances = all_pages... |
start all stopped instances log.info('Starting EC2 instances: %s', stopped_instances) client_ec2.start_instances(InstanceIds=stopped_instances) if wait: # wait for instances to come up waiter_inst_running = client_ec2.get_waiter('instance_running') waiter_inst_running.wait(InstanceIds=stopped_instances) # wait for stat... |
def _filter_db_instances_by_status(awsclient, db_instances, status_list): """helper to select dbinstances. :param awsclient: :param db_instances: :param status_list: :return: list of db_instances that match the filter """ client_rds = awsclient.get_client('rds') db_instances_with_status = [] for db in db_instances: res... |
def _stop_ecs_services(awsclient, services, template, parameters, wait=True): """Helper to change desiredCount of ECS services to zero. By default it waits for this to complete. Docs here: http://docs.aws.amazon.com/cli/latest/reference/ecs/update-service.html :param awsclient: :param services: :param template: the clo... |
services: log.info('Resize ECS service \'%s\' to desiredCount=0', service['LogicalResourceId']) cluster, desired_count = _get_service_cluster_desired_count( template, parameters, service['LogicalResourceId']) log.debug('cluster: %s' % cluster) response = client_ecs.update_service( cluster=cluster, service=service['Phys... |
def stop_stack(awsclient, stack_name, use_suspend=False): """Stop an existing stack on AWS cloud. :param awsclient: :param stack_name: :param use_suspend: use suspend and resume on the autoscaling group :return: exit_code """ exit_code = 0 # check for DisableStop #disable_stop = conf.get('deployment', {}).get('DisableS... |
else: client_cfn = awsclient.get_client('cloudformation') client_autoscaling = awsclient.get_client('autoscaling') client_rds = awsclient.get_client('rds') client_ec2 = awsclient.get_client('ec2') resources = all_pages( client_cfn.list_stack_resources, { 'StackName': stack_name }, lambda r: r['StackResourceSummaries'] ... |
response.get('Processes', [])] for asg in autoscaling_groups: # find instances in autoscaling group ec2_instances = all_pages( client_autoscaling.describe_auto_scaling_instances, {}, lambda r: [i['InstanceId'] for i in r.get('AutoScalingInstances', []) if i['AutoScalingGroupName'] == asg['PhysicalResourceId']], ) if us... |
client_autoscaling.suspend_processes( AutoScalingGroupName=asg['PhysicalResourceId'], ScalingProcesses=scaling_process_types ) _stop_ec2_instances(awsclient, ec2_instances) else: # resize autoscaling group (min, max = 0) log.info('Resize autoscaling group \'%s\' to minSize=0, maxSize=0', asg['LogicalResourceId']) respo... |
terminate waiter_inst_terminated = client_ec2.get_waiter('instance_terminated') waiter_inst_terminated.wait(InstanceIds=running_instances) # setting ECS desiredCount to zero services = [ r for r in resources if r['ResourceType'] == 'AWS::ECS::Service' ] if services: template, parameters = _get_template_parameters(awscl... |
in resources if r['ResourceType'] == 'AWS::RDS::DBInstance' ] running_db_instances = _filter_db_instances_by_status( awsclient, db_instances, ['available'] ) for db in running_db_instances: log.info('Stopping RDS instance \'%s\'', db) client_rds.stop_db_instance(DBInstanceIdentifier=db) return exit_code |
def _get_autoscaling_min_max(template, parameters, asg_name): """Helper to extract the configured MinSize, MaxSize attributes from the template. :param template: cloudformation template (json) :param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'} :param asg_name: logical resource name of the autosca... |
None) max = asg.get('Properties', {}).get('MaxSize', None) if 'Ref' in min: min = params.get(min['Ref'], None) if 'Ref' in max: max = params.get(max['Ref'], None) if min and max: return int(min), int(max) |
def _get_service_cluster_desired_count(template, parameters, service_name): """Helper to extract the configured desiredCount attribute from the template. :param template: cloudformation template (json) :param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'} :param service_name: logical resource name o... |
desired_count = service.get('Properties', {}).get('DesiredCount', None) if 'Ref' in cluster: cluster = params.get(cluster['Ref'], None) if not isinstance(desired_count, int) and 'Ref' in desired_count: desired_count = params.get(desired_count['Ref'], None) return cluster, int(desired_count) |
def start_stack(awsclient, stack_name, use_suspend=False): """Start an existing stack on AWS cloud. :param awsclient: :param stack_name: :param use_suspend: use suspend and resume on the autoscaling group :return: exit_code """ exit_code = 0 # check for DisableStop #disable_stop = conf.get('deployment', {}).get('Disabl... |
else: client_cfn = awsclient.get_client('cloudformation') client_autoscaling = awsclient.get_client('autoscaling') client_rds = awsclient.get_client('rds') resources = all_pages( client_cfn.list_stack_resources, { 'StackName': stack_name }, lambda r: r['StackResourceSummaries'] ) autoscaling_groups = [ r for r in resou... |
starting db instances db_instances = [ r['PhysicalResourceId'] for r in resources if r['ResourceType'] == 'AWS::RDS::DBInstance' ] stopped_db_instances = _filter_db_instances_by_status( awsclient, db_instances, ['stopped'] ) for db in stopped_db_instances: log.info('Starting RDS instance \'%s\'', db) client_rds.start_d... |
'AWS::EC2::Instance' ] _start_ec2_instances(awsclient, instances) services = [ r for r in resources if r['ResourceType'] == 'AWS::ECS::Service' ] if (autoscaling_groups and not use_suspend) or services: template, parameters = _get_template_parameters(awsclient, stack_name) # setting ECS desiredCount back if services: _... |
# find instances in autoscaling group instances = all_pages( client_autoscaling.describe_auto_scaling_instances, {}, lambda r: [i['InstanceId'] for i in r.get('AutoScalingInstances', []) if i['AutoScalingGroupName'] == asg['PhysicalResourceId']], ) _start_ec2_instances(awsclient, instances) # resume all autoscaling pro... |
max = _get_autoscaling_min_max( template, parameters, asg['LogicalResourceId']) response = client_autoscaling.update_auto_scaling_group( AutoScalingGroupName=asg['PhysicalResourceId'], MinSize=min, MaxSize=max ) return exit_code |
def is_running(self): """Property method that returns a bool specifying if the process is currently running. This will return true if the state is active, idle or initializing. :rtype: bool """ return self._state in [self.STATE_ACTIVE, self.STATE_IDLE, self.STATE_INITIALIZING] |
def process_signal(self, signum): """Invoked whenever a signal is added to the stack. :param int signum: The signal that was added """ if signum == signal.SIGTERM: LOGGER.info('Received SIGTERM, initiating shutdown') self.stop() elif signum == signal.SIGHUP: LOGGER.info('Received SIGHUP') if self.config.reload(): LOGGE... |
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', self.APPNAME, self.VERSION) self.setup() while ... |
self.is_stopped]): break self.set_state(self.STATE_ACTIVE) self.process() |
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() |
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` - :attr:`Controller.STATE_STOP_REQUESTED` - :att... |
state not in [self.STATE_STOPPING, self.STATE_STOPPED]: LOGGER.warning('Attempt to set invalid state while waiting to ' 'shutdown: %s ', self._STATES[state]) return elif self.is_stopping and state != self.STATE_STOPPED: LOGGER.warning('Attempt to set invalid post shutdown state: %s', self._STATES[state]) return elif se... |
self.STATE_STOP_REQUESTED, self.STATE_STOPPING]: LOGGER.warning('Attempt to set invalid post sleeping state: %s', self._STATES[state]) return LOGGER.debug('State changed from %s to %s', self._STATES[self._state], self._STATES[state]) self._state = state |
def stop(self): """Override to implement shutdown steps.""" LOGGER.info('Attempting to stop the process') self.set_state(self.STATE_STOP_REQUESTED) # Call shutdown for classes to add shutdown steps self.shutdown() # Wait for the current run to finish while self.is_running and self.is_waiting_to_stop: LOGGER.info('Waiti... |
self.on_shutdown() # Change our state self.set_state(self.STATE_STOPPED) |
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) |
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: dictionary containing the st... |
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') image_filter = [ { 'Name': 'state... |
for i in client_ec2.describe_images( Owners=owners, Filters=image_filter )['Images']: m = re.search(r'(Ops_Base-Image)_(\d+.\d+.\d+)_(\d+)$', i['Name']) if m: version = StrictVersion(m.group(2)) #timestamp = m.group(3) creation_date = parse_ts(i['CreationDate']) if creation_date > latest_ts and version >=latest_version... |
def _add_default_arguments(parser): """Add the default arguments to the parser. :param argparse.ArgumentParser parser: The argument parser """ parser.add_argument('-c', '--config', action='store', dest='config', help='Path to the configuration file') parser.add_argument('-f', '--foreground', action='store_true', dest='... |
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(val, 'ascii') |
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 = [] for k, v in iteritems(api_query): if k in ('title', ... |
) else: part = (k, (None, v)) partlist.append(part) auth1 = OAuth1( self.consumer_token.key, client_secret=self.consumer_token.secret, resource_owner_key=session['mwoauth_access_token']['key'], resource_owner_secret=session['mwoauth_access_token']['secret']) return Request( url=url, files=partlist, auth=auth1, method="... |
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.php" else: api_url = self.api_url size = sum([sys.getsizeof(... |
(the limit is somewhat arbitrary, # see https://www.mediawiki.org/wiki/API:Edit#Large_texts) then # transmit as multipart message req = self._prepare_long_request(url=api_url, api_query=api_query) req.send() if self.return_json: return req.response.json() else: return req.response.text else: auth1 = OAuth1( self.consum... |
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: Any options available t... |
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 kwargs: Any options a... |
loado(json.load(fp, **kwargs), class_=class_) |
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(). :return: Single obj... |
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 :return: Single object d... |
for i in obj] elif isinstance(obj, dict): return _dict_to_pio(obj, class_=class_) else: raise ValueError('expecting list or dictionary as outermost structure') |
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) if class_: return class_(**... |
return System(**d) elif d['category'] == 'system.chemical': return ChemicalSystem(**d) elif d['category'] == 'system.chemical.alloy': # Legacy support return Alloy(**d) elif d['category'] == 'system.chemical.alloy.phase': # Legacy support return ChemicalSystem(**d) raise ValueError('Dictionary does not contain a valid ... |
def get_command(arguments): """Utility function to extract command from docopt arguments. :param arguments: :return: command """ cmds = list(filter(lambda k: not (k.startswith('-') or k.startswith('<')) and arguments[k], arguments.keys())) if len(cmds) != 1: raise Exception('invalid command line!') return cmds[0] |
def dispatch(cls, arguments, **kwargs): """Dispatch arguments parsed by docopt to the cmd with matching spec. :param arguments: :param kwargs: :return: exit_code """ # first match wins # spec: all '-' elements must match, all others are False; # '<sth>' elements are converted to call args on order of # appearance # # k... |
spec, func in cls._specs: # if command and arguments.get(command) and match(args): args = [] # specified args in order of appearance options = list(filter(lambda k: k.startswith('-') and (arguments[k] or k in spec), arguments.keys())) cmds = list(filter(lambda k: not (k.startswith('-') or k.startswith('<')) and argumen... |
element.startswith('-'): # element is an option if element in options: args.append(arguments.get(element, False)) options.remove(element) elif element.startswith('<') and \ not arguments.get(element) is False: # element is an argument args.append(arguments.get(element)) if element in args_spec: args_spec.remove(element... |
cmds from command line have been matched if args_spec: continue # not all args from spec have been provided if cmd_spec: continue # not all cmds from spec have been provided # all options and cmds matched : call the cmd # TODO leave out all args to deal with "empty" signature exit_code = func(*args, **kwargs) return ex... |
Exception('No implementation for spec: %s' % arguments) |
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 as_reference: return troposphere.GetAt... |
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 key filters filter_rules = [] # look for filter rules for filter_typ... |
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'] } filters_spec['Key']['FilterR... |
def convert_representation(self, i): """ Return the proper representation for the given integer """ if self.number_representation == 'unsigned': return i elif self.number_representation == 'signed': if i & (1 << self.interpreter._bit_width - 1): return -((~i + 1) & (2**self.interpreter._bit_width - 1)) else: return i e... |
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 hardware would work. Defaults to False, or... |
`%generate_random false` """ line = line.strip().lower() if not line or line == 'true': self.interpreter.generate_random = True elif line == 'false': self.interpreter.generate_random = False else: stream_content = {'name': 'stderr', 'text': "unknwon value '{}'".format(line)} self.send_response(self.iopub_socket, 'strea... |
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. Note that each cell is executed only executed after all lines... |
line.strip().lower() if not line or line == 'true': self.interpreter.postpone_execution = True elif line == 'false': self.interpreter.postpone_execution = False else: stream_content = {'name': 'stderr', 'text': "unknwon value '{}'".format(line)} self.send_response(self.iopub_socket, 'stream', stream_content) return {'s... |
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` or `%reg R8-R12` """ message = "" for reg in [i.strip() for i in line.repl... |
reg: # We have a range (Rn-Rk) r1, r2 = reg.split('-') # TODO do we want to allow just numbers? n1 = re.search(self.interpreter.REGISTER_REGEX, r1).groups()[0] n2 = re.search(self.interpreter.REGISTER_REGEX, r2).groups()[0] n1 = self.interpreter.convert_to_integer(n1) n2 = self.interpreter.convert_to_integer(n2) for i ... |
{}\n".format(reg, val) stream_content = {'name': 'stdout', 'text': message} self.send_response(self.iopub_socket, 'stream', stream_content) |
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` """ # TODO add support for directives message = "" for address in [i.strip() for i in l... |
in address: # We have a range (n-k) m1, m2 = address.split('-') n1 = re.search(self.interpreter.IMMEDIATE_NUMBER, m1).groups()[0] n2 = re.search(self.interpreter.IMMEDIATE_NUMBER, m2).groups()[0] n1 = self.interpreter.convert_to_integer(n1) n2 = self.interpreter.convert_to_integer(n2) for i in range(n1, n2 + 1): val = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.