content
stringlengths
42
6.51k
def get_string(array): """return the string for the array""" return "".join([str(x) for x in array])
def _bits_to_int(bits): """Converts bits to int.""" result = 0 for bit in bits: result = (result << 1) | bit return result
def mode_mods_to_int(mode: str) -> int: """Converts mode_mods (str) to mode_mods (int).""" # NOTE: This is a temporary function to convert the leaderboard mode to an int. # It will be removed when the site is fully converted to use the new # stats table. for mode_num, mode_str in enumerate(( ...
def incrementString(text="AAAA"): """Returns the text incremented by one letter The text must be alphabetic or a ValueError is raised. >>> incrementString("A") 'B' >>> incrementString("Z") 'AA' >>> incrementString("AM") 'AN' >>> incrementString("AZ") 'BA' >>> incrementS...
def bytes_label(size): """Returns a human-readable file size with unit label.""" try: size = float(size.encode('ascii', errors='ignore').strip()) except: # probably already text-formatted return size suffix = 'B' suffixes = ['PB', 'TB', 'GB', 'MB', 'KB'] while size >= 102...
def removeengineeringpids(pids): """Removing propcodes that are associated with engineering and calibration proposals""" new_pids=[] for pid in pids: if not pid.count('ENG_') and not pid.count('CAL_'): new_pids.append(pid) return new_pids
def plural_if(zstring, zcondition): """ Returns zstring pluralized (adds an 's' to the end) if zcondition is True or if zcondition is not equal to 1. Example usage could be ``plural_if("cow", len(cow_list))``. """ # If they gave us a boolean value, just use that, otherwise, assume the # v...
def union(span, other): """Union of two spans.""" if span is None or other is None: return None return min(span[0], other[0]), max(span[1], other[1])
def as_cli_arg(property: str) -> str: """We'd like to match command line arguments to their corresponding python variables, but sadly python doesn't allow variable/field names with hyphens. As such, we convert the underscores to hyphens when using command line args. Parameters ---------- ...
def checkListsEqualSize(list1,list2): """ if false, return false,longuestlist else return true,list1 """ if (len(list1)>len(list2)): #~ flagsToQuery[6]= 'HSV > RBG' return False elif(len(list1)<len(list2)): #~ flagsToQuery[6]= 'HSV < RBG' return Fals...
def sum_multiples(start, end, divisor): """ >>> sum_multiples(1, 12, 4) 24 >>> sum_multiples(1, 12, 3) 30 """ result = 0 counter = start while counter <= end: if counter % divisor == 0: result += counter counter += 1 return result
def handle_omeka(omeka_data): """ General handling normally done every time after we grab Omeka data via the API with get_all. """ for obj in omeka_data: # Handle the weird 'element_texts' format by flattening as best we can if 'element_texts' in obj: for element_text in ...
def fixed_mul(a, b): """Multiply fixed values""" return (a >> 8) * (b >> 8)
def filter_list(iterable, include_values): """ Create new list that contains only values specified in the ``include_values`` attribute. Parameters ---------- iterable : list List that needs to be filtered. include_values : list, tuple List of values that needs to be include...
def count_leading_values(lst, char): """count the number of char at the beginnig of the string/bytearray lst""" n = 0 l = len(lst) while n < l and lst[n] == char: n += 1 return n
def format_subarticle(article): """ Format the list of subarticles. :param article: string containing the list of articles :type article: str :return: list of subarticles :rtype: [str] """ articles = article.split(';') articles = [a for sublist in articles for a ...
def merge_index_boundaries(indices): """ Auxiliary function to merge the boundaries of adjacent spans into continuous ones. """ merged_indices = [] j = 0 while j < len(indices): curr_start, curr_end = indices[j] continue_merge = j < len(indices) - 1 and curr_end == indices[j + 1]...
def _dict_keys_get(d, keys): """Recursively get values from d using `__getitem__` """ d = d for k in keys: d = d[k] return d
def quote(string): """ Surround a string with double quotes """ return f'"{string}"'
def str2intlist(s, repeats_if_single=None): """Parse a config's "1,2,3"-style string into a list of ints. Args: s: The string to be parsed, or possibly already an int. repeats_if_single: If s is already an int or is a single element list, repeat it this many times to create the list....
def RKOCstr2code(ocstr): """ Converts output of runge_kutta_order_conditions() to numpy-executable code. """ factors=ocstr.split(',') occode='np.dot(b,' for factor in factors[0:len(factors)-1]: occode=occode+'np.dot('+factor+',' occode=occode+factors[len(factors)-1] o...
def convert_weights_to_dict(weights_list): """ The weights are passed in as a list and we need to convert them to a dict """ db_formatted_weights = {} for weight_details in weights_list: weight_name = weight_details.name weight_value = weight_details.weight db_formatted_weights[weigh...
def n_dgt_Fibo(n): """ Tihs funcion returns the n-th number of the Fibonacci sequence. """ u = 1 v = 1 j = 2 while len(str(v)) < n: u, v = v, u+v j += 1 return j
def db2lin(value): """Convert logarithimic units to linear >>> round(db2lin(10.0), 2) 10.0 >>> round(db2lin(20.0), 2) 100.0 >>> round(db2lin(1.0), 2) 1.26 >>> round(db2lin(0.0), 2) 1.0 >>> round(db2lin(-10.0), 2) 0.1 """ return 10**(value / 10)
def epoch_time(start_time, end_time): """ Function to calculate total time taken in an epoch """ elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) return elapsed_mins, elapsed_secs
def psmid_to_scan(psmid): """ Extract charge from Percolator PSMId. Expects the following formatted PSMId: `run` _ `SII` _ `MSGFPlus spectrum index` _ `PSM rank` _ `scan number` _ `MSGFPlus-assigned charge` _ `rank` See https://github.com/percolator/percolator/issues/147 """ psmid = ps...
def __gen_array(page_id, array_data): """Generate an array of elements.""" content = [] for item in array_data['items']: genfun = globals()['__gen_' + item['type']] content.append(genfun(page_id, item)) if array_data['enclosedInView']: if array_data['orientation'] == 'vertical':...
def naming_convention(dic, convert): """ Convert a nested dictionary from one convention to another. Args: dic (dict): dictionary (nested or not) to be converted. convert (func): function that takes the string in one convention and returns it in the other one. Ret...
def colval(letter: str): """ chess columns are 1-indexed, subtract one to operate on 'board' """ return { "a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "g": 6, "h": 7 }[letter]
def is_string(value): """ Tests the value to determine whether it is a string. :param any value: :return: True of the value is a string (an instance of the str class) >>> is_string( 'Hello' ) True >>> is_string( ['Hello'] ) False """ return isinstance(value, str)
def change_angle_origin(angles, max_positive_angle): """ :param angles: a list of angles :param max_positive_angle: the maximum positive angle, angles greater than this will be shifted to negative angles :return: list of the same angles, but none exceed the max :rtype: list """ if len(angles...
def splitit(l, n): """Utility function to evenly split a list. Handles edge cases. There is probably a 1-liner list comprehension to do this, but it would be super gnarly. @param l list to split (not a generator) @param n number of chunks to split the list into @return list of n lists """ # ...
def dialect_del_fixer(values: str) -> str: """ Fix unprintable delimiter values provided as CLI args """ if values == '\\t': val = '\t' elif values == 'tab': val = '\t' elif values == '\\n': val = '\n' else: val = values return val
def get_real_platform(single_platform: str) -> str: """ Replace different platform variants of the platform provided platforms with the two canonical ones we are using: amd64 and arm64. """ return single_platform.replace("x86_64", "amd64").replace("aarch64", "arm64").replace("/", "-")
def check_data(data): """For a 44-year-old, the api should always return an age, a full retirement age and a value for benefits at age 70 """ if ( data["current_age"] == 44 and data["data"]["full retirement age"] == "67" and data["data"]["benefits"]["age 70"] ): r...
def perm(N, R): """ The permutation function P(N,R) = N!/(N-R)! :param N Total elements. :param R Number to choose. :return <int:permutations> """ result = 1 while N > R: result *= N N -= 1 return result
def supports_raw_attributes(config: dict) -> bool: """Get the supports_raw_attributes config setting.""" return config.get("supports_raw_attributes", False)
def clean_text(text: str) -> str: """ Removes extra spaces and new lines from the text. """ return text.replace('\n', ' ').strip()
def flatten_material(material): """ Flattens a given material. Args: material (dict): material config. Returns: list """ lattice = material["lattice"] return [ material["_id"], material["name"], ", ".join(material["tags"]), len(material["basi...
def getHeaders(environ): """ Get all Headers and return them back as dictionary """ headers = {} for key in list(environ.keys()): if key.startswith('HTTP_'): headers[key[5:]] = environ.get(key) return headers
def is_hex(color): """ Method to check if a color code is hexadecimal (HEX) This method returns the value True if the input argument corresponds to an hexadecimal color code. Parameters ---------- color: :obj: Color code Returns ------- bool True if the input colo...
def csw_query(identifier): """ Create CSW GetRecordById query for a given identifier. """ return f''' <csw:GetRecordById xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" service="CSW" version="2.0.2" outputSchema="http://www.isotc211.org/2005/gmd"> <csw:Id>{identifier}</csw:Id> <csw:ElementSetN...
def ensure_complete_modality(modality_dict, require_rpc=False): """ Ensures that a certain modality (MSI, PAN, SWIR) has all of the required files for computation through the whole pipeline. :param modality_dict: Mapping of a certain modality to its image, rpc, and info files. :type modality_dict: ...
def _add_workdir(path, **kwargs): """Return Dockerfile WORKDIR instruction to set working directory.""" return "WORKDIR {}".format(path)
def remove_citations(descr, citations): """This method is used to replace and citation in markdown format with a link leading to the resource """ for citation in citations: descr = descr.replace("(Citation: " + citation['source_name'] + ")","") return descr
def value_for_key(tuple_of_tuples, key): """Processes a tuple of 2-element tuples and returns the value corresponding to the given key. If no value is found, the key is returned. """ for t in tuple_of_tuples: if t[0] == key: return t[1] else: return key
def get_label2id(labels): """ Get label2id mapping based on labels Args: labels: list of labels. Return: label2id map """ return {v: str(k) for k, v in enumerate(labels)}
def productDict(pairsData): """ transform the data into Dict with product info :param pairsData: (companyName,product) :return: dict={companyName:[product1,...]...} """ product_dict = {} for company_name,product in pairsData: if company_name not in product_dict: product_d...
def test_depth(array_like): """Test object to see how much nested depth it has. Compatible with arbitrarily nested list, tuple, dict, or numpy.ndarray. Compare with numpy.ndarray.ndim. Here we only test array_like[0], which is not thorough. E.g. test_depth( [1, [0, [3]]] ) == 1 ...
def delta_function(value, bands=''): """ Use a delta function to set a specific value. Alternatively you can directly set the value of a parameter if it is going to be constant. This functionality is useful if you want to avoid deleting the `DISTRIBUTION` entry for a parameter in your configuration ...
def linear_intersect(lambda1,lambda2): """ Given two lambda functions corresponding to linear y=mx+b Find the point of intersection x_intersect = (b2-b1)/(m1 - m2) intersect = (tuple) (x,y) intersect """ intersect = (None,None) # extract b's b1 = lambda1(0.0) b2 = lambda2(0.0) # samp...
def has_wildcard(workflow_id_or_label): """Check if string or any element in list/tuple has a wildcard (? or *). Args: workflow_id_or_label: Workflow ID (str) or label (str). Or array (list, tuple) of them. """ if workflow_id_or_label is None: return False ...
def getInterfaceRecord(networkRecords, mac): """ Get the interface record of xen by it's mac. Arguments: interfaces -- Interfaces on xen server. mac -- Mac of the interface. Returns: network object on success else None. """ interfaces = [rec for rec in networkRecords if...
def makeListofDicts(StateVector): """ Just get the data back from the complicated object FFS """ data = [] # empty list. Each element will be a dict for plane in StateVector: data.append(plane.__dict__) return data
def replace(old, new, names, count=-1): """Replace characters that match string.""" return [i.replace(old, new, count) for i in names]
def valid_bytes_128_after(valid_bytes_48_after): """ Fixture that yields a :class:`~bytes` that is 128 bits and is ordered "greater than" the result of the :func:`~valid_bytes_128_after` fixture. """ return valid_bytes_48_after + b'\0' * 10
def attempt(func, *args, **kwargs): """Attempt to call a function.""" if "maxattempt" in kwargs: maxattempt = kwargs.pop("maxattempt") else: maxattempt = 100 test = 1 count = 1 while test: try: func(*args, **kwargs) test = 0 except (Value...
def str2chksm( s ): """ str2chksm(s) -> int,int Keyword arguments: s -- string with first 14 or 15 characters being IMEI Description: If the input string first splitable string has 14 characters then generate the Check Digit for the IMEI code. Return id,None. If the input string first spli...
def difference( f_inverted_index, s_inverted_index ) -> list: """ Operator "OR" :type f_inverted_index: list :type s_inverted_index: list """ if (not f_inverted_index) and (not s_inverted_index): return [] if not f_inverted_index: return [] if not s_invert...
def condense_border_none(css: str) -> str: """Condense border:none; to border:0;. """ return css.replace('border:none;', 'border:0;')
def check_substring(string, substring, normalize = False): """ Normalize compares lower-case """ if normalize: return substring.lower() in string.lower() else: return substring in string
def RPL_TRACELOG(sender, receipient, message): """ Reply Code 261 """ return "<" + sender + ">: " + message
def count_ports(port_mask): """Return the number of ports of given portmask""" ports_in_binary = format(int(port_mask, 16), 'b') nof_ports = ports_in_binary.count('1') return nof_ports
def vec_mul(a, b): """ Multiply two vectors or a vector and a scalar element-wise Parameters ---------- a: list[] A vector of scalar values b: list[] A vector of scalar values or a scalar value. Returns ------- list[] A vector product of a and b """ ...
def _extractFileData(file, dicomMetadata, archivePath=None): """ Extract the useful data to be stored in the `item['dicom']['files']`. In this way it become simpler to sort them and store them. """ result = { 'dicom': { 'SeriesNumber': dicomMetadata.get('SeriesNumber'), ...
def pythagorean_triples(n): """ Return list of pythagorean triples as non-descending tuples of ints from 1 to n. Assume n is positive. @param int n: upper bound of pythagorean triples >>> pythagorean_triples(5) [(3, 4, 5)] """ # helper to check whether a triple is pythagorean and ...
def gen_HttpApiLog(source, action, target): """Generate a Http Api Log object from action and target.""" httpapilog = { "@type": "HttpApiLog", "Subject": source, "Predicate": action, "Object": target } return httpapilog
def check_nomenclature(glycan): """checks whether the proposed glycan has the correct nomenclature for glycowork\n | Arguments: | :- | glycan (string): glycan in IUPAC-condensed format """ if not isinstance(glycan, str): print("You need to format your glycan sequences as strings.") return if '?' i...
def cm2inch(*tupl): """ Convert a value or tuple of values from cm to inches. Source: https://stackoverflow.com/a/22787457 Input --- tupl : float, int or tuple of arbitrary size Values to convert Returns --- Converted values in inches. """ inch = 2.54 if is...
def extract_terms(document): """ document = "545,32 8:1 18:2" extract_terms(document) => returns [[8, 1], [18, 2]] """ terms = [item.split(':') for item in document.split() if item.find(':') >= 0] terms = [[int(term), int(frequency)] for term, frequency in terms] return terms
def extract_nsynth_volume(filename): """function to extract volume level from nsynth dataset base filenames keyboard_acoustic_000-059-075.wav -> 75""" return filename[-6:-4]
def strip_unneeded(text: str) -> str: """Get rid of unneeded characters in text and return it. """ text = text.strip().replace("+", "").replace(",", "").replace(" ", "") if not text: text = "0" return text
def azero(seq): """Return True if all numbers in 'seq' are 0s.""" return not filter(None, seq)
def define_num_LM_eq(lc_list): """ define_num_LM_eq Define the number of equations needed to define the boundary boundary conditions Args: lc_list(): list of all the defined contraints Returns: num_LM_eq(int): number of new equations needed to define the boundary boundary condition...
def hashable(obj): """ Return whether the `obj` is hashable. Parameters ---------- obj : object The object to check. Returns ------- bool """ try: hash(obj) except TypeError: return False return True
def _prioritify(line_of_css, css_props_text_as_list): """Return args priority, priority is integer and smaller means higher.""" sorted_css_properties, groups_by_alphabetic_order = css_props_text_as_list priority_integer, group_integer = 9999, 0 for css_property in sorted_css_properties: if css_p...
def try_get_dn_part(subject, oid=None): """ Tries to extracts the OID from the X500 name. :param subject: :param oid: :return: """ try: if subject is None: return None if oid is None: return None for sub in subject: if oid is not N...
def _find_lines_after_prefix(text, prefix, num_lines): """Searches |text| for a line which starts with |prefix|. Args: text: String to search in. prefix: Prefix to search for. num_lines: Number of lines, starting with line with prefix, to return. Returns: Matched lines. Returns None otherwise. ...
def get_classification(average) -> str: """Return a string containing the classification of the student according to the Programme Specification.""" if average >= 70: return "First Class Honours" if average >= 60: return "Second Class Honours [Upper Division]" if average >= 50: ...
def convertnontitled(nontitledparagraphs): """ Convert non-titled bullets to strings """ string_list = [] for paragraphs in nontitledparagraphs: lines = [] for para in paragraphs: lines.extend(para) string_list.append(b' '.join(lines)) return string_list
def getField(row, field, sheet="submissions"): """ Each row is an array, and this function lets you get a specific value from that row This function is used because row size varies across time and certain rows may not have values at certain positions Also this function lets you u...
def no_disp_settings_page(on=0): """Esconder a Pagina Configuracoes de Video DESCRIPTION Esta opcao esconde a pagina "Configuracoes" do controle de propriedades de video. COMPATIBILITY Todos. MODIFIED VALUES NoDispSettingsPage : dword : 00000000 = Desabili...
def evaluate_groups_score(groups): """Evaluate score of groups.""" return sum([x * y for x, y in zip(groups.keys(), groups.values())])
def sort_defects_on_status(defects): """Sort the defects on status.""" new_bucket = ["New", "To Do"] analyzing_bucket = ["Analyzing", "To_Analyzing"] solving_bucket = ["Solving", "Analyzing_done", "To_Solving"] verifying_bucket = ["Verifying", "To_Reviewing", "Reviewing", "To_Verifying"] closin...
def Read(filename): """Read entire contents of file with name 'filename'.""" fp = open(filename) try: return fp.read() finally: fp.close()
def is_cs_pubkey(provided): """ Check if the value is a proper WAMP-cryptosign public key. :param provided: The value to check. :return: True iff the value is of correct type. """ return type(provided) == bytes and len(provided) == 32
def make_url_of_flair_text(string): """Takes string that MAY not start with http://, if it doesn't it prepends that elsewise returns""" if string is None: return '' # If empty or None return empty string if string.startswith('https://'): return string else: string = "https://" ...
def _extract_meta_instance_id(form): """Takes form json (as returned by xml2json)""" if form.get('Meta'): # bhoma, 0.9 commcare meta = form['Meta'] elif form.get('meta'): # commcare 1.0 meta = form['meta'] else: return None if meta.get('uid'): # bhoma...
def split_string(str, limit, sep="\n"): """ Split string Parameters ---------- str : str string to split limit : int string length limit sep : str separator default: "\n" Returns ------- True if blockquotes are balanced, False otherwise """...
def solution(board, boardSize): """Checks to see if the board is a solution. Args: board (int[]) : The representation of the chess board. boardSize (int) : The size of the n*n chess board. """ # If there is no board, no solution. if not board: return False """ ...
def _matches_app_id(app_id, pkg_info): """ :param app_id: the application id :type app_id: str :param pkg_info: the package description :type pkg_info: dict :returns: True if the app id is not defined or the package matches that app id; False otherwise :rtype: bool """ ...
def distance(x1, y1, x2, y2): """ This calculates the distance between (x1, y1) and (x2, y2) """ return ((x1 - y1) ** 2 + (x2 - y2) ** 2) ** 0.5
def calculateReturn(arrayOfReturns): """Function for calculation of returns function to make code more readable Args: arrayOfReturns ([Float]): Array of retuns from specific month Returns: Float : Returns sum devided by 5 """ return round((sum(arrayOfReturns)/5),2)
def stem(filename): """Get the stem of a filename""" if '.' in filename: return ''.join(filename.split(".")[:-1]) return filename
def validate(var,vals,types): """This function checks if an input is valid by ensuring that does not have a restricted value and that it is of a specified type.""" return bool(var not in vals and isinstance(var,types))
def my_momentum(M, v): """ Calculate total momentum. Args: mass (float): particle mass vel (np.array): particle velocities, shape (natom, ndim) Return: float: total momentum """ return sum(M*v)
def left_join(phrases: tuple) -> str: """ Join strings and replace "right" to "left" """ return ','.join(phrases).replace("right", "left")
def AT(y,x): """ Returns control codes to set the coordinates of the text cursor. Use this in a ``PRINT`` or ``SET`` command. Example: ``PRINT("normal",AT(5,15),"row 5 column 15",AT(14,4),"row 14 column 4")`` Args: - y - integer - the y coordinate to move to (0-23) - x ...
def is_number(arg: str): """ string is number like 1.0, -1 >>> is_number('1.5') """ if len(arg) > 1 and arg[0] == '0': return False if arg.startswith('-'): arg = arg[1:] if arg.isdigit(): return True if arg.find('.') > 0: args = arg.split('.') ...
def filt_dct(dct): """Filter None values from dict.""" return dict((k,v) for k,v in dct.items() \ if v is not None)