content
stringlengths
42
6.51k
def diophantine_count(a, n): """Computes the number of nonnegative solutions (x) of the linear Diophantine equation a[0] * x[0] + ... a[N-1] * x[N-1] = n Theory: For natural numbers a[0], a[2], ..., a[N - 1], n, and j, let p(a, n, j) be the number of nonnegative solutions. Then one has: p(a, m, j) = sum p(a[1:], m - k * a[0], j - 1), where the sum is taken over 0 <= k <= floor(m // a[0]) Examples -------- >>> diophantine_count([3, 2, 1, 1], 47) 3572 >>> diophantine_count([3, 2, 1, 1], 40) 2282 """ def p(a, m, j): if j == 0: return int(m == 0) else: return sum( [p(a[1:], m - k * a[0], j - 1) for k in range(1 + m // a[0])] ) return p(a, n, len(a))
def to_pages_by_lines(content: str, max_size: int): """Shortens the youtube video description""" pages = [''] i = 0 for line in content.splitlines(keepends=True): if len(pages[i] + line) > max_size: i += 1 pages.append('') pages[i] += line return pages
def Repr(obj, as_ref=True): """A version of __repr__ that can distinguish references. Sometimes we like to print an object's full representation (e.g. with its fields) and sometimes we just want to reference an object that was printed in full elsewhere. This function allows us to make that distinction. Args: obj: The object whose string representation we compute. as_ref: If True, use the short reference representation. Returns: A str representation of |obj|. """ if hasattr(obj, 'Repr'): return obj.Repr(as_ref=as_ref) # Since we cannot implement Repr for existing container types, we # handle them here. elif isinstance(obj, list): if not obj: return '[]' else: return ('[\n%s\n]' % (',\n'.join( ' %s' % Repr(elem, as_ref).replace('\n', '\n ') for elem in obj))) elif isinstance(obj, dict): if not obj: return '{}' else: return ('{\n%s\n}' % (',\n'.join( ' %s: %s' % (Repr(key, as_ref).replace('\n', '\n '), Repr(val, as_ref).replace('\n', '\n ')) for key, val in obj.items()))) else: return repr(obj)
def seconds_to_human(sec): """ Converts seconds into human readable format Input: seconds_to_human(142) Output: 00h 02m 22.000s """ days = sec // (24 * 60 * 60) sec -= days * (24 * 60 * 60) hours = sec // (60 * 60) sec -= hours * (60 * 60) minutes = sec // 60 sec -= minutes * 60 ret = "%02dh %02dm %06.3fs" % (hours, minutes, sec) if days > 0: if days > 1: ret = "%dd " % days + ret else: ret = "%dd " % days + ret return ret
def count_longest_run(lst): """ Return longest run in given experiment outcomes list """ Y_longest_run = count = 0 current = lst[0] for outcome in lst: if outcome == current: count += 1 else: count = 1 current = outcome Y_longest_run = max(count, Y_longest_run) return Y_longest_run
def min_max_tuples(fst, snd): """ Given two tuples (fst_min, fst_max) and (snd_min, snd_max) return (min, max) where min is min(fst_min, snd_min) and max is max(fst_max, snd_max). :param fst: tuple :type fst: tuple :param fst: tuple :type snd: tuple :return: tuple :rtype: tuple """ fst_min, fst_max = fst snd_min, snd_max = snd return (min(fst_min, snd_min), max(fst_max, snd_max))
def kebab_case_to_human(word): """Should NOT be used to unslugify as '-' are also used to replace other special characters""" if word: return word.replace("-", " ").title()
def get_db_hostname(url, db_type): """Retreive db hostname from jdbc url """ if db_type == 'ORACLE': hostname = url.split(':')[3].replace("@", "") else: hostname = url.split(':')[2].replace("//", "") return hostname
def get_sgr_from_api(security_group_rules, security_group_rule): """ Check if a security_group_rule specs are present in security_group_rules Return None if no rules match the specs Return the rule if found """ for sgr in security_group_rules: if (sgr['ip_range'] == security_group_rule['ip_range'] and sgr['dest_port_from'] == security_group_rule['dest_port_from'] and sgr['direction'] == security_group_rule['direction'] and sgr['action'] == security_group_rule['action'] and sgr['protocol'] == security_group_rule['protocol']): return sgr return None
def generate_binary_tree(op_str, first_child, second_child): """ Given operator string and two child, creates tree. """ if op_str == "+": return first_child + second_child elif op_str == "-": return first_child - second_child elif op_str == "*": return first_child * second_child elif op_str == "/": return first_child / second_child elif op_str == "**": return first_child ** second_child else: raise ValueError("Unknown opeartor {}".format(op_str))
def answer(question): """ Evaluate expression """ if not question.startswith("What is"): raise ValueError("unknown operation") math = question[7:-1].replace("minus", "-").replace("plus", "+") math = math.replace("multiplied by", "*").replace("divided by", "/") math = math.split() if not math or not math[0].lstrip("-").isnumeric(): raise ValueError("syntax error") current = [int(math[0])] for index in range(1, len(math)): if not math[index].lstrip("-").isnumeric(): if math[index] not in "/*+-": raise ValueError("unknown operation") current.append(math[index]) if index < len(math) - 1 and math[index + 1] in "/*+-": raise ValueError("syntax error") else: try: if current[-1] == "+": current = [current[0] + int(math[index])] elif current[-1] == "-": current = [current[0] - int(math[index])] elif current[-1] == "*": current = [current[0] * int(math[index])] elif current[-1] == "/": current = [current[0] / int(math[index])] else: raise ValueError("syntax error") except TypeError: raise ValueError("syntax error") if len(current) == 1: return current[0] raise ValueError("syntax error")
def id_tokenizer(words: list) -> list: """Function to convert all id like tokens to universal iiiPERCENTiii token. words: Word tokenized text of pdf (preproccesed) return: Converted list of tokens """ final_words = words[:] for c,word in enumerate(final_words): new_word = word.replace('-','') if len(new_word) != len(word) and new_word.isdigit(): final_words[c] = "iiiIDiii" return final_words
def render_config_template(template): """ Generates a configuration from the provided template + variables defined in current scope :param template: a config content templated with {{variables}} """ all_vars = {k: v for d in [globals(), locals()] for k, v in d.items()} return template.format(**all_vars)
def _operation_name_without_postfix(operation_id): """ :param operation_id: operation name with optional postfix - text after / sign :return: operation type - all characters before postfix (all characters if no postfix found) """ postfix_sign = '/' # if the operation id has custom postfix if postfix_sign in operation_id: if operation_id.count(postfix_sign) > 1: raise ValueError(f'Incorrect number of postfixes in {operation_id}') return operation_id.split('/')[0] else: return operation_id
def copy_to_permanent_storage(overall_dir): """ Calls script within directory to copy all files in directory to permanent storage. Args: overall_dir (str): overall directory where everything is located. Return: None. """ """ copy_executable = os.path.join(overall_dir, "copyall.sh") lib.call("{0}".format(copy_executable), "could not copy to permanent storage {}".format(overall_dir)) """ return "unimplemented"
def searchInsertB(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ low = 0 high = len(nums)-1 while high>=low: middle = (low+high) // 2 if nums[middle] == target: return middle elif nums[middle] < target: low=middle+1 else: high=middle-1 return low
def is_unique_2(given_string): """ Assumes that lowercase and uppercase letters are SAME E.g. Returns False for "AaBbCc" """ lowered_string = given_string.lower() length_of_string = len(lowered_string) converted_set = set(lowered_string) length_of_set = len(converted_set) if length_of_string == length_of_set: print("Test string {} is UNIQUE".format(given_string)) return True else: print("Test string {} is NOT UNIQUE".format(given_string)) return False
def read_bytes(buf, size): """ Reads bytes from a buffer. Returns a tuple with buffer less the read bytes, and the bytes. """ res = buf[0:size] return (buf[size:], res)
def _csr_filename(file_prefix): """ Construct the name of a file for use in storing a certificate signing request. :param str file_prefix: base file name for the certificate signing request (without the extension) :return: certificate signing request file name :rtype: str """ return file_prefix + ".csr"
def adjust_by_hours(num_hours, time): """Takes in military time as a string, and adjusts it by the specified number of hours""" time = int(time) time += num_hours*100 return str(time)
def get_nested_dict(input_dict, key): """ Helper function to interpret a nested dict input. """ current = input_dict toks = key.split("->") n = len(toks) for i, tok in enumerate(toks): if tok not in current and i < n - 1: current[tok] = {} elif i == n - 1: return current, toks[-1] current = current[tok] return None
def _f(field): """SQL for casting as float""" return f"CAST({field} AS FLOAT)"
def _combine_graph_data(graphs): """ Concatenate data series from multiple graphs into a single series Returns ------- val List of the form [(x_0, [y_00, y_01, ...]), (x_1, ...)] where the y-values are obtained by concatenating the data series. When some of the graphs do not have data for a given x-value, the missing data is indicated by None values. n_series Number of data series in output. Equal to the sum of n_series of the input graphs. """ all_data = {} n_series = sum(graph.n_series if graph.n_series else 1 for graph in graphs) template = [None]*n_series pos = 0 for graph in graphs: series = graph.get_data() for k, v in series: prev = all_data.get(k, template) if graph.scalar_series: v = [v] all_data[k] = prev[:pos] + v + prev[pos+graph.n_series:] pos += graph.n_series val = list(all_data.items()) val.sort() return val, n_series
def flatten_dicts(dicts): """ Flatten all the dicts, but assume there are no key conflicts. """ out = {} for adict in dicts.values(): for key, value in adict.items(): out[key] = value return out
def is_vararg(param_name): """ Determine if a parameter is named as a (internal) vararg. :param param_name: String with a parameter name :returns: True iff the name has the form of an internal vararg name """ return param_name.startswith('*')
def dec_to_ip(dec): """Convert decimal number back to IPv4 format. This uses bit-shifting, which could also be used in conversion to a decimal value. """ return f"{(dec >> 24) & 0xFF}.{(dec >> 16) & 0xFF}.{(dec >> 8) & 0xFF}.{dec & 0xFF}"
def word_vector(text): """ Calculates a word frequency vector given text input :param input: string :return: """ word_list = text.split() word_vector = {} for word in word_list: word = word.lower() if word in word_vector: word_vector[word] += 1 else: word_vector[word] = 1 return word_vector
def get_strings_from_seqs(seqs): """ Extract strings from FASTA sequence records. """ strings = [] for s in seqs: strings.append(s.getString()) return strings
def min_longitude(coordinates): """ This function returns the minimum value of longitude of a list with tuples [(lat, lon), (lat, lon)]. :param coordinates: list list with tuples. Each tuple has coordinates float values. [(lat, lon), (lat, lon)] Ex: [(-00.00, -00.00), (00.00, 00.00)] :return: float minimum longitude value """ min_lon = min(coordinates, key=lambda t: t[1])[1] return min_lon
def count_infected(pop): """ counts number of infected """ return sum(p.is_infected() for p in pop)
def _remove_retweeted_tag(tweets): """ This method removes the "rt" of retweeted texts at the beginning of a message. """ cleaned_tweets = [] for tweet in tweets: if tweet.startswith('rt', 0, 2 ): cleaned_tweets.append(tweet[3:]) else: cleaned_tweets.append(tweet) return cleaned_tweets
def next_departure_after(time, bus): """Return next bus departure after time.""" return time - (time % bus) + bus
def dict_to_label_attr_map(input_dict): """ Converting python dict with one value into Params.label_attr_map format """ return {key+':': [key, type(val)] for key, val in input_dict.items()}
def hex_life(is_alive:bool, live_neighbors:int) -> bool: """Work out the life status of a tile, given its current status and neighbors""" if is_alive: return live_neighbors in (1,2) else: return live_neighbors == 2
def langstring(value: str, language: str = "x-none") -> dict: """Langstring.""" return { "langstring": { "lang": language, "#text": value, } }
def GetStartingGapLength(sequence): """ This function takes in a sequence, and counts from the beginning how many gaps exist at the beginning of that sequence, up till the first ATG (start codon). Parameters: - sequence: a string along which you wish to count the number of gaps """ gaps = 0 for i, position in enumerate(sequence): if sequence[i:i+3] == 'ATG': break elif sequence[i] == '-': gaps += 1 else: pass return gaps
def anagram2(S1,S2): """ Checks if the two strings are anagram or not""" S1 = S1.replace(' ', '').lower() S2 = S2.replace(' ', '').lower() if len(S1) != len(S2): return False # Edge case check count = {} for (x, y) in zip(S1,S2): count[x] = count.get(x,0)+1 count[y] = count.get(y,0)-1 for i in count: if count[i] !=0: return False return True
def _build_response_body(contact_id, response): """Builds a dictionary representing the response body""" contact_details = { 'contactId': contact_id } item = response['Item'] if 'name' in item: contact_details['name'] = item['name']['S'] if 'telephone' in item: contact_details['telephone'] = item['telephone']['S'] return contact_details
def delete_label(name,repos, session, origin): """ Deletes label :param name: name of the label to delete :param repos: name of the repository where is the label :param session: session for communication :param origin: from where the label came from :return: message code 200 (int) """ for repo in repos: if(repo != origin): r = session.delete("https://api.github.com/repos/"+repo+"/labels/" + name) return "200"
def is_subcmd(opts, args): """if sys.argv[1:] does not match any getopt options, we simply assume it is a sub command to execute onecmd()""" if not opts and args: return True return False
def get_where_value(conds): """ [ [where_column, where_operator, where_value], [where_column, where_operator, where_value], ... ] """ where_value = [] for cond in conds: where_value.append(cond[2]) return where_value
def divide_and_round(n): """ Divides an integer n by 2 and rounds up to the nearest whole number """ print("4") if n % 2 == 0: n = n / 2 return int(n) else: n = (n + 1) / 2 return int(n)
def __str__(self): """Override of default str() implementation.""" return dict(self).__str__()
def convert_version_string_to_int(string, number_bits): """ Take in a verison string e.g. '3.0.1' Store it as a converted int: 3*(2**number_bits[0])+0*(2**number_bits[1])+1*(2**number_bits[2]) >>> convert_version_string_to_int('3.0.1',[8,8,16]) 50331649 """ numbers = [int(number_string) for number_string in string.split(".")] if len(numbers) > len(number_bits): raise NotImplementedError( "Versions with more than {0} decimal places are not supported".format( len(number_bits) - 1)) # add 0s for missing numbers numbers.extend([0] * (len(number_bits) - len(numbers))) #convert to single int and return number = 0 total_bits = 0 for num, bits in reversed(list(zip(numbers, number_bits))): max_num = (bits + 1) - 1 if num >= 1 << max_num: raise ValueError( "Number {0} cannot be stored with only {1} bits. Max is {2}".format(num, bits, max_num)) number += num << total_bits total_bits += bits return number
def solve(n, t, indices): """ Solve the problem here. :return: The expected output. """ def make_jump(arr, j): for z in range(len(arr)): arr[z] = (arr[z] + j) % t return arr def rotate_right(arr): return [arr[-1]] + arr[0:len(arr) - 1] indices = [indices[z] - indices[0] for z in range(len(indices))] to_compare = [indices[z] for z in range(len(indices))] total = 0 while True: jump = t - to_compare[-1] total += jump to_compare = rotate_right(make_jump(to_compare, jump)) if to_compare == indices: break return total - 1
def compute_mallows_insertion_distribution(length, phi): """ Helper function for the mallows distro above. For Phi and a given number of candidates, compute the insertion probability vectors. Method mostly implemented from Lu, Tyler, and Craig Boutilier. "Learning Mallows models with pairwise preferences." Proceedings of the 28th International Conference on Machine Learning ( ICML-11). 2011. Parameters ----------- length: integer Number of insertion vectors to compute. Equal to the number of items that the distribution is over. phi: float Dispersion parameter. 0.0 gives a unanimous culture while 1.0 gives the impartial culture. Returns ----------- vec_dist: dict A mapping from index ---> insertion vector where each element of the insertion vector (insert[i]) is the probability that candidate[index] is inserted at insert[i]. Hence the the length of insert is equal to index+1 (so 1, 2, 3 ....) Notes ----------- """ # For each element in length, compute an insertion # probability distribution according to phi. vec_dist = {} for i in range(length): # Start with an empty distro of length i+1 dist = [0] * (i+1) #compute the denom = phi^0 + phi^1 + ... phi^(i-1) denom = sum([pow(phi,k) for k in range(len(dist))]) #Fill each element of the distro with phi^i-j / denom for j in range(len(dist)): dist[j] = pow(phi, i - j) / denom #print(str(dist) + "total: " + str(sum(dist))) vec_dist[i] = dist return vec_dist
def partition(nums, lo, hi): """ Lomuto Partition Scheme Picks the last element hi as a pivot and returns the index of pivot value in the sorted array. """ pivot = nums[hi] i = lo for j in range(lo, hi): if nums[j] < pivot: nums[i], nums[j] = nums[j], nums[i] i += 1 nums[i], nums[hi] = nums[hi], nums[i] return i
def chunker(big_lst): """ Breaks a big list into a list of lists. Removes any list with no data then turns remaining lists into key: value pairs with first element from the list being the key. Returns a dictionary. """ chunks = [big_lst[x:x + 27] for x in range(0, len(big_lst), 27)] # Remove the list if it contains no data. for chunk in chunks: if any(chunk): continue else: chunks.remove(chunk) chunked_list = {words[0]: words[1:] for words in chunks} return chunked_list
def f2f1(f1, f2, *a, **k): """ Apply the second function after the first. Call `f2` on the return value of `f1`. Args and kwargs apply to `f1`. Example ------- >>> f2f1(str, int, 2) 2 """ return f2(f1(*a, **k))
def scale(input_interval, output_interval, value): """ For two intervals (input and output) Scales a specific value linear from [input_min, input_max] to [output_min, output_max]. """ min_to, max_to = output_interval min_from, max_from = input_interval mapped_value = min_to + (max_to - min_to) * ((value - min_from) / (max_from - min_from)) return mapped_value
def renameRes(res): """ This function will rename the string resname for grace, e.g. D will become a delta sign """ if "CD1" in res: return res.replace("CD1","\\xd1") elif "CD2" in res: return res.replace("CD2","\\xd2") elif "CG1" in res: return res.replace("CG1","\\xg1") elif "CG2" in res: return res.replace("CG2","\\xg2") elif "CB" in res: return res.replace("CB","\\xb") else: print(res+ " could not be converted")
def friendly_size(size: float) -> str: """Convert a size in bytes (as float) to a size with unit (as a string)""" unit = "B" # Reminder: 1 KB = 1024 B, and 1 MB = 1024 KB, ... for letter in "KMG": if size >= 1024: size /= 1024 unit = f"{letter}B" # We want to keep 2 digits after floating point # because it is a good balance between precision and concision return f"{size:0.2f} {unit}"
def _to_modifier(suffix: str, scope: str) -> str: """Return the C++ kSuffix{X} corresponding to the 'w', 's', and 'u' suffix character in the TZ database files. """ if suffix == 'w': return f'{scope}::ZoneContext::kSuffixW' elif suffix == 's': return f'{scope}::ZoneContext::kSuffixS' elif suffix == 'u': return f'{scope}::ZoneContext::kSuffixU' else: raise Exception(f'Unknown suffix {suffix}')
def generate_reverse_graph(adj): """ This function is for used with the adj_graph defined in GEOMETRY_TASK_GRAPH outputs - adj_reversed: a reversed version of adj (All directed edges will be reversed.) """ adj_reversed = [[] for _ in range(len(adj))] for nid_u in range(len(adj)): for nid_v, eid_uv in adj[nid_u]: adj_reversed[nid_v].append( (nid_u,eid_uv) ) # return adj_reversed
def v_equil(alpha, cli, cdi): """Calculate the equilibrium glide velocity. Parameters ---------- alpha : float Angle of attack in rad cli : function Returns Cl given angle of attack cdi : function Returns Cd given angle of attack Returns ------- vbar : float Equilibrium glide velocity """ den = cli(alpha)**2 + cdi(alpha)**2 return 1 / den**(.25)
def create_headers(bearer_token): """Create headers to make API call Args: bearer_token: Bearer token Returns: Header for API call """ headers = {"Authorization": f"Bearer {bearer_token}"} return headers
def by_range(blocks, block_range): """Sort blocks by Logical Erase Block number. Arguments: List:blocks -- List of block objects to sort. List:block_range -- range[0] = start number, range[1] = length Returns: List -- Indexes of blocks sorted by LEB. """ peb_range = range(block_range[0],block_range[1]) return [i for i in blocks if i in peb_range]
def iou(box1, box2, denom="min"): """ compute intersection over union score """ int_tb = min(box1[0]+0.5*box1[2], box2[0]+0.5*box2[2]) - \ max(box1[0]-0.5*box1[2], box2[0]-0.5*box2[2]) int_lr = min(box1[1]+0.5*box1[3], box2[1]+0.5*box2[3]) - \ max(box1[1]-0.5*box1[3], box2[1]-0.5*box2[3]) intersection = max(0.0, int_tb) * max(0.0, int_lr) area1, area2 = box1[2]*box1[3], box2[2]*box2[3] control_area = min(area1, area2) if denom == "min" \ else area1 + area2 - intersection return intersection / control_area
def get_settable_properties(cls): """Gets the settable properties of a class. Only returns the explicitly defined properties with setters. Args: cls: A class in Python. """ results = [] for attr, value in vars(cls).items(): if isinstance(value, property) and value.fset is not None: results.append(attr) return results
def buildUpdateFields(params): """Join fields and values for SQL update statement """ return ",".join(["%s = \"%s\"" % (k, v) for k, v in params.items()])
def extract_interface_info( pgm, end_pgm, procedure_functions, current_modu, current_intr, line ): """This function extracts INTERFACE information, such as the name of interface and procedure function names, and populates procedure_functions dictionary. Params: pgm (tuple): Current program information. end_pgm (typle): End of current program indicator. procedure_functions (dict): A dictionary to hold interface-to-procedure function mappings. current_modu (str): Module name that current interface is located under. current_intr (str): Current interface name. line (str): A line from Fortran source code. Returns: (current_intr) Currently handling interface name. """ if pgm[0] and pgm[1] == "interface": current_intr = pgm[2] procedure_functions[current_modu][current_intr] = {} elif end_pgm[0] and end_pgm[1] == "interface": current_intr = None elif current_intr: if "procedure" in line: # Partition the string, which should have one of syntaxes like: # module procedure __function_name__ # module procedure , __function_name__ # module procedure __function_name__ , __function_name__ , ... # by keyword procedure. Then, only extract function names, which # always will be located at [-1] after partitioning. Finally, split # the string of function names by comma and store in the # functions list. functions = line.partition("procedure")[-1].split(",") for func in functions: func = func.strip() procedure_functions[current_modu][current_intr][func] = None else: pass return current_intr
def split_table(test_case_details): """ Method to split tables from the Json stored in the test_case table. Args: test_case_details(Json): JSON from test_case table Returns: splited table names in dictionary """ table_dict = {} tables = test_case_details["table"] for each_table in tables: table_dict['src_table'] = each_table table_dict['target_table'] = tables[each_table] return table_dict
def codeToArray(code): """Splits code string into array separated by newline character""" convList = [] code = code.split("\n") for element in code: convList.append(element.strip()) return convList
def rhoair( dem, tday ): """Requires T in Kelvin""" t = tday+273.15 b = ( ( t - ( 0.00627 * dem ) ) / t ) return( 349.467 * pow( b, 5.26 ) / t )
def mod_min(a, b): """ return r such that r = a (mod b), with minimum |r| """ # like divmod_min, just skipping a single add r = (a % b) diff = b - r if abs(r) > abs(diff): r = -diff return r
def stock_price_summary(price_changes): """ (list of number) -> (number, number) tuple price_changes contains a list of stock price changes. Return a 2-item tuple where the first item is the sum of the gains in price_changes and the second is the sum of the losses in price_changes. >>> stock_price_summary([0.01, 0.03, -0.02, -0.14, 0, 0, 0.10, -0.01]) (0.14, -0.17) >>> stock_price_summary([]) (0, 0) >>> stock_price_summary([0.00, 0.00, -0.00, -0.00, 0.00, 0, 0.0, 0.0]) (0, 0) """ gains = 0 losses = 0 for item in price_changes: if item > 0: gains += item if item < 0: losses += item return (gains, losses)
def extract_pred(predictions): """ extract the model prediction without the label at the beginning :param predictions: list of Strings / complete predicted output :return: list of Strings / predicted output without labels """ array = [] for pred in predictions: try: x = pred.split(':', 1)[1] except IndexError: try: if pred.startswith('partially correct'): x = pred.split(' ', 1)[2] else: x = pred.split(' ', 1)[1] except IndexError: x = pred array.append(x) return array
def CRC_calc(data): """Sensirion Common CRC checksum for 2-byte packets. See ch 6.2 Parameters ---------- data : sequence of 2 bytes Returns ------- int, CRC check sum """ crc = 0xFF for i in range (0, 2): crc = crc ^ data[i] for j in range(8, 0, -1): if crc & 0x80: crc = (crc << 1) ^ 0x31 else: crc = crc << 1 crc = crc & 0x0000FF return crc
def position(x): """ Function to calculate position bias """ position=list() num_seqs = len(x) num_bases = len(x[1]) for j in range(0,num_bases): #each base count_A=0 ; count_T=0 ; count_C=0 ; count_G=0 ; count_other=0 ; total=0 for i in range(0,num_seqs): #each sequence if x[i][j]=='A': count_A=count_A+1 elif x[i][j]=='T': count_T=count_T+1 elif x[i][j]=='C': count_C=count_C+1 elif x[i][j]=='G': count_G=count_G+1 else: count_other=count_other+1 pos = j total=count_A+count_T+count_C+count_G+count_other freq_a=float(count_A)/float(total) freq_t=float(count_T)/float(total) freq_c=float(count_C)/float(total) freq_g=float(count_G)/float(total) freq_other=float(count_other)/float(total) result_a = (pos, 'a', freq_a) result_c = (pos, 'c', freq_c) result_g = (pos, 'g', freq_g) result_t = (pos, 't', freq_t) results=(result_a, result_c, result_g, result_t) [position.append(result) for result in results] return(position)
def merge_text_meta(left_text, right_text, overwrite=False): """ Merge known text keys from right to left, add unknown text_keys. """ if overwrite: left_text.update(right_text) else: for text_key in right_text.keys(): if not text_key in left_text: left_text[text_key] = right_text[text_key] return left_text
def loads(value: str) -> int: """ """ if len(value) > 3: raise ValueError("base25 input too large") return int(value, 25)
def ar(series, params, offset): """ Calculate the auto regression part. :param series: list with transactions :param params: list of coefficients, last value is the constant :param offset: index of last predicted value :return: float """ return params[-1] + sum([params[i] * series[offset-i] for i in range(len(params) - 1)])
def hour_min_second(seconds): """Convert given numbers of seconds to the format hour:min:secs. Args: seconds(int): The number of seconds Return: str: a string on the format hours:mins:secs """ minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) return "%02d:%02d:%02d" % (hours, minutes, seconds)
def add_to_dict_if_not_present(target_dict, target_key, value): """Adds the given value to the give dict as the given key only if the given key is not in the given dict yet. """ if target_key in target_dict: return False target_dict[target_key] = value return True
def getWordTag(wordTag): """ Split word and tag from word/tag pair Example: good/JJ -> word: good, tag: JJ """ if wordTag == "///": return "/", "/" index = wordTag.rfind("/") word = wordTag[:index].strip() #tag = wordTag[index +1:].lower().strip() tag = wordTag[index +1:].strip() return word, tag
def missing_remediation(rule_obj, r_type): """ For a rule object, check if it is missing a remediation of type r_type. """ rule_id = rule_obj['id'] check = len(rule_obj['remediations'][r_type]) > 0 if not check: return "\trule_id:%s is missing %s remediations" % (rule_id, r_type)
def html_escape(text): """Produce entities within text.""" html_escape_table = { "&": "&amp;", '"': "&quot;", "'": "&apos;", ">": "&gt;", "<": "&lt;", } return "".join(html_escape_table.get(c, c) for c in text)
def misra_dict_to_text(misra_dict): """Convert dict to string readable by cppcheck's misra.py addon.""" misra_str = '' for num1 in misra_dict: for num2 in misra_dict[num1]: misra_str += '\n{} {}.{}\n'.format(misra_dict[num1][num2]['type'], num1, num2) misra_str += '{}\n'.format(misra_dict[num1][num2]['text']) misra_str += '{}\n'.format(misra_dict[num1][num2]['category']) return misra_str
def _list_to_str(ticker_list): """parses/joins ticker list Args: ticker_list (:obj:`list` or str): ticker(s) to parse Returns: (str): list of tickers """ if isinstance(ticker_list, str): return ticker_list.upper() elif isinstance(ticker_list, list): return ','.join(ticker_list).upper() else: raise TypeError
def is_commanddictnode_defined(node): """ A child node is defined if it has either a helptext/callback/summary. If a node's callback is None it can still be undefined. """ return (('callback' in node and not node['callback'] is None) or 'help_text' in node or 'summary' in node)
def midpoint(startPt, endPt): """ Midpoint of segment :param startPt: Starting point of segment :param endPt: Ending point of segment :return: """ return [(startPt[0]+endPt[0])/2, (startPt[1]+endPt[1])/2]
def neg3D(v3D): """Returns the negative of the 3D vector""" return -v3D[0], -v3D[1], -v3D[2]
def unlist(given_list): """Convert the (possibly) single item list into a single item""" list_size = len(given_list) if list_size == 0: return None elif list_size == 1: return given_list[0] else: raise ValueError(list_size)
def _monotone_end_condition(inner_slope, secant_slope): """ Return the "outer" (i.e. first or last) slope given the "inner" (i.e. second or penultimate) slope and the secant slope of the first or last segment. """ # NB: This is a very ad-hoc algorithm meant to minimize the change in slope # within the first/last curve segment. Especially, this should avoid a # change from negative to positive acceleration (and vice versa). # There might be a better method available!?! if secant_slope < 0: return -_monotone_end_condition(-inner_slope, -secant_slope) assert 0 <= inner_slope <= 3 * secant_slope if inner_slope <= secant_slope: return 3 * secant_slope - 2 * inner_slope else: return (3 * secant_slope - inner_slope) / 2
def native16_to_be(word, signed=False) -> bytes: """ Packs an int into bytes after swapping endianness. Args: signed (bool): Whether or not `data` is signed word (int): The integer representation to converted and packed into bytes """ return word.to_bytes(2, 'big', signed=signed)
def is_invalid_call(s): """ Checks if a callsign is valid """ w = s.split('-') if len(w) > 2: return True if len(w[0]) < 1 or len(w[0]) > 6: return True for p in w[0]: if not (p.isalpha() or p.isdigit()): return True if w[0].isalpha() or w[0].isdigit(): return True if len(w) == 2: try: ssid = int(w[1]) if ssid < 0 or ssid > 15: return True except ValueError: return True return False
def _sanitize_name(name: str) -> str: """The last part of the access path is the function/attribute name""" return name.split(".")[-1]
def steps_to_basement(instructions): """Determine number of steps needed to reach the basement.""" floor = 0 for step, instruction in enumerate(instructions): if instruction == '(': floor += 1 elif instruction == ')': floor -= 1 if floor == -1: return step + 1 raise RuntimeError('Failed to reach basement.')
def midpoint(point1, point2): """ calc midpoint between point1 and point2 """ return ((point1[0] + point2[0]) * .5, (point1[1] + point2[1]) * .5)
def rectangle_intersects(recta, rectb): """ Return True if ``recta`` and ``rectb`` intersect. >>> rectangle_intersects((5,5,20, 20), (10, 10, 1, 1)) True >>> rectangle_intersects((40, 30, 10, 1), (1, 1, 1, 1)) False """ ax, ay, aw, ah = recta bx, by, bw, bh = rectb return ax <= bx + bw and ax + aw >= bx and ay <= by + bh and ay + ah >= by
def to_sequence_id(sequence_name) -> int: """ Turn an arbitrary value to a known sequence id. Will return an integer in range 0-11 for a valid sequence, or -1 for all other values Should handle names as integers, floats, any numeric, or strings. :param sequence_name: :return: """ try: sequence_id = int(sequence_name) except ValueError: sequence_id = -1 if 0 <= sequence_id < 11: return sequence_id return -1
def color_performance(column): """ color values in given column using green/red based on value>0 Args: column: Returns: """ color = 'green' if column > 0 else 'red' return f'color: {color}'
def generate_facial_features(facial_features, is_male): """ Generates a sentence based on the attributes that describe the facial features """ sentence = "He" if is_male else "She" sentence += " has" def nose_and_mouth(attribute): """ Returns a grammatically correct sentence based on the attribute """ if attribute == "big nose" or attribute == "pointy nose": return "a " + attribute elif attribute == "mouth slightly open": return "a slightly open mouth" return attribute if len(facial_features) == 1: attribute = nose_and_mouth(" ".join(facial_features[0].lower().split("_"))) return sentence + " " + attribute + "." for i, attribute in enumerate(facial_features): attribute = nose_and_mouth(" ".join(attribute.lower().split("_"))) if i == len(facial_features) - 1: sentence = sentence[:-1] sentence += " and " + attribute + "." else: sentence += " " + attribute + "," return sentence
def _is_descriptor(obj): """ A copy of enum._is_descriptor from Python 3.6. Returns True if obj is a descriptor, False otherwise. """ return ( hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__'))
def cleanEOL(s): """Remove \r from the end of string `s'.""" return s.rstrip("\r")
def assign_indent_numbers(lst, inum, dic): """ Associate keywords with their respective indentation numbers """ for i in lst: dic[i] = inum return dic
def input_colorpicker(field): """Return HTML markup for a color picker.""" return {"field": field}
def get_wheel_package_name(provider_package_id: str) -> str: """ Returns PIP package name for the package id. :param provider_package_id: id of the package :return: the name of pip package """ return "apache_airflow_providers_" + provider_package_id.replace(".", "_")
def validateSubSequence(array, sequence): """ ### Description validateSubSequence -> validates if a sequence of elements is a subsequence of a list. ### Parameters - array: the list where it will validate the subsequence. - sequence: the potential subsequence of elements ### Returns - True when the sequence is a valid subsequence of array. - False when the sequence is not a valid subsequence of array. """ arrIdx = 0 seqIdx = 0 while arrIdx < len(array) and seqIdx < len(sequence): if array[arrIdx] == sequence[seqIdx]: seqIdx += 1 arrIdx += 1 return seqIdx == len(sequence)
def build_n_sequence_dictionary(n : int, txt : str) -> dict: """ Returns a dict counting appearances of n-long progressions Parameters ---------- n : int The length of progressions to count txt : str A comma-separated string of roman numerals Returns ------- dict Maps sequences in txt of length n to the number of times they appear in txt """ seq_dict = dict() pieces = txt.split('\n') # For every song in the string, which are separated by '\n' for piece in pieces: roman_numerals = piece.split(',') # For every sequence of n roman numerals for i in range(len(roman_numerals) - n): seq = tuple(roman_numerals[i:i+n]) # Increment the count for this specific sequence seq_dict[seq] = seq_dict.get(seq, 0) + 1 return seq_dict