content
stringlengths
42
6.51k
def _extract_geojson_srid(obj): """ Extracts the SRID code (WKID code) from geojson. If not found, SRID=4326 :returns: Integer """ meta_srid = obj.get('meta', {}).get('srid', None) # Also try to get it from `crs.properties.name`: crs_srid = obj.get('crs', {}).get('properties', {}).get('name', None) if crs_srid is not None: # Shave off the EPSG: prefix to give us the SRID: crs_srid = crs_srid.replace('EPSG:', '') if (meta_srid is not None and crs_srid is not None and str(meta_srid) != str(crs_srid)): raise ValueError( 'Ambiguous CRS/SRID values: %s and %s' % (meta_srid, crs_srid) ) srid = meta_srid or crs_srid return srid or 4326
def factorial(n: int) -> int: """Computes n!""" result = 1 for i in range (1, n + 1): result *= i return result
def pretty_cmd(cmd): """Print task command in a pretty way.""" string = cmd[0] for elm in cmd[1:]: if elm[0] == "-" and elm[1].isalpha(): string += "\n+ {}".format(elm) elif elm[0] == "-" and elm[1] == "-" and elm[2].isalpha(): string += "\n+ {}".format(elm) else: string += "\t{}".format(elm) return string
def total_ordering(cls): # pragma: no cover """Class decorator that fills in missing ordering methods""" convert = { '__lt__': [ ('__gt__', lambda self, other: not (self < other or self == other)), ('__le__', lambda self, other: self < other or self == other), ('__ge__', lambda self, other: not self < other)], '__le__': [ ('__ge__', lambda self, other: not self <= other or self == other), ('__lt__', lambda self, other: self <= other and not self == other), ('__gt__', lambda self, other: not self <= other)], '__gt__': [ ('__lt__', lambda self, other: not (self > other or self == other)), ('__ge__', lambda self, other: self > other or self == other), ('__le__', lambda self, other: not self > other)], '__ge__': [ ('__le__', lambda self, other: (not self>= other) or self == other), ('__gt__', lambda self, other: self >= other and not self == other), ('__lt__', lambda self, other: not self >= other)] } roots = set(dir(cls)) & set(convert) if not roots: raise ValueError( 'must define at least one ordering operation: < > <= >=') root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__ for opname, opfunc in convert[root]: if opname not in roots: opfunc.__name__ = opname try: op = getattr(int, opname) except AttributeError: # py25 int has no __gt__ pass else: opfunc.__doc__ = op.__doc__ setattr(cls, opname, opfunc) return cls
def format_relation( relation_type: str, start_id: str, end_id: str, **properties) -> dict: """Formats a relation.""" relation = { ':TYPE': relation_type, ':START_ID': start_id, ':END_ID': end_id, } relation.update(properties) return relation
def LineStyle(argument): """Dictionary for switching the line style argument""" switcher = { 'Line': '-', 'Dash': '--', 'DashDot': '-.', 'Dotted': ':' } return switcher.get(argument, 'k-')
def _scale_one_value( value, scaled_min, scaled_max, global_min, global_max ): """Scale value to the range [scaled_min, scaled_max]. The min/max of the sequence/population that value comes from are global_min and global_max. Parameters ---------- value : int or float Single number to be scaled scaled_min : int or float The minimum value that value can be mapped to. scaled_max : int or float The maximum value that value can be mapped to. global_min : int or float The minimum value of the population value comes from. Value must not be smaller than this. global_max : int or float The maximum value of the population value comes from. Value must not be bigger than this. Returns ------- scaled_value: float Value mapped to the range [scaled_min, scaled_max] given global_min and global_max values. """ assert value >= global_min assert value <= global_max # Math adapted from this SO answer: https://tinyurl.com/j5rppewr numerator = (scaled_max - scaled_min) * (value - global_min) denominator = global_max - global_min scaled_value = (numerator / denominator) + scaled_min return scaled_value
def to_bool(string): """Convert string value of true/false to bool""" return string.upper() == "TRUE"
def TruncateInSpace(labText,maxLenLab): """ This truncates a string to a given length but tries to cut at a space position instead of splitting a word. """ if len( labText ) > maxLenLab: idx = labText.find(" ",maxLenLab) # sys.stderr.write("idx=%d\n"%idx) if idx < 0: idx = maxLenLab # BEWARE: This must not fall in the middle of an html entity "&amp;", etc... ... idxSemiColon = labText.find(";",idx) # sys.stderr.write("idxSemiColon=%d\n"%idxSemiColon) if idxSemiColon < 0: idx = maxLenLab else: idx = idxSemiColon + 1 # Just after the semi-colon. # sys.stderr.write("labText=%s idx=%d\n"%(labText,idx)) return labText[:idx] else: return labText
def make_iterable(values, collection=None): """ converts the provided values to iterable. it returns a collection of values using the given collection type. :param object | list[object] | tuple[object] | set[object] values: value or values to make iterable. if the values are iterable, it just converts the collection to given type. :param type[list | tuple | set] collection: collection type to use. defaults to list if not provided. :rtype: list | tuple | set """ if collection is None: collection = list if values is None: return collection() if not isinstance(values, (list, tuple, set)): values = (values,) return collection(values)
def __pos__(self) : """Return self""" return self;
def whether_existing(gram, phrase2index, tot_phrase_list): """If : gram not in phrase2index, Return : not_exist_flag Else : Return : index already in phrase2index. """ if gram in phrase2index: index = phrase2index[gram] return index else: index = len(tot_phrase_list) phrase2index[gram] = index tot_phrase_list.append(gram) return index
def defval(val, default=None): """ Returns val if is not None, default instead :param val: :param default: :return: """ return val if val is not None else default
def initialize_distribution(states, actions): """ initialize a distribution memory :param states: a list of states :param actions: a list of actions :return: a dictionary to record values """ dist = {} for i in states: dist[i] = {} for j in actions: dist[i][j] = [0.0] return dist
def mySortNum(L): """Purpose: to sort a list of lists Parameters: the list in question Return: A sorted list""" n = len(L) if n == 0: return L x = L[0] L1 = [] L2 = [] L3 = [] for i in range(1, n): if L[i][1] < x[1]: L1.append(L[i]) if L[i][1] > x[1]: L2.append(L[i]) if L[i][1] == x[1]: L3.append(L[i]) if 0 <= len(L1) and len(L1) <= 1 and 0 <= len(L2) and len(L2) <= 1: L = L1 + [x] + L3 + L2 return L else: L1 = mySortNum(L1) L2 = mySortNum(L2) L = L1 + [x] + L3 + L2 return L
def _normalize_number(number, intmax): """ Return 0.0 <= number <= 1.0 or None if the number is invalid. """ if isinstance(number, float) and 0.0 <= number <= 1.0: return number elif isinstance(number, int) and 0 <= number <= intmax: return number / intmax return None
def hex2rgb(hx): """ transform 6-digit hex number into [r,g,b] integers :param hx: :return: """ assert len(hx) == 6 rgb = [] for r in range(3): ss = "0x" + hx[2 * r: 2 * r + 2] rr = int(ss, 16) rgb.append(rr) return rgb
def first_non_repeating_letter(string: str) -> str: """ A function named first_non_repeating_letter that takes a string input, and returns the first character that is not repeated anywhere in the string. :param string: :return: """ result = '' string_lower = string.lower() for i, s in enumerate(string_lower): if string_lower.count(s) == 1: return string[i] return result
def cnvrt(val: str) -> str: """Convert special XML characters into XML entities.""" val = str(val) val = val.replace("&", "&amp;") val = val.replace('"', "&quot;") val = val.replace("'", "&apos;") val = val.replace("<", "&lt;") val = val.replace(">", "&gt;") return val
def quick_sorted(items): """Return a list of all items, in non-decreasing order.""" # Base case: the empty list is already sorted. if items == []: return [] # Reduction step: take the first item (call it the pivot) # and put the remaining items in two partitions, # those smaller or equal than the pivot, and those greater. pivot = items[0] left_unsorted = [] right_unsorted = [] for index in range(1, len(items)): if items[index] <= pivot: left_unsorted.append(items[index]) else: right_unsorted.append(items[index]) # Recursive step: sort each of the partitions. left_sorted = quick_sorted(left_unsorted) right_sorted = quick_sorted(right_unsorted) # Inductive step: put the sorted partitions and the pivot # in the correct order. return left_sorted + [pivot] + right_sorted
def get_move(old_i, new_i): """ Returns a string corresponding to the move between two positions of a tile old_i: a tuple representing the old index of the tile new_i: a tuple representing the new index of the tile """ dx = new_i[0] - old_i[0] dy = new_i[1] - old_i[1] if dx > 0: return "left" elif dx < 0: return "right" elif dy > 0: return "up" elif dy < 0: return "down" else: return ""
def transform_sheet_data(sheet_data): """Do anything to change how the data will appear on the spreadsheet. Each key in the dictionary represents a different column""" try: transformed = {} for k, v in sheet_data.items(): transformed[k] = v return transformed except Exception as e: return sheet_data
def B_0(phi_0, m, om, N): """Buoyancy perturbation amplitude. Wavenumber and frequency should be in angular units.""" return (1j*m*N**2/(N**2 - om**2))*phi_0
def chooseSize(string): """ Determines appropriate latex size to use so that the string fits in RAVEN-standard lstlisting examples without flowing over to newline. Could be improved to consider the overall number of lines in the string as well, so that we don't have multi-page examples very often. @ In, string, string, the string by which to determine the size @ Out, chooseSize, string, the LaTeX-ready size at which the string should be represented """ longest = 0 for line in string.split('\n'): longest = max(longest,len(line.rstrip())) if longest < 64: return '\\normalsize' elif longest < 70: return '\\small' elif longest < 77: return '\\footnotesize' elif longest < 96: return '\\scriptsize' else: return '\\tiny'
def ResolveSubnetURI(project, region, subnet, resource_parser): """Resolves the URI of a subnet.""" if project and region and subnet and resource_parser: return str( resource_parser.Parse( subnet, collection='compute.subnetworks', params={ 'project': project, 'region': region })) return None
def parse_magic_invocation(line): """ Parses the magic invocation for the commands As a general rule we want to forward the arguments to sfdx But we also need to pass the variable to capture the results %%sfdx:cmd {var?} {...options} """ args = {"variable": None, "sfdx_args": ""} line = line.strip() if line.startswith("-"): args["sfdx_args"] = line return args else: [variable, *sfdx_args] = line.split(" ") args = {"variable": variable, "sfdx_args": " ".join(sfdx_args)} return args
def getDivisors(intVal): """returns the integer divisors of intVal""" ret = [] for i in range(1,intVal//2+1): if(intVal % i == 0): ret.append(i) return ret
def map_or(func, obj): """ Applies func to obj if it is not None. """ if obj is None: return obj return func(obj)
def get_extension_id(arg): """ Return the extension id from the given console argument :param arg: The console argument :return: The extension id """ if arg.startswith('http://'): arg = arg.replace('http://', 'https://') if arg.startswith('https://'): return arg.split('/')[-1:][0] return arg
def get_seconds(d=0, h=0, m=0, s=0, ms=0): """ Converts inputs to seconds. :param d: Days. :param h: Hours. :param m: Minutes. :param s: Seconds. :param ms: Milliseconds. :return: float representing seconds. """ if (d, h, m, s) == (0, 0, 0): raise Exception("Cannot return 0 seconds. ") return s + 60*m + 60*60*h + 60*60*24*d + 0.001*ms
def message_type_to_notification_class(flash_message_category): """Map a Flask flash message category to a Bulma notification CSS class. See https://bulma.io/documentation/elements/notification/ for the list of Bulma notification states. """ return {"info": "is-info", "success": "is-success", "warning": "is-warning",}.get( flash_message_category, "is-info" )
def is_number(s): """ Check whether string is a number. Plazy version: 0.1.4+ Parameters ---------- s : str String to check. Keyword Arguments ----------------- Returns ------- out : bool Examples -------- .. code-block:: python :linenos: :emphasize-lines: 4,5,6,7,8,9,10 import plazy if __name__ == "__main__": is_number = plazy.is_number("1") # True is_number = plazy.is_number("0.234") # True is_number = plazy.is_number("-0.234") # True is_number = plazy.is_number("1e3") # True is_number = plazy.is_number("plazy") # False is_number = plazy.is_number("1.23k9") # False is_number = plazy.is_number("x.3253254") # False See Also -------- """ try: float(s) return True except ValueError: return False
def subclasses_wrapper(klass): """Wrapper around __subclass__ as it is not as easy as it should.""" method = getattr(klass, '__subclasses__', None) if method is None: return [] try: return method() except TypeError: try: return method(klass) except TypeError: return []
def fresnel_t(pol, kz1, kz2, n1, n2): """Fresnel transmission coefficient. Args: pol (int): polarization (0=TE, 1=TM) kz1 (float or array): incoming wave's z-wavenumber (k*cos(alpha1)) kz2 (float or array): transmitted wave's z-wavenumber (k*cos(alpha2)) n1 (float or complex): first medium's complex refractive index (n+ik) n2 (float or complex): second medium's complex refractive index (n+ik) Returns: Complex Fresnel transmission coefficient (float or array) """ if pol == 0: return 2 * kz1 / (kz1 + kz2) else: return 2 * n1 * n2 * kz1 / (n2 ** 2 * kz1 + n1 ** 2 * kz2)
def countIndent(string): """ Finds how many spaces are in a string before alpanumeric characters appear """ spaces = 0 for c in string: if c == " ": spaces += 1 else: break return spaces
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type( """ import re import unicodedata from six import text_type value = text_type(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf8').strip().lower() value = re.sub(r'[^\w\s\-\.]', '', value) value = re.sub(r'[-\s]+', '-', value) return value
def nullish_coalescing(value, default): """ nullish coalescing utility call Provides a return of the provided value unless the value is a ``None``, which instead the provided default value is returned instead. Args: value: the value default: the default value Returns: the provided value if not ``None``; otherwise, the default value """ if value is None: return default return value
def coluna_para_num(col): """ coluna_para_num: string -> inteiro Esta funcao recebe uma string que representa uma das tres colunas do tabuleiro e devolve o numero da coluna, contando da esquerda para a direita. """ col_num = { 'a': 1, 'b': 2, 'c': 3 } return col_num[col]
def IsLicenseFile(name): """Returns true if name looks like a license file.""" return name in ['LICENSE', 'LICENSE.md', 'COPYING', 'COPYING.txt']
def append_list_comprehension(n): """ >>> append_list_comprehension(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] """ return [i for i in range(n)]
def reverse_transform_values(transform_list: list) -> list: """Changes the values for all transforms in the list so the result is equal to the reverse transform :param transform_list: List of transforms to be turned into a flow field, where each transform is expressed as a list of [transform name, transform value 1, ... , transform value n]. Supported options: ['translation', horizontal shift in px, vertical shift in px] ['rotation', horizontal centre in px, vertical centre in px, angle in degrees, counter-clockwise] ['scaling', horizontal centre in px, vertical centre in px, scaling fraction] :return: List of reversed transforms """ reversed_transform_list = [] for value_list in transform_list: transform, values = value_list[0], value_list[1:] if transform == 'translation': # translate: value is a list of [horizontal movement, vertical movement] reversed_transform_list.append([transform, -values[0], -values[1]]) if transform == 'scaling': # zoom: value is a list of [horizontal coord, vertical coord, scaling] reversed_transform_list.append([transform, values[0], values[1], 1/values[2]]) if transform == 'rotation': # rotate: value is a list of [horizontal coord, vertical coord, rotation in deg] reversed_transform_list.append([transform, values[0], values[1], -values[2]]) return reversed_transform_list
def compare_measure_bounding_boxes(self, other): """Compares bounding boxes of two measures and returns which one should come first""" if self['left'] >= other['left'] and self['top'] >= other['top']: return +1 # self after other elif self['left'] < other['left'] and self['top'] < other['top']: return -1 # other after self else: overlap_y = min(self['bottom'] - other['top'], other['bottom'] - self['top']) \ / min(self['bottom'] - self['top'], other['bottom'] - other['top']) if overlap_y >= 0.5: if self['left'] < other['left']: return -1 else: return 1 else: if self['left'] < other['left']: return 1 else: return -1
def _node_merge_dict(primary_label, primary_key, nodes): """ Convert a set of :class:`.Node` objects into a dictionary of :class:`.Node` lists, keyed by a 3-tuple of (primary_label, primary_key, frozenset(labels)). :param primary_label: :param primary_key: :param nodes: :return: dict of (p_label, p_key, frozenset(labels)) to list(nodes) """ d = {} for node in nodes: p_label = getattr(node, "__primarylabel__", None) or primary_label p_key = getattr(node, "__primarykey__", None) or primary_key key = (p_label, p_key, frozenset(node.labels)) d.setdefault(key, []).append(node) return d
def to_kwargs_str(in_dict): """Transforms a dictionary into a string that can be transformed back via get_kwargs. All values need to be lists. Parameters ---------- in_dict : dictionary Returns ------- str Keys and values are separated by colon+space ": " . List items are separated by spaces " " . Key-value pairs are separated by semicolons ";" . Example: input: {key1: [value1, value2, value3], key2: [value]} output: "key1: value1 value2 value3; key2: value" """ out = '' for key, val in in_dict.items(): out += f'{key}:' assert isinstance( val, list), f'input value for {key} needs to be a list' for v in val: out += f' {v}' out += ';' return out
def list_services(config_dict): """ List available services Args: config_dict (dict): configuration dictionary Returns: list: list of available services """ return list(config_dict.keys())
def get_total_counts(counts): """counts is a dict of dicts""" return sum([sum(vals.values()) for vals in counts.values()])
def tranche99(filt, cutoff=99.6): """ return True if the tranche is below 99.6 VQSRTrancheINDEL90.00to99.00 """ if filt is None: return True if filt[:4] != "VQSR": return False try: return float(filt.split("to")[1]) < cutoff except: return False
def parse_slurm_job_cpus(cpus): """Return number of cores allocated on each node in the allocation. This method parses value of Slurm's SLURM_JOB_CPUS_PER_NODE variable's value. Args: cpus (str): the value of SLURM_JOB_CPUS_PER_NODE Returns: list (int): the number of cores on each node """ result = [] for part in cpus.split(','): if part.find('(') != -1: cores, times = part.rstrip(')').replace('(x', 'x').split('x') for _ in range(0, int(times)): result.append(int(cores)) else: result.append(int(part)) return result
def fair_split(A, B): """ >>> fair_split([0, 4, -1, 0, 3], [0, -2, 5, 0, 3]) 2 >>> fair_split([2, -2, -3, 3], [0, 0, 4, -4]) 1 >>> fair_split([3, 2, 6],[4, 1, 6]) 0 >>> fair_split([1, 4, 2, -2, 5], [7, -2, -2, 2, 5]) 2 """ fair_count = 0 for ii in range(1,len(A)): # O(N * 4n) comlexity. This will not scale at all even though the code is clean. The sum is being # recalculated in every loop iteration. if ( sum(A[:ii]) == sum(A[ii::]) == sum(B[:ii]) == sum(B[ii::] ) ): fair_count += 1 return fair_count
def get_square(x, y, board): """ This function takes a board and returns the value at that square(x,y). """ return board[x][y]
def scoreToReputation(score): """ Converts score (in number format) to human readable reputation format :type score: ``int`` :param score: The score to be formatted (required) :return: The formatted score :rtype: ``str`` """ to_str = { 4: 'Critical', 3: 'Bad', 2: 'Suspicious', 1: 'Good', 0.5: 'Informational', 0: 'Unknown' } return to_str.get(score, 'None')
def calculate_adsorption_energy(adsorbed_energy, slab_energy, n_species, adsorbant_t): """Calculates the adsorption energy in units of eV Parameters ---------- adsorbed_energy : (:py:attr:`float`): slab energy of slab and adsorbed species from DFT slab_energy : (:py:attr:`float`): bare slab energy from DFT n_species : (:py:attr:`int`): number of adsorbed species at the surface adsorbant_t : (:py:attr:`array_like`): dft energy of adsorbing species as a function of temperature Returns ------- :py:attr:`array_like` adsorption energy as a function of temperature """ return ((adsorbed_energy - (slab_energy + (n_species * adsorbant_t))) / n_species)
def parse_options(options): """Parse the analysis options field to a dictionary.""" ret = {} for field in options.split(","): if "=" not in field: continue key, value = field.split("=", 1) ret[key.strip()] = value.strip() return ret
def update_quotes(char, in_single, in_double): """ Code adapted from: https://github.com/jkkummerfeld/text2sql-data/blob/master/tools/canonicaliser.py """ if char == '"' and not in_single: in_double = not in_double elif char == "'" and not in_double: in_single = not in_single return in_single, in_double
def _get_request_header(request, header_name, default=''): """Helper method to get header values from a request's META dict, if present.""" if request is not None and hasattr(request, 'META') and header_name in request.META: return request.META[header_name] else: return default
def clean_string(text): """ Function for basic cleaning of cruft from strings. :param text: string text :return: cleaned string """ replacements = {'&amp;': '&', '&lt;': '<', '&gt;': '>'} for x, y in replacements.items(): text = text.replace(x, y) return text
def make_db_entry(run_time_ix_seconds, run_time_ecl2ix_seconds, num_processes): """ Linked to indices above. """ return [run_time_ix_seconds, run_time_ecl2ix_seconds, num_processes]
def mapValues( d, f ): """Return a new dict, with each value mapped by the given function""" return dict([ ( k, f( v ) ) for k, v in d.items() ])
def create_masks(degree): """ Create masks for taking bits from text bytes and putting them to image bytes. :param degree: number of bits from byte that are taken to encode text data in audio :return: mask for a text and a mask for a sample """ text_mask = 0b1111111111111111 sample_mask = 0b1111111111111111 text_mask <<= (16 - degree) text_mask %= 65536 sample_mask >>= degree sample_mask <<= degree return text_mask, sample_mask
def InvertDict( aDict ): """Return an inverse mapping for the given dictionary""" assert len( set( aDict.values() ) ) == len( aDict ) return dict( ( v, k ) for k, v in aDict.items() )
def converttostr(input_seq, seperator): """ Desc: Function to convert List of strings to a string with a separator """ # Join all the strings in list final_str = seperator.join(input_seq) return final_str
def fmt_time(s, minimal=True): """ Args: s: time in seconds (float for fractional) minimal: Flag, if true, only return strings for times > 0, leave rest outs Returns: String formatted 99h 59min 59.9s, where elements < 1 are left out optionally. """ ms = s-int(s) s = int(s) if s < 60 and minimal: return "{s:02.3f}s".format(s=s+ms) m, s = divmod(s, 60) if m < 60 and minimal: return "{m:02d}min {s:02.3f}s".format(m=m, s=s+ms) h, m = divmod(m, 60) return "{h:02d}h {m:02d}min {s:02.3f}s".format(h=h, m=m, s=s+ms)
def wait_screen_load(path): """ Waits Nation Selection screen to load :param path: dominions log path :return: True if load was complete """ valid = False i = 0 while i < 1000000: try: with open(path + 'log.txt') as file: blurb = file.read() load_complete = blurb.rfind('playturn: autohost') # battle loaded if load_complete == -1: i += 1 continue if load_complete != -1: # Player Won valid = True break except FileNotFoundError: i += 1 return valid
def get_lonlats(transmitters): """ Return a list of longitude-latitude pairs (float pairs) representing the locations of the given transmitters. If ``transmitters`` is empty, then return the empty list. INPUT: - ``transmitters``: a list of transmitters of the form output by :func:`read_transmitters` OUTPUT: String """ return [(t['longitude'], t['latitude']) for t in transmitters]
def skaff_description_get(short: bool=True) -> str: """ Returns the description string of the skaff program. A concise description will be returned if 'short' is set to True; otherwise the full version is returned instead. """ short_description = "An Extensible Project Scaffolding Tool" long_description = ("Skaff is a Python library for building programming " "language dependent scaffolding of software projects, " "and a command-line tool that uses this library with " "built-in (CMake-based) C/C++ support.") if short: return short_description else: return long_description
def unprefix(prefix, d, all=False): """ Returns a new dict by removing ``prefix`` from keys. If ``all`` is ``False`` (default) then drops keys without the prefix, otherwise keeping them. """ d1 = dict(d) if all else {} d1.update((k[len(prefix):], v) for k, v in d.items() if k.startswith(prefix)) return d1
def parse_version_tag(version_tag): """ :param str version_tag: the version tag. :return: Given a version tag, return it as a list of ints :rtype: list[int] """ return [int(x) for x in version_tag.lower().replace('v', '').split('.')]
def getBit(num, n): """ Return the nth bit (0-indexed) of num. """ shifted = num >> n return shifted & 1
def set_bit(a, order): """ Set the value of a bit at index <order> to be 1. """ return a | (1 << order)
def HexToByte( hexStr ): """ Convert a string hex byte values into a byte string. The Hex Byte values may or may not be space separated. """ # The list comprehension implementation is fractionally slower in this case # # hexStr = ''.join( hexStr.split(" ") ) # return ''.join( ["%c" % chr( int ( hexStr[i:i+2],16 ) ) \ # for i in range(0, len( hexStr ), 2) ] ) bytes = [] hexStr = ''.join( hexStr.split(" ") ) for i in range(0, len(hexStr), 2): bytes.append( chr( int (hexStr[i:i+2], 16 ) ) ) return ''.join( bytes )
def get_hand(indices, game_lines): """Return a subset of the game between the supplied indices.""" hand_start_index, hand_end_index = indices return game_lines[hand_start_index : hand_end_index + 1]
def split_fields(fields): """ >>> from comma.csv.applications.csv_eval import split_fields >>> split_fields('') [] >>> split_fields('x') ['x'] >>> split_fields('x,y') ['x', 'y'] """ return fields.split(',') if fields else []
def IsFloat(str): """ ISFLOAT checks if a given string is a float. Call - OUTPUT=IsFloat(STR) INPUT VARIABLE: STR - A string for checking whether a float or not OUTPUT VARIABLE: OUTPUT - A boolean value corresponding to whether STR is a float (returns TRUE) or not (returns FALSE) """ #See if STR is a float try: float(str) #If test fails, return FALSE except Exception: return False #If passed the test, return TRUE return True
def isSuffixOf(xs, ys): """``isSuffixOf :: Eq a => [a] -> [a] -> Bool`` Returns True if the first list is a suffix of the second. The second list must be finite. """ return xs == ys[-len(xs):]
def beta(temp, optimum=295.65, tmin=278.15, tmax=313.15, k=0.003265): """Calculate the environment parameter beta. This is like a birth rate that reaches a maximum at an optimal temperature, and a range of birth rates is specified by a parabolic width parameter of k=0.003265. 1 - k*(temp-optimum)**2 Arguments --------- temp : float The environment temperature experienced by the daisies Keyword arguments ----------------- optimum = 295.65 : float The optimum temperature for daisy birthrate. tmin = 278.15 : float Maximum temperature for birthrate. tmax = 313.15 : float Minimum temperature for birthrate. k = 0.003265 : float Quadratic width parameter. """ if (temp>tmin)&(temp<tmax): return 1 - k*(temp-optimum)**2 else: return 0
def kwh_to_gwh(kwh): """"Conversion of MW to GWh Arguments --------- kwh : float Kilowatthours Return ------ gwh : float Gigawatthours """ gwh = kwh * 0.000001 return gwh
def upcase(val: str) -> str: """Make all characters in a string upper case.""" return val.upper()
def find_line_starting_with_seq(the_list, seq, from_index=0, to_index=-1): """ Returns index of line in the document that starts with specified char sequence. Or -1 if sequence not found. :param the_list: list of strings :param seq: char sequence to find; :param from_index: index in the list; :param to_index: index in the list, open range; if is negative, the list will be searched till the end; :return: index of the first occurrence of 'seq' in the list or -1 if not found """ if to_index < 0: to_index = len(the_list) if from_index > to_index: from_index = to_index for i in range(from_index, to_index): if the_list[i].startswith(seq): return i return -1
def post_process_headways(avg_headway, number_of_trips_per_hour, trip_per_hr_threshold=.5, reset_headway_if_low_trip_count=180): """Used to adjust headways if there are low trips per hour observed in the GTFS dataset. If the number of trips per hour is below the trip frequency interval, headways are changed to reset_headway_if_low_trip_count_value (defaults to 180 minutes).""" if number_of_trips_per_hour <= trip_per_hr_threshold: # If Number of Trips Per Hour is less than .5, set to 180. avg_headway = reset_headway_if_low_trip_count return avg_headway
def prime_factors(n: int) -> list: """ Returns all prime factors of n """ i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) if len(factors) == 1 and factors[0] == n: raise ValueError("Number to be factored should not be a prime") return factors
def gen_resource_arr(search_results: dict): """ Generates an array which contains only the names of the current selected resources Args: search_results (dict): The output of searcher.py Returns: list: All resource keys that show up in the search_results dict. """ resources = [] # only wms and dataset might have downloadable content for search_results_key, search_results_val in search_results.items(): resources.append(search_results_key) return resources
def fam2hogid(fam_id): """ For use with OMA HOGs Get hog id given fam :param fam_id: fam :return: hog id """ hog_id = "HOG:" + (7-len(str(fam_id))) * '0' + str(fam_id) return hog_id
def check_duplicates_in_tag_tuple(tagtuple): """Check if there is duplicate in a tag tuple, case sensitive Args: tagTuple (tuple) : the tag tuple to check """ _dup = -1 for _i, _k in enumerate(tagtuple): if _k in tagtuple[:_i]: _dup = _i break return _dup
def area_square(side_length: float) -> float: """ Calculate the area of a square. >>> area_square(10) 100 >>> area_square(-1) Traceback (most recent call last): ... ValueError: area_square() only accepts non-negative values """ if side_length < 0: raise ValueError("area_square() only accepts non-negative values") return side_length ** 2
def int_to_en(num): """Given an int32 number, print it in English.""" d = { 0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen", 16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen", 20: "twenty", 30: "thirty", 40: "forty", 50: "fifty", 60: "sixty", 70: "seventy", 80: "eighty", 90: "ninety", } k = 1000 m = k * 1000 b = m * 1000 t = b * 1000 assert num >= 0 if num < 20: return d[num] if num < 100: if num % 10 == 0: return d[num] return d[num // 10 * 10] + " " + d[num % 10] if num < k: if num % 100 == 0: return d[num // 100] + " hundred" return d[num // 100] + " hundred and " + int_to_en(num % 100) if num < m: if num % k == 0: return int_to_en(num // k) + " thousand" return int_to_en(num // k) + " thousand, " + int_to_en(num % k) if num < b: if (num % m) == 0: return int_to_en(num // m) + " million" return int_to_en(num // m) + " million, " + int_to_en(num % m) if num < t: if (num % b) == 0: return int_to_en(num // b) + " billion" return int_to_en(num // b) + " billion, " + int_to_en(num % b) if num % t == 0: return int_to_en(num // t) + " trillion" return int_to_en(num // t) + " trillion, " + int_to_en(num % t)
def get_shard(org): """ Gets the org shard to build and return the API URL :param org: organization dictionary :return: base url with correct shard """ urlLength = org['url'].find('com') + 3 orgShard = org['url'][8:urlLength] base_url = 'https://' + orgShard + '/api/v1' return base_url
def coerce_to_int(val, default=0xDEADBEEF): """ Attempts to cast given value to an integer, return the original value if failed or the default if one provided. """ try: return int(val) except (TypeError, ValueError): if default != 0xDEADBEEF: return default return val
def is_sequence_like(x): """ Returns True if x exposes a sequence-like interface. """ required_attrs = ( '__len__', '__getitem__' ) return all(hasattr(x, attr) for attr in required_attrs)
def pColorCC( color ): """ returns the likelihood of observing host galaxy with the given rest-frame B-K color, assuming the SN is a CC RETURNS : P(B-K|CC) """ if color < 3 : return( 0.484, 0.05, 0.05 ) elif color < 4 : return( 0.485, 0.05, 0.05 ) else : return( 0.032, 0.05, 0.05 )
def decode_channel_parameters(channel): """Decode a channel object's parameters into human-readable format.""" channel_types = { 1: 'device', 5: 'static', 6: 'user input', 7: 'system' } io_options = { 0: 'readonly', 1: 'readwrite' } datatype_options = { 1: "float", 2: 'string', 3: 'integer', 4: 'boolean', 5: 'datetime', 6: 'timespan', 7: 'file', 8: 'latlng' } channel['channelType'] = channel_types[channel['channelType']] channel['io'] = io_options[channel['io']] channel['dataType'] = datatype_options[channel['dataType']] return channel
def intersperse(lst, item): """ Adds the item between each item in the list. :param lst: :param item: :return: """ result = [item] * (len(lst) * 2 - 1) result[0::2] = lst return result
def bounds1D(full_width, step_size): """ Return the bbox coordinates for a single dimension given the size of the chunked dimension and the size of each box """ assert step_size > 0, "invalid step_size: {}".format(step_size) assert full_width > 0, "invalid volume_width: {}".format(full_width) start = 0 end = step_size bounds = [] while end < full_width: bounds.append(slice(start, end)) start += step_size end += step_size #last window bounds.append(slice(start, end)) return bounds
def is_x_power_of_2(x): """return if x is a power of 2 in O(1)""" # drops the lowest bit and checks if it's zero # power of 2 comes in the form: 1, 10, 100, 1000 etc. exactly 1 bit set return x & (x - 1) == 0
def get_domain_name_for(host_string): """ Replaces namespace:serviceName syntax with serviceName.namespace one, appending default as namespace if None exists """ return ".".join( reversed( ("%s%s" % (("" if ":" in host_string else "default:"), host_string)).split( ":" ) ) )
def _single_list_check_str(X): """ If type is string, return string in list """ if(type(X) == str): X = [X] return X
def parse_args_tags(args_tag, to='dict'): """ parse argument string of tags 'tag:value tag:value' into a dictionary. Args: args_tag (str): tags in string format 'tag:value tag:value' to (str): Make a 'list' or 'dict' (default) Returns: (list(str) or dict(str)): """ if to == 'list': tag_thing = [] else: tag_thing = {} if args_tag: if to == 'list': tag_thing = ['{}'.format(kv[0]) for kv in args_tag] if to == 'dict': tag_thing = {k: v for k, v in [kv[0].split(':') for kv in args_tag]} return tag_thing
def iindex(x, iterable): """Like list.index, but for a general iterable. Note that just like ``x in iterable``, this will not terminate if ``iterable`` is infinite, and ``x`` is not in it. Note that as usual when working with general iterables, the iterable will be consumed, so this only makes sense for memoized iterables (and even then it may be better to extract the desired part as a list and then search there). """ for j, elt in enumerate(iterable): if elt == x: return j raise ValueError("{} is not in iterable".format(x))
def get_nested_item(d, list_of_keys): """Returns the item from a nested dictionary. Each key in list_of_keys is accessed in order. Args: d: dictionary list_of_keys: list of keys Returns: item in d[list_of_keys[0]][list_of_keys[1]]... """ dct = d for i, k in enumerate(list_of_keys): assert ( k in dct ), f"Key {k} is not in dictionary after seeing {i+1} keys from {list_of_keys}" dct = dct[k] return dct
def set_nreg(reg): """ Set number of extra parameters due to regularization """ if reg is not None: if reg == 'Tikhonov': N = 1 elif reg == 'GP': N = 3 elif reg == 'GP2': N = 2 else: print("%s is not a valid regularization method. Using no regularization." %reg) N = 0 else: N = 0 return N
def toTable(config): """Transforms a two-level dictionary of configuration options into a list-of-dictionaries, each with the following fields: * section * field * value """ table = [] for section in config.keys(): for k, v in config[section].items(): table.append({ "section": section, "field": k, "value": v }) return table