code
stringlengths
1
18.2k
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 ))
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: :return: """ # Note that hasattr...
isinstance(dict, dct_or_obj): value = dct_or_obj[key] if has(key, dct_or_obj) else default elif isinstance(object, dct_or_obj): value = getattr(key, dct_or_obj) if hasattr(dct_or_obj, key) else default else: value = default # 0 and False are ok, None defaults if value == None: return default return value
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
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((list, tuple), value) and not isinstance(str, value) else default ))
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: raise ValueError("Expected at l...
for key in resolved_keys: current_value = prop_or(default, key, default_to({}, current_value)) return current_value
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 resolved value or an error. E.g. ...
dct)
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: e.g. dict(foo=dict(bar=[dict(g...
b """ return item_path_or(default, map(lambda segment: int(segment) if isint(segment) else segment, keys.split('.')), dct)
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)
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 on each value that wasn't filtered out retu...
dct) # scalar return dct
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 is as long as the key...
values in pick_dct :return: """ if isinstance(dict, dct): # Filter out keys and then recurse on each value that wasn't filtered out return map_with_obj( lambda k, v: pick_deep(prop(k, pick_dct), v), pick(keys(pick_dct), dct) ) if isinstance((list, tuple), dct): # run pick_deep on each value return map( lambda tup: pick...
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 """ return _map_deep(...
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 """ return _map_deep(lambda...
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), dct): # Call each value with the index as ...
Even if this is called with map_keys_deep we can't manipulate index values here return map(lambda iv: f(iv[0], _map_deep(f, iv[1]))[1], enumerate(dct)) # scalar return dct
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}} to pass, {foo: {bar:...
if all pass else false """ def recurse_if_param_exists(params, key, value): """ If a param[key] exists, recurse. Otherwise return True since there is no param to contest value :param params: :param key: :param value: :return: """ return dict_matches_params_deep( prop(key, params), value ) if has(key, params) else True ...
to contest value :param params: :param index: :param value: :return: """ return dict_matches_params_deep( params[index], value ) if isinstance((list, tuple), params_dct) and index < length(params_dct) else True if isinstance(dict, dct): # Filter out keys and then recurse on each value return all_pass_dict( # Recurse on...
shallow merge, giving dct priority with (hopefully) unmatchable values merge(map_with_obj(lambda k, v: 1 / (-e * pi), params_dct), dct) ) if isinstance((list, tuple), dct): if isinstance((list, tuple), params_dct) and length(dct) < length(params_dct): # if there are more param items then dct items fail return False # r...
not truthy, False, None, 0, are considered equal return params_dct == dct
def join(strin, items): """ Ramda implementation of join :param strin: :param items: :return: """ return strin.join(map(lambda item: str(item), items))
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, valued by the mapped value """ f_d...
f_dict
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, v in dct.items(): f_dict[f(k)] = v r...
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 """ f_dict = {} for k, v in dc...
f_dict
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 type. [ (list, ["append"]), (dict, ["merge"]) ], # next, choos...
# finally, choose the strategies in # the case where the types conflict: ["override"] ) return my_merger.merge(dct1, dct2)
def merge_all(dcts): """ Shallow merge all the dcts :param dcts: :return: """ return reduce( lambda accum, dct: merge(accum, dct), dict(), dcts )
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
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))
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), # convert to int lambda s: int(s), # ...
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( both(lambda _: identity(segment), ha...
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 """ segment = head(lens_path)...
up to the given index and set the index to v try: l[i] = v except IndexError: for _ in range(i - len(l) + 1): l.append(None) l[i] = v if not (length(lens_path) - 1): # Done new_value = value else: # Find the value at the path or create a {} or [] at obj[segment] found_or_created = item_path_or( if_else( lambda segment:...
)(head(tail(lens_path))), segment, obj ) # Recurse on the rest of the path new_value = fake_lens_path_set(tail(lens_path), value, found_or_created) # Set or replace if segment.isnumeric(): set_array_index(int(segment), new_value, obj_copy) else: obj_copy[segment] = new_value return obj_copy
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] value = key_string_and_value[1] item_key_path = key_str...
(not []) and the value is set, don't do anything both(always(length(container_key_path)), fake_lens_path_view(container_key_path)), # Else we are at the top level, so use the existing accum or create a [] or {} # depending on if our item key is a number or not lambda x: default_to( if_else( lambda segment: segment.isnu...
fake_lens_path_set( item_key_path, value, container ) return compose( reduce( reduce_func, # null initial value None ), to_pairs )(obj)
def ppj(json_data): """ppj :param json_data: dictionary to print """ return str(json.dumps( json_data, sort_keys=True, indent=4, separators=(',', ': ')))
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) return super(AdminModeratorMixin, self).change_view( request=request, object_id=ob...
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/$', self.admin_site.admin_view(self.moderate_view), name='%s_%s_moderate' % info), ] + ...
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 )
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()) logging.config.dictConfig(configs) else: logging.conf...
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
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
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
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
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
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
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
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) else: self.__routes[type_route] = [route] return RouteMapping
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 = platform.platform(True, True) if dist...
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.stderr.write('\nERROR: Startup of %s Failed\n.' % sys.argv[0].split('/')[-1]) exception_log ...
%s\n' % error) handle.write('Traceback:\n') output = traceback.format_exception(*sys.exc_info()) _dev_null = [(handle.write(line), sys.stdout.write(line)) for line in output] handle.write('{:->80}\n'.format(' [END]')) handle.flush() sys.stderr.write('\nException log: %s\n\n' % exception_log) sys.exit(1)
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 self._gid
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 self._uid
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() != self.uid: fd = open(self.pidfile_path, 'w') ...
off parent: %s', error) # Set the user id if self.uid != os.getuid(): os.setuid(self.uid) # Set the group id if self.gid != os.getgid(): try: os.setgid(self.gid) except OSError as error: LOGGER.error('Could not set group: %s', error) # Decouple from parent environment os.chdir('/') os.setsid() os.umask(0o022) # Fork ag...
%s', error) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() si = open(os.devnull, 'r') so = open(os.devnull, 'a+') se = open(os.devnull, 'a+') os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) # Automatically call self...
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/tmp/%s.errors' % app, '/tmp/%s.errors' % app]: if os.access(path.dirname(exception...
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.pidfile) if not os.access(path.dirname(pidfile), os.W_OK): raise Value...
app), '/var/tmp/%s.pid' % app, '/tmp/%s.pid' % app, '%s.pid' % app]: if os.access(path.dirname(pidfile), os.W_OK): return pidfile raise OSError('Could not find an appropriate place for a pid file')
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 pidfile = self._get_pidfile_path() if os.path.e...
%s\n' % pid) return True except OSError as error: LOGGER.debug('Found pidfile, no process # %s', error) os.unlink(pidfile) # Check the os for a process that is not this one that looks the same pattern = ' '.join(sys.argv) pattern = '[%s]%s' % (pattern[0], pattern[1:]) try: output = subprocess.check_output('ps a | grep ...
a | grep "%s"' % pattern) output = stdout.read() except subprocess.CalledProcessError: return False pids = [int(pid) for pid in (re.findall(r'^([0-9]+)\s', output.decode('latin-1')))] if os.getpid() in pids: pids.remove(os.getpid()) if not pids: return False if len(pids) == 1: pids = pids[0] sys.stderr.write('Process a...
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
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()))
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.lstrip('_').split('_') return...
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_string. """ parts = s...
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_regex.sub(r'\1_\2', came...
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: Dictionary. :return: Di...
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']) log.info('\t' 'Memory: ' + str(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_unsuccessful_ping=False, runtime='python2.7', settings=None, environment=None, retention_in_days=None...
:return: exit_code """ # TODO: the signature of this function is too big, clean this up # also consolidate create, update, config and add waiters! if lambda_exists(awsclient, function_name): function_version = _update_lambda(awsclient, function_name, handler_filename, handler_function, folders, role, description, timeo...
handler_filename, handler_function, folders, description, timeout, memory, subnet_ids, security_groups, artifact_bucket, zipfile, runtime=runtime, environment=environment) # configure cloudwatch logs if retention_in_days: log_group_name = '/aws/lambda/%s' % function_name put_retention_policy(awsclient, log_group_name, ...
alias and fail command return 1 else: log.info(colored.red('Please consider adding a reaction to a ' + 'ping event to your lambda function')) _deploy_alias(awsclient, function_name, function_version) return 0
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 waiting for you...') return 0
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 metric in metrics: response = clie...
%s' % (metric, repr(aggregate_datapoints(response['Datapoints'])))) return 0
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 {}'.format(version)) else: log.info('rolling back...
version, alias_name) return 0
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_name, alias_name=ALIAS_NAME) client_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: :param time_event_sources: :param delete_logs: :return: exi...
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): shutil.rmtree(path) else: os.remove(path)
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_name) payload = '{"ramuda_action":...
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: :param outfile: write response to file :...
open(payload[7:], 'r') as pfile: payload = pfile.read() if version: response = client_lambda.invoke( FunctionName=function_name, InvocationType=invocation_type, Payload=payload, Qualifier=version ) else: response = client_lambda.invoke( FunctionName=function_name, InvocationType=invocation_type, Payload=payload, Qualif...
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_group_name = '/aws/lambda/%s' % function_n...
not out of order # so we hold the timestamp of the last logentry and start the next iteration # from there while True: logentries = filter_log_events(awsclient, log_group_name, start_ts=start_ts, end_ts=end_ts) if logentries: for e in logentries: actual_date, actual_time = decode_format_timestamp(e['timestamp']) if cur...
logentries: start_ts = logentries[-1]['timestamp'] + 1 time.sleep(2) continue break
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) raise TypeConversionError( "invalid datetime string: version string found {}".form...
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 word, not a byte. The filled value with its
location (Do we want that, or the value at that location [Decompiled instruction]) try: Ra, Rb, Rc = self.get_three_parameters(self.THREE_PARAMETER_WITH_BRACKETS, params) except iarm.exceptions.ParsingError: Ra, label = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) # TODO the address must be withi...
not PC: {}".format(Rb)) def ADR_func(): self.register[Ra] = self.register[Rb] + self.convert_to_integer(Rc[1:]) return ADR_func