content
stringlengths
42
6.51k
def make_group_index(psm_list): """Makes a dictionary of PSM index lists (values) that have the same grouper string (key) """ group_index = {} for i, psm in enumerate(psm_list): if psm.meets_all_criteria: if psm.grouper in group_index: group_index[psm.grouper].append(i) else: group_index[psm.grouper] = [i] return group_index
def FindNonTrivialOrbit(generators): """ Given a generating set <generators> (a Python list containing permutations), this function returns an element <el> with a nontrivial orbit in the group generated by <generators>, or <None> if no such element exists. (Useful for order computation / membership testing.) """ if generators == []: return None n = generators[0].n for P in generators: for el in range(n): if P[el] != el: return el
def pressure_and_volume_to_temperature( pressure: float, moles: float, volume: float ) -> float: """ Convert pressure and volume to temperature. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature """ return round(pressure * volume / (0.0821 * moles))
def one_list_to_val(val): """ Convert a single list element to val :param val: :return: """ if isinstance(val, list) and len(val) == 1: result = val[0] else: result = val return result
def cram(text, maxlen): """Omit part of a string if needed to make it fit in a maximum length.""" if len(text) > maxlen: pre = max(0, (maxlen-3)//2) post = max(0, maxlen-3-pre) return text[:pre] + '...' + text[len(text)-post:] return text
def get_prefix(filename: str) -> str: """ Returns the prefix of an AFNI file. (Everything before the final "+".) """ return "".join(filename.split("+")[:-1])
def lower (s): """ None-tolerant lower case """ if s is not None: s = s.strip().lower() return s
def get_new_hw(h, w, size, max_size): """Get new hw.""" scale = size * 1.0 / min(h, w) if h < w: newh, neww = size, scale * w else: newh, neww = scale * h, size if max(newh, neww) > max_size: scale = max_size * 1.0 / max(newh, neww) newh = newh * scale neww = neww * scale neww = int(neww + 0.5) newh = int(newh + 0.5) return neww, newh
def is_file_wanted(f, extensions): """ extensions is an array of wanted file extensions """ is_any = any([f.lower().endswith(e) for e in extensions]) return is_any
def S_G_calc(va,vb,vc,vag,vbg,vcg,ia,ib,ic,Zload,a): """Power absorbed/produced by grid voltage source.""" return (1/2)*((-(ia-(va/Zload))/a).conjugate()*vag+(-(ib-(vb/Zload))/a).conjugate()*vbg+(-(ic-(vc/Zload))/a).conjugate()*vcg)
def rescale_points(points, scale): """ Take as input a list of points `points` in (x,y) coordinates and scale them according to the rescaling factor `scale`. :param points: list of points in (x,y) coordinates :type points: list of Tuple(int, int) :param scale: scaling factor :type scale: float :return: list of downscaled (x,y) points """ return [(int(x * scale), int(y * scale)) for (x, y) in points]
def binary_to_classes(binary_predictions): """ Expands the singular binary predictions to two classes :param binary_predictions: :return: The predictions broken into two probabilities. """ return [[1.0 - x[0], x[0]] for x in binary_predictions]
def interval_toggle(swp_on, mode_choice, dt): """change the interval to high frequency for sweep""" if dt <= 0: # Precaution against the user dt = 0.5 if mode_choice: if swp_on: return dt * 1000 return 1000000 return 1000000
def remove_duplicate_nested_lists(l): """ removes duplicates from nested integer lists """ uniq = set(tuple(x) for x in l) L = [ list(x) for x in uniq ] return L
def make_label(title): """Make the [] part of a link. Rewrite if last word is 'option'.""" # Special handling if the last word of the title is option. # The word option indicates the preceding word should have the # prefix '--' in the link label since it is a command line option. # Titles with '--' seem to break on GitHub pages. parts = title.split() if parts[-1] == "option": parts.pop(-1) parts[-1] = "--" + parts[-1] title = " ".join(parts) return "[" + title + "]"
def normalize_text(text): """ Replace some special characters in text. """ # NOTICE: don't change the text length. # Otherwise, the answer position is changed. text = text.replace("''", '" ').replace("``", '" ').replace("\t", " ") return text
def truncate_long_strings_in_objects(obj, max_num_chars=1000): """ Recursively truncates long strings in JSON objects, useful for reducing size of log messsages containing payloads with attachments using data URLs. Args: obj: Any type supported by `json.dump`, usually called with a `dict`. max_num_chars: `int`. The number of characters to truncate long strings to. """ if isinstance(obj, dict): new = {} for key, value in obj.items(): new_key = truncate_long_strings_in_objects(key, max_num_chars) new_value = truncate_long_strings_in_objects(value, max_num_chars) new[new_key] = new_value return new elif isinstance(obj, list): new = [] for item in obj: new.append(truncate_long_strings_in_objects(item, max_num_chars)) return new elif isinstance(obj, str): return obj[:max_num_chars] else: return obj
def iptonum(ip): """Convert IP address string to 32-bit integer, or return None if IP is bad. >>> iptonum('0.0.0.0') 0 >>> hex(iptonum('127.0.0.1')) '0x7f000001' >>> hex(iptonum('255.255.255.255')) '0xffffffffL' >>> iptonum('127.0.0.256') >>> iptonum('1.2.3') >>> iptonum('a.s.d.f') >>> iptonum('1.2.3.-4') >>> iptonum('') """ segments = ip.split('.') if len(segments) != 4: return None num = 0 for segment in segments: try: segment = int(segment) except ValueError: return None if segment < 0 or segment > 255: return None num = num << 8 | segment return num
def getSubstringDelimited(str_begin, str_finish, string): """ Returns a string delimited by two strings :param str_begin: first string that is used as delimiter :param str_finish: second string used as delimiter :param string: string to be processed :return: string parsed, empty string if there are no matches """ if len(str_begin) == 0: pos_beg = 0 else: pos_beg = string.find(str_begin) + len(str_begin) pos_end = string.find(str_finish) if 0 <= pos_beg < len(string) and 0 <= pos_end < len(string): return string[pos_beg:pos_end] else: return ''
def remove_non_characters2(x: str)->str: """ Input: String Output: String Removes everything that is not letters or numbers. """ z = list([val for val in x if val.isalnum()]) return ''.join(z)
def calc_linear_doublelayer_capacitance(eps, lamb): """ Capacitance due to the linearized electric double layer units: F/m^2 Notes: Squires, 2010 - "linearized electric double layer capacitance" Adjari, 2006 - "Debye layer capacitance (per unit area) at low voltage" Inputs: eps = permittivity of the fluid (F/m) lamb = linearized Debye length (m) """ Cdl_linear = eps/lamb return Cdl_linear
def url_builder(city_id: int, user_api: str, unit: str) -> str: """ Build complete API url. :param city_id: City ID. :param user_api: User API key. :param unit: Unit preferred. :return: """ api = 'http://api.openweathermap.org/data/2.5/weather?id=' full_api_url = \ api + str(city_id) + '&mode=json&units=' + unit + '&APPID=' + user_api return full_api_url
def get_common_date_pathrow(red_band_name_list, green_band_name_list, blue_band_name_list): """ :param red_band_name_list: :param green_band_name_list: :param blue_band_name_list: :return: """ red_date_pathrow = [ '_'.join(item.split('_')[:2]) for item in red_band_name_list] green_date_pathrow = [ '_'.join(item.split('_')[:2]) for item in green_band_name_list] blue_date_pathrow = [ '_'.join(item.split('_')[:2]) for item in blue_band_name_list] # for item in red_date_pathrow: # print(item) # print('************************') # get common bands (same date and pathrow) # the order of this list is random, how to avoid it? solution: sorted the output date_pathrow = sorted(set(red_date_pathrow) & set(green_date_pathrow) & set(blue_date_pathrow)) # date_pathrow = set(red_date_pathrow) & set(green_date_pathrow) return date_pathrow
def perm(n, arr): """ Returns the n-th permutation of arr. Requirements: len(arr) > 1 n needs to between 0 and len(arr)! - 1 """ # create list of factorials factorials = [0, 1] while(len(arr) != len(factorials)): factorials.append(factorials[-1] * len(factorials)) factorials.reverse() # convert n to its representation in the factorial numbering system fact_index = 0 m = 10 # 10 is used instead of 0 so m can be a a bunch of 0's if needed while(n > 0): if (n >= factorials[fact_index]): m += 1 n -= factorials[fact_index] else: fact_index += 1 m = 10 * m while(fact_index < len(factorials)-1): m = 10 * m fact_index += 1 m = [int(x) for x in str(m)] m.pop(0) # create permuted list new_arr = [] for x in m: new_arr.append(arr.pop(int(x))) return new_arr
def get_property_token(_property=None): """Get property token""" return _property.token if _property else None
def value_func_with_quote_handling(value): """ To pass values that include spaces through command line arguments, they must be quoted. For instance: --parameter='some value with space' or --parameter="some value with space". In this value parser, we remove the quotes to receive a clean string. """ if value[0] == value[-1] and value[0] in ["'", '"']: return value[1:-1] return value
def inverse_mod(num_a, num_b): """Returns inverse of a mod b, zero if none Uses Extended Euclidean Algorithm :param num_a: Long value :param num_b: Long value :returns: Inverse of a mod b, zero if none. """ num_c, num_d = num_a, num_b num_uc, num_ud = 1, 0 while num_c: quotient = num_d // num_c num_c, num_d = num_d - (quotient * num_c), num_c num_uc, num_ud = num_ud - (quotient * num_uc), num_uc if num_d == 1: return num_ud % num_b return 0
def sample_n_unique(sampling_f, n): """Helper function. Given a function `sampling_f` that returns comparable objects, sample n such unique objects. """ res = [] while len(res) < n: candidate = sampling_f() if candidate not in res: res.append(candidate) return res
def magic_square_params(diagonal_size): """ This is a helper function to create the gene_set, optimal_fitness and the expected sum of all the rows, columns and diagonals. :param diagonal_size: The diagonal length of the magic square. :type diagonal_size: int """ numbers = list(range(1, diagonal_size**2+1)) optimal_fitness = 2 + 2 * diagonal_size expected_sum = diagonal_size * (diagonal_size**2 + 1) / 2 return numbers, optimal_fitness, expected_sum
def air_flux(air_flow: float, co2_source: float, co2_target: float) -> float: """ Equation 8.46 Args: co2_source, co2_target: CO2-concentration at location (mg m^-3) air_flow: the air flux from location 1 to location 2 (m^3 m^-2 s^-1) return: CO2 flux accompanying an air flux from location 1 to location 2 [mg m^-2 s^-1] """ return air_flow * (co2_source - co2_target)
def truncate_chars_end_word(value: str, max_length: int): """ Truncates a string after a specified character length but does not cut off mid-word. """ if len(value) > max_length: truncd_val = value[:max_length] if value[max_length] != " ": truncd_val = truncd_val[:truncd_val.rfind(" ")] return truncd_val + "..." return value
def _standardize_args(inputs, initial_state, constants, num_constants): """Standardizes `__call__` to a single list of tensor inputs. When running a model loaded from a file, the input tensors `initial_state` and `constants` can be passed to `RNN.__call__()` as part of `inputs` instead of by the dedicated keyword arguments. This method makes sure the arguments are separated and that `initial_state` and `constants` are lists of tensors (or None). Arguments: inputs: Tensor or list/tuple of tensors. which may include constants and initial states. In that case `num_constant` must be specified. initial_state: Tensor or list of tensors or None, initial states. constants: Tensor or list of tensors or None, constant tensors. num_constants: Expected number of constants (if constants are passed as part of the `inputs` list. Returns: inputs: Single tensor or tuple of tensors. initial_state: List of tensors or None. constants: List of tensors or None. """ if isinstance(inputs, list): # There are several situations here: # In the graph mode, __call__ will be only called once. The initial_state # and constants could be in inputs (from file loading). # In the eager mode, __call__ will be called twice, once during # rnn_layer(inputs=input_t, constants=c_t, ...), and second time will be # model.fit/train_on_batch/predict with real np data. In the second case, # the inputs will contain initial_state and constants as eager tensor. # # For either case, the real input is the first item in the list, which # could be a nested structure itself. Then followed by initial_states, which # could be a list of items, or list of list if the initial_state is complex # structure, and finally followed by constants which is a flat list. assert initial_state is None and constants is None if num_constants: constants = inputs[-num_constants:] inputs = inputs[:-num_constants] if len(inputs) > 1: initial_state = inputs[1:] inputs = inputs[:1] if len(inputs) > 1: inputs = tuple(inputs) else: inputs = inputs[0] def to_list_or_none(x): if x is None or isinstance(x, list): return x if isinstance(x, tuple): return list(x) return [x] initial_state = to_list_or_none(initial_state) constants = to_list_or_none(constants) return inputs, initial_state, constants
def check_valid(num): """Return true if valid board spot.""" return -1 < num < 5
def duo_fraud(rec): """ author: airbnb_csirt description: Alert on any Duo authentication logs marked as fraud. reference: https://duo.com/docs/adminapi#authentication-logs playbook: N/A """ return rec['result'] == 'FRAUD'
def fixspacing(s): """Try to make the output prettier by inserting blank lines in random places. """ result = [] indent = -1 for line in s.splitlines(): line = line.rstrip() # Some lines had ' ' if not line: continue indent, previndent = len(line) - len(line.lstrip()), indent if indent <= previndent and indent < 8: if indent < previndent or not indent: result.append('') result.append(line) result.append('') return '\n'.join(result)
def mulsca(scalar, matrix): """ Multiplies a matrix to a scalar NOTE: Does not validates any matrix sizes or 0 scalar Parameters ---------- scalar(int) : Number scalar to multiply matrix(list) : Matrix to be multiplied Returns ------- list : multiplied matrix """ for i in range(len(matrix)): for j in range(len(matrix[0])): matrix[i][j] = matrix[i][j] * scalar return matrix
def clean_event_id(event_id): """ Clean the event id by replacing few characters with underscore. Makes it easier to save. Args: event_id (str): Ideally should be time stamp YYYY-MM-DDTHH:MM:SS.000 Returns (str): Cleaned event id """ # Replace '.' and '-' in event_id before saving char_to_replace = ['.', '-', ':', '/'] event_id_new = event_id for char in char_to_replace: event_id_new = event_id_new.replace(char, "_") return event_id_new
def get_from_configs(configs): """ Obtains information from user defined configs """ arg_types = configs['arg_types'] ranges = None if 'ranges' not in configs else configs['ranges'] return arg_types, ranges
def drastic_t_norm(a, b): """ Drastic t-norm function. Parameters ---------- a: numpy (n,) shaped array b: numpy (n,) shaped array Returns ------- Returns drastic t-norm of a and b Examples -------- >>> a = random.random(10,) >>> b = random.random(10,) >>> c = drastic_t_norm(a, b) """ return b * (a == 1) + a * (b == 1)
def shorten_namespace(elements, nsmap): """ Map a list of XML tag class names on the internal classes (e.g. with shortened namespaces) :param classes: list of XML tags :param nsmap: XML nsmap :return: List of mapped names """ names = [] _islist = True if not isinstance(elements, (list, frozenset)): elements = [elements] _islist = False for el in elements: for key, value in nsmap.items(): if value in el: if key == "cim": name = el.split(value)[-1] name = name[1:] if name.startswith("}") else name elif "{"+value+"}" in el: name = el.replace("{"+value+"}", key+"_") else: name = el.replace(value, key+"_") names.append(name) if el.startswith("#"): names.append(el.split("#")[-1]) if not _islist and len(names) == 1: names = names[0] if not names: return None return names
def hierarchicalCluster(distmatrix,n,method): """Get hierarchical clusters from similarity matrix. Using hierarchical cluster algorithm to get clusters from similarity matrix. now support three methods: single-linked, complete-linked, average-linked. The function is coded by 'FrankOnly'. More details in "https://github.com/Frankonly/DataMining/tree/master/CD%20algorithm" Args: distmatrix: A similarity matrix. If vertix i and vertix j are not connected, set distmatrix[i][j] = distmatrix[j][i] = -1 . n: The number of clusters after clustering. method: A cluster algorithm used. "single", "complete" or "average". Returns: A 2-d list presents clusters. Each list contains indices of vertices. For example: [[0, 3, 4], [1], [2, 5]] Raises: ValueError: An error occurred with wrong parameter RuntimeError: An error occurred when no clustes can be merged. """ if method not in ["single", "complete", "average"]: raise ValueError("no such method: {}".format(method)) clusters = [[i] for i in range(len(distmatrix))] abandon = [False for i in range(len(distmatrix))] newDist = distmatrix.copy() for _ in range(len(clusters) - n): minDist = 0x7fffffff #the max number of int32. x,y = 0,0 for i in range(len(newDist)): if not abandon[i]: for j in range(i+1,len(newDist[i])): if not abandon[j] and newDist[i][j] < minDist and newDist[i][j] != -1: minDist,x,y=newDist[i][j],i,j if minDist == 0x7fffffff: raise RuntimeError("single vertices are more than n") # The function run faster if merge the smaller one into the larger one. if len(clusters[x]) < len(clusters[y]): x,y = y,x abandon[y] = True for i in range(len(newDist[x])): if not abandon[i] and i != x: if newDist[x][i] == -1: newDist[x][i] = newDist[i][x] = newDist[y][i] elif newDist[y][i] == -1: newDist[x][i] = newDist[i][x] = newDist[x][i] else: if method == "single": newDist[x][i] = newDist[i][x] = min(newDist[x][i],newDist[y][i]) elif method == "complete": newDist[x][i] = newDist[i][x] = max(newDist[x][i],newDist[y][i]) else: newDist[x][i] = newDist[i][x] = (newDist[x][i] * len(clusters[x]) + newDist[y][i] * len(clusters[y])) \ / (len(clusters[x]) + len(clusters[y])) clusters[x].extend(clusters[y]) finalClusters = [clusters[i] for i in range(len(clusters)) if not abandon[i]] return finalClusters
def sigfig(number, digits=3): """ Round a number to the given number of significant digits. Example: >>> sigfig(1234, 3) 1230 number (int or float): The number to adjust digits=3 (int): The number of siginficant figures to retain Returns a number.""" input_type = type(number) output_num = '' digit_count = 0 period_found = False for digit in str(float(number)): if digit == '.': period_found = True output_num += '.' elif digit_count < digits: output_num += digit digit_count += 1 else: output_num += '0' return input_type(float(output_num))
def wdl(value): """ convert win/draw/lose into single char - french localized :param value: string :return: single char string """ return {'win': 'G', 'draw': 'N', 'lose': 'P'}.get(value)
def str_parse_as_utf8(content) -> str: """Returns the provided content decoded as utf-8.""" return content.decode('utf-8')
def brute_force(my_in): """ Don't joke! :-) """ for i in range(len(my_in)): for j in range(i+1,len(my_in)): if my_in[i]+my_in[j]==2020: return(my_in[i]*my_in[j])
def part_2(data: list) -> int: """Takes list of tuples and returns the sum of sum of letters who appear in each line of a data sub-item""" return sum(sum(1 for let in set(item[0]) if item[0].count(let) == item[1]) for item in data)
def fixed_negative_float(response: str) -> float: """ Keysight sometimes responds for ex. '-0.-1' as an output when you input '-0.1'. This function can convert such strings also to float. """ if len(response.split('.')) > 2: raise ValueError('String must of format `a` or `a.b`') parts = response.split('.') number = parts[0] decimal = parts[1] if len(parts) > 1 else '0' decimal = decimal.replace("-", "") output = ".".join([number, decimal]) return float(output)
def check_class_has_docstring(class_docstring, context, is_script): """Exported classes should have docstrings. ...all functions and classes exported by a module should also have docstrings. """ if is_script: return # assume nothing is exported class_name = context.split()[1] if class_name.startswith('_'): return # not exported if not class_docstring: return 0, len(context.split('\n')[0]) if not eval(class_docstring).strip(): return True
def convert_dict_to_text_block(content_dict): """ Convert the given dictionary to multiline text block of the format key1: value1 key2: value2 """ message = "" for k, v in content_dict.items(): message += "{}: _{}_\n".format(k, v) return message
def linear_forecast(slope, intercept, value): """Apply the linear model to a given value. Args: slope (float): slope of the linear model intercept (float): intercept of the linear model value (float): int or float value Returns: float: slope * x + intercept Example: >>> linear_forecast(2, -1, 3) 5.0 """ return slope * float(value) + intercept
def m_to_km(meters): """Convert meters to kilometers.""" if meters is None: return None return meters / 1000
def get_height(root): """ Get height of a node We're going to be skeptical of the height stored in the node and verify it for ourselves. Returns the height. 0 if non-existent node """ if root is None: return 0 return max(get_height(root.left), get_height(root.right)) + 1
def is_event(timeclass): """ It's an event if it starts with a number... """ if not isinstance(timeclass,str): return False return timeclass[0].isdigit()
def check(x): """ Checking for password format Format::: (min)-(max) (letter): password """ count = 0 dashIndex = x.find('-') colonIndex = x.find(':') minCount = int(x[:dashIndex]) maxCount = int(x[(dashIndex + 1):(colonIndex - 2)]) letter = x[colonIndex - 1] password = x[(colonIndex + 2):] for c in password: if (c == letter): count += 1 check = ((count >= minCount) and (count <= maxCount)) return check
def _standardize_value(value): """ Convert value to string to enhance the comparison. :arg value: Any object type. :return: str: Converted value. """ if isinstance(value, float) and value.is_integer(): # Workaround to avoid erroneous comparison between int and float # Removes zero from integer floats value = int(value) return str(value)
def order_request_parameters(request_id): """Take a request identifier and if it has a URI, order it parameters. Arguments: request_id -- String that specifies request that is going to be processed """ _last_slash_position = request_id.rfind('/') if 0 > _last_slash_position: return request_id #parameters not found last_string = request_id[_last_slash_position:] if 1 > len(last_string): return request_id #request_id ends with / start_param = last_string.find('?') if 0 > start_param: return request_id parameters = last_string[start_param+1:] if 1 > len(parameters): return request_id fragment_pos = parameters.find('#') if fragment_pos < 0: #dont have identifier operator query_parameters = ('&').join(sorted(parameters.split('&'))) ordered_request = request_id[0:_last_slash_position]+\ last_string[0:start_param+1]+\ query_parameters else: query_parameters = ('&').join(sorted((parameters[:fragment_pos])\ .split('&'))) ordered_request = request_id[0:_last_slash_position]+\ last_string[0:start_param+1]+\ query_parameters+parameters[fragment_pos:] return ordered_request
def get_ordinal(number): """Produces an ordinal (1st, 2nd, 3rd, 4th) from a number""" if number == 1: return 'st' elif number == 2: return 'nd' elif number == 3: return 'rd' else: return 'th'
def unixtime2mjd(unixtime): """ Converts a UNIX time stamp in Modified Julian Day Input: time in UNIX seconds Output: time in MJD (fraction of a day) """ # unixtime gives seconds passed since "The Epoch": 1.1.1970 00:00 # MJD at that time was 40587.0 result = 40587.0 + unixtime / (24. * 60. * 60.) return result
def subtour(n, edges): """ Given a list of edges, finds the shortest subtour. """ visited = [False] * n cycles = [] lengths = [] selected = [[] for _ in range(n)] for x, y in edges: selected[x].append(y) while True: current = visited.index(False) thiscycle = [current] while True: visited[current] = True neighbors = [x for x in selected[current] if not visited[x]] if len(neighbors) == 0: break current = neighbors[0] thiscycle.append(current) cycles.append(thiscycle) lengths.append(len(thiscycle)) if sum(lengths) == n: break return cycles[lengths.index(min(lengths))]
def _get_skill_memcache_key(skill_id, version=None): """Returns a memcache key for the skill. Args: skill_id: str. ID of the skill. version: int or None. Schema version of the skill. Returns: str. The memcache key of the skill. """ if version: return 'skill-version:%s:%s' % (skill_id, version) else: return 'skill:%s' % skill_id
def remove_phrases(words: list) -> list: """ Removes phrases from Synsets. Phrases are expressions with multiple words linked with _. :param words: The list of words in a synset :return: All the words that are not phrases or parts of phrases. """ # We need to sanitize synsets from phrasal expressions that contain "_" phrasal_expression_slices = set() phrasal_expressions = set() # Get all phrasal expressions (that contain '_') for word in words: if '_' in word: split_word = word.split("_") for w in split_word: phrasal_expression_slices.add(w) phrasal_expressions.add(word) valid_members = list() # Get all the words that are in the synset but not part of the phrasal expression: for word in words: if word not in phrasal_expression_slices and word not in phrasal_expressions: valid_members.append(word) return valid_members
def find_brute_force(T, P): """Return the index of first occurance of P; otherwise, returns -1.""" n, m = len(T), len(P) if m == 0: return 0 for i in range(n - m + 1): j = 0 while j < m and T[i + j] == P[j]: j += 1 if j == m: return i return -1
def c(phrase): """ C + Phrases!!! """ return 'C {}'.format(phrase.replace('_', ' '))
def getobjectref(blocklst, commdct): """ makes a dictionary of object-lists each item in the dictionary points to a list of tuples the tuple is (objectname, fieldindex) """ objlst_dct = {} for eli in commdct: for elj in eli: if "object-list" in elj: objlist = elj["object-list"][0] objlst_dct[objlist] = [] for objlist in list(objlst_dct.keys()): for i in range(len(commdct)): for j in range(len(commdct[i])): if "reference" in commdct[i][j]: for ref in commdct[i][j]["reference"]: if ref == objlist: objlst_dct[objlist].append((blocklst[i][0], j)) return objlst_dct
def cal_occurence(correspoding_text_number_list): """ calcualte each occurence of a number in a list """ di = dict() for i in correspoding_text_number_list: i = str(i) s = di.get(i, 0) if s == 0: di[i] = 1 else: di[i] = di[i] + 1 return di
def get_cdelt(hd): """ Return wavelength stepsize keyword from a fits header. Parameters ---------- hd: astropy.io.fits header instance Returns ------- cdelt: float Wavelength stepsize, or None if nothing suitable is found. """ cdelt = None if str('CDELT1') in hd: cdelt = hd[str('CDELT1')] elif str('CD1_1') in hd: cdelt = hd[str('CD1_1')] return cdelt
def build_targets_from_builder_dict(builder_dict, do_test_steps, do_perf_steps): """Return a list of targets to build, depending on the builder type.""" if builder_dict['role'] in ('Test', 'Perf') and builder_dict['os'] == 'iOS': return ['iOSShell'] if builder_dict.get('extra_config') == 'Appurify': return ['VisualBenchTest_APK'] if 'SAN' in builder_dict.get('extra_config', ''): # 'most' does not compile under MSAN. return ['dm', 'nanobench'] t = [] if do_test_steps: t.append('dm') if builder_dict.get('extra_config') == 'VisualBench': t.append('visualbench') elif do_perf_steps: t.append('nanobench') if t: return t else: return ['most']
def closest(x,y): """ Finds the location of a value in vector x that is from all entries of x closest to a given value y. Returns the position as a boolean vector of same size as x. """ import numpy as np return np.argmin(abs(x-y))
def make_subtitle(rho_rms_aurora, rho_rms_emtf, phi_rms_aurora, phi_rms_emtf, matlab_or_fortran, ttl_str=""): """ Parameters ---------- rho_rms_aurora: float rho_rms for aurora data differenced against a model. comes from compute_rms rho_rms_emtf: rho_rms for emtf data differenced against a model. comes from compute_rms phi_rms_aurora: phi_rms for aurora data differenced against a model. comes from compute_rms phi_rms_emtf: phi_rms for emtf data differenced against a model. comes from compute_rms matlab_or_fortran: str "matlab" or "fortran". A specifer for the version of emtf. ttl_str: str string onto which we add the subtitle Returns ------- ttl_str: str Figure title with subtitle """ ttl_str += ( f"\n rho rms_aurora {rho_rms_aurora:.1f} rms_{matlab_or_fortran}" f" {rho_rms_emtf:.1f}" ) ttl_str += ( f"\n phi rms_aurora {phi_rms_aurora:.1f} rms_{matlab_or_fortran}" f" {phi_rms_emtf:.1f}" ) return ttl_str
def ConstructTestName(filesystem_name): """Returns a camel-caps translation of the input string. Args: filesystem_name: The name of the test, as found on the file-system. Typically this name is_of_this_form. Returns: A camel-caps version of the input string. _ delimiters are removed, and the first letters of words are capitalized. """ names = filesystem_name.split('_') test_name = '' for word in names: test_name += word.upper()[0] + word[1:] return test_name
def margcond_str(marg, cond): """ Returns a name from OrderedDict values in marg and cond """ marg = list(marg.values()) if isinstance(marg, dict) else list(marg) cond = list(cond.values()) if isinstance(cond, dict) else list(cond) marg_str = ','.join(marg) cond_str = ','.join(cond) return '|'.join([marg_str, cond_str]) if cond_str else marg_str
def symm_subset(Vt, k): """ Trims symmetrically the beginning and the end of the vector """ if k == 0: Vt_k = Vt else: Vt_k = Vt[k:] Vt = Vt[0:-k] return Vt, Vt_k
def name_to_entity(name: str): """Transform entity name to entity id.""" return name.lower().replace(" ", "_")
def reduce_alphabet(character, mapping): """Reduce alphabet according to pre-defined alphabet mapping. Parameters ---------- character : type Description of parameter `character`. mapping : str Name of map function. Returns ------- type Description of returned object. """ for key in mapping.keys(): if character in key: return mapping[key] return None
def _size_from_shape(shape: tuple) -> int: """ From a tuple reprensenting a shape of a vector it retrives the size. For example (5, 1, 8) --> 40 :param shape: the shape :return: the corresponding size """ if not shape: return 0 out = 1 for k in shape: out *= k return out
def preprocess_arguments(argsets, converters): """convert and collect arguments in order of priority Parameters ---------- argsets : [{argname: argval}] a list of argument sets, each with lower levels of priority converters : {argname: function} conversion functions for each argument Returns ------- result : {argname: argval} processed arguments """ result = {} for argset in argsets: for (argname, argval) in argset.items(): # check that this argument is necessary if not argname in converters: raise ValueError("Unrecognized argument: {0}".format(argname)) # potentially use this argument if argname not in result and argval is not None: # convert to right type argval = converters[argname](argval) # save result[argname] = argval # check that all arguments are covered if not len(converters.keys()) == len(result.keys()): missing = set(converters.keys()) - set(result.keys()) s = "The following arguments are missing: {0}".format(list(missing)) raise ValueError(s) return result
def has_duplicates(t): """Checks whether any element appears more than once in a sequence. Simple version using a for loop. t: sequence """ d = {} for x in t: if x in d: return True d[x] = True return False
def check_num_of_letters(num_of_letters: int) -> int: """Accepts `num_of_letters` to check if it is less than 3. If `num_of_letters` is greater than or equals to 3, return `num_of_letters` as-is. Otherwise, return `num_of_letters` with the value of 6. Args: num_of_letters (int) Returns: num_of_letters (int) """ if num_of_letters < 3: print("Number of letters defined by user is less than 3. \ Using default value of 6.") return 6 else: return num_of_letters
def camel_case(name: str) -> str: """ Convert name from snake_case to CamelCase """ return name.title().replace("_", "")
def shape(matrix): """ calculate shape of matrix """ shape = [] while type(matrix) is list: shape.append(len(matrix)) matrix = matrix[0] return shape
def find_max(dates): """Find maximum date value in list""" if len(dates) == 0: raise ValueError("dates must have length > 0") max = dates[0] for i in range(1, len(dates)): if dates[i] > max: max = dates[i] return max
def _textTypeForDefStyleName(attribute, defStyleName): """ ' ' for code 'c' for comments 'b' for block comments 'h' for here documents """ if 'here' in attribute.lower() and defStyleName == 'dsOthers': return 'h' # ruby elif 'block' in attribute.lower() and defStyleName == 'dsComment': return 'b' elif defStyleName in ('dsString', 'dsRegionMarker', 'dsChar', 'dsOthers'): return 's' elif defStyleName == 'dsComment': return 'c' else: return ' '
def square_table_while(n): """ Returns: list of squares less than (or equal to) N This function creates a list of integer squares 1*1, 2*2, ... It only adds those squares that are less than or equal to N. Parameter n: the bound on the squares Precondition: n >= 0 is a number """ seq = [] k = 0 while k*k < n: seq.append(k*k) k = k+1 return seq
def remove_rectangle(rlist, u_low, u): """ Function to remove non-optimal rectangle from the list of rectangles Parameters ---------- rlist : list List of rectangles. u_low : list Lower bound of the rectangle to remove. u : list Upper bound of the rectangle to remove. Returns ------- list Updated list of rectangles. """ return [r for r in rlist if r != [u_low, u]]
def run_args(args): """Run any methods eponymous with args""" if not args: return False g = globals() true_args = {k for k, v in args.items() if v} args_in_globals = {g[k] for k in g if k in true_args} methods = {a for a in args_in_globals if callable(a)} for method in methods: method(args) return True
def remove_every_other(lst): """Return a new list of other item. >>> lst = [1, 2, 3, 4, 5] >>> remove_every_other(lst) [1, 3, 5] This should return a list, not mutate the original: >>> lst [1, 2, 3, 4, 5] """ return [item for item in lst if lst.index(item) % 2 == 0] # Answer key. NEED TO rememeber slicing return lst[::2]
def xrepr(obj, *, max_len=None): """Extended ``builtins.repr`` function. Examples: .. code-block:: pycon >>> xrepr('1234567890', max_len=7) '12'... :param int max_len: When defined limits maximum length of the result string representation. :returns str: """ result = str(repr(obj)) if max_len is not None and len(result) > max_len: ext = '...' if result[0] in ('"', "'"): ext = result[0] + ext elif result[0] == '<': ext = '>' + ext result = result[:(max_len - len(ext))] + ext return result
def _print_scores(dict_all_info, order, pdbcode): """ Returns the information with the order for export (final_cavities) """ idx = 0 print(f"PDB Cavity_ID, score, size, median_bur, 7thq_bur, hydrophob, interchain, altlocs, missingatoms_res") for cav in order: print(f'{pdbcode} {idx:<10d}{dict_all_info[cav]["score"]:>5.1f}{dict_all_info[cav]["size"]:>7d}{int(dict_all_info[cav]["median_buriedness"]):>8d}' f'{int(dict_all_info[cav]["7thq_buriedness"]):>10d}{dict_all_info[cav]["hydrophobicity"]:>10.2f}{dict_all_info[cav]["interchain"]:>10d}' f'{dict_all_info[cav]["altlocs"]:>10d}{dict_all_info[cav]["missingatoms"]+dict_all_info[cav]["missingres"]:>10d}') idx += 1 return None
def in_filter(url, field_name, val_list): """Summary Args: url (TYPE): Description field_name (TYPE): Description val_list (TYPE): Description Returns: TYPE: Description """ vals = ",".join(val_list) return f"{url}?{field_name}=in.({vals})"
def success(test, msg=None): """Create success status and message object :param test: test with status to be altered :param msg: optional message for success reason :return: updated test object """ if msg is None: msg = 'Test entirely succeeded' test['status'] = 'SUCCESS' test['message'] = msg return test
def filter_user(user_ref): """Filter out private items in a user dict. 'password', 'tenants' and 'groups' are never returned. :returns: user_ref """ if user_ref: user_ref = user_ref.copy() user_ref.pop('password', None) user_ref.pop('tenants', None) user_ref.pop('groups', None) user_ref.pop('domains', None) try: user_ref['extra'].pop('password', None) user_ref['extra'].pop('tenants', None) except KeyError: # nosec # ok to not have extra in the user_ref. pass return user_ref
def del_btn(value): """Delete the last character from current value.""" if len(value) > 1: if value[-1] == " ": return value[0:-3] else: return value[0:-1] else: return 0
def sizeof_fmt(num): """ Returns a number of bytes in a more human-readable form. Scaled to the nearest unit that there are less than 1024 of, up to a maximum of TBs. Thanks to stackoverflow.com/questions/1094841. """ for unit in ['bytes', 'KB', 'MB', 'GB']: if num < 1024.0: return "%3.1f%s" % (num, unit) num /= 1024.0 return "%3.1f%s" % (num, 'TB')
def _map_field(mapping, field, properties=None): """ Takes a mapping dictionary, a field name, and a properties dictionary. If the field is nested (e.g., 'user.name'), returns a nested mapping dictionary. """ fields = field.split('.', 1) if properties is None: properties = {'properties': {}} if 'properties' not in properties: properties['properties'] = {} # base case: not a nested field if len(fields) == 1: new_map = {fields[0]: mapping} properties['properties'].update(new_map) # recursive case: nested field else: if fields[0] in properties['properties']: new_properties = properties['properties'][fields[0]] new_map = _map_field(mapping, fields[1], new_properties) properties['properties'][fields[0]].update(new_map) else: new_map = _map_field(mapping, fields[1]) properties['properties'][fields[0]] = new_map return properties
def snake2pascal(string: str): """String Convert: snake_case to PascalCase""" return ( string .replace("_", " ") .title() .replace(" ", "") )
def IsEventLog(file_path): """Check if file is event log. Currently only checking by extention. Params: file_path: the name of the file to check Returns: bool """ if (file_path.lower().endswith('.evtx') or file_path.lower().endswith('.evt')): return True return False
def cpe_parse(cpe23_uri): """ :param cpe23_uri: :return: """ result = { "vendor": '', "product": '', "version": '', "update": '', "edition": '', "language": '', "sw_edition": '', "target_sw": '', "target_hw": '', "other": '', } try: if cpe23_uri: part = cpe23_uri.split(":") result["vendor"] = part[3] result["product"] = part[4] result["version"] = part[5] result["update"] = part[6] result["edition"] = part[7] result["language"] = part[8] result["sw_edition"] = part[9] result["target_sw"] = part[10] result["target_hw"] = part[11] result["other"] = part[12] return result except Exception as ex: import traceback;traceback.print_exc()
def _build_schema_resource(fields): """Generate a resource fragment for a schema. Args: fields (Sequence[google.cloud.bigquery.schema.SchemaField): schema to be dumped. Returns: Sequence[Dict]: Mappings describing the schema of the supplied fields. """ return [field.to_api_repr() for field in fields]
def _args_to_str(args): """Turn a list of strings into a string that can be used as function args""" return ", ".join(["'{}'".format(a.replace("'", "'")) for a in args])
def clamp(x, a, b): """ Clamps a value x between a minimum a and a maximum b :param x: The value to clamp :param a: The minimum :param b: The maximum :return: The clamped value """ return max(a, min(x, b))