content
stringlengths
42
6.51k
def _read_data_configs(config_data): """Creates list of dictionaries. Each dict is a set of config parameters for the data. Args: config_data: dictionary with data parameters Returns: list with all config parameters. """ parameters_data = [] for config in config_data: parameters = {} if config['data_name'] == 'simple_linear': parameters['data_name'] = config['data_name'] parameters['sample_size'] = config['data_n'] parameters['num_covariates'] = config['data_num_covariates'] parameters['noise'] = config['data_noise'] parameters['linear'] = config['data_linear'] else: parameters['data_name'] = config['data_name'] parameters['data_path'] = config['data_path'] parameters['data_low_dimension'] = config['data_low_dimension'] parameters_data.append(parameters) return parameters_data
def print_failed(failed): """Print failed counts.""" lines = [] for key, val in sorted(failed.items()): if key != 'failed-cutoff': pretty_key = key.replace('-', ' ').title() lines.append(f' {pretty_key}: {len(val)}') return '\n'.join(lines)
def GetCmdReturn(shell_text, cmd): """Return the result of a command launched in MicroPython :param shell_text: The text catched on the shell panel :type shell_text: str :param cmd: The cmd return asked :type cmd: str :return: the return of the command searched :rtype: str """ if cmd == "": return "clean" try: return_cmd = shell_text.split(cmd) return_cmd = return_cmd[len(return_cmd) - 1] return_cmd = return_cmd[:-4] except Exception: print("Error command back: |" + shell_text + "|") return "err" return return_cmd
def choose_best(ordered_choices, possible, check, default=None): """ Select the best xref from several possible xrefs given the ordered list of xref database names. This function will iterate over each database name and select all xrefs that come from the first (most preferred) database. This uses the check function to see if the database contains the correct information because this doesn't always just check based upon the database names or xref, but also the rna_type (in some cases). Using a function gives a lot of flexibility in how we select the acceptable xrefs. Parameters ---------- ordered_choices : list A list of several possible xref database names. These should be in the order in which they are preferred. possible : list The list of xrefs to find the best for. check : callable A callable object to see if given xref and database name match. default : obj, None The default value to return if we cannot find a good xref. Returns ------- selected : obj The list of xrefs which are 'best' given the choices. If there is no good xref the default value is returned. """ for choice in ordered_choices: found = [entry for entry in possible if check(choice, entry)] if found: return (choice, found) return (None, default)
def bracket_block(text): """ finds start and end of the first bracketed block """ istart=text.find('(') cursor=istart if cursor != -1: counter=1 while (cursor<len(text)) and counter>0: cursor+=1 if text[cursor]=='(': counter += 1 elif text[cursor]==')': counter -= 1 return istart, cursor
def extract_longitude(input_string): """ Extracts the longitude from the provided text, value is all in degrees and negative if West of London. :param input_string: Text to extract the longitude from. :return: Longitude """ if "E" in input_string: find_me = "E" elif "W" in input_string: find_me = "W" else: # 9999 is a non-sensical value for Lat or Lon, allowing the user to # know that the GPS unit was unable to take an accurate reading. return 9999 index = input_string.index(find_me) deg_start = index - 12 deg_end = index - 9 deg = input_string[deg_start:deg_end] min_start = index - 9 min_end = index - 1 deg_decimal = input_string[min_start:min_end] longitude = (float(deg)) + ((float(deg_decimal)) / 60) if find_me == "W": longitude *= -1 return longitude
def command( *args ): """ Returns the command as a string joining the given arguments. Arguments with embedded spaces are double quoted, as are empty arguments. """ cmd = '' for s in args: if cmd: cmd += ' ' if not s or ' ' in s: cmd += '"'+s+'"' else: cmd += s return cmd
def find_stem(arr): """ From https://www.geeksforgeeks.org/longest-common-substring-array-strings/ """ # Determine size of the array n = len(arr) # Take first word from array # as reference s = arr[0] ll = len(s) res = "" for i in range(ll): for j in range(i + 1, ll + 1): # generating all possible substrings of our ref string arr[0] i.e s stem = s[i:j] k = 1 for k in range(1, n): # Check if the generated stem is common to to all words if stem not in arr[k]: break # If current substring is present in all strings and its length is # greater than current result if (k + 1 == n and len(res) < len(stem)): res = stem return res
def latex_var(name, value, desc=None, xspace=True): """Create a variable NAME with a given VALUE. Primarily for output to LaTeX. Returns a string.""" xspace_str = r"\xspace" if xspace else "" return "".join(['\\newcommand{\\', str(name), '}{', str(value), xspace_str, '}'] + ([' % ', desc] if desc else []) + ['\n'])
def has_two_elements_that_sum_bonus(elements, k): """ Bonus: This implementation is a bit uglier, but it's still O(n) space and goest over it once """ required = set() for e in elements: difference = k - e if e in required: return True else: required.add(difference) return False
def enforce_min_sites(cache, min_sites): """Remove blocks with fewer than min_sites informative sites and then merge adjacent blocks in the same state.""" cache = [c for c in cache if c['informative-sites'] >= min_sites] if len(cache) < 2: return cache icache = [cache[0]] for i, c in enumerate(cache[1:]): if c['same'] != icache[-1]['same'] or c['chrom'] != icache[-1]['chrom']: icache.append(c) continue icache[-1]['end'] = c['end'] icache[-1]['informative-sites'] += c['informative-sites'] return icache
def environment_setting_format(value): """Space-separated values in 'key=value' format.""" try: env_name, env_value = value.split('=') except ValueError: message = ("Incorrectly formatted environment settings. " "Argument values should be in the format a=b c=d") raise ValueError(message) return {'name': env_name, 'value': env_value}
def sidebar_update(res): """[summary] Args: res ([type]): [description] Returns: [type]: [description] """ sidebar_updates = { "event": "sidebar_update", "plugin_id": "sales.zuri.chat", "data": { "name": "Company Sales Prospects", "group_name": "SALES", "show_group": False, "button_url": "/sales", "public_rooms": [res], "joined_rooms": [res], }, } return sidebar_updates
def get_minimun(list_values): """ function to obtain the min. score of ppmi :param list_values: :return: """ min_score = min(list_values) return min_score
def square_params(x_initial, x, y_initial, y): """ Calculates square parameters acquired from the mouse movements for rendering the square on the image. """ side = abs(y_initial - y) x_top = round(x - side/2) x_bottom = round(x + side/2) y_top = min(y_initial, y) y_bottom = max(y_initial, y) return (x_top, y_top), (x_bottom, y_bottom), side
def _extra_args_to_dict(extra_args): """Parses comma-separated list of flag_name=flag_value to dict.""" args_dict = {} if extra_args is None: return args_dict for extra_arg in extra_args.split(','): (flag_name, flag_value) = extra_arg.split('=') flag_name = flag_name.strip('-') # Check for boolean values. if flag_value.lower() == 'true': flag_value = True elif flag_value.lower() == 'false': flag_value = False args_dict[flag_name] = flag_value return args_dict
def eliminate_internal_polygons(polys_in): """Eliminate any polygons in a list that are fully contained within another polygon""" polys_out = [] poly_num = len(polys_in) # Iterate through list of polygons twice for comparisons for i in range(0,poly_num): within_flag = False for j in range(0,poly_num): # Ignore if comparing a polygon to itself if (i == j): pass # If 'i' is within 'j', switch the flag to true to indicate it else: chk = polys_in[i].within(polys_in[j]) if chk: within_flag = True else: pass # If 'i' still has within_flag == False, append it to the output list if not within_flag: polys_out.append(polys_in[i]) return polys_out
def resource_name(obj_type): """ Transforms an object type into a resource name :param obj_type: The object type, i.e. ``user`` or ``user_reference`` :returns: The name of the resource, i.e. the last part of the URL for the resource's index URL :rtype: str """ if obj_type.endswith('_reference'): # Strip down to basic type if it's a reference obj_type = obj_type[:obj_type.index('_reference')] if obj_type == 'escalation_policy': return 'escalation_policies' else: return obj_type+'s'
def find_smaller_of_a_kind(playable_items): """ Gets list of playable moves from find_3_of_a_kind and adds smaller possible moves to that list For (3b,3g,3r,3s) this will add (3b,3g,3r), (3b,3g,3s), ... :param playable_items: Possible moves, the user can do :return: list of possible moves, including shorter moves """ # print("Finding smaller of a kind") for street in playable_items: if len(street) == 4: for element in street: # print("Removing"+str(element)) smaller_street = street.copy() smaller_street.remove(element) # print(smaller_street) if smaller_street not in playable_items: playable_items.append(smaller_street) return playable_items
def extract_1_gram(token_list): """ Extract 1-gram in a bug report text part """ features = set() for term in token_list: if len(term) > 0: features.add(term) return features
def floor_amount(x): """Returns x floored to n significant figures. from https://mail.python.org/pipermail/tutor/2009-September/071393.html """ factor = 1000000 return 1.0 * int(x * factor) / factor
def one_k_encoding(value, choices): """ Creates a one-hot encoding with an extra category for uncommon values. :param value: The value for which the encoding should be one. :param choices: A list of possible values. :return: A one-hot encoding of the :code:`value` in a list of length :code:`len(choices) + 1`. If :code:`value` is not in :code:`choices`, then the final element in the encoding is 1. """ encoding = [0] * (len(choices) + 1) index = choices.index(value) if value in choices else -1 encoding[index] = 1 return encoding
def madd(a,b,c): """Return a+c*b where a and b are vectors.""" if len(a)!=len(b): raise RuntimeError('Vector dimensions not equal') return [ai+c*bi for ai,bi in zip(a,b)]
def pad_if_needed(inp_list): """ Checks the number of elements in the input list, if number is odd then one element is added input: inp_list, list containing n elements returs: inp_list, list containing n or n+1 elements """ n = len(inp_list) if n % 2 == 0: return inp_list, False else: inp_list.append(0) return inp_list, True
def chocolate_feast(n, c, m): """Hackerrank Problem: https://www.hackerrank.com/challenges/chocolate-feast/problem Function that calculates how many chocolates Bobby can purchase and eat. Problem stated below: Little Bobby loves chocolate. He frequently goes to his favorite 5&10 store, Penny Auntie, to buy them. They are having a promotion at Penny Auntie. If Bobby saves enough wrappers, he can turn them in for a free chocolate. For example, Bobby has n = 15 to spend on bars of chocolate that cost c = 3 each. He can turn in m = 2 wrappers to receive another bar. Initially, he buys 5 bars and has 5 wrappers after eating them. He turns in 4 of them, leaving him with 1, for 2 more bars. After eating those two, he has 3 wrappers, turns in 2 leaving him with 1 wrapper and his new bar. Once he eats that one, he has 2 wrappers and turns them in for another bar. After eating that one, he only has 1 wrapper, and his feast ends. Overall, he has eaten 5 + 2 + 1 + 1 = 9 bars. Args: n (int): Int representing Bobby's initial amount of money c (int): Int representing the cost of a chocolate bar m (int): Int representing the number of wrappers he can turn in for a free bar Returns: int: The number of chocolate bars Bobby can purchase and eat """ # We look for the candies + wrappers candies = n // c wrappers = n // c while wrappers >= m: wrappers -= m wrappers += 1 candies += 1 return candies
def solve_substring_left_to_right(text): """ Solve a flat/small equation that has no nested parentheses Read from left to right, regardless of the operation :param str text: A flat equation to solve :return: The result of the given equation :rtype: int """ text = text.replace("(", "") text = text.replace(")", "") inputs = text.split(" ") total = 0 next_operation = total.__radd__ for input in inputs: if input == "+": next_operation = total.__radd__ elif input == "*": next_operation = total.__rmul__ else: value = int(input) total = next_operation(value) return total
def wxToGtkLabel(s): """ The message catalog for internationalization should only contain labels with wx style ('&' to tag shortcut character) """ return s.replace("&", "_")
def Min(a, b) : """Max define as algrebraic forumal with 'abs' for proper computation on vectors """ return (a + b - abs(b - a)) / 2
def parse_snippets(snippets: dict): """ Parses raw snippets definitions with possibly multiple keys into a plan snippet map """ result = {} for k in snippets.keys(): for name in k.split('|'): result[name] = snippets[k] return result
def version(showfile=True): """ Returns the CVS revision number. """ myversion = "$Id: plotbandpass3.py,v 1.210 2021/02/19 18:10:02 thunter Exp $" if (showfile): print("Loaded from %s" % (__file__)) return myversion
def set_piece(board, index, val): """Sets the nth piece of the provided board""" negative = board < 0 board = board if board >= 0 else -board factor = 10 ** index chopped = board // factor leftover = board % factor old_piece = chopped % 10 chopped -= old_piece chopped += val modified_board = (chopped * factor) + leftover if negative: modified_board *= -1 return modified_board
def quast_qc_check(quast_results, estimated_genome_size): """ QUAST PASS CRITERIA: 1. total length within +/- 10% of expected genome size Args: quast_results (dict): Quast results qc_thresholds (dict): Threshold values for determining QC pass/fail Returns: boolean: Assembly passes our QUAST quality criteria """ total_length = quast_results['total_length'] return bool(total_length <= (estimated_genome_size * 1.1) and \ total_length >= (estimated_genome_size * 0.9))
def create_resumo(fulltext): """ Get the first `resumo_length` (hard-coded) characters from `fulltext` that appear after `beginning_marker` (hard-coded) or small variations of it. If `beginning_marker` is not found, return `fulltext`. """ beginning_marker = 'resolve' resumo_length = 500 if fulltext == None: return None marker_pos = fulltext.find(beginning_marker) if marker_pos != -1: marker_pos = marker_pos + len('resolve') if fulltext[marker_pos] == 'u': marker_pos = marker_pos + 1 if fulltext[marker_pos] == ':': marker_pos = marker_pos + 1 return fulltext[marker_pos: marker_pos + resumo_length].strip() return fulltext[:resumo_length].strip()
def get_tlv(tlvs, cls): """Find the instance of a class in a list""" for tlv in tlvs: if isinstance(tlv, cls): return tlv
def multList(list_a, list_b): """ Zips 'list_a' items with 'list_b' items and multiplies them together :param list_a: list of digits :param list_b: list of digits :return: list of digits """ return [x*y for x, y in zip(list_a, list_b)]
def get_base_worker_instance_name(experiment): """GCE will create instances for this group in the format "w-|experiment|-$UNIQUE_ID". 'w' is short for "worker".""" return 'w-' + experiment
def long_url(l): """This function is defined in order to differntiate website based on the length of the URL""" l= str(l) if len(l) < 53: return 0 elif len(l)>=53 and len(l)<75: return 2 else: return 1
def smtp_config_writer_ssl(kwargs, config): """ Set SSL/TLS config. :param kwargs: Values. Refer to `:func:smtp_config_writer`. :type kwargs: dict :param config: Configuration dictionary. :type config: dict """ if kwargs['is_ssl'] is not None: config['is_ssl'] = str(kwargs['is_ssl']).lower() return config
def get_movies(movie_dict, target_genres): """ Returns a list of movie names that has in its list of genres all genres in target_genres. """ movie_names = [] # Fill in body of the function here. return movie_names
def kml_start(params): """Define basic kml header string""" kmlstart = ''' <Document> <name>%s</name> <open>1</open> <description>%s</description> ''' return kmlstart % (params[0], params[1])
def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
def remove_empty_lines(txt): """ replace("\n\n", "\n") does not work in cases with more than two empty consective empty lines """ return "\n".join(t for t in txt.splitlines() if t.strip())
def calc_score( winning_deck ): """ This function returns the score of the winning player """ score = 0 for point, card in enumerate( winning_deck[::-1] ): score += (point+1) * card return score
def inverse_map(i: int, n: int): """ Accumulative STP of logical variables is bijective. Given a result i (\delta_{2^n}^i), find the corresponding logical values. :return a list of 0/1 """ r = [] while n > 0: if i % 2 == 0: r.append(0) i = i // 2 else: r.append(1) i = (i + 1) // 2 n = n - 1 r.reverse() return r
def compute_unique_id(x): """RPython equivalent of id(x). The 'x' must be an RPython instance. This operation can be very costly depending on the garbage collector. To remind you of this fact, we don't support id(x) directly. """ return id(x) # XXX need to return r_longlong on some platforms
def update_extreme(val, fncn, new_val): """ Calculate min / max in the presence of None values """ if val is None: return new_val else: return fncn(val, new_val)
def multithresh(arr, lbs, ubs, ths): """ Multilevel thresholding of a 1D array. Somewhat similar to bit depth reduction. **Parameters**\n arr: 1D array Array for thresholding. lbs, ubs: list/tuple/array, list/tuple/array Paired lower and upper bounds for each thresholding level. ths: list/tuple/array Thresholds for the values within the paired lower and upper bounds. """ for lb, ub, th in zip(lbs, ubs, ths): if (arr > lb) & (arr < ub): return th
def is_e164_format(phone): """Return true if string is in E.164 format with leading +, for example "+46701740605" """ return len(phone) > 2 and phone[0] == "+" and phone[1:].isdigit() and len(phone) <= 16
def clean_field(node): """Get Edges & Nodes""" return_value = [] if node.get("edges"): fields = node["edges"]["node"] for key, val in fields.items(): if val: items = clean_field(val) return_value.extend([f"{key}.{i}" for i in items]) else: return_value.append(key) return return_value
def load_player(data): """ Loading the player specs. Parameters: data(dict): Nested dictionaries containing all information of the game. Returns: player_specs(tuple): Tuple of player specs. """ player_specs = (data['Player']['Position'], data['Player']['Inventory']) return player_specs
def make_dict(list1, list2): """ Makes a dictionary using the provided lists. Input: list1 (list): List to be used for keys. list2 (list): list to be used for values. Output: out_dict (dict): Dictionary using the input lists """ out_dict = {} i = 0 for item in list1: out_dict[item] = list2[i] if i < len(list2) else None i += 1 return out_dict
def LinkConfig(reset=0, loopback=0, scrambling=1): """Link Configuration of TS1/TS2 Ordered Sets.""" value = ( reset << 0) value |= ( loopback << 2) value |= ((not scrambling) << 3) return value
def solution(dataset: list) -> int: """ "there is a '\n' on the end of the first line but zip() will only go to the sortest length. If both lines have '\n's then they will be equivalent and won't be counted""" return sum(i != j for i, j in zip(*dataset))
def is_image(name, exts=None): """return True if the name or path is endswith {jpg|png|gif|jpeg}""" default = ['jpg', 'png', 'gif', 'jpeg'] if exts: default += exts flag = False for ext in default: if name.lower().endswith(ext): flag = True break return flag
def number_of_samples(X, y, **kwargs): """It represents the total number of samples in the dataset""" try: return X.shape[0] except: return len(X)
def decodeModifiers (modifier): """ {:032b} 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 0 0 1 0 1 0 1 1 0 11 12 13 14 15 31 cmd 00000000000100000000000100001000 b11 alt 00000000000010000000000100100000 b12 ctrl 00000000000001000000000100000001 b13 shft 00000000000000100000000100000010 b14 caps 00000000000000010000000100000000 b15 """ result = [] bincode = '{:032b}'.format(modifier) if bincode[11] == '1': result.append('Cmd') if bincode[12] == '1': result.append('Alt') if bincode[13] == '1': result.append('Ctrl') if bincode[14] == '1': result.append('Shift') if bincode[15] == '1': result.append('Caps') return '+'.join(result)
def split_list_with_len(lst: list, length: int): """ return a list of sublists with len == length (except the last one) """ return [lst[i:i + length] for i in range(0, len(lst), length)]
def get_initial_state(inp): """ return tuple of (terminals,initial assignments) where terminals is a dictionnay key = target and value is a list of start and end coordinates """ terminals = {} assignments = {} for row_ind in range(len(inp)): for col_ind in range(len(inp[row_ind])): current_char = inp[row_ind][col_ind] if current_char != "_": fields = terminals.get(current_char) if fields : fields.append((col_ind,row_ind)) else : terminals[current_char] = [(col_ind,row_ind)] assignments[(col_ind,row_ind)] = current_char return (terminals,assignments)
def add_toc(txt): """Add github-style ToC to start of md content. """ lines = txt.split('\n') toc_lines = [] mindepth = None for line in lines: if not line.startswith('#'): continue parts = line.split() hashblock = parts[0] if set(hashblock) != set(["#"]): continue depth = len(hashblock) if mindepth is None: mindepth = depth depth -= mindepth toc_lines.append("%s- [%s](#%s)" % ( ' ' * 4 * depth, ' '.join(parts[1:]), '-'.join(x.lower() for x in parts[1:]) )) if not toc_lines: return txt return '\n'.join(toc_lines) + "\n\n" + txt
def _merge(old, new): """Concatenate two environment paths avoiding repeats. Here `old` is the environment string before the base class initialize function is called and `new` is the string after the call. The new string will be a fixed string if it is not obtained from the current enviroment, or the same as the old string if obtained from the same enviroment. The aim here is not to append the new string if it is already contained in the old string so as to limit the growth of the environment string. Parameters ---------- old : string Previous enviroment string. new : string New environment string. Returns ------- ret : string Updated environment string. """ if new in old: return old if not old: return new # Neither new nor old is empty. Give old priority. return ';'.join([old, new])
def is_iterable(maybe_iter, unless=(dict)): """ Return whether ``maybe_iter`` is an iterable, unless it's an instance of one of the base class, or tuple of base classes, given in ``unless``. Example:: >>> is_iterable('foo') False >>> is_iterable(['foo']) True >>> is_iterable(['foo'], unless=list) False >>> is_iterable(xrange(5)) True """ if isinstance(maybe_iter, str): return False try: # pragma: no cover iter(maybe_iter) except TypeError: # pragma: no cover return False return not isinstance(maybe_iter, unless)
def get_a_field_set_from_data(data, index=0): """ Extract a unique (non-repeating) columnar set from supplied data It takes parameters: data (data in the form of a list of lists) and optionally: index (by default 0, it is the column field to extract) It returns a set of column field data scanned from all rows """ return { row[index] for row in data }
def className(obj): """ Return the name of a class as a string. """ return obj.__class__.__name__
def handle_tensorboard_not_found(e): """Handle exception: tensorboard script not found.""" return "Tensorboard not found on your system." \ " Please install tensorflow first. Sorry.", 503
def test(arg: str) -> bool: """Hello >>> 1 + 13 14 :param arg: An argument :return: Return the resulting value """ return arg == 'foo'
def valid_parentheses_brackets(input_string: str) -> bool: """ Determine whether the brackets, braces, and parentheses in a string are valid. Works only on strings containing only brackets, braces, and parentheses. Explanation: https://www.educative.io/edpresso/the-valid-parentheses-problem :param input_string: :return: Boolean >>> valid_parentheses_brackets('()') True >>> valid_parentheses_brackets('()[]{}') True >>> valid_parentheses_brackets('{[()]}') True >>> valid_parentheses_brackets('(})') False Time complexity: O(n) where n is the length of the input string. Space complexity: O(n) where n is the length of the input string. """ open_stack: list = [] map_close_to_open: dict = { ')': '(', '}': '{', ']': '[' } for character in input_string: if character in map_close_to_open: if open_stack and open_stack.pop() == map_close_to_open[character]: pass else: return False else: open_stack.append(character) return False if open_stack else True
def ean8_check_digit(num): """ EAN checksum gewichtete Summe: die letzte Stelle (vor der Pruefziffer) mal 3, die vorletzte mal 1, ..., addiert Pruefziffer ist dann die Differenz dieser Summe zum naechsten Vielfachen von 10 :param num: (?) :return: (?) """ s = str(num)[::-1] # in string wandeln, umkehren checksum = 0 even = True for char in s: n = int(char) if even: n *= 3 checksum += n even = not even return (10 - (checksum % 10)) % 10
def remove_possible_title_from_text( text: str, title: str, min_title_length: int = 3, overlap_ratio: float = 0.5 ) -> str: """ Remove title from text document. :param text: text string :param title: title to remove :param min_title_length: minimum length of title to remove :param overlap_ratio: minimum ratio required to remove. :return cleaned: return cleaned text """ def _high_intersection(s1, s2): return len(s1.intersection(s2)) > overlap_ratio * len(s2) titile_tokesn = set(title.lower().split(' ')) if (len(titile_tokesn) < min_title_length) or (len(text) <= len(title)): return text text_beginning_tokens = set(text.lower().split(' ')) if _high_intersection(text_beginning_tokens, titile_tokesn): text = text[len(title) :] return text
def get_progress_rate(k, c_species, v_reactants): """Returns the progress rate for a reaction of the form: va*A+vb*B --> vc*C. INPUTS ======= k: float Reaction rate coefficient c_species: 1D list of floats Concentration of all species v_reactants: 1D list of floats Stoichiometric coefficients of reactants RETURNS ======== w: float prgress rate of this reaction NOTES ===== PRE: - k, each entry of c_species and v_reactants have numeric type - c_species and v_reactants have the same length POST: - k, c_species and v_reactants are not changed by this function - raises a ValueError if k <= 0 - raises an Exception if c_species and v_reactants have different length - returns the prgress rate w for the reaction EXAMPLES ========= >>> get_progress_rate(10, [1.0, 2.0, 3.0], [2.0, 1.0, 0.0]) 20.0 """ if k <= 0: raise ValueError('k must be positive.') if len(c_species) != len(v_reactants): raise Exception('List c_species and list v_reactants must have same length.') w = k for c, v in zip(c_species, v_reactants): w *= pow(c, v) return w
def is_iterable(x): """Determines whether the element is iterable. >>> isiterable([1, 2, 3]) True >>> isiterable('abc') True >>> isiterable(5) False""" try: iter(x) return True except TypeError: return False
def register_to_signed_int(x, base=16): """ Modbus uses 16-bit integers, which can sometimes be treated as a signed 15-bit number. This handles converting a signed 16-bit number to a proper int Optionally can also work on other bases, but that's not normally needed """ if x & (1 << (base-1)): y = x - (1 << base) else: y = x return y
def count_string_dictionary(list_of_strings): """ Count the number of instances in a list and return them in a dictionary where the keys are the strings and the value the number of times it appeared in the list """ to_return = {} for e in list_of_strings: try: to_return[e] += 1 except KeyError: to_return[e] = 1 return to_return
def _find_file_type(file_names, extension): """ Returns files that end with the given extension from a list of file names. """ return [f for f in file_names if f.lower().endswith(extension)]
def generate_combinations(items, count_min, count_max, cur_items): """Generate possible combinations of items froum count_min to count_max.""" if len(cur_items) == count_max: return [cur_items] combinations = [] if len(cur_items) >= count_min: combinations.append(cur_items) for item in items.items(): item_name, _ = item next_items = items.copy() next_items.pop(item_name) next_combinations = generate_combinations( next_items, count_min, count_max, cur_items + [item] ) combinations.extend(next_combinations) return combinations
def delete_suppliers_list(data): """Delete the list of suppliers added by ``add_suppliers_to_markets``. This information was used by ``allocate_suppliers`` and ``update_market_production_volumes``, but is no longer useful.""" for ds in data: if 'suppliers' in ds: del ds['suppliers'] return data
def remove_trailing_space(s, punctuation="!?.,"): """ Removes a trailing space in a sentence eg. "I saw a foo ." to "I saw a foo." """ for punc in punctuation: if len(s) < 2: return s if " %s" % punc == s[-2:]: s = s[:-2] + punc for punc in punctuation: if "%s%s" % (punc, punc) == s[-2:]: s = s[:-1] return s
def zero_remove(line): """ This function just returns a sublist of the passed parameter after removing all zeros It takes O(n) time --> linear runtime complexity :param line: :return non_zero: """ non_zero = [] for num in line: if num != 0: non_zero.append(num) return non_zero
def get_remaining_cores(sellers): """ sellers is a list of list where each list contains follwing item in order 1. Seller Name 2. Number of available cores 3. Price of each core return the total number of cores unallocated """ rem_core=0 for selleri in sellers: rem_core+=selleri[1] return rem_core
def getSize(isInside): """ Returns size of points depending on if they're close to rect """ if isInside: return 1.5 else: return 0.2
def num_length(num): """ Returns the length in digits of num :param num: Num :return: Length in digits """ return len(str(num))
def create_alias(name): """ Clean an alias to be an acceptable Python variable """ return name.replace(' ', '_').replace('.', '_').lower()
def Hermite( x, n ): """ Function used to compute the Hermite polynomials. Args: x (any): variable. n (int): polynomials order Returns: any: returns the value of the polynomials at a given order for a given variable value. Testing: Already tested in some functions of the "functions.py" library. """ if n == 0: return 1 elif n == 1: return 2 * x else: return 2 * x * Hermite( x, n-1 ) - 2 * ( n-1 ) * Hermite( x, n-2 )
def dict_values(dict, tuple_index, tuple_index_value): """ :param dict: a dictionary whose keys are a tuple :param tuple_index: index of tuple that is of interest :param tuple_index_value: value required of tuple at tuple_index :return: list of appropriate keys of dict & corresponding values """ keys = [] values = [] for tuple in dict: tuple_value_of_interest = tuple[tuple_index] if tuple_value_of_interest == tuple_index_value: keys.append(tuple) values.append(dict[tuple]) else: pass return keys, values
def dirname_from_params(**kwargs): """Concatenate key, value pairs alphabetically, split by underscore.""" ordered = sorted(kwargs.items()) words = ["_".join([key, str(value)]) for key, value in ordered] return "_".join(words)
def vector_add(v, w): """adds two vectors componentwise""" return [v_i + w_i for v_i, w_i in zip(v,w)]
def divisors_more_concise(integer: int): """ Here's what someone else did, using 'or' to conditionally return """ return [i for i in range(2, integer) if not integer % i] or '%d is prime' % integer
def permutations(values): """Permutes the provided list Args: values (list): List to permute values within Returns: list: List of permutations of values """ if len(values) == 1: return values[0] ret = [] i = 0 for item in values: values.remove(item) perms = permutations(values) for perm in perms: ret.append(item + perm) values.insert(i, item) i += 1 return ret
def round_nearest(hours, interval=0.5): """Rounds the given hours to the nearest interval-hour""" if interval <= 0: raise ValueError('interval must be greater than zero') return round(hours / interval) * interval
def transformIntoZero(value): """fonction permettant de transformer un string vide en 0""" if value == "": return 0 else: return value
def _bound(color_component: float, minimum: float=0, maximum: float=255) -> float: """ Bound the given color component value between the given min and max values. The minimum and maximum values will be included in the valid output. i.e. Given a color_component of 0 and a minimum of 10, the returned value will be 10. """ color_component_out = max(color_component, minimum) return min(color_component_out, maximum)
def ssa_from_acf_slope(volume_fraction, acf_slope_at_origin): """ compute the ssa from given slope of an autocorrelation function C(r) at the origin and the volume fraction. This relation is often called Debye relation """ ################################################## # replace the following by the correct code ################################################## rho_ice = 917 return 4 * acf_slope_at_origin / volume_fraction / rho_ice
def overlap(start1, end1, start2, end2): """ Check if the two ranges overlap. """ return end1 >= start2 and end2 >= start1
def construct_doc2author(corpus, author2doc): """Create a mapping from document IDs to author IDs. Parameters ---------- corpus: iterable of list of (int, float) Corpus in BoW format. author2doc: dict of (str, list of int) Mapping of authors to documents. Returns ------- dict of (int, list of str) Document to Author mapping. """ doc2author = {} for d, _ in enumerate(corpus): author_ids = [] for a, a_doc_ids in author2doc.items(): if d in a_doc_ids: author_ids.append(a) doc2author[d] = author_ids return doc2author
def query_delete_table(table): """Generate table delete query for table with name 'table'""" return 'DROP TABLE IF EXISTS ' + table
def reverse(pattern): """[reverses a string] Args: pattern ([string]): [string to be reversed] Returns: [string]: [reversed version of inputted string "pattern"] """ return ''.join(reversed(pattern)) # OR return pattern[::-1]
def type_or_class_match(node_a, node_b): """ Checks whether `node_a` is an instance of the same type as `node_b`, or if either `node_a`/`node_b` is a type and the other is an instance of that type. This is used in subgraph matching to allow the subgraph pattern to be either a graph of instantiated nodes, or node types. :param node_a: First node. :param node_b: Second node. :return: True if the object types of the nodes match according to the description, False otherwise. :raise TypeError: When at least one of the inputs is not a dictionary or does not have a 'node' attribute. :raise KeyError: When at least one of the inputs is a dictionary, but does not have a 'node' key. :see: enumerate_matches """ if isinstance(node_b['node'], type): return issubclass(type(node_a['node']), node_b['node']) elif isinstance(node_a['node'], type): return issubclass(type(node_b['node']), node_a['node']) return isinstance(node_a['node'], type(node_b['node']))
def to_data(s): """ Format a data variable name. """ if s.startswith('GPSTime'): s = 'Gps' + s[3:] if '_' in s: return "".join([i.capitalize() for i in s.split("_")]) return s
def flatten_list(list_of_lists): """ Will convert a list of lists in a list with the items inside each sub-list. Parameters ---------- list_of_lists: list[list[object]] Returns ------- list """ if not list_of_lists: return [] if isinstance(list_of_lists[0], list): lst = [] for l in list_of_lists: lst.extend(l) return lst return list_of_lists
def flatten(arr, type): """Flatten an array of type.""" res = [] for i in arr: if isinstance(i, type): res.append(i) else: res.extend(flatten(i, type)) return res
def issouth(bb1, bb2, north_vector=[0,1,0]): """ Returns True if bb1 is south of bb2 For obj1 to be south of obj2 if we assume a north_vector of [0,1,0] - The max Y of bb1 is less than the min Y of bb2 """ #Currently a North Vector of 0,1,0 (North is in the positive Y direction) #is assumed. At some point this should be updated to allow for non-traditional #North to be taken and to allow for directions based on perspective. if north_vector != [0,1,0]: raise NotImplementedError _,bb1_max = bb1 bb2_min,_ = bb2 x1,y1,z1 = bb1_max x2,y2,z2 = bb2_min return y1 < y2