content
stringlengths
42
6.51k
def prepare_input_parameters(caller, default_parameters, custom_parameters=None): """Prepares an input parameter dictionary for operator benchmarks. Performs the union of default_parameters and custom_parameters i.e., takes the parameters provided, if any, in custom_parameters and replaces them in the defau...
def get_create_tables_queries(graph_name, backend): """Format a SQlite CREATE TABLE statement with the name of the RDF graph to insert.""" if backend == "sqlite": return [( f"CREATE TABLE {graph_name} (" f"subject TEXT, " f"predicate TEXT, " f"object TEXT)...
def check_mod(module_name, version=None): """ returns true if module of input version can be imported """ try: new_module = __import__(module_name) except: return False if version is not None: if new_module.__version__ == version: return True else: ...
def get_4x4_homothety(x,y,z): """return a homothety 4x4 matrix""" a= [x,0,0,0] b= [0,y,0,0] c= [0,0,z,0] d= [0,0,0,1] return [a,b,c,d]
def findSumPairs(data, sum): """ This function returns the pair elements which result the desired sum """ pairs = [] for i in range(len(data)): for j in range(i+1, len(data)): if data[i]+data[j] == sum: pairs.append(tuple([data[i],data[j]])) return pairs
def num_to_bytes(num): """Converts the number to a bytestring""" length = (num.bit_length() + 7) // 8 return num.to_bytes(length, "big")
def read(filepath): """ Read the entire text contents from a file into a string. """ fc = '' with open(filepath, 'rt') as fin: fc = fin.read() return fc
def merge(line): """ Helper function that merges a single row or column in 2048 """ zeros = [] for _ in line: zeros.append(0) result_index = 0 #in this step restlt = [0,0,0,0] result = zeros[:] for _ in range(len(line)): if line[_] != 0: result[result_inde...
def convert_iface(iface): """Convert iface string like 'any', 'eth', 'eth0' to iptables iface naming like *, eth+, eth0. """ if iface == 'any': return '*' else: # append '+' quantifier to iface if not iface[-1].isdigit(): iface += '+' return iface
def select_case(select_key, next_state): """ This method returns select case for a parser :param select_key: the action to read registers :type select_key: str :param next_state: the next state associated with the select key :type next_state: str :returns: str -- the code in plain text ...
def all_equal(items): """Test whether all items in list are equal """ return all(item == items[0] for item in items)
def selection(t1, f): """ Perform select operation on table t that satisfy condition f. Example: > R = [["A", "B", "C"], [1, 2, 3], [4, 5, 6]] ># Define function f that returns True iff > # the last element in the row is greater than 3. > def f(row): row[-1] > 3 > select(R, f) [["A"...
def _hgvs_coord_to_ci(s, e): """convert start,end interval in inclusive, discontinuous HGVS coordinates (..,-2,-1,1,2,..) to continuous interbase (right-open) coordinates (..,-2,-1,0,1,..)""" def _hgvs_to_ci(c): assert c != 0, "received CDS coordinate 0; expected ..,-2,-1,1,1,..." retur...
def occurrences(l: list) -> dict: """ 1.4 Return a dictionnary, containing the number of occurrences of an element in a list given in argument """ d = dict() for el in l: d[el] = l.count(el) return d
def double_stuff (things) : """ Returns a new list with doubl ethe values than the previous list """ # accum list new_list = [] # iterate over each item in the prev list for thing in things : # double each item new_elem = thing * 2 # add to the new list new_list.app...
def false_to_none(ctx, param, value): """Convert a false value to a None""" if value: retval = True else: retval = None return retval
def incr_id_after(id, start, n): """Perform the id adjustment necessary for adding n lines before start id. The exact logic is as follows: Suppose start has length k. Find all ids with length at least k, where the first k-1 numbers agree with start, and the k'th number is greater than or equal ...
def get_categorized_testlist(alltests, ucat): """ Sort the master test list into categories. """ testcases = dict() for category in ucat: testcases[category] = list(filter(lambda x: category in x['category'], alltests)) return(testcases)
def escape_char(text: str): """Escape special character for XHTML. Args: text: input string Returns: """ return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def _get_html_content(elements): """Returns the html content from the best element match or another content treated as html. This is totally against the specification but this importer assumes that the text representation is unprocessed markup language from the blog. This is most likely a dialect of H...
def get_name_no_py(context): """return the component name without .py extension (if existing) Args: context (dict): complete package and component transformation Returns: str: component name without possible .py extension. Examples: >>> get_name_no_py({'componentName':"nopy"})...
def select_best_RSS(interested_list, gene_type): """ranks are list as following: perfect, shift perfect, +/-1, shift +/-1""" ranks = [[],[],[],[]] perfect_len = 23 if gene_type == 1: pass elif gene_type == 0: perfect_len = -12 else: print("WANRING: not support IG yet...")...
def round_filters(filters, width_coefficient, depth_divisor): """ Round number of filters based on width multiplier. """ filters *= width_coefficient new_filters = int(filters + depth_divisor / 2) // depth_divisor * depth_divisor new_filters = max(depth_divisor, new_filters) # Make sure th...
def create_profile_name_from_role_arn( role_arn, account_alias, profile_name_format ): """Create a profile name for a give role ARN and account alias.""" profile_name = role_arn.split("role/")[-1].replace("/", "-") if profile_name_format == "RoleName-AccountAlias": return f"{profile_name}-{accou...
def path_to_key(path): """Convert path to `key`, by replacing pathseps with periods.""" return path.replace('/', '.').replace('\\', '.')
def traverse_list_backward(tail): """Traverse the linked list in backward direction""" if tail is None: return -1 curr = tail arr = [] while curr: arr.append(curr.data) curr = curr.prev return ' '.join(map(str, arr))
def escape(data): """Escape control characters""" data = data.replace('\x10', '\x10\x10') data = data.replace('\x01', '\x10\x01') data = data.replace('\x04', '\x10\x04') return data
def remove_parens(ingredient): """Remove parentesise from string `ingredient`.""" split1 = ingredient.split('(') if len(split1) == 1: return split1[0] split2 = ' '.join(split1[1:]).split(') ') split2.append('') # append extra item to list in case parens comes last return split1[0] + ' '...
def get_chunk_type(tok): """ Args: tok: id of token, ex 4 idx_to_tag: dictionary {4: "B-PER", ...} Returns: tuple: "B", "PER" """ # tag_name = idx_to_tag[tok] tag_class = tok.split('-')[0] tag_type = tok.split('-')[-1] return tag_class, tag_type
def getOrderedTeamGames(teamGames): """ input: team games output: map team -> ordered list of games (by time) """ orderedTeamGames = {} for team in teamGames: orderedTeamGames[team] = [] currentTeamGames = teamGames[team] keylist = list(currentTeamGames) keylist.s...
def bool_to_int(value): """Translates python booleans to RPC-safe integers""" if value is True: return("1") elif value is False: return("0") else: return(value)
def toString(s): """ Method aimed to convert a string in type str @ In, s, string, string to be converted @ Out, response, string, the casted value """ if type(s) == type(""): return s else: return s.decode()
def goods_to_chores(items:str, preferences_on_goods:list)->list: """ Converts preferences on goods to preferences on chores. :param items: the set of all items :param preferences_on_goods: a list of strings representing bundles of goods, in decreasing order of preference. :return: a list of strings...
def graph6_to_data(string): """Convert graph6 character sequence to 6-bit integers.""" v = [ord(c) - 63 for c in string] if len(v) > 0 and (min(v) < 0 or max(v) > 63): return None return v
def predcedence(operator): """Return the predcedence of an operator.""" if operator in '+-': return 0 elif operator in '*/': return 1
def get_plural(val_list): """ Get Plural: Helper function to return 's' if a list has more than one (1) element, otherwise returns ''. Returns: str: String of 's' if the length of val_list is greater than 1, otherwise ''. """ return 's' if len(val_list) > 1 else ''
def invalid_part(form_list, iban_part): """Check if syntax of the part of IBAN is invalid.""" for lng, typ in form_list: if lng > len(iban_part): lng = len(iban_part) for ch in iban_part[:lng]: a = ("A" <= ch <= "Z") n = ch.isdigit() c = n or a or ...
def filter_blanks_and_comments(s, sep='#') : """ Helper function for kvstring_to_dict. Given 's', one string of the form 'key:value\nkey2:value2\n' (with any number of key value strings), turn it into a list of lines, where the blanks on the ends have been filtered, and any comments at the end-...
def pre_check_state(s,N,args): """ imposes that that a bit with 1 must be preceded and followed by 0, i.e. a particle on a given site must have empty neighboring sites. # Works only for lattices of up to N=32 sites (otherwise, change mask) # """ mask = (0xffffffff >> (32 - N)) # works for la...
def evaluate_percentage_of_code(total_lines_of_code, lines_of_code_per_language): """ Return Percentage of code per language. """ percentage_of_code = {} for key in lines_of_code_per_language.keys(): percentage_of_code[key] = lines_of_code_per_language[key] / total_lines_of_code * 100 r...
def normalize_string_to_speak(to_speak: str) -> str: """ Normalizes spoken strings for TTS engines to handle :param to_speak: String to speak :return: string with any invalid characters removed and punctuation added """ if not to_speak: raise ValueError("Expected a string and got None") ...
def encode_synchsafe_int( i ): """Encode SynchSafe integers for ID3v2 tags""" return ( ( ( i & 0x0FE00000 ) << 3 ) | ( ( i & 0x001FC000 ) << 2 ) | ( ( i & 0x00003F80 ) << 1 ) | ( i & 0x0000007F ) ).to_bytes( 4, 'big' )
def _get_warmup_factor_at_iter(method: str, curr_iter: int, warmup_iters: int, warmup_factor: float) -> float: """Return the learning rate warmup factor at a specific iteration. Parameters ---------- method: str Warmup method; either "constant" or "linear". curr_iter: int Iteration ...
def ordinal(n): """Gets the ordinal string of any int from 1 to 100. Args: n (int): int to get ordinal of Returns: String: ordinal string of n """ # Determines suffix based about n % 10 suffix = ['th', 'st', 'nd', 'rd', 'th'][min(n % 10, 4)] # Updates suffix for special cas...
def name2seq(name): """ :param name: raw video name :return: sequence number of that video """ return int(name.split("_t0")[-1].split("_")[0])
def format_seconds(n: int) -> str: """Format seconds into pretty string format.""" days = int(n // (24 * 3600)) n = n % (24 * 3600) hours = int(n // 3600) n %= 3600 minutes = int(n // 60) n %= 60 seconds = int(n) if days > 0: strtime = f'{days}d{(hours)}h:{minutes}m:{seconds}...
def add_default_config(config: dict): """ The default configuration structure. """ config['crypto'] = {'remote_password_salt_file' : 'salt_file', # Remote file used to store the password salt 'crypt_password' : None } return config
def pretty_print_timediff(delta): """ formats timediff in seconds to readable format """ ms = delta - int(delta) h = int(delta) / 3600 t = int(delta) % 3600 m = t / 60 s = t % 60 return (h, m, float(s) + ms)
def generate_prefixes(vocabulary): """Return a set of unique prefixes from the given list of strings.""" # Generate prefixes using the first half of each string return set(word[:len(word)//2] for word in vocabulary)
def get_inheritors(cls): """Get a set of all classes that inherit from the given class.""" subclasses = set() work = [cls] while work: parent = work.pop() for child in parent.__subclasses__(): if child not in subclasses: subclasses.add(child) w...
def get_python_api_filename(entity_lower: str) -> str: """Returns the default API filename. :param entity_lower: The entity name in lower case. :return: """ return f"{entity_lower}_api.py"
def update_args_dict(args_dict, updater): """Update a dict of arg values with more values from a list or dict.""" if isinstance(updater, list): for arg in updater: key, sep, value = arg.partition('=') if sep == '=': args_dict[key] = value if isinstance(updater, dict): for key, value in...
def _format_for_visualisation(patterns, window, min_pattern_length): """Transform the pattern discovery results into the specified data structure used in the Mupadie visualisation. Args: patterns: The discovered patterns. window: The window parameter as set by the user of the application. min_pattern_length: ...
def timer(start_time, end_time): """ Returns the minutes and seconds. """ time = end_time - start_time mins = int(time / 60) secs = int(time - (mins * 60)) return mins, secs
def get_item(obj, key): """ Use as dict|get_item:key """ if key in obj: return obj[key] return ''
def get_season_later_url(base_url: str) -> str: """Creates the URL for the season later endpoint.""" return f"{base_url}/season/later"
def is_full_qualified_map_name(name): """Checks whether a map-name is fully qualified :param name: Generator configuration entity :type name: str :returns: The result of the check :rtype: bool """ splitted_name = name.rsplit('/') return len(splitted_name) > 1
def required_props(props): """ Pull names of required props from the props object Parameters ---------- props: dict Returns ------- list List of prop names (str) that are required for the Component """ return [prop_name for prop_name, prop in list(props.items()) ...
def some_sample_config(some_sample_path): """Return a list containing the key and the sample path for some config.""" return ["--config", some_sample_path]
def to_jaden_case(string: str) -> str: """ My implementation """ return ' '.join([word.capitalize() for word in string.split()])
def is_long_enough(linedict, cutoff): """ a nicer version of filter_results_by_length, not tested yet though """ prefixes = ("s", "q") def percent_match(prefix): length = abs(float(linedict[prefix + "start"]) - float( linedict[prefix + "end"])) if length / float(linedict[prefix ...
def is_even(num): """ Check for number is even. """ return num % 2 == 0
def cluster_ips(test_vars): """ Return a list of known cluster IPs. The cluster mgmt IP, at a minimum, must be known. Cluster node and vserver IPs are also added to the list of cluster IPs that is returned. """ c_ips = [test_vars["cluster_mgmt_ip"]] if "cluster_node_ips" in test_vars: ...
def split(sorted_data_points, attr_index, split_value): """Splits a list of data points sorted by a given element into two lists with one list containing tuples <= split_value and one list containing tuples > split_value. :param sorted_data_points: List of data points sorted by their values of the a...
def add_pem_headfoot(public_key): """ Return string, representing PEM text for a public key Keyword Parameters: public_key -- String, representing the public key text >>> add_pem_headfoot('foo') '-----BEGIN PUBLIC KEY-----\\nfoo\\n-----END PUBLIC KEY-----' """ preamble = "-----BEGIN P...
def is_nurse(user): """ Helper function that checks if a user is a nurse :param user: The user to be checked :return: True if user is a nurse """ if user: return user.groups.filter(name='Nurse').count() != 0 return False
def upthendown_bounce( new_config, new_app_running, happy_new_tasks, old_app_live_tasks, ): """Starts a new app if necessary; only kills old apps once all the requested tasks for the new version are running. See the docstring for brutal_bounce() for parameters and return value. """ if n...
def cases_change(average_cases, new_cases): """ WHAT IT DOES: Calculates if the newest number of cases is less than or greater than the average cases over 14 days. PARAMETERS: An average cases integer, a new cases integer RETURNS: A string message with the percent increase or decrease of cases """...
def gen_overlay_dirs(environment, region): """Generate possible overlay directories.""" return [ # Give preference to explicit environment-region dirs "%s-%s" % (environment, region), # Fallback to environment name only environment, ]
def format_message(data, split, name): """Formats a given byte message in hex format split into payload and subcommand sections. :param data: A series of bytes :type data: bytes :param split: The location of the payload/subcommand split :type split: integer :param name: The name featured in...
def ComplementConstraint(A, b, C): """Complements a constraint and RHS for a complementing set C.""" A_C = A[:] b_C = b for c in C: A_C[c - 1] *= -1 b_C -= A[c - 1] return A_C, b_C
def getid(obj): """ Abstracts the common pattern of allowing both an object or an object's ID (UUID) as a parameter when dealing with relationships. """ # Try to return the object's UUID first, if we have a UUID. try: if obj.uuid: return obj.uuid except AttributeError: ...
def check_if_key_exists(a_key, expected_dict): """ Return True or False if a_key exists in the expected_dict dictionary. """ for key, value in expected_dict.items(): if key == a_key: return True elif isinstance(value, dict): return check_if_key_exists(a_key, value...
def safe_octal(octal_value): """ safe_octal(octal_value) -> octal value in string This correctly handles octal values specified as a string or as a numeric. """ try: return oct(octal_value).replace('o', '') # fix futurized octal value with 0o prefix except TypeError: return str(octal_value).replace...
def relative_rv(wav_1, wav_2): """Calculate the radial velocity difference between two wavelength values.""" c = 299792.458 # km / s difference = wav_2 - wav_1 relative = difference / wav_1 return relative * c
def make_car(car_brand, car_model, **optionals): """[Make a car with a bunch of specifications] Args: manufacturer (str): Car brand model (str): Car model *Kwargs: optionals (key, value): field => value Returns: dict: {brand: car_brand, model: car_model, key: value} ...
def is_valid_walk(walk): """ You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- e...
def mult(value, arg): """Multiplies the arg and the value""" return float(value) * int(arg)
def merge_recursive_in_place(d, d2): """ Parameters ---------- d d2 Returns ------- """ if d2 is None: return d if isinstance(d, dict) and isinstance(d2, dict): for k in set(d2.keys()) & set(d.keys()): d[k] = merge_recursive_in_place(d.get(k, None...
def create_new_question_entry(question, answers): """ Creates a new entry for a question in the .json file (with id=1) and returns it """ new_question_entry = { 'question': question, 'answers': [] } for answer in answers: answer_entry = { "answer": answer, ...
def regula_falsi(f, interval): """ Splits an interval in two using the regula falsi method. """ a, b = interval c = a - f(a) * (b - a)/(f(b) - f(a)) return [[a, c], [c, b]]
def determine_mode(row): """ Args: row : a row in a pandas DataFrame Returns: new column in the DataFrame, that identifies when heat pump is heating or cooling """ if row['heat_flow_rate'] > 0: return 'Heating' else: return 'Cooling'
def convex_hull(points): """Calculating 2D convex hull using Graham algorithm (XY plane). Based on https://leetcode.com/problems/erect-the-fence/discuss/103300/Detailed-explanation-of-Graham-scan-in-14-lines-(Python) """ # Computes the cross product of vectors p1p2 and p2p3 # value of...
def bh_mass_from_bulge_mass(bulge_mass): """ Kormendy & Ho (2013) fitting function for the Mbh--Mbulge power law relation. Parameters ---------- bulge_mass : ndarray Numpy array of shape (ngals, ) storing the stellar mass of the bulge in units of solar mass assuming h=0.7 Retur...
def postprocess(preds): """ Postprocess summaries using rules. """ processed = [] for ps in preds: new = [] if len(ps) > 2 and ps[-1] != '.' and ps[-2] == '.': ps = ps[:-1] for i, p in enumerate(ps): if i > 0 and ps[i-1] == p: continue ...
def template_format(template): """Parse template string to identify digit formatting, e.g. a template med#####.xml.gz will give output (#####, {:05}) """ num_hashes = sum([1 for c in template if c == "#"]) return "#"*num_hashes, "{:0" + str(num_hashes) + "}"
def _get_diag_map(dim): """Generates lexicographic mapping to diagonal in a serialized matrix-type For input dimension dim we calculate mapping to * in Matrix M below |* 0 0| M = |0 * 0| |0 0 *| in a dimension agnostic way. """ # Preallocate mapping_list = [None] * dim ...
def creditsValidator (creditsValue): """Check that creditsValue is valid number of credits. Credit range: 1 <= creditsValue <= 4 :param int creditsValue: The number of credits to check :except TypeError: creditsValue should be an int :return: The number of credits if valid, else None :rtyp...
def get_portf_delete_data_toggle(uid): """ Add this function inside a button or a href """ return_data = 'data-toggle="modal" data-target="#popup_delete_'+ str(uid) +'"' return return_data
def round(x: int, divisor: int) -> int: """Round x to the multiplicity of divisor not greater than x""" return int(x / divisor) * divisor
def _provenance_str(provenance): """Utility function used by compare_provenance to print diff """ return ["%s==%s" % (key, value) for (key, value) in provenance]
def odd_snap(number: int) -> int: """snaps a number to the next odd number""" if (number % 2) == 0: return number + 1 else: return number
def require_all(json, keys): """ Require that the given dict-from-json-object contains all given keys """ for k in keys: if k not in json: return False return True
def query_string(query_dict): """Convert a dictionary into a query string URI. Args: query_dict (dict): Dictionary of query keys and values. Returns: str: Query string, i.e. ?query1=value&query2=value. """ queries = [ '{0}={1}'.format(key, query_dict[key]) for key in query_...
def process_events(data): """ Process response events data, return list of event dictionaries: About events: [ [timestamp, event type, event text], [timestamp, event type, event text], ... ] Sample output showing events as a list of lists { "active"...
def safe_index(alist, elem): """ Return index of element e in list l. If e is not present, return the last index """ try: return alist.index(elem) except ValueError: return len(alist) - 1
def getName(string): """Grab the name as written in files (Helper)""" newString = '' reachedLetter = False for char in string: if char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': reachedLetter = True if reachedLetter == True and char == '\n': break if reach...
def collector_url_from_hostport(host, port): """ Create an appropriate collector URL given the parameters. """ return ''.join(['http://', host, ':', str(port), '/api/v1/spans'])
def reverse_dict(dic): """ Return a reversed dictionary. Each former value will be the key of a list of all keys that were mapping to it in the old dict. """ return {new_key: [old_key for old_key, old_val in dic.items() if old_val == new_key] for new_key in set(dic.values()...
def is_non_ascii(text: str) -> bool: """ Check if text has non-ascci characters. Useful heuristic to find text containing emojis and non-english characters. Args: text: Sentence Returns: True if the text contains non-ascii characters. """ try: text.encode("asci...