INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Prepares for the CallBackResolver and handles the response and exceptions: param request HttpRequest: rtype: HttpResponse
def handle(self, request: HttpRequest) -> HttpResponse: """ Prepares for the CallBackResolver and handles the response and exceptions :param request HttpRequest :rtype: HttpResponse """ self.__request_start = datetime.now() self.__request = request self.__...
Executes the resolved end - point callback or its fallback: rtype: Response or object
def exec_route_callback(self) -> Response or object: """ Executes the resolved end-point callback, or its fallback :rtype: Response or object """ if self.__method.lower() in self.__end_points: for bound in self.__end_points[self.__method.lower()]: rou...
Determines whether a route matches the actual requested route or not: param actual_route str: param expected_route: rtype: Boolean
def request_matches_route(self, actual_route: str, expected_route: str): """ Determines whether a route matches the actual requested route or not :param actual_route str :param expected_route :rtype: Boolean """ expected_params = self.get_url_params(expected_route...
Runs the pre - defined authenticaton service: param bound_route str route matched: param actual_params dict actual url parameters: rtype: bool
def authenticate(self, bound_route, actual_params) -> bool: """ Runs the pre-defined authenticaton service :param bound_route str route matched :param actual_params dict actual url parameters :rtype: bool """ if self.__auth_service is not None: auth_ro...
Assembles a dictionary whith the parameters schema defined for this route: param expected_params dict parameters schema defined for this route: param actual_params dict actual url parameters: rtype: dict
def get_callback_pattern(expected_params, actual_params): """ Assembles a dictionary whith the parameters schema defined for this route :param expected_params dict parameters schema defined for this route :param actual_params dict actual url parameters :rtype: dict """ ...
Gets route parameters as dictionary: param end_point str target route: rtype: list
def get_url_params(end_point: str) -> list: """ Gets route parameters as dictionary :param end_point str target route :rtype: list """ var_params = end_point.split('/') if len(var_params) == 1 and var_params[0] == '': return [] elif len(var_p...
Extracts the route from the accessed URL and sets it to __end_point_uri: rtype: bool
def set_end_point_uri(self) -> bool: """ Extracts the route from the accessed URL and sets it to __end_point_uri :rtype: bool """ expected_parts = self.__route.split("/") actual_parts = self.__uri.split("/") i = 0 for part in expected_parts: i...
Default callback for route not found: param request HttpRequest: rtype: Response
def no_route_found(self, request): """ Default callback for route not found :param request HttpRequest :rtype: Response """ response_obj = OrderedDict() response_obj["status"] = False response_obj["exceptions"] = { "message": "No route found fo...
Defaulf welcome page when the route/ is note mapped yet: rtype: HttpResponse
def welcome_page(self): """ Defaulf welcome page when the route / is note mapped yet :rtype: HttpResponse """ message = "HTTP/1.1 200 OK RINZLER FRAMEWORK" return HttpResponse( "<center><h1>{0}({1})</h1></center>".format(message, self.app.app_name), ...
Default callback for OPTIONS request: rtype: Response
def default_route_options(): """ Default callback for OPTIONS request :rtype: Response """ response_obj = OrderedDict() response_obj["status"] = True response_obj["data"] = "Ok" return Response(response_obj, content_type="application/json", charset="utf-...
Appends default headers to every response returned by the API: param response HttpResponse: rtype: HttpResponse
def set_response_headers(self, response: HttpResponse) -> HttpResponse: """ Appends default headers to every response returned by the API :param response HttpResponse :rtype: HttpResponse """ public_name = os.environ.get('SERVER_PUBLIC_NAME') response_headers = { ...
Defines whether the JSON response will be indented or not: param request_headers: dict: return: self
def get_json_ident(request_headers: dict) -> int: """ Defines whether the JSON response will be indented or not :param request_headers: dict :return: self """ if 'HTTP_USER_AGENT' in request_headers: indent = 2 if re.match("[Mozilla]{7}", request_headers['HTTP...
Implementation of prop ( get_item ) that also supports object attributes: param key:: param dct_or_obj:: return:
def prop(key, dct_or_obj): """ Implementation of prop (get_item) that also supports object attributes :param key: :param dct_or_obj: :return: """ # Note that hasattr is a builtin and getattr is a ramda function, hence the different arg position if isinstance(dict, dct_or_obj): ...
Returns true if all dct values pass f: param f: binary lambda predicate: param dct:: return: True or false
def all_pass_dict(f, dct): """ Returns true if all dct values pass f :param f: binary lambda predicate :param dct: :return: True or false """ return all(map_with_obj_to_values( lambda key, value: f(key, value), dct ))
Ramda propOr implementation. This also resolves object attributes so key can be a dict prop or an attribute of dct_or_obj: param default: Value if dct_or_obj doesn t have key_or_prop or the resolved value is null: param key:: param dct_or_obj:: return:
def prop_or(default, key, dct_or_obj): """ Ramda propOr implementation. This also resolves object attributes, so key can be a dict prop or an attribute of dct_or_obj :param default: Value if dct_or_obj doesn't have key_or_prop or the resolved value is null :param key: :param dct_or_obj: ...
Ramda propEq plus propOr implementation: param default:: param key:: param value:: param dct:: return:
def prop_eq_or(default, key, value, dct): """ Ramda propEq plus propOr implementation :param default: :param key: :param value: :param dct: :return: """ return dct[key] and dct[key] == value if key in dct else default
Ramda propEq/ propIn plus propOr: param default:: param key:: param value:: param dct:: return:
def prop_eq_or_in_or(default, key, value, dct): """ Ramda propEq/propIn plus propOr :param default: :param key: :param value: :param dct: :return: """ return has(key, dct) and \ (dct[key] == value if key in dct else ( dct[key] in value if isinstance((lis...
Optional version of item_path with a default value. keys can be dict keys or object attributes or a combination: param default:: param keys: List of keys or dot - separated string: param dict_or_obj: A dict or obj: return:
def item_path_or(default, keys, dict_or_obj): """ Optional version of item_path with a default value. keys can be dict keys or object attributes, or a combination :param default: :param keys: List of keys or dot-separated string :param dict_or_obj: A dict or obj :return: """ if not keys:...
Given a string of path segments separated by. splits them into an array. Int strings are converted to numbers to serve as an array index: param keys: e. g. foo. bar. 1. goo: param dct: e. g. dict ( foo = dict ( bar = [ dict ( goo = a ) dict ( goo = b ) ] ): return: The resolved value or an error. E. g. for above the re...
def item_str_path(keys, dct): """ Given a string of path segments separated by ., splits them into an array. Int strings are converted to numbers to serve as an array index :param keys: e.g. 'foo.bar.1.goo' :param dct: e.g. dict(foo=dict(bar=[dict(goo='a'), dict(goo='b')]) :return: The r...
Given a string of path segments separated by. splits them into an array. Int strings are converted to numbers to serve as an array index: param default: Value if any part yields None or undefined: param keys: e. g. foo. bar. 1. goo: param dct: e. g. dict ( foo = dict ( bar = [ dict ( goo = a ) dict ( goo = b ) ] ): ret...
def item_str_path_or(default, keys, dct): """ Given a string of path segments separated by ., splits them into an array. Int strings are converted to numbers to serve as an array index :param default: Value if any part yields None or undefined :param keys: e.g. 'foo.bar.1.goo' :param dct...
Implementation of ramda has: param prop:: param object_or_dct:: return:
def has(prop, object_or_dct): """ Implementation of ramda has :param prop: :param object_or_dct: :return: """ return prop in object_or_dct if isinstance(dict, object_or_dct) else hasattr(object_or_dct, prop)
Implementation of omit that recurses. This tests the same keys at every level of dict and in lists: param omit_props:: param dct:: return:
def omit_deep(omit_props, dct): """ Implementation of omit that recurses. This tests the same keys at every level of dict and in lists :param omit_props: :param dct: :return: """ omit_partial = omit_deep(omit_props) if isinstance(dict, dct): # Filter out keys and then recurse o...
Implementation of pick that recurses. This tests the same keys at every level of dict and in lists: param pick_dct: Deep dict matching some portion of dct.: param dct: Dct to filter. Any key matching pick_dct pass through. It doesn t matter what the pick_dct value is as long as the key exists. Arrays also pass through ...
def pick_deep(pick_dct, dct): """ Implementation of pick that recurses. This tests the same keys at every level of dict and in lists :param pick_dct: Deep dict matching some portion of dct. :param dct: Dct to filter. Any key matching pick_dct pass through. It doesn't matter what the pick_dct value i...
Implementation of map that recurses. This tests the same keys at every level of dict and in lists: param f: 2 - ary function expecting a key and value and returns a modified value: param dct: Dict for deep processing: return: Modified dct with matching props mapped
def map_with_obj_deep(f, dct): """ Implementation of map that recurses. This tests the same keys at every level of dict and in lists :param f: 2-ary function expecting a key and value and returns a modified value :param dct: Dict for deep processing :return: Modified dct with matching props mapped ...
Implementation of map that recurses. This tests the same keys at every level of dict and in lists: param f: 2 - ary function expecting a key and value and returns a modified key: param dct: Dict for deep processing: return: Modified dct with matching props mapped
def map_keys_deep(f, dct): """ Implementation of map that recurses. This tests the same keys at every level of dict and in lists :param f: 2-ary function expecting a key and value and returns a modified key :param dct: Dict for deep processing :return: Modified dct with matching props mapped """...
Used by map_deep and map_keys_deep: param map_props:: param f: Expects a key and value and returns a pair: param dct:: return:
def _map_deep(f, dct): """ Used by map_deep and map_keys_deep :param map_props: :param f: Expects a key and value and returns a pair :param dct: :return: """ if isinstance(dict, dct): return map_key_values(lambda k, v: f(k, _map_deep(f, v)), dct) elif isinstance((list, tuple...
Filters deeply by comparing dct to filter_dct s value at each depth. Whenever a mismatch occurs the whole thing returns false: param params_dct: dict matching any portion of dct. E. g. filter_dct = { foo: { bar: 1 }} would allow { foo: { bar: 1 car: 2 }} to pass { foo: { bar: 2 }} would fail { goo:... } would fail: par...
def dict_matches_params_deep(params_dct, dct): """ Filters deeply by comparing dct to filter_dct's value at each depth. Whenever a mismatch occurs the whole thing returns false :param params_dct: dict matching any portion of dct. E.g. filter_dct = {foo: {bar: 1}} would allow {foo: {bar: 1, car: 2}} ...
Ramda implementation of join: param strin:: param items:: return:
def join(strin, items): """ Ramda implementation of join :param strin: :param items: :return: """ return strin.join(map(lambda item: str(item), items))
Implementation of Ramda s mapObjIndexed without the final argument. This returns the original key with the mapped value. Use map_key_values to modify the keys too: param f: Called with a key and value: param dct:: return { dict }: Keyed by the original key valued by the mapped value
def map_with_obj(f, dct): """ Implementation of Ramda's mapObjIndexed without the final argument. This returns the original key with the mapped value. Use map_key_values to modify the keys too :param f: Called with a key and value :param dct: :return {dict}: Keyed by the original key, va...
Calls f with each key of dct possibly returning a modified key. Values are unchanged: param f: Called with each key and returns the same key or a modified key: param dct:: return: A dct with keys possibly modifed but values unchanged
def map_keys(f, dct): """ Calls f with each key of dct, possibly returning a modified key. Values are unchanged :param f: Called with each key and returns the same key or a modified key :param dct: :return: A dct with keys possibly modifed but values unchanged """ f_dict = {} for k, ...
Calls f with each key and value of dct possibly returning a modified key. Values are unchanged: param f: Called with each key and value and returns the same key or a modified key: param dct:: return: A dct with keys possibly modifed but values unchanged
def map_keys_with_obj(f, dct): """ Calls f with each key and value of dct, possibly returning a modified key. Values are unchanged :param f: Called with each key and value and returns the same key or a modified key :param dct: :return: A dct with keys possibly modifed but values unchanged ""...
Deep merge by this spec below: param dct1:: param dct2:: param merger Optional merger: return:
def merge_deep(dct1, dct2, merger=None): """ Deep merge by this spec below :param dct1: :param dct2: :param merger Optional merger :return: """ my_merger = merger or Merger( # pass in a list of tuples,with the # strategies you are looking to apply # to each ty...
Shallow merge all the dcts: param dcts:: return:
def merge_all(dcts): """ Shallow merge all the dcts :param dcts: :return: """ return reduce( lambda accum, dct: merge(accum, dct), dict(), dcts )
Like from pairs but combines duplicate key values into arrays: param pairs:: return:
def from_pairs_to_array_values(pairs): """ Like from pairs but combines duplicate key values into arrays :param pairs: :return: """ result = {} for pair in pairs: result[pair[0]] = concat(prop_or([], pair[0], result), [pair[1]]) return result
Returns the given prop of each item in the list: param prp:: param lst:: return:
def map_prop_value_as_index(prp, lst): """ Returns the given prop of each item in the list :param prp: :param lst: :return: """ return from_pairs(map(lambda item: (prop(prp, item), item), lst))
Converts a key string like foo. bar. 0. wopper to [ foo bar 0 wopper ]: param { String } keyString The dot - separated key string: return { [ String ] } The lens array containing string or integers
def key_string_to_lens_path(key_string): """ Converts a key string like 'foo.bar.0.wopper' to ['foo', 'bar', 0, 'wopper'] :param {String} keyString The dot-separated key string :return {[String]} The lens array containing string or integers """ return map( if_else( isinstance(int)...
Simulates R. view with a lens_path since we don t have lens functions: param lens_path: Array of string paths: param obj: Object containing the given path: return: The value at the path or None
def fake_lens_path_view(lens_path, obj): """ Simulates R.view with a lens_path since we don't have lens functions :param lens_path: Array of string paths :param obj: Object containing the given path :return: The value at the path or None """ segment = head(lens_path) return if_else( ...
Simulates R. set with a lens_path since we don t have lens functions: param lens_path: Array of string paths: param value: The value to set at the lens path: param obj: Object containing the given path: return: The value at the path or None
def fake_lens_path_set(lens_path, value, obj): """ Simulates R.set with a lens_path since we don't have lens functions :param lens_path: Array of string paths :param value: The value to set at the lens path :param obj: Object containing the given path :return: The value at the path or None "...
Undoes the work of flatten_dict
def unflatten_dct(obj): """ Undoes the work of flatten_dict @param {Object} obj 1-D object in the form returned by flattenObj @returns {Object} The original :param obj: :return: """ def reduce_func(accum, key_string_and_value): key_string = key_string_and_value[0] val...
ppj
def ppj(json_data): """ppj :param json_data: dictionary to print """ return str(json.dumps( json_data, sort_keys=True, indent=4, separators=(',', ': ')))
Override change view to add extra context enabling moderate tool.
def change_view(self, request, object_id, form_url='', extra_context=None): """ Override change view to add extra context enabling moderate tool. """ context = { 'has_moderate_tool': True } if extra_context: context.update(extra_context) re...
Add aditional moderate url.
def get_urls(self): """ Add aditional moderate url. """ from django.conf.urls import url urls = super(AdminModeratorMixin, self).get_urls() info = self.model._meta.app_label, self.model._meta.model_name return [ url(r'^(.+)/moderate/$', ...
Renders a HttpResponse for the ongoing request: param indent int: rtype: HttpResponse
def render(self, indent=0): """ Renders a HttpResponse for the ongoing request :param indent int :rtype: HttpResponse """ self.__indent = indent return HttpResponse( str(self), content_type=self.__content_type, charset=self.__charset, **self.__kwargs ...
Setup logging configuration
def setup_logging(default_path='logging.yaml', env_key='LOG_CFG'): """ Setup logging configuration """ path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as f: configs = yaml.safe_load(f.read(...
Binds a GET route with the given callback: rtype: object
def get(self, route: str(), callback: object()): """ Binds a GET route with the given callback :rtype: object """ self.__set_route('get', {route: callback}) return RouteMapping
Binds a POST route with the given callback: rtype: object
def post(self, route: str(), callback: object()): """ Binds a POST route with the given callback :rtype: object """ self.__set_route('post', {route: callback}) return RouteMapping
Binds a PUT route with the given callback: rtype: object
def put(self, route: str(), callback: object()): """ Binds a PUT route with the given callback :rtype: object """ self.__set_route('put', {route: callback}) return RouteMapping
Binds a PATCH route with the given callback: rtype: object
def patch(self, route: str(), callback: object()): """ Binds a PATCH route with the given callback :rtype: object """ self.__set_route('patch', {route: callback}) return RouteMapping
Binds a PUT route with the given callback: rtype: object
def delete(self, route: str(), callback: object()): """ Binds a PUT route with the given callback :rtype: object """ self.__set_route('delete', {route: callback}) return RouteMapping
Binds a HEAD route with the given callback: rtype: object
def head(self, route: str(), callback: object()): """ Binds a HEAD route with the given callback :rtype: object """ self.__set_route('head', {route: callback}) return RouteMapping
Binds a OPTIONS route with the given callback: rtype: object
def options(self, route: str(), callback: object()): """ Binds a OPTIONS route with the given callback :rtype: object """ self.__set_route('options', {route: callback}) return RouteMapping
Sets the given type_route and route to the route mapping: rtype: object
def __set_route(self, type_route, route): """ Sets the given type_route and route to the route mapping :rtype: object """ if type_route in self.__routes: if not self.verify_route_already_bound(type_route, route): self.__routes[type_route].append(route)...
Return a string identifying the operating system the application is running on.
def operating_system(): """Return a string identifying the operating system the application is running on. :rtype: str """ if platform.system() == 'Darwin': return 'OS X Version %s' % platform.mac_ver()[0] distribution = ' '.join(platform.linux_distribution()).strip() os_platform =...
Daemonize if the process is not already running.
def start(self): """Daemonize if the process is not already running.""" if self._is_already_running(): LOGGER.error('Is already running') sys.exit(1) try: self._daemonize() self.controller.start() except Exception as error: sys....
Return the group id that the daemon will run with
def gid(self): """Return the group id that the daemon will run with :rtype: int """ if not self._gid: if self.controller.config.daemon.group: self._gid = grp.getgrnam(self.config.daemon.group).gr_gid else: self._gid = os.getgid() ...
Return the user id that the process will run as
def uid(self): """Return the user id that the process will run as :rtype: int """ if not self._uid: if self.config.daemon.user: self._uid = pwd.getpwnam(self.config.daemon.user).pw_uid else: self._uid = os.getuid() return ...
Fork into a background process and setup the process copied in part from http:// www. jejik. com/ files/ examples/ daemon3x. py
def _daemonize(self): """Fork into a background process and setup the process, copied in part from http://www.jejik.com/files/examples/daemon3x.py """ LOGGER.info('Forking %s into the background', sys.argv[0]) # Write the pidfile if current uid != final uid if os.getuid...
Return the normalized path for the connection log raising an exception if it can not written to.
def _get_exception_log_path(): """Return the normalized path for the connection log, raising an exception if it can not written to. :return: str """ app = sys.argv[0].split('/')[-1] for exception_log in ['/var/log/%s.errors' % app, '/var/tm...
Return the normalized path for the pidfile raising an exception if it can not written to.
def _get_pidfile_path(self): """Return the normalized path for the pidfile, raising an exception if it can not written to. :return: str :raises: ValueError :raises: OSError """ if self.config.daemon.pidfile: pidfile = path.abspath(self.config.daemon....
Check to see if the process is running first looking for a pidfile then shelling out in either case removing a pidfile if it exists but the process is not running.
def _is_already_running(self): """Check to see if the process is running, first looking for a pidfile, then shelling out in either case, removing a pidfile if it exists but the process is not running. """ # Look for the pidfile, if exists determine if the process is alive ...
Remove the pid file from the filesystem
def _remove_pidfile(self): """Remove the pid file from the filesystem""" LOGGER.debug('Removing pidfile: %s', self.pidfile_path) try: os.unlink(self.pidfile_path) except OSError: pass
Write the pid file out with the process number in the pid file
def _write_pidfile(self): """Write the pid file out with the process number in the pid file""" LOGGER.debug('Writing pidfile: %s', self.pidfile_path) with open(self.pidfile_path, "w") as handle: handle.write(str(os.getpid()))
Convert a string from snake case to camel case. For example some_var would become someVar.
def to_camel_case(snake_case_string): """ Convert a string from snake case to camel case. For example, "some_var" would become "someVar". :param snake_case_string: Snake-cased string to convert to camel case. :returns: Camel-cased version of snake_case_string. """ parts = snake_case_string.lstr...
Convert a string from snake case to camel case with the first letter capitalized. For example some_var would become SomeVar.
def to_capitalized_camel_case(snake_case_string): """ Convert a string from snake case to camel case with the first letter capitalized. For example, "some_var" would become "SomeVar". :param snake_case_string: Snake-cased string to convert to camel case. :returns: Camel-cased version of snake_case_...
Convert a string from camel case to snake case. From example someVar would become some_var.
def to_snake_case(camel_case_string): """ Convert a string from camel case to snake case. From example, "someVar" would become "some_var". :param camel_case_string: Camel-cased string to convert to snake case. :return: Snake-cased version of camel_case_string. """ first_pass = _first_camel_case...
Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on each of the keys in the dictionary and returns a new dictionary.
def keys_to_snake_case(camel_case_dict): """ Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on each of the keys in the dictionary and returns a new dictionary. :param camel_case_dict: Dictionary with the keys to convert. :type camel_case_dict: Di...
List the deployed lambda functions and print configuration.
def list_functions(awsclient): """List the deployed lambda functions and print configuration. :return: exit_code """ client_lambda = awsclient.get_client('lambda') response = client_lambda.list_functions() for function in response['Functions']: log.info(function['FunctionName']) ...
Create or update a lambda function.
def deploy_lambda(awsclient, function_name, role, handler_filename, handler_function, folders, description, timeout, memory, subnet_ids=None, security_groups=None, artifact_bucket=None, zipfile=None, fail_deployment_on_unsuccessfu...
Write zipfile contents to file.
def bundle_lambda(zipfile): """Write zipfile contents to file. :param zipfile: :return: exit_code """ # TODO have 'bundle.zip' as default config if not zipfile: return 1 with open('bundle.zip', 'wb') as zfile: zfile.write(zipfile) log.info('Finished - a bundle.zip is wai...
Print out cloudformation metrics for a lambda function.
def get_metrics(awsclient, name): """Print out cloudformation metrics for a lambda function. :param awsclient :param name: name of the lambda function :return: exit_code """ metrics = ['Duration', 'Errors', 'Invocations', 'Throttles'] client_cw = awsclient.get_client('cloudwatch') for m...
Rollback a lambda function to a given version.
def rollback(awsclient, function_name, alias_name=ALIAS_NAME, version=None): """Rollback a lambda function to a given version. :param awsclient: :param function_name: :param alias_name: :param version: :return: exit_code """ if version: log.info('rolling back to version {}'.form...
Delete a lambda function.
def delete_lambda(awsclient, function_name, events=None, delete_logs=False): """Delete a lambda function. :param awsclient: :param function_name: :param events: list of events :param delete_logs: :return: exit_code """ if events is not None: unwire(awsclient, events, function_na...
Deprecated: please use delete_lambda!
def delete_lambda_deprecated(awsclient, function_name, s3_event_sources=[], time_event_sources=[], delete_logs=False): # FIXME: mutable default arguments! """Deprecated: please use delete_lambda! :param awsclient: :param function_name: :param s3_event_sources: :para...
Deletes files used for creating bundle. * vendored/ * * bundle. zip
def cleanup_bundle(): """Deletes files used for creating bundle. * vendored/* * bundle.zip """ paths = ['./vendored', './bundle.zip'] for path in paths: if os.path.exists(path): log.debug("Deleting %s..." % path) if os.path.isdir(path): shu...
Send a ping request to a lambda function.
def ping(awsclient, function_name, alias_name=ALIAS_NAME, version=None): """Send a ping request to a lambda function. :param awsclient: :param function_name: :param alias_name: :param version: :return: ping response payload """ log.debug('sending ping to lambda function: %s', function_n...
Send a ping request to a lambda function.
def invoke(awsclient, function_name, payload, invocation_type=None, alias_name=ALIAS_NAME, version=None, outfile=None): """Send a ping request to a lambda function. :param awsclient: :param function_name: :param payload: :param invocation_type: :param alias_name: :param version: ...
Send a ping request to a lambda function.
def logs(awsclient, function_name, start_dt, end_dt=None, tail=False): """Send a ping request to a lambda function. :param awsclient: :param function_name: :param start_dt: :param end_dt: :param tail: :return: """ log.debug('Getting cloudwatch logs for: %s', function_name) log_g...
This will require validating version string ( such as 3. 3. 5 ). A version string could be converted to a datetime value if this validation is not executed.
def __validate_datetime_string(self): """ This will require validating version string (such as "3.3.5"). A version string could be converted to a datetime value if this validation is not executed. """ try: try: StrictVersion(self._value) ...
ADR Ra [ PC #imm10_4 ] ADR Ra label
def ADR(self, params): """ ADR Ra, [PC, #imm10_4] ADR Ra, label Load the address of label or the PC offset into Ra Ra must be a low register """ # TODO may need to rethink how I do PC, may need to be byte alligned # TODO This is wrong as each address is a...
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 ]
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 definitio...
LDRB Ra [ Rb Rc ] LDRB Ra [ Rb #imm5 ]
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.exc...
LDRH Ra [ Rb Rc ] LDRH Ra [ Rb #imm6_2 ]
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 i...
LDRSB Ra [ Rb Rc ]
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) ...
LDRSH Ra [ Rb Rc ]
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)...
POP { RPopList }
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 Regi...
PUSH { RPushList }
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 RPushLis...
STM Ra! { RLoList }
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....
STR Ra [ Rb Rc ] STR Ra [ Rb #imm7_4 ] STR Ra [ SP #imm10_4 ]
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...
STRB Ra [ Rb Rc ] STRB Ra [ Rb #imm5 ]
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): ...
STRH Ra [ Rb Rc ] STRH Ra [ Rb #imm6_2 ]
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):...
Helper to stop ec2 instances. By default it waits for instances to stop.
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_e...
Helper to start ec2 instances
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 s...
helper to select dbinstances.
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...
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
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: ...
Stop an existing stack on AWS cloud.
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 = co...
Helper to extract the configured MinSize MaxSize attributes from the template.
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 resourc...
Helper to extract the configured desiredCount attribute from the template.
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: lo...
Start an existing stack on AWS cloud.
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 = ...
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.
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, sel...
Invoked whenever a signal is added to the stack.
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.SIG...