content
stringlengths
42
6.51k
def hadamard_complex(x_re, x_im, y_re, y_im): """Hadamard product for complex vectors""" result_re = x_re * y_re - x_im * y_im result_im = x_re * y_im + x_im * y_re return result_re, result_im
def render_pep440(vcs): """Convert git release tag into a form that is PEP440 compliant.""" if vcs is None: return None tags = vcs.split('-') # Bare version number if len(tags) == 1: return tags[0] else: return tags[0] + '+' + '.'.join(tags[1:])
def check_answer(guess, answer, turns): """checks answer against guess. Returns the number of turns remaining.""" if guess > answer: print("Too high.") return turns - 1 elif guess < answer: print("Too low.") return turns - 1 else: print(f"You got it! The answer was {answer}.")
def twosComp(val, bits): """compute the 2's complement of int value val""" if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value return val # return positive value as is
def _earliest_run_start( prev1_start, prev1_haplo, curr1_haplo, prev2_start, prev2_haplo, curr2_haplo): """ find the earliest "prev start" such that the "prev" and "curr" haplos match """ earliest_start = None if prev1_haplo == curr1_haplo: earliest_start = prev1_start if prev2_haplo == curr2_haplo: if earliest_start is None or prev2_start < prev1_start: earliest_start = prev2_start return earliest_start
def gcd(a, b): """Finding the greatest common divisor""" assert int(a) == a and int(b) == b, 'The numbers must be integers only' if a < 0: a = -1*a if b < 0: b = -1*b if b == 0: return a else: return gcd(b, a%b)
def lerpv3(a,b,t): """linear interplation (1-t)*a + (t)*b""" return ( (1-t)*a[0] + (t)*b[0], (1-t)*a[1] + (t)*b[1], (1-t)*a[2] + (t)*b[2] )
def maximize(low, high, objective, stop): """ Find the scalar argument which maximizes the objective function. The search space is bounded to the closed interval [low, high]. input: low: the lower bound of the search interval high: the upper bound of the search interval objective: an objective function, which takes and returns a scalar stop: a function which returns whether the search should be stopped, given the following parameters: - number of times the objective function has been called - width of the current search interval - the maximum value of the objective function so far output: a tuple consisting of: - the argument which maximizes the objective function - the maximum value of the objective function """ # The algorithm below is inspired by the Nelder-Mead and bisection methods. # This method tracks a set of four points and their associated values, as # returned by the objective function. One of the values must be less than or # equal to the remaining values. Its point -- the argmin -- is iteratively # updated. If the argmax is not on the boundary, then the argmin is updated # to bisect the two argmax points. Otherwise, the two argmin points are # updated to trisect the two argmax points. Iteration continues until the # stop function returns truth. diff = high - low a, b, c, d = low, low + 1 / 3 * diff, low + 2 / 3 * diff, high w, x, y, z = [objective(i) for i in (a, b, c, d)] argmax = lambda: max(enumerate([w, x, y, z]), key=lambda k: k[1])[0] n = 4 i = argmax() while not stop(n, d - a, [w, x, y, z][i]): if i == 0: diff = b - a b, c, d = a + 1 / 3 * diff, a + 2 / 3 * diff, b x, y, z = objective(b), objective(c), x n += 2 elif i == 3: diff = d - c a, b, c = c, c + 1 / 3 * diff, c + 2 / 3 * diff w, x, y = y, objective(b), objective(c) n += 2 elif i == 1: if c - b > b - a: c, d = (b + c) / 2, c y, z = objective(c), y else: b, c, d = (a + b) / 2, b, c x, y, z = objective(b), x, y n += 1 else: if d - c > c - b: a, b, c = b, c, (c + d) / 2 w, x, y = x, y, objective(c) else: a, b = b, (b + c) / 2 w, x = x, objective(b) n += 1 i = argmax() return ([a, b, c, d][i], [w, x, y, z][i])
def column(matrix, i): """ Gets column of matrix. INPUTS: Matrix, Int of column to look at RETURNS: Array of the column """ return [row[i] for row in matrix]
def _dtree_filter_comp(dtree_data, filter_key, bin_class_type): """ List comprehension filter helper function to filter the data from the `get_tree_data` function output Parameters ---------- dtree_data : dictionary Summary dictionary output after calling `get_tree_data` on a scikit learn decision tree object filter_key : str The specific variable from the summary dictionary i.e. `dtree_data` which we want to filter based on leaf class_names bin class type : int Takes a {0,1} class-value depending on the class to be filtered Returns ------- tree_data : list Return a list containing specific tree metrics from the input fitted Classifier object """ # Decision Tree values to filter dtree_values = dtree_data[filter_key] # Filter based on the specific value of the leaf node classes leaf_node_classes = dtree_data['all_leaf_node_classes'] # perform the filtering and return list return [i for i, j in zip(dtree_values, leaf_node_classes) if bin_class_type is None or j == bin_class_type]
def get_forward_kin(var_name): """ Function that returns UR script for get_forward_kin(). Transformation from joint space to tool space. Args: var_name: String. name of variable to store forward kinematics information Returns: script: UR script """ return "%s = get_forward_kin()\n" % (var_name)
def to_lower_case(s): """ transform a unicode string 's' to lowercase ok, this one is trivial, I know """ return s.lower()
def format_bids_name(*args): """ write BIDS format name (may change this later) :param args: items to join :return: name """ return ("_").join(args)
def find_workexperience_line_indexes_in_resume_object(parsed_resume_no_empty_lines, filtered_resume_info): """Finds the first and last indexes in resume_object, where the lines correspond to the work_experience. Returns the index if found, else None.""" we_first_line_text = "" if not parsed_resume_no_empty_lines else parsed_resume_no_empty_lines[0] we_last_line_text = "" if not parsed_resume_no_empty_lines else parsed_resume_no_empty_lines[-1] first_line_index = 0 last_line_index = 0 if we_first_line_text and we_last_line_text: for i, line in enumerate(filtered_resume_info): if line['line_text'] == we_first_line_text: first_line_index = i if line['line_text'] == we_last_line_text: last_line_index = i return {'start_index': first_line_index, 'end_index': last_line_index}
def get_aF(r1_norm, r2_norm): """ Computes the semi-major axis of the fundamental ellipse. This value is kept constant for all the problem as long as the boundary conditions are not changed. Parameters ---------- r1_norm: float Norm of the initial vector position. r2_norm: float Norm of the final vector position. Returns ------- a_F: float Semi-major axis of the fundamental ellipse. Notes ----- No labeled equation (appears between [3] and [4]) from Avanzini's report [1]. """ a_F = (r1_norm + r2_norm) / 2 return a_F
def line_sep_before_code(ls): """for markdown""" r, is_code = [], False for ln in ls: if not is_code: if ln.startswith(' '): r.append('') is_code = True else: if not ln.startswith(' '): is_code = False r.append(ln) return r
def munge_pair(pair): """ Convert integer values to integers """ name, value, offset = pair if name in ['secure-mode', 'keep-pwd']: value = ord(value) return (name, value, offset)
def clean_web_text(st): """Clean text.""" st = st.replace("<br />", " ") st = st.replace("&quot;", '"') st = st.replace("<p>", " ") if "<a href=" in st: while "<a href=" in st: start_pos = st.find("<a href=") end_pos = st.find(">", start_pos) if end_pos != -1: st = st[:start_pos] + st[end_pos + 1 :] else: print("incomplete href") print("before", st) st = st[:start_pos] + st[start_pos + len("<a href=")] print("after", st) st = st.replace("</a>", "") # st = st.replace("\\n", " ") # st = st.replace("\\", " ") while " " in st: st = st.replace(" ", " ") return st
def subtract_lists(x,y): """Subtract Two Lists (List Difference)""" return [item for item in x if item not in y]
def _get_recursive_config_key(config, key): """ Get the config value identified by the list of nested key values. :param config: Configuration dictionary. :param key: List of nested keys (in-order) for which the value should be retrieved. :return: The value in the configuration dictionary corresponding to the nested key. """ return _get_recursive_config_key((config or {}).get(key[0]), key[1:]) if len(key) else config
def sort_group(indx, column1, column2): """ Parameters ---------- indx : integer column1 : list data type (contains strings of SOC NAMES / WORK STATES which need to be ordered.) column2 : list data type (contains integers which denote numbers of of certified applications.) Returns ------- sort_group : list Returns a list where the entry at index 'indx' of column1 has been put in its proper place as per alphabetical ordering. Examples -------- >>> t1 = ['aaa', 'a', 'az', 'ay', 'ab', 'aa', 'ac', 'd', 'b', 'c'] >>> t2 = [7,6,5,5,5,5,5,4,3,3] >>> Bu = sort_group(2, t1, t2) >>> Bu ['aaa', 'a', 'aa', 'az', 'ay', 'ab', 'ac', 'd', 'b', 'c'] The returned result is always a list of the same length as column1. """ j = indx+1 check = True while ( (check) and (j<len(column2)) ): if ( column2[indx] == column2[j] ): if ( column1[indx] > column1[j] ): dum = column1[indx] column1[indx] = column1[j] column1[j] = dum if ( column2[indx] > column2[j] ): check = False j += 1 return column1
def create_dico(item_list): """ Create a dictionary of items from a list of list of items. """ assert type(item_list) is list dico = {} for items in item_list: for item in items: if item not in dico: dico[item] = 1 else: dico[item] += 1 return dico
def seconds_to_timestamps(seconds): """Return a dict of timestamp strings for the given numnber of seconds""" m, s = divmod(seconds, 60) h, m = divmod(m, 60) hms_parts = [] if h: hms_parts.append('{}h'.format(h)) if m: hms_parts.append('{}m'.format(m)) if s: hms_parts.append('{}s'.format(s)) return { 'colon': '{:02}:{:02}:{:02}'.format(h, m, s), 'hms': ''.join(hms_parts) }
def strtoint(value): """Cast a string to an integer.""" if value is None: return None return int(value)
def rest_api_parameters(in_args, prefix='', out_dict=None): """Transform dictionary/array structure to a flat dictionary, with key names defining the structure. Example usage: >>> rest_api_parameters({'courses':[{'id':1,'name': 'course1'}]}) {'courses[0][id]':1, 'courses[0][name]':'course1'} """ if out_dict==None: out_dict = {} if not type(in_args) in (list,dict): out_dict[prefix] = in_args return out_dict if prefix == '': prefix = prefix + '{0}' else: prefix = prefix + '[{0}]' if type(in_args)==list: for idx, item in enumerate(in_args): rest_api_parameters(item, prefix.format(idx), out_dict) elif type(in_args)==dict: for key, item in in_args.items(): rest_api_parameters(item, prefix.format(key), out_dict) return out_dict
def get_year_from_date_sk(date_sk): """ Return year from integer date in form YYYYMMDD. date_sk: Integer date in form YYYYMMDD """ return int(date_sk / 10000)
def generate_year_list(start, stop=None): """ make a list of column names for specific years in the format they appear in the data frame start/stop inclusive """ if isinstance(start, list): data_range = start elif stop: data_range = range(start, stop+1) else: data_range = [start] yrs = [] for yr in data_range: yrs.append("{0} [YR{0}]".format(yr)) return yrs
def is_float(s): """ Returns True if the given string is a float, False otherwise :param s: str :return: bool """ try: a = float(s) except (TypeError, ValueError): return False else: return True
def is_nested_list(mlist): """Is a list nested? Args: l ([list]): A Python list. Returns: [bool]: 1 is is a nested list, 0 is not and -1 is not a list. Examples: >>> from ee_extra import is_nested_list >>> is_nested_list([1,2,3]) >>> # 0 >>> is_nested_list([1,[2],3]) >>> # 1 >>> is_nested_list("Lesly") >>> # -1 """ if not isinstance(mlist, list): return -1 # is not a list if not any([isinstance(line, list) for line in mlist]): return 0 # if a list but not nested else: return 1
def bin_digit(t, i): """Returns the ith digit of t in binary, 0th digit is the least significant. >>> bin_digit(5,0) 1 >>> bin_digit(16,4) 1 """ return (t >> i) % 2
def get_positions(start_idx, end_idx, length): """ Get subj/obj position sequence. """ return list(range(-start_idx, 0)) + [0]*(end_idx - start_idx + 1) + \ list(range(1, length-end_idx))
def is_untracked2(untracked_files): """Function: is_untracked2 Description: Method stub holder for git.Repo.git.is_untracked(). Arguments: """ status = False if untracked_files: return status else: return False
def gammacorrectbyte(lumbyte: int, gamma: float ) -> int: """Apply a gamma factor to a luminosity byte value Args: lumbyte: byte luminosity value gamma : gamma adjustment Returns: a gamma adjusted byte value """ return int(((lumbyte / 255) ** gamma) * 255)
def rreplace(s, old, new, occurrence): """ Credits go here: https://stackoverflow.com/questions/2556108/rreplace-how-to-replace-the-last-occurrence-of-an-expression-in-a-string :param s: string to be processed :param old: old char to be replaced :param new: new char to replace the old one :param occurrence: how many places from end to replace the old char :return: modified string """ li = s.rsplit(old, occurrence) return new.join(li)
def calc_list_average(l): """ Calculates the average value of a list of numbers Returns a float """ total = 0.0 for value in l: total += value return total / len(l)
def pc(key): """ Changes python key into Pascale case equivalent. For example, 'this_function_name' becomes 'ThisFunctionName'. :param key: :return: """ return "".join([token.capitalize() for token in key.split('_')])
def count_emotion(session): """ Count number utterance per emotion for IEMOCAP session. Arguments --------- session: list List of utterance for IEMOCAP session. Returns ------- dic: dict Number of example per emotion for IEMOCAP session. """ dic = { "neu": 0, "hap": 0, "sad": 0, "ang": 0, "sur": 0, "fea": 0, "dis": 0, "fru": 0, "exc": 0, "xxx": 0, } for i in range(len(session)): if session[i][1] == "neu": dic["neu"] += 1 elif session[i][1] == "hap": dic["hap"] += 1 elif session[i][1] == "sad": dic["sad"] += 1 elif session[i][1] == "ang": dic["ang"] += 1 elif session[i][1] == "sur": dic["sur"] += 1 elif session[i][1] == "fea": dic["fea"] += 1 elif session[i][1] == "dis": dic["dis"] += 1 elif session[i][1] == "fru": dic["fru"] += 1 elif session[i][1] == "exc": dic["exc"] += 1 elif session[i][1] == "xxx": dic["xxx"] += 1 return dic
def white(s): """Color text white in a terminal.""" return "\033[1;37m" + s + "\033[0m"
def _try_convert(value): """Return a non-string from a string or unicode, if possible. ============= ===================================================== When value is returns ============= ===================================================== zero-length '' 'None' None 'True' True case insensitive 'False' False case insensitive '0', '-0' 0 0xN, -0xN int from hex (positive) (N is any number) 0bN, -0bN int from binary (positive) (N is any number) * try conversion to int, float, complex, fallback value """ if len(value) == 0: return '' if value == 'None': return None lowered_value = value.lower() if lowered_value == 'true': return True if lowered_value == 'false': return False valueneg = value[1:] if value[0] == '-' else value if valueneg == '0': return 0 if valueneg == '': return value try: return int(value) except ValueError: pass try: return float(value) except ValueError: pass try: return complex(value) except ValueError: return value
def min_to_hours(time): """ Returns hours in HH.MM - string format from integer time in hours. """ time /= 60 hours = int(time) minutes = (time * 60) % 60 return "%d:%02d" % (hours, minutes)
def issubclass_safe(x, klass): """return issubclass(x, klass) and return False on a TypeError""" try: return issubclass(x, klass) except TypeError: return False
def _parse_indent(indent): """Parse indent argument to indent string.""" try: return ' ' * int(indent) except ValueError: return indent
def vector_add(v, w): """adds corresponding elements""" return [v_i + w_i for v_i, w_i in zip(v, w)]
def trim_urls(attrs, new=False): """Bleach linkify callback to shorten overly-long URLs in the text. Pretty much straight out of the bleach docs. https://bleach.readthedocs.io/en/latest/linkify.html#altering-attributes """ if not new: # Only looking at newly-created links. return attrs # _text will be the same as the URL for new links. text = attrs['_text'] if len(text) > 32: attrs['_text'] = text[0:30] + '...' return attrs
def merge(line): """ Helper function that merges a single row or column in 2048 """ new_line = [x for x in line if x !=0] while len(new_line) < len(line): new_line.append(0) for ind in range(len(new_line)-1): if new_line[ind] == new_line[ind+1]: new_line[ind] *= 2 new_line.pop(ind+1) new_line.append(0) return new_line
def entry_dict_from_list(all_slab_entries): """ Converts a list of SlabEntry to an appropriate dictionary. It is assumed that if there is no adsorbate, then it is a clean SlabEntry and that adsorbed SlabEntry has the clean_entry parameter set. Args: all_slab_entries (list): List of SlabEntry objects Returns: (dict): Dictionary of SlabEntry with the Miller index as the main key to a dictionary with a clean SlabEntry as the key to a list of adsorbed SlabEntry. """ entry_dict = {} for entry in all_slab_entries: hkl = tuple(entry.miller_index) if hkl not in entry_dict.keys(): entry_dict[hkl] = {} if entry.clean_entry: clean = entry.clean_entry else: clean = entry if clean not in entry_dict[hkl].keys(): entry_dict[hkl][clean] = [] if entry.adsorbates: entry_dict[hkl][clean].append(entry) return entry_dict
def _make_options_dict(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, sign=None, formatter=None): """ make a dictionary out of the non-None arguments, plus sanity checks """ options = {k: v for k, v in locals().items() if v is not None} if suppress is not None: options['suppress'] = bool(suppress) if sign not in [None, '-', '+', ' ', 'legacy']: raise ValueError("sign option must be one of " "' ', '+', '-', or 'legacy'") return options
def FrequentWords(text, k): """Generate k-frequent words of text.""" thisdict = {} for i in range(len(text) - k + 1): kmer = text[i: (i + k)] # print(kmer) try: thisdict[kmer] = thisdict[kmer] + 1 # print(thisdict.keys()) except KeyError: thisdict.update({kmer: 1}) maxcount = max(thisdict.values()) maxlist = [] for i in thisdict.keys(): if thisdict[i] == maxcount: maxlist.append(i) return maxlist
def mf_replace(m, basic_dict): """ """ try: param = m.groups()[0] # There should be only one param defined if param in basic_dict.keys(): return basic_dict[param] except Exception: return None
def spw_filter(string): """Filter stopwords in a given string --> Titles of researchers' publications""" stopwords = ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 'can', 'cannot', 'will', 'just', "don't", 'should', "should've", 'now', "aren't", "couldn't", "didn't", "doesn't", "hadn't", "hasn't", "haven't", "isn't", "mightn't", "mustn't", "needn't", "shan't", "shouldn't", "wasn't", "weren't", "won't", "wouldn't"] return [tk.strip() for tk in string.lower().split() if tk not in stopwords]
def Publish(source_file): """Publish the given source file.""" return {'published_file': '/published/file.abc'}
def format_prayer(prayer: dict) -> str: """Format the reading. :param prayer Name of the prayer :return: Formatted prayer """ return f'<i><u><b>{prayer["Name"]}</b></u></i>\n\n{prayer["Prayer"]}'
def same_len(count, a:tuple): """Are a[0] and a[1] the same length?""" if len(a[0]) == len(a[1]): return count + 1 return count
def dim_comparator(val1, val2, name1, name2, dim_string, tolerance=0): """ Get the string representation of the relations. Args: val1: dimensional value of object 1 (int). val2: dimensional value of object 2 (int). name1: name of object 1 (str). name2: name of object 2 (str). dim_string: dimension being compared (str). tolerance: level of tolerance for the comparator (int). Return: A string representing the correct comparative relation between the objects in the dimension. """ diff = val1 - val2 if abs(diff) <= tolerance: # val1 == val2 return 's_' + dim_string + '(' + str(name1) + ',' + str(name2) + ')' elif diff > tolerance: # val1 > val2 return 'm_' + dim_string + '(' + str(name1) + ',' + str(name2) + ')' elif diff < -tolerance: # val1 < val2 return 'l_' + dim_string + '(' + str(name1) + ',' + str(name2) + ')'
def convert_tags(tags): """ Convert tags from AWS format [{'Key': '...', 'Value': '...'}, ...] to {'Key': 'Value', ...} format :param tags: tags in native AWS format :return: dict with tags ready to store in DynamoDB """ # dynamodb does not like empty strings # but Value can be empty, so convert it to None empty_converter = lambda x: x if x != "" else None return {tag['Key']: empty_converter(tag['Value']) for tag in tags} if tags else {}
def escape_latex(s): """Borrowed from PyLaTeX (MIT license). Thanks. https://github.com/JelteF/PyLaTeX/blob/master/pylatex/utils.py """ _latex_special_chars = { '&': r'\&', '%': r'\%', '$': r'\$', '#': r'\#', '_': r'\_', '{': r'\{', '}': r'\}', '~': r'\textasciitilde{}', '^': r'\^{}', '\\': r'\textbackslash{}', '\n': r'\\', '-': r'{-}', '\xA0': '~', # Non-breaking space } return ''.join(_latex_special_chars.get(c, c) for c in s)
def parse_cl_key_value(params): """ Convenience in parsing out parameter arrays in the form of something=something_else: --channel-name "H1=FAKE-STRAIN" """ return dict([val.split("=") for val in params])
def split_ranges(total, after=False, before=False): """ Given a range 1, 2, ..., total (page numbers of a doc). Split it in two lists. Example: Input: total = 9, after=1, before=False Output: list1 = [1]; list2 = [2, 3, 4, ..., 9]. Input: total = 9; after=False, before=1 Output: list1 = [], list2 = [1, 2, 3, 4, ..., 9] Input: total = 5; after=4; before=False Output: list1 = [1, 2, 3, 4] list2 = [5] Input: total = 5; after=False; before=False; Output: list1 = [1, 2, 3, 4, 5], list2 = [] (it means, by default, all pages are inserted at the end of the doc) """ if after and not before: if not isinstance(after, int): raise ValueError( "argument 'after' is supposed to be an int" ) list1 = list(range(1, after + 1)) list2 = list(range(after + 1, total + 1)) return list1, list2 if not after and before: if not isinstance(before, int): raise ValueError( "argument 'before' is supposed to be an int" ) list1 = list(range(1, before)) list2 = list(range(before, total + 1)) return list1, list2 list1 = list(range(1, total + 1)) list2 = [] return list1, list2
def parse_typename(typename): """ Parse a TypeName string into a namespace, type pair. :param typename: a string of the form <namespace>/<type> :return: a tuple of a namespace type. """ if typename is None: raise ValueError("function type must be provided") idx = typename.rfind("/") if idx < 0: raise ValueError("function type must be of the from namespace/name") namespace = typename[:idx] if not namespace: raise ValueError("function type's namespace must not be empty") type = typename[idx + 1:] if not type: raise ValueError("function type's name must not be empty") return namespace, type
def combine_strings(splitter): """Combine words into a list""" combined: str = " ".join(splitter) return combined
def level_to_kelvin(level): """Convert a level to a kelvin temperature.""" if level < 0: return 2200 if level > 100: return 6000 return (6000-2200) * level/100 + 2200
def replace_user_in_file_path(file_name, user): """Replace user name in give file path Args: file_name (str): Path to file user (str): New user to replace with Returns: str: New file path """ file_items = [x.strip() for x in file_name.strip().split('/') if len(x.strip())] file_items[1] = user return "/" + '/'.join(file_items).strip()
def combination(n,m): """ Calculate the combination :math:`C_{n}^{m}`, .. math:: C_{n}^{m} = \\frac{n!}{m!(n-m)!}. Parameters ---------- n : int Number n. m : int Number m. Returns ------- res : int The calculated result. Examples -------- >>> combination(6, 2) 15 """ if m>n or n <0 or m <0: print("wrong number in combination") return if m==0 or n==m: return 1 largest = max(m, n-m) smallest = min(m, n-m) numer = 1.0 for i in range(largest+1, n+1): numer *= i denom = 1.0 for i in range(1,smallest+1): denom *= i res = int(numer/denom) return res
def checkIfTableNeedExist(database, cursor, tableNameList): """ Input: the connected database this function will check if the tables that is needed for this program exists or not if yes: return 1 if no: return -1 """ for tableName in tableNameList: cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?;",(tableName,)) results = cursor.fetchall() if len(results) == 0: return -1 return 1
def my_formatter(tick_value, pos): """convert 0.0 to 0 in the plot. Examples: ax.xaxis.set_major_formatter(formatter) ax.yaxis.set_major_formatter(formatter) """ if isinstance(tick_value, float): rounded_value = round(tick_value, ndigits=10) if rounded_value.is_integer(): return int(rounded_value) else: return rounded_value else: return str(tick_value)
def get_w(node_s, node_w): """ node_s can be a set, list or a single node """ if isinstance(node_s, int): return node_w[node_s] else: return sum([node_w[n] for n in node_s])
def calculate_capacitance_factor( subcategory_id: int, capacitance: float, ) -> float: """Calculate the capacitance factor (piCV). :param subcategory_id: the capacitor subcategory identifier. :param capacitance: the capacitance value in Farads. :return: _pi_cv; the calculated capacitance factor. :rtype: float :raise: KeyError if passed an unknown subcategory ID. """ _dic_factors = { 1: [1.2, 0.095], 2: [1.4, 0.12], 3: [1.6, 0.13], 4: [1.2, 0.092], 5: [1.1, 0.085], 6: [1.2, 0.092], 7: [0.45, 0.14], 8: [0.31, 0.23], 9: [0.62, 0.14], 10: [0.41, 0.11], 11: [0.59, 0.12], 12: [1.0, 0.12], 13: [0.82, 0.066], 14: [0.34, 0.18], 15: [0.321, 0.19], 16: [1.0, 0.0], 17: [1.0, 0.0], 18: [1.0, 0.0], 19: [1.0, 0.0], } _f0 = _dic_factors[subcategory_id][0] _f1 = _dic_factors[subcategory_id][1] return _f0 * capacitance**_f1
def _embedding_aggregator(output_queue, n_worker): """ Process that aggregates the results of the workers. This should be the main/original process. Parameters ---------- output_queue: Queue This queue is the output queue of the workers. n_worker: int The number of worker processes. Returns ------- Aggregated embedding dictionary. """ embedding = {} num_done = 0 while num_done < n_worker: new_embedding = output_queue.get() if new_embedding == "DONE": num_done += 1 else: embedding.update(new_embedding) return embedding
def normalize_zip(code): """ Helper function to return 5 character zip codes only. :param code: string to normalize and format as a zip code :return: a five character digit string to compare as a zip code """ if code is None: return '' elif not isinstance(code, str): code = str(code) normalized_code = '' code = code.strip() # ensure hyphenated part is ignored code = code.split('-')[0] code = code.split(' ')[0] # perform zero padding upto 5 chars code = code.zfill(5) for char in code: if char.isdigit(): normalized_code += char return normalized_code
def quick_material(name): """ Get params of common materials. params: name: str, name of material. return: dictionary of material parameters. """ if name=='GB_Q345': return{ 'gamma':7849, 'E':2e11, 'mu':0.3, 'alpha':1.17e-5, 'fy':345e6 } elif name=='GB_Q235': pass
def pprint_things(l): """Pretty print""" return ''.join("{:25}".format(e) for e in l.split("\t")) + "\n"
def _lst_for_pes(pes_dct, run_pes_idxs): """ Get a dictionary of requested species matching the PES_DCT format """ red_pes_dct = {} for (form, pidx, sidx), chnls in pes_dct.items(): # Grab PES if idx in run_pes_idx dct run_chnl_idxs = run_pes_idxs.get(pidx, None) if run_chnl_idxs is not None: # Grab the channels if they are in run_chnl_idxs red_chnls = () for chnl in chnls: cidx, _ = chnl if cidx in run_chnl_idxs: red_chnls += (chnl,) red_pes_dct[(form, pidx, sidx)] = red_chnls return red_pes_dct
def floatnan(s): """converts string to float returns NaN on conversion error""" try: return float(s) except ValueError: return float('NaN')
def pointsToProperties(points): """Converts a (coordiante, properties) tuple to the properties only Arguments: points (array or tuple): point data to be reduced to properties Returns: array: property data Notes: Todo: Move this to a class that handles points and their meta data """ if isinstance(points, tuple) and len(points) > 1: return points[1] else: return None
def AsList(arg): """Returns the given argument as a list; if already a list, return it unchanged, otherwise return a list with the arg as only element. """ if isinstance(arg, (list)): return arg if isinstance(arg, (tuple, set)): return list(arg) return [arg]
def custom_tuple(tup): """ customize tuple to have comma separated numbers """ tuple_string = "(" for itup in tup: tuple_string += "{:,d}".format(itup) + ", " if len(tup) == 1: return tuple_string[:-2] + ",)" return tuple_string[:-2] + ")"
def human_bytes(n): """ Return the number of bytes n in more human readable form. """ if n < 1024: return '%d B' % n k = (n - 1) / 1024 + 1 if k < 1024: return '%d KB' % k return '%.1f MB' % (float(n) / (2**20))
def patient_scan(patientcfg, add_sequence=None, sep=None): """Get patient/scan id Parameters ---------- patientcfg : Dict < json (patient config file with pid, scanid in top level) add_sequence : Bool (Flag to join sequence id with pid, scanid) sep : Str (separator, default '_') Returns ------- patient_scan_id : str (concatenated) """ if "pid" in patientcfg: patient_id = patientcfg["pid"] else: raise KeyError("patient_config:pid") if "scanid" in patientcfg: scan_id = patientcfg["scanid"] else: raise KeyError("patient_config:scanid") if add_sequence is None: add_sequence = False if sep is None: sep = '_' ps_id = [] ps_id.extend((patient_id, sep, scan_id)) if add_sequence: # if True, default False if "sequenceid" in patientcfg: seq_id = patientcfg["sequenceid"] ps_id.extend((sep, seq_id)) else: raise KeyError("patient_config:sequenceid") patient_scan_id = "".join(ps_id) return patient_scan_id
def filter_names(name): """ This is just the filter function for the framework search :param name: :return: """ return name.lower()
def ellipsize(s, max_length=60): """ >>> print(ellipsize(u'lorem ipsum dolor sit amet', 40)) lorem ipsum dolor sit amet >>> print(ellipsize(u'lorem ipsum dolor sit amet', 20)) lorem ipsum dolor... """ if len(s) > max_length: ellipsis = '...' return s[:(max_length - len(ellipsis))] + ellipsis else: return s
def pgcd(a, b): """Computes the biggest common divider""" while b != 0: r = a % b a, b = b, r return a
def is_whitespace(ch): """Given a character, return true if it's an EDN whitespace character.""" return ch == "," or ch.isspace()
def cobbdouglas(x, par): """ Cobb douglas utility function for 2 goods. INPUT: Parameters par (alpha) : relative preference for consumption to leisure, 0<alpha<1 Consumption bundle x : Consumption tuple x[0] : consumption x[1] : leisure OUTPUT u : utility (negative)""" c=x[0] l=x[1] alpha=par u= (c**alpha)*l**(1-alpha) return -u
def gate(self=str('h'), targetA=None, targetB=None, targetC=None, angle=None, theta=None, Utheta=None, Uphi=None, Ulambda=None, custom_name=None, custom_params=None): """Generate a gate from it's name as a string passed to self, and a list of targets passed to targets. Args: self(str): The name used to represent the gate in QASM. For example, a Hadamard Gate is 'h'. (default str('h')) targetA(int): First target qubit. (default None) targetB(int): Second target qubit. (default None) targetC(int): Third target qubit. (default None) angle(float): Angle to specify in Radians for rotation gates like RX, RY, RZ. (default None) theta(float): Theta value in to specify for rotation gates like RX, RY, RZ. Exactly the same as the angle parameter. (default None) Utheta(str): Theta value for U-gates. (default None) Uphi(str): Phi value for U-gates. (default None) Ulambda(str): Lambda value for U-gates. (default None) custom_name(str): Name for user-defined opaque gate declarations, unitary gate declarations, and user-defined unitary gates. (default None) custom_params(str): Parameters for user-defined opaque gate declarations, unitary gate declarations, and user-defined unitary gates. (default None) Returns: str: A string object containing the specified gate as QASM.""" angle_gates = ['rx', 'ry', 'rz', 'crx', 'cry', 'crz', 'rxx', 'ryy', 'rzz', 'rzx', 'p'] if angle is None and theta is not None: angle = theta # Ensure Integer Variables Have Correct Types if targetA is not None: targetA = int(targetA) if targetB is not None: targetB = int(targetB) if targetC is not None: targetC = int(targetC) # Check if a U gate was specified. if self == 'U': # Compile a U gate. compiled_gate = f'U({Utheta},{Uphi},{Ulambda}) q[{targetA}];' # Return compiled U gate. return compiled_gate # Create an empty string for variable 'targets' targets = '' # Check if targetA is not a default value. # Generate first target qubit. targetA_qasm = f'q[{targetA}]' # Add translated target to 'targets'. targets = targets + targetA_qasm # Check if targetB is not a default value. if targetB is not None and targetB >= 0: # Generate second target qubit. targetB_qasm = f', q[{targetB}]' # Add translated target to 'targets'. targets = targets + targetB_qasm # Check if targetC is not a default value. if targetC is not None and targetC >= 0: # Generate third target qubit. targetC_qasm = f', q[{targetC}]' # Add translated instruction to 'targets'. targets = targets + targetC_qasm # Compile gate instruction by combining the gate name with the target specification(s). compiled_gate = f'{self} ' + f'{targets};' # Check if specified gate is a unitary gate. if self == 'unitary': # Compile unitary gate. compiled_gate = f'{custom_name}({custom_params}) {targets};' # Check if gate is declaring a unitary gate. elif self == 'gate': # Compile unitary gate declaration. compiled_gate = f'gate {custom_name}({custom_params}) {targets};' # Check if gate is declaring an opaque gate. elif self == 'opaque': # Compile opaque gate declaration. compiled_gate = f'opaque {custom_name}({custom_params}) {targets};' elif self in angle_gates: compiled_gate = f'{self}({angle}) {targets};' # Return compiled gate. return compiled_gate
def solve(task: str) -> int: """Find number of steps required to jump out of maze.""" current_index = 0 steps = 0 data = [int(item) for item in task.strip().split("\n")] while 0 <= current_index < len(data): next_index = current_index + data[current_index] data[current_index] += 1 current_index = next_index steps += 1 return steps
def _get_updated_values(before_values, after_values): """ Get updated values from 2 dicts of values Args: before_values (dict): values before update after_values (dict): values after update Returns: dict: a diff dict with key is field key, value is tuple of (before_value, after_value) """ assert before_values.keys() == after_values.keys() return dict([(k, [before_values[k], after_values[k]]) for k in before_values.keys() if before_values[k] != after_values[k]])
def levensthein_dist(input_command: str, candidate: str) -> int: """ Implement the Levenshtein distance algorithm to determine, in case of a non-existing handle, if theres a very similar command to suggest. :param input_command: The non-existing handle the user gave as input :param candidate: The (possible similar) alternative command :return: The similarity between the two strings measured by the levensthein distance """ if not input_command or not candidate: return max(len(input_command), len(candidate)) # at least one string is empty dp_table = [[0 for col in range(len(input_command) + 1)] for row in range(len(candidate) + 1)] dp_table[0] = list(range(0, len(input_command) + 1)) for i in range(1, len(candidate) + 1): dp_table[i][0] = i # now choose minimum levensthein distance from the three option delete/replace/insert # if chars are the same -> levensthein distance is the same as for those substring without these chars of input_command # and candidate for i in range(1, len(candidate) + 1): for j in range(1, len(input_command) + 1): # choose minimum edit distance from delete, replace or insert at current substring if input_command[j - 1] == candidate[i - 1]: dp_table[i][j] = dp_table[i - 1][j - 1] else: dp_table[i][j] = min(min(dp_table[i][j - 1], dp_table[i - 1][j - 1]), dp_table[i - 1][j]) + 1 return dp_table[len(candidate)][len(input_command)]
def strand_to_fwd_prob(strand): """Converts strand into a numeric value that RSEM understands. Args: strand: string 'forward', 'reverse', 'unstranded' Returns: numeric value corresponding the forward strand probability Raises: KeyError if strand is not 'forward', 'reverse' or 'unstranded' """ conversion = {'forward': 1, 'unstranded': 0.5, 'reverse': 0} return conversion[strand]
def ascii_chr(value): """ Converts byte to ASCII char :param value: ASCII code of character :return: char """ return bytes([value])
def process_function_types(type_string): """ Pre-process the function types for the Funcdecl """ split_string = type_string.split(' ') return ' '.join(str for str in split_string if '__attribute__' not in str)
def isabs(s): """Test whether a path is absolute""" return s.startswith('/')
def make_list(val): """make val a list, no matter what""" try: r = list(val) except TypeError: r = [val] return r
def is_hangul_char(character): """Test if a single character is in the U+AC00 to U+D7A3 code block, excluding unassigned codes. """ return 0xAC00 <= ord(character) <= 0xD7A3
def sum_of_squares(n): """ Calculate the sum of the squares of the first n natural numbers """ return sum(i ** 2 for i in range(1, n + 1))
def bin2balance_mxrb(b): """ Convert balance in binary encoding to Mxrb (a.k.a. XRB) The returned floating-point value will not be fully precise, as it has only 8 bytes of precision and not the needed 16 bytes (128 bits). """ assert isinstance(b, bytes) return 1.0 * int.from_bytes(b, 'big') / (10**24 * 10**6)
def tokenize(text): """Tokenize the given text. Returns the list of tokens. Splits up at spaces, and tabs, single and double quotes protect spaces/tabs, backslashes escape *any* subsequent character. """ words = [] word = '' quote = None escaped = False for letter in text: if escaped: word += letter escaped = False else: if letter == '\\': escaped = True elif quote is not None and letter == quote: quote = None words.append(word) word = '' elif quote is None and letter in " \t": words.append(word.strip()) word = '' elif quote is None and letter in '"\'' and len(word.strip()) == 0: word = '' quote = letter else: word += letter if len(word.strip()) > 0: words.append(word.strip()) return [word for word in words if len(word) > 0]
def remove_blank(x): """creating a function to remove the empty words""" if(x !=' ' ): return(x)
def url(data): """ Adds a http:// to the start of the url in data. """ return "http://%s" % data["metadata"]["url"]
def compare(x, y): """Comparison helper function for multithresholding. Gets two values and returns 1.0 if x>=y otherwise 0.0.""" if x >= y: return 1.0 else: return 0.0
def get_expts(context, expts): """Takes an expts list and returns a space separated list of expts.""" return '"' + ' '.join([expt['name'] for expt in expts]) + '"'