code
stringlengths
1
18.2k
def reapply(config): """Reapply current revision""" with open(config, 'r'): main.reapply(yaml.load(open(config)))
def show(config): """Show revision list""" with open(config, 'r'): main.show(yaml.load(open(config)))
def raise_(type_, value=None, traceback=None): # pylint: disable=W0613 """ Does the same as ordinary ``raise`` with arguments do in Python 2. But works in Python 3 (>= 3.3) also! Please checkout README on https://github.com/9seconds/pep3134 to get an idea about possible pitfals. But short story is: please be pretty car...
def raise_from(exc, cause): """ Does the same as ``raise LALALA from BLABLABLA`` does in Python 3. But works in Python 2 also! Please checkout README on https://github.com/9seconds/pep3134 to get an idea about possible pitfals. But short story is: please be pretty carefull with tracebacks. If it is possible, use sys.ex...
= sys.exc_info()[1] exc.__original_exception__.__suppress_context__ = True exc.__original_exception__.__cause__ = cause exc.__original_exception__.__context__ = None raise exc
def find_files(self, root): """ Helper method to get all files in the given root. """ def is_ignored(path, ignore_patterns): """ Check if the given path should be ignored or not. """ filename = os.path.basename(path) ignore = lambda pattern: fnmatch.fnmatchcase(filename, pattern) return any(ignore(pattern) for pattern ...
def make_po_file(self, potfile, locale): """ Creates or updates the PO file for self.domain and :param locale:. Uses contents of the existing :param potfile:. Uses mguniq, msgmerge, and msgattrib GNU gettext utilities. """ pofile = self._get_po_path(potfile, locale) msgs = self._get_unique_messages(potfile) msgs = self...
def goodFormater(badFormat, outputPath, year, length): '''[summary] reformats the input results into a dictionary with module names as keys and their respective results as values outputs to csv if outputPath is specified Arguments: badFormat {dict} -- candNumber : [results for candidate] outputPath {str} -- the path to...
initialize with empt array goodFormat.setdefault(row[(2 * i) + 1], []) # add value of module to module goodFormat[row[(2*i)+1]].append(int(row[2*(i + 1)])) goodFormat.pop('0') goodFormat['Averages'] = everyonesAverage(year, badFormat, length) if outputPath is not None: # if requested to reformat and save to file result...
def plotter(path, show, goodFormat): '''makes some plots creates binned histograms of the results of each module (ie count of results in ranges [(0,40), (40, 50), (50,60), (60, 70), (70, 80), (80, 90), (90, 100)]) Arguments: path {str} -- path to save plots to show {boolean} -- whether to show plots using python goodFo...
70', '70 to 80', '80 to 90', '90 to 100']) ax.set_ylabel("# of candidates") ax.set_xlabel( "grade bins \n total candidates: {}".format(len(module[1]))) if path is not None and show is not False: # if export path directory doesn't exist: create it if not pathlib.Path.is_dir(path.as_posix()): pathlib.Path.mkdir(path.as_p...
def myGrades(year, candidateNumber, badFormat, length): '''returns final result of candidateNumber in year Arguments: year {int} -- the year candidateNumber is in candidateNumber {str} -- the candidateNumber of candidateNumber badFormat {dict} -- candNumber : [results for candidate] length {int} -- length of each row i...
1)]) for i in range(length-1)]) / 8 return myFinalResult
def myRank(grade, badFormat, year, length): '''rank of candidateNumber in year Arguments: grade {int} -- a weighted average for a specific candidate number and year badFormat {dict} -- candNumber : [results for candidate] year {int} -- year you are in length {int} -- length of each row in badFormat divided by 2 Returns...
def everyonesAverage(year, badFormat, length): ''' creates list of weighted average results for everyone in year Arguments: year {int} badFormat {dict} -- candNumber : [results for candidate] length {int} -- length of each row in badFormat divided by 2 returns: list -- weighted average results of everyone in year ''' r...
def askInitial(): '''Asks the user for what it wants the script to do Returns: [dictionary] -- answers to the questions ''' return inquirer.prompt([ inquirer.Text( 'inputPath', message="What's the path of your input file (eg input.csv)"), inquirer.List( 'year', message="What year are you in", choices=[1, 2, 3, 4] ), in...
def howPlotAsk(goodFormat): '''plots using inquirer prompts Arguments: goodFormat {dict} -- module : [results for module] ''' plotAnswer = askPlot() if "Save" in plotAnswer['plotQ']: exportPlotsPath = pathlib.Path(askSave()) if "Show" in plotAnswer['plotQ']: plotter(exportPlotsPath, True, goodFormat) else: plotter(expo...
def howPlotArgs(goodFormat): '''plots using argparse if can, if not uses howPlotask() Arguments: goodFormat {dict} -- module : [results for module] ''' if args.exportplots is not None: exportPlotsPath = pathlib.Path(args.exportplots) if args.showplots: plotter(exportPlotsPath, True, goodFormat) else: plotter(exportPlot...
def main(args): '''main entry point of app Arguments: args {namespace} -- arguments provided in cli ''' print("\nNote it's very possible that this doesn't work correctly so take what it gives with a bucketload of salt\n") ######################### # # # # # prompt # # # # # ######################### if not len(sys.argv...
{:.2f}%'.format( weightedAverage)) finalReturn.append('Your rank is {}th of {} ({:.2f} percentile)'.format( rank, howManyCandidates, (rank * 100) / howManyCandidates)) elif "Get your weighted average" in initialAnswers['whatToDo']: candidateNumber = askCandidateNumber() weightedAverage = myGrades(year, candidateNumber,...
args.input: inputPath = pathlib.Path(askInput()) else: inputPath = pathlib.Path(args.input) if not args.year: year = int(askYear()) else: year = int(args.year) # create a list from every row badFormat = badFormater(inputPath) # create a list from every row howManyCandidates = len(badFormat) - 1 length = int(len(badForm...
formatOutputPath = pathlib.Path(args.format) goodFormat = goodFormater(badFormat, formatOutputPath, year, length) if args.plot: howPlotArgs(goodFormat) elif args.plot: goodFormat = goodFormater(badFormat, None, year, length) howPlotArgs(goodFormat) [print('\n', x) for x in finalReturn] ######################### # # # e...
def read_config(config_path_or_dict=None): """ Read config from given path string or dict object. :param config_path_or_dict: :type config_path_or_dict: str or dict :return: Returns config object or None if not found. :rtype: :class:`revision.config.Config` """ config = None if isinstance(config_path_or_dict, dict): co...
def validate(self): """ Check the value of the config attributes. """ for client in self.clients: for key in REQUIRED_KEYS: if key not in client: raise MissingConfigValue(key) if 'revision_file' not in client: client.revision_file = DEFAULT_REVISION_FILEPATH.format( client.key )
def wrap(func, with_func): r"""Copies the function signature from the wrapped function to the wrapping function. """ func.__name__ = with_func.__name__ func.__doc__ = with_func.__doc__ func.__dict__.update(with_func.__dict__) return func
def decorator(func): r"""Makes the passed decorators to support optional args. """ def wrapper(__decorated__=None, *Args, **KwArgs): if __decorated__ is None: # the decorator has some optional arguments. return lambda _func: func(_func, *Args, **KwArgs) else: return func(__decorated__, *Args, **KwArgs) return wrap(wrap...
def task(__decorated__=None, **Config): r"""A decorator to make tasks out of functions. Config: * name (str): The name of the task. Defaults to __decorated__.__name__. * desc (str): The description of the task (optional). * alias (str): The alias for the task (optional). """ if isinstance(__decorated__, tuple): # the t...
def arg(name=None, **Config): # wraps the _arg decorator, in order to allow unnamed args r"""A decorator to configure an argument of a task. Config: * name (str): The name of the arg. When ommited the agument will be identified through the order of configuration. * desc (str): The description of the arg (optional). * t...
def _arg(__decorated__, **Config): r"""The worker for the arg decorator. """ if isinstance(__decorated__, tuple): # this decorator is followed by another arg decorator __decorated__[1].insert(0, Config) return __decorated__ else: return __decorated__, [Config]
def group(__decorated__, **Config): r"""A decorator to make groups out of classes. Config: * name (str): The name of the group. Defaults to __decorated__.__name__. * desc (str): The description of the group (optional). * alias (str): The alias for the group (optional). """ _Group = Group(__decorated__, Config) if iscla...
def exit_hook(callable, once=True): r"""A decorator that makes the decorated function to run while ec exits. Args: callable (callable): The target callable. once (bool): Avoids adding a func to the hooks, if it has been added already. Defaults to True. Note: Hooks are processedd in a LIFO order. """ if once and callabl...
def member(Imported, **Config): r"""Helps with adding imported members to Scripts. Note: Config depends upon the Imported. It could be that of a **task** or a **group**. """ __ec_member__ = Imported.__ec_member__ __ec_member__.Config.update(**Config) state.ActiveModuleMemberQ.insert(0, __ec_member__)
def configure_basic_logging(self, main_module_name, **kwargs): '''Use common logging options to configure all logging. Basic logging configuration is used to set levels for all logs from the main module and to filter out logs from other modules unless they are of one level in priority higher. :param main_module_name: n...
other_filter = OtherLoggingFilter(main_module_name, other_log_level) for handler in logging.root.handlers: handler.addFilter(other_filter)
def save(self, conflict_resolver=choose_mine): '''Save all options in memory to the `config_file`. Options are read once more from the file (to allow other writers to save configuration), keys in conflict are resolved, and the final results are written back to the file. :param conflict_resolver: a simple lambda or func...
def kw_str_parse(a_string): """convert a string in the form 'a=b, c=d, e=f' to a dict""" try: return dict((k, eval(v.rstrip(','))) for k, v in kw_list_re.findall(a_string)) except (AttributeError, TypeError): if isinstance(a_string, collections.Mapping): return a_string return {}
def is_not_null_predicate( raw_crash, dumps, processed_crash, processor, key='' ): """a predicate that converts the key'd source to boolean. parameters: raw_crash - dict dumps - placeholder in a fat interface - unused processed_crash - placeholder in a fat interface - unused processor - placeholder in a fat interface -...
def predicate(self, *args, **kwargs): """the default predicate for Support Classifiers invokes any derivied _predicate function, trapping any exceptions raised in the process. We are obligated to catch these exceptions to give subsequent rules the opportunity to act. An error during the predicate application is a failu...
def action(self, *args, **kwargs): """the default action for Support Classifiers invokes any derivied _action function, trapping any exceptions raised in the process. We are obligated to catch these exceptions to give subsequent rules the opportunity to act and perhaps mitigate the error. An error during the action app...
def act(self, *args, **kwargs): """gather a rules parameters together and run the predicate. If that returns True, then go on and run the action function returns: a tuple indicating the results of applying the predicate and the action function: (False, None) - the predicate failed, action function not run (True, True) ...
def function_invocation_proxy(fn, proxy_args, proxy_kwargs): """execute the fuction if it is one, else evaluate the fn as a boolean and return that value. Sometimes rather than providing a predicate, we just give the value of True. This is shorthand for writing a predicate that always returns true.""" try: return fn(*p...
def act(self, *args, **kwargs): """gather a rules parameters together and run the predicate. If that returns True, then go on and run the action function returns: a tuple indicating the results of applying the predicate and the action function: (False, None) - the predicate failed, action function not run (True, True) ...
def load_rules(self, an_iterable): """cycle through a collection of Transform rule tuples loading them into the TransformRuleSystem""" self.rules = [ TransformRule(*x, config=self.config) for x in an_iterable ]
def append_rules(self, an_iterable): """add rules to the TransformRuleSystem""" self.rules.extend( TransformRule(*x, config=self.config) for x in an_iterable )
def apply_all_rules(self, *args, **kwargs): """cycle through all rules and apply them all without regard to success or failure returns: True - since success or failure is ignored""" for x in self.rules: self._quit_check() if self.config.chatty_rules: self.config.logger.debug( 'apply_all_rules: %s', to_str(x.__class__) ...
def get_wordset(poems): """get all words""" words = sorted(list(set(reduce(lambda x, y: x + y, poems)))) return words
def compare(stanzas, gold_schemes, found_schemes): """get accuracy and precision/recall""" result = SuccessMeasure() total = float(len(gold_schemes)) correct = 0.0 for (g, f) in zip(gold_schemes, found_schemes): if g == f: correct += 1 result.accuracy = correct / total # for each word, let rhymeset[word] = set of words...
zip(range(wi + 1, stanzasize), g[wi + 1:])))) frhymeset_word = set( map(lambda x: x[0], filter(lambda x: x[1] == f[wi], zip(range(wi + 1, stanzasize), f[wi + 1:])))) if len(grhymeset_word) == 0: continue tot_words += 1 if len(frhymeset_word) == 0: continue # find intersection correct = float(len(grhymeset_word.intersec...
def naive(gold_schemes): """find naive baseline (most common scheme of a given length)?""" scheme_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', 'schemes.json') with open(scheme_path, 'r') as f: dist = json.loads(f.read()) best_schemes = {} for i in dist.keys(): if not dist[i]: continue best_s...
def less_naive(gold_schemes): """find 'less naive' baseline (most common scheme of a given length in subcorpus)""" best_schemes = defaultdict(lambda: defaultdict(int)) for g in gold_schemes: best_schemes[len(g)][tuple(g)] += 1 for i in best_schemes: best_schemes[i] = tuple(max(best_schemes[i].items(), key=lambda x: x[1...
def requires_git(func: Callable) -> Callable: """ Decorator to ensure `git` is accessible before calling a function. :param func: the function to wrap :return: the wrapped function """ def decorated(*args, **kwargs): try: run([GIT_COMMAND, "--version"]) except RunException as e: raise RuntimeError("`git` does not appea...
def get_git_root_directory(directory: str): """ Gets the path of the git project root directory from the given directory. :param directory: the directory within a git repository :return: the root directory of the git repository :exception NotAGitRepositoryException: raised if the given directory is not within a git rep...
def get_directory_relative_to_git_root(directory: str): """ Gets the path to the given directory relative to the git repository root in which it is a subdirectory. :param directory: the directory within a git repository :return: the path to the directory relative to the git repository root """ return os.path.relpath(os...
def printStack(self,wrappedStack,include=None,filters=["*"]): """Prints the stack""" rawStack = wrappedStack['rawStack'] print "==== Stack {} ====".format(rawStack.name) print "Status: {} {}".format(rawStack.stack_status,defaultify(rawStack.stack_status_reason,'')) for resourceType, resources in wrappedStack['resources...
def do_browse(self,args): """Open the current stack in a browser.""" rawStack = self.wrappedStack['rawStack'] os.system("open -a \"Google Chrome\" https://us-west-2.console.aws.amazon.com/cloudformation/home?region=us-west-2#/stack/detail?stackId={}".format(rawStack.stack_id))
def do_refresh(self,args): """Refresh view of the current stack. refresh -h for detailed help""" self.wrappedStack = self.wrapStack(AwsConnectionFactory.instance.getCfResource().Stack(self.wrappedStack['rawStack'].name))
def do_print(self,args): """Print the current stack. print -h for detailed help""" parser = CommandArgumentParser("print") parser.add_argument('-r','--refresh',dest='refresh',action='store_true',help='refresh view of the current stack') parser.add_argument('-i','--include',dest='include',default=None,nargs='+',help='re...
def do_resource(self,args): """Go to the specified resource. resource -h for detailed help""" parser = CommandArgumentParser("resource") parser.add_argument('-i','--logical-id',dest='logical-id',help='logical id of the child resource'); args = vars(parser.parse_args(args)) stackName = self.wrappedStack['rawStack'].name...
def do_asg(self,args): """Go to the specified auto scaling group. asg -h for detailed help""" parser = CommandArgumentParser("asg") parser.add_argument(dest='asg',help='asg index or name'); args = vars(parser.parse_args(args)) print "loading auto scaling group {}".format(args['asg']) try: index = int(args['asg']) asgSu...
def do_eni(self,args): """Go to the specified eni. eni -h for detailed help.""" parser = CommandArgumentParser("eni") parser.add_argument(dest='eni',help='eni index or name'); args = vars(parser.parse_args(args)) print "loading eni {}".format(args['eni']) try: index = int(args['eni']) eniSummary = self.wrappedStack['re...
def do_logGroup(self,args): """Go to the specified log group. logGroup -h for detailed help""" parser = CommandArgumentParser("logGroup") parser.add_argument(dest='logGroup',help='logGroup index or name'); args = vars(parser.parse_args(args)) print "loading log group {}".format(args['logGroup']) try: index = int(args['...
def do_stack(self,args): """Go to the specified stack. stack -h for detailed help.""" parser = CommandArgumentParser("stack") parser.add_argument(dest='stack',help='stack index or name'); args = vars(parser.parse_args(args)) print "loading stack {}".format(args['stack']) try: index = int(args['stack']) stackSummary = s...
def do_template(self,args): """Print the template for the current stack. template -h for detailed help""" parser = CommandArgumentParser("template") args = vars(parser.parse_args(args)) print "reading template for stack." rawStack = self.wrappedStack['rawStack'] template = AwsConnectionFactory.getCfClient().get_templat...
def do_copy(self,args): """Copy specified id to stack. copy -h for detailed help.""" parser = CommandArgumentParser("copy") parser.add_argument('-a','--asg',dest='asg',nargs='+',required=False,default=[],help='Copy specified ASG info.') parser.add_argument('-o','--output',dest='output',nargs='+',required=False,default=...
def do_parameter(self,args): """Print a parameter""" parser = CommandArgumentParser("parameter") parser.add_argument(dest="id",help="Parameter to print") args = vars(parser.parse_args(args)) print "printing parameter {}".format(args['id']) try: index = int(args['id']) parameter = self.wrappedStack['resourcesByTypeName'...
def clone_data(self, data_path): """ Clones data for given data_path: :param str data_path: Git url (git/http/https) or local directory path """ self.data_path = data_path data_url = urlparse.urlparse(self.data_path) if data_url.scheme in SCHEMES or (data_url.scheme == '' and ':' in data_url.path): data_name = os.path....
{}'.format(err)) branch = out.strip() if branch != self.branch: if not synced: msg = ('Local branch is `{}`, but requested `{}` and you have uncommitted/pushed changes\n' 'You must either clear your local data or manually checkout the correct branch.' ).format(branch, self.branch) raise GitDataBranchException(msg) else...
delete if already there shutil.rmtree(data_destination) self.logger.info('Cloning config data from {}'.format(self.data_path)) if not os.path.isdir(data_destination): cmd = "git clone -b {} --depth 1 {} {}".format(self.branch, self.data_path, data_destination) rc, out, err = self.cmd.gather(cmd) if rc: raise GitDataExc...
def commit(self, msg): """ Commit outstanding data changes """ self.logger.info('Commit config: {}'.format(msg)) with Dir(self.data_path): self.cmd.check_assert('git add .') self.cmd.check_assert('git commit --allow-empty -m "{}"'.format(msg))
def push(self): """ Push changes back to data repo. Will of course fail if user does not have write access. """ self.logger.info('Pushing config...') with Dir(self.data_path): self.cmd.check_assert('git push')
def prompt_for_new_password(): """ Prompt the user to enter a new password, with confirmation """ while True: passw = getpass.getpass() passw2 = getpass.getpass() if passw == passw2: return passw print 'Passwords do not match'
def unicode2Date(value, format=None): """ CONVERT UNICODE STRING TO UNIX TIMESTAMP VALUE """ # http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior if value == None: return None if format != None: try: if format.endswith("%S.%f") and "." not in value: value += ".000" return _unix2Date(datetime2...
FOR DEBUGGING pass formats = [ "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%S.%f" ] for f in formats: try: return _unix2Date(datetime2unix(datetime.strptime(value, f))) except Exception: pass deformats = [ "%Y-%m",# eg 2014-07-16 10:57 +0200 "%Y%m%d", "%d%m%Y", "%d%m%y", "%d%b%Y", "%d%b%y", "%d%B%Y", "%d%B%y", "%Y%m%d%H%M%S",...
def _mod(value, mod=1): """ RETURN NON-NEGATIVE MODULO RETURN None WHEN GIVEN INVALID ARGUMENTS """ if value == None: return None elif mod <= 0: return None elif value < 0: return (value % mod + mod) % mod else: return value % mod
def listIDs(basedir): """Lists digital object identifiers of Pairtree directory structure. Walks a Pairtree directory structure to get IDs. Prepends prefix found in pairtree_prefix file. Outputs to standard output. """ prefix = '' # check for pairtree_prefix file prefixfile = os.path.join(basedir, 'pairtree_prefix') if...
def _set_conn(self): """Establish connection to the server""" if self._tls: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) try: conn = ldap.initialize(self._url) conn.set_option(ldap.OPT_NETWORK_TIMEOUT, self._timeout) conn.simple_bind_s(self._binddn, self._bindpw) except Exception as e: if hasattr(...
def _get_ldap_msg(e): """Extract LDAP exception message""" msg = e if hasattr(e, 'message'): msg = e.message if 'desc' in e.message: msg = e.message['desc'] elif hasattr(e, 'args'): msg = e.args[0]['desc'] return msg
def _search(self, base, fltr, attrs=None, scope=ldap.SCOPE_SUBTREE): """Perform LDAP search""" try: results = self._conn.search_s(base, scope, fltr, attrs) except Exception as e: log.exception(self._get_ldap_msg(e)) results = False return results
def _set_fqdn(self): """Get FQDN from LDAP""" results = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-localhost'], scope=ldap.SCOPE_BASE ) if not results and type(results) is not list: r = None else: dn, attrs = results[0] r = attrs['nsslapd-localhost'][0].decode('utf-8') self._fqdn = r log.debug('FQDN: %s' %...
def _set_hostname_domain(self): """Extract hostname and domain""" self._hostname, _, self._domain = str(self._fqdn).partition('.') log.debug('Hostname: %s, Domain: %s' % (self._hostname, self._domain))
def _set_ip(self): """Resolve FQDN to IP address""" self._ip = socket.gethostbyname(self._fqdn) log.debug('IP: %s' % self._ip)
def _set_base_dn(self): """Get Base DN from LDAP""" results = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-defaultnamingcontext'], scope=ldap.SCOPE_BASE ) if results and type(results) is list: dn, attrs = results[0] r = attrs['nsslapd-defaultnamingcontext'][0].decode('utf-8') else: raise Exception self._base...
def users(self, user_base='active'): """Return dict of users""" if not getattr(self, '_%s_users' % user_base): self._get_users(user_base) return getattr(self, '_%s_users' % user_base)
def _get_users(self, user_base): """"Get users from LDAP""" results = self._search( getattr(self, '_%s_user_base' % user_base), '(objectClass=*)', ['*'], scope=ldap.SCOPE_ONELEVEL ) for dn, attrs in results: uid = attrs.get('uid')[0].decode('utf-8', 'ignore') getattr(self, '_%s_users' % user_base)[uid] = FreeIPAUser(dn...
def find_users_by_email(self, email, user_base='active'): """Return list of users with given email address""" users = [] for user in getattr(self, 'users')(user_base).values(): mail = user.mail if mail and email in mail: users.append(user) log.debug('%s users with email address %s: %s' % (user_base.capitalize(), email,...
def _get_anon_bind(self): """Check anonymous bind :return: 'on', 'off', 'rootdse' or None """ r = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-allow-anonymous-access'], scope=ldap.SCOPE_BASE ) dn, attrs = r[0] state = attrs.get('nsslapd-allow-anonymous-access')[0].decode('utf-8', 'ignore') if state in ['on',...
def _ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=dict): '''Loads the contents of the YAML stream into :py:class:`collections.OrderedDict`'s See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts ''' class OrderedLoader(Loader): pass def construct_mapping...
def expand(data): '''Generates configuration sets based on the YAML input contents For an introduction to the YAML mark-up, just search the net. Here is one of its references: https://en.wikipedia.org/wiki/YAML A configuration set corresponds to settings for **all** variables in the input template that needs replacing....
a list, then we'll iterate over it for every possible combination of elements in the lists. If the element in question is not a list, then it is considered unique and repeated for each yielded configuration set. Example .. code-block:: yaml name: [john, lisa] version: [v1, v2] text: > hello, world! Should yield to the ...
{'name': 'john', 'version': 'v1', '_unique': ['i1', 'i2']}, {'name': 'john', 'version': 'v2', '_unique': ['i1', 'i2']}, {'name': 'lisa', 'version': 'v1', '_unique': ['i1', 'i2']}, {'name': 'lisa', 'version': 'v2', '_unique': ['i1', 'i2']}, ] Parameters: data (str): YAML data to be parsed Yields: dict: A dictionary of k...
def generate(variables, template): '''Yields a resolved "template" for each config set and dumps on output This function will extrapolate the ``template`` file using the contents of ``variables`` and will output individual (extrapolated, expanded) files in the output directory ``output``. Parameters: variables (str): A...
def aggregate(variables, template): '''Generates a resolved "template" for **all** config sets and returns This function will extrapolate the ``template`` file using the contents of ``variables`` and will output a single (extrapolated, expanded) file. Parameters: variables (str): A string stream containing the variable...
def _delete_sourcesystem_cd(conn: Connection, table: Table, sourcesystem_cd: str) -> int: """ Remove all table records with the supplied upload_id :param conn: sql connection :param table: table to modify :param sourcesystem_cd: target sourcesystem code :return: number of records removed """ return conn.execute(delete(...
def _delete_upload_id(conn: Connection, table: Table, upload_id: int) -> int: """Remove all table records with the supplied upload_id :param conn: sql connection :param table: table to modify :param upload_id: target upload_id :return: number of records removed """ return conn.execute(delete(table).where(table.c.upload...
def _nested_fcn(f: Callable, filters: List): """ Distribute binary function f across list L :param f: Binary function :param filters: function arguments :return: chain of binary filters """ return None if len(filters) == 0 \ else filters[0] if len(filters) == 1 \ else f(filters[0], I2B2CoreWithUploadId._nested_fcn(f, f...
def _add_or_update_records(cls, conn: Connection, table: Table, records: List["I2B2CoreWithUploadId"]) -> Tuple[int, int]: """Add or update the supplied table as needed to reflect the contents of records :param table: i2b2 sql connection :param records: records to apply :return: number of records added / modified """ n...
for k, v in as_dict(record).items() if v is not None and k not in cls._no_update_fields and k not in cls.key_fields} vals = [table.c[k] != v for k, v in known_values.items()] val_filter = I2B2CoreWithUploadId._nested_fcn(or_, vals) known_values['update_date'] = record.update_date upd = update(table).where(and_(key_filt...
def equality(self, other): """Calculate equality based on equality of all group items.""" if not len(self) == len(other): return False return super().equality(other)
def similarity(self, other): """Calculate similarity based on best matching permutation of items.""" # Select the longer list as the basis for comparison if len(self.items) > len(other.items): first, second = self, other else: first, second = other, self items = list(first.items) # backup items list length = len(items)...
async def peers(client: Client, leaves: bool = False, leaf: str = "") -> dict: """ GET peering entries of every node inside the currency network :param client: Client to connect to the api :param leaves: True if leaves should be requested :param leaf: True if leaf should be requested :return: """ if leaves is True: ret...