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]....
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 ...
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://...
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 = ...
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...
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 '--'...
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`. ...
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....
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 ...
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: ...
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(...
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_...
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 t...
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. ...
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...
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, ...
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 locat...
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_...
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 keyw...
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....
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...
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 ...
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,) ...
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, (lis...
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 ...
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(numb...
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 =...
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 c...
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: ...
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[(colonI...
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 z...
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: retur...
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 / (2...
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 = [...
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:...
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 expres...
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: objli...
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: ...
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': retur...
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: ...
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 fi...
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_st...
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 o...
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 ...
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 argumen...
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: ...
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 ...
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 """ ...
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 re...
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: ...
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...
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: ...
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]["sc...
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'] = 'SUCCES...
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('g...
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: ...
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 = {'propert...
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 ...
def cpe_parse(cpe23_uri): """ :param cpe23_uri: :return: """ result = { "vendor": '', "product": '', "version": '', "update": '', "edition": '', "language": '', "sw_edition": '', "target_sw": '', "target_hw": '', "other...
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() f...
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))