content
stringlengths
42
6.51k
def id2char(dictid): """ Converts single id (int) to character""" if dictid > 0: return chr(dictid) else: return ' '
def linreg(X, Y): """ Summary Linear regression of y = ax + b Usage real, real, real = linreg(list, list) Returns coefficients to the regression line "y=ax+b" from x[] and y[], and R^2 Value """ if len(X) != len(Y): raise ValueError("unequal length") N = len(...
def afs_concordant(af1, af2): """ Checks whether the allele frequencies of two palindromic variants are concordant. Concordant if both are either >0.5 or both are <0.5. Args: af1, af2 (float): Allele frequencies from two datasets Returns: Bool: True if concordant """ assert i...
def convert_bool(bool_str: str) -> bool: """Convert HTML input string to boolean""" return bool_str.strip().lower() in {"true", "yes", "on", "1", "enable"}
def format_taxon_str(row) -> str: """Format a taxon name including common name, if available""" common_name = row.get('taxon.preferred_common_name') return f"{row['taxon.name']}" + (f' ({common_name})' if common_name else '')
def is_int(string: str) -> bool: """ Gets an string and tries to convert it to int :param string: string to be converted :return: True or False """ try: int(string) return True except ValueError: return False
def _serialise(block): """ Serialise block data structure. :param block: block data structure to serialise. :return: string representation of block. """ out = [] for type in ['points', 'curves', 'loops', 'surfaces']: if type not in block: continue for element in b...
def set_master_selectors(facts): """ Set selectors facts if not already present in facts dict Args: facts (dict): existing facts Returns: dict: the facts dict updated with the generated selectors facts if they were not already present """ if 'master' in f...
def HTMLColorToRGB(colorstring): """ convert #RRGGBB to an (R, G, B) tuple from http://code.activestate.com/recipes/266466-html-colors-tofrom-rgb-tuples/ """ colorstring = colorstring.strip() if colorstring[0] == '#': colorstring = colorstring[1:] if len(colorstring) != 6: raise ValueErr...
def underscore_to_camel(underscore_str): """Convert a underscore_notation string to camelCase. This is useful for converting python style variable names to JSON style variable names. """ return ''.join(w.title() if i else w for i, w in enumerate(underscore_str.split('_')))
def isscalar(string): """ Return True / False if input string can transform to a scalar Can not deal with too large number (float) """ try: float(string) return True except ValueError: return False
def num_permutazioni2(n): """ritorna il numero di permutazioni di n oggetti""" if n==0: return 1 risp=0 for first in range(n): risp += num_permutazioni2(n-1) return risp
def digit_sum(n: int) -> int: """ Returns the sum of the digits of the number. >>> digit_sum(123) 6 >>> digit_sum(456) 15 >>> digit_sum(78910) 25 """ return sum(int(digit) for digit in str(n))
def flatten_list(nested_list): # Essentially we want to loop through each element in the list # and check to see if it is of type integer or list """ Flatten a arbitrarily nested list Args: nested_list: a nested list with item to be either integer or list example: [2,[[...
def double_eights(n): """Return true if n has two eights in a row. >>> double_eights(8) False >>> double_eights(88) True >>> double_eights(2882) True >>> double_eights(880088) True >>> double_eights(12345) False >>> double_eights(80808080) False """ "*** YOUR ...
def _get_weights(max_length, alphabet): """Get weights for each offset in str of certain max length. Args: max_length: max length of the strings. Returns: A list of ints as weights. Example: If max_length is 2 and alphabet is "ab", then we have order "", "a", "aa", "...
def implements(obj: type, interface: type) -> bool: """Return true if the give object (maybe an instance or class) implements the interface. """ kimplements = getattr(obj, "__implements__", ()) if not isinstance(kimplements, (list, tuple)): kimplements = (kimplements,) for implementedint...
def build_profile(first,last, **user_info): """Build a dict containing everything we know about user""" user_info['first_name'] = first user_info['last_name'] = last return user_info
def sls_cmd(command, spec): """Returns a shell command string for a given Serverless Framework `command` in the given `spec` context. Configures environment variables (envs).""" envs = ( f"STAGE={spec['stage']} " f"REGION={spec['region']} " f"MEMORY_SIZE={spec['memory_size']} " ...
def get_specification_kinds(specifications): """Required by the framework function""" specifications.setdefault("interface specification", {"tags": ['categories']}) specifications.setdefault("event specification", {"tags": ["environment processes", "functions models"]}) specifications.setdefault("instan...
def schelling_draw(agent): """ Portrayal Method for canvas """ if agent is None: return portrayal = {"Shape": "circle", "r": 0.5, "Filled": "true", "Layer": 0, "stroke_color" : "#4a4a4a"} if agent.type == "Orange": portrayal["Color"] = ["#ff962e", "#ff962e"] else: po...
def angle_subtract(a, b): """Find the difference between two angles. The result should be between -180 (if a<b) and +180 (if a>b) """ res = (a - b) % 360 if res > 180: res -= 360 return res
def pathCount(stairs: int): """number of unique ways to climb N stairs using 1 or 2 steps""" #we've reached the top if stairs == 0: return 1 else: if stairs < 2: return pathCount(stairs - 1) return pathCount(stairs - 2) + pathCount(stairs - 1)
def findDisappearedNumbers(nums): """ :type nums: List[int] :rtype: List[int] """ # For each number i in nums, # we mark the number that i points as negative. # Then we filter the list, get all the indexes # who points to a positive number for i in range(len(nums)): index = a...
def normalize_output(generated_images): """ Normalize from [-1,1] to [0, 255] """ return (generated_images * 127.5) + 127.5
def average(values): """ Return the average of a set of scalar values using built in python functions. """ return sum(values) / len(values)
def calcular_precio_producto(coste_producto): """ num -> num se ingresa un numero y se obtiene el precio del producto sumandole el 50% al coste :param coste_producto: valor numerico del coste :return: precio del producto >>> calcular_precio_producto(1000) 1500.0 >>> calcular_precio_...
def sort_children_key(name): """Sort members of an object :param name: name :type name: str :return: the order of sorting :rtype: int """ if name.startswith("__"): return 3 elif name.startswith("_"): return 2 elif name.isupper(): return 1 else: re...
def make_dictnames(tmp_arr, offset=0): """ Helper function to create a dictionary mapping a column number to the name in tmp_arr. """ col_map = {} for i, col_name in enumerate(tmp_arr): col_map.update({i + offset: col_name}) return col_map
def get_nested_key(element, keys): """ Returns the key at the nested position inside element, which should be a nested dictionary. """ keys = list(keys) if not keys: return element key = keys.pop(0) if key not in element: return return get_nested_key(element[key], keys)
def _encode_for_display(text): """ Encodes strings so they can display as ASCII in a Windows terminal window. This function also encodes strings for processing by xml.etree.ElementTree functions. Returns an ASCII-encoded version of the text. Unicode characters are converted to ASCII placeholders (f...
def n_char(record:str, char="", digit=False): """ This function get the number of characters of certain kind from a string """ if digit or char!="": if digit: n = len([k for k in record if k.isdigit()]) else: n = len([k for k in record if k==char]) else: ...
def precisionatk_implementation(y_true, y_pred, k): """Fujnction to calculate precision at k for a given sample Arguments: y_true {list} -- list of actual classes for the given sample y_pred {list} -- list of predicted classes for the given sample k {[int]} -- top k predictions we are i...
def _get_timestamps(ix_list, ix, orig_ixs): """Returns the first and the last position in a list of an index. Args: ix_list (List): A sorted list of indicies, indicies appear multiple times ix (Int): Index Returns: Tuples: Returns two tuples. """ first_ix = ix_list.index(ix...
def lorentzian_function(x_L, sigma_L, amplitude_L): """Compute a Lorentzian function used for fitting data.""" return amplitude_L * sigma_L**2 / (sigma_L**2 + x_L ** 2)
def getLonLatCrs(searchList): """get the correct names of the columns holding the coordinates @param header Header of the CSV @returns (lon, lat, crs) where lon, lat, crs are the column names """ lng = None lat = None crs = None for t in searchList: if t.lower() in ("longitude", ...
def configure_proxy_settings(ip, port, username=None, password=None): """ Configuring proxies to pass to request :param ip: The IP address of the proxy you want to connect to ie 127.0.0.1 :param port: The port number of the prxy server you are connecting to :param username: The username if requred authentication, ...
def _flatten(source, key=None): """Flattens a dicts values into str for submission Args: source (dict): Data to flatten, with potentially nonhomogeneous value types (specifically, container types). Returns: Dict with all values as single objects. """ result_dict = {} ...
def human_readable_size(byte_size): """Return human-readable size string, using base-10 prefixes.""" if byte_size < 10**3: return f'{byte_size}B' if byte_size < 10**6: return f'{byte_size / 10**3:.1f}kB' if byte_size < 10**9: return f'{byte_size / 10**6:.1f}MB' return f'{byte...
def count_leading_spaces(string: str) -> int: """ Count the number of spaces in a string before any other character. :param string: input string :return: number of spaces """ return len(string) - len(string.lstrip(" "))
def split_identifier(identifier): """ Split an SQL identifier into a two element tuple of (namespace, name). The identifier could be a table, column, or sequence name might be prefixed by a namespace. """ try: namespace, name = identifier.split('"."') except ValueError: name...
def prune_cells(grid): """Given a grid, scan each row for solved cells, and remove those numbers from every other cell in the row. Note that 'grid' can be an iterable of rows, columns, or 3x3 squares. Since the component cells (sets) are modified in-place it still works if you rearrange things....
def row_col_indices_from_flattened_indices(indices, num_cols): """Computes row and column indices from flattened indices. Args: indices: An integer tensor of any shape holding the indices in the flattened space. num_cols: Number of columns in the image (width). Returns: row_indices: The row in...
def searchRange( nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ res=[-1,-1] l,r=0,len(nums)-1 while l<=r: m=l+(r-l)//2 if nums[m]<target: l=m+1 else: r=m-1 res[0]=l l,r=0,len(nums)-1 while l<=r:...
def get_change(m): """ get_change finds the minimum number of coins needed to change the input value (an integer) into coins with denominations 1, 5, and 10. :param m: integer represents the change :return: the min number of coins needed to change m """ m1 = m % 10 m2 = m1 % 5 return...
def merge(left, right): """ deep merge dictionary on the left with the one on the right. Fill in left dictionary with right one where the value of the key from the right one in the left one is missing or None. """ if isinstance(left, dict) and isinstance(right, dict): for key, v...
def fixture_inst_jenny(): """Define example instance data: Jenny.""" return { 'InstanceId': '8675309', 'State': { 'Name': 'stopped' }, 'PublicIpAddress': '10.11.12.13', 'Tags': [{ 'Key': 'Name', 'Value': 'minecraft-main-server-jenny' ...
def vecDotProduct(inVecA, inVecB): """ returns dotproct inVecZ dot inVecB """ return inVecA[0] * inVecB[0] + inVecA[1] * inVecB[1] + inVecA[2] * inVecB[2]
def _maybe_encode_unicode_string(record): """Encodes unicode strings if needed.""" if isinstance(record, str): record = bytes(record, "utf-8").strip() return record
def get_header(token): """Return HTTP header.""" return { "Content-Type": "application/json", "Authorization": "Bearer {}".format(token), }
def capitalize(string): """ Capitalizes the first letter of a string. """ return string[0].upper() + string[1:]
def extractPath(val): """ extract the path from the string returned by an ls -l|a command """ return 'gs://' + val.split('gs://')[1].split('#')[0]
def clean_dict(dictionary, to_del='_'): """ Delete dictionary items with keys starting with specified string Works recursively Args: :dictionary: Dictionary object :to_del: Starts-with identifier """ to_delete = [] for k, v in dictionary.items(): if isinstance(v, d...
def vdc(n, base=2): """ Create van der Corput sequence source for van der Corput and Halton sampling code https://laszukdawid.com/2017/02/04/halton-sequence-in-python/ """ vdc, denom = 0, 1 while n: denom *= base n, remainder = divmod(n, base) vdc += remainder / denom ...
def denormalize(val): """ De-normalize a string """ if val.find('_') != -1: val = val.replace('_','-') return val
def _handle_sort_key(model_name, sort_key=None): """Generate sort keys according to the passed in sort key from user. :param model_name: Database model name be query.(alarm, meter, etc.) :param sort_key: sort key passed from user. return: sort keys list """ sort_keys_extra = {'alarm': ['name', ...
def decode_to_str(batch_text, max_len=512) : """ Converts bytes string data to text. And truncates to max_len. """ return [ ' '.join(text.decode('utf-8').split()[:max_len]) if isinstance(text, bytes) else text[:max_len] for text in batch_text ]
def isPhoneNumber(text): """check if string matches phone number pattern""" if len(text) != 12: return False for i in range(0, 3): if not text[i].isdecimal(): return False if text[3] != '-': return False for i in range(4, 7): if not text[i].isdecimal(): ...
def get_max_delta_score(spliceai_ano_dict_by_symbol): """ get_max_delta_score =================== Method to get the max SpliceAI delta score from a specific ref/alt key in the spliceai_region_dict Parameters: ----------- 1) spliceai_ano_dict_by_symbol: (dict) A sub-dict of the spliceai_regi...
def factorial(n): """Compute n! where n is an integer >= 0.""" if (isinstance)(n, int) and n >= 0: acc = 1 for x in range(1, n + 1): acc *= x return acc else: raise TypeError("the argument to factorial must be an integer >= 0")
def get_username(strategy, uid, user=None, *args, **kwargs): """Removes unnecessary slugification and cleaning of the username since the uid is unique and well formed""" if not user: username = uid else: username = strategy.storage.user.get_username(user) return {'username': userna...
def helper(numRows, triangle): """ [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] """ if numRows <= 2: return triangle[numRows-1] line = [1] prev_line = helper(numRows-1, triangle) for i in range(len(prev_line)-1): line.append(prev_line[i] + pre...
def DeepSupervision(criterion, xs, y): """DeepSupervision Applies criterion to each element in a list. Args: criterion: loss function xs: tuple of inputs y: ground truth """ loss = 0.0 for x in xs: loss += criterion(x, y) loss /= len(xs) return loss
def square_variables(n, m): """dict of symbols and list of values for m-bit binary numbers arranged in an n-by-n square; symbols maps array indices to string encoding those indices""" symbols = dict() values = range(2**m) for i in range(n): for j in range(n): symbols[(i, j)] = '(...
def add_sub_idx(i1: int, change: int): """ Adds or subtracts an index from another one and skips 0 if encountered. :param i1: The start index :param change: The change (+ or -) :return: The new index >>> add_sub_idx(-10, 10) 1 >>> add_sub_idx(10, -10) -1 >>> add_sub_idx(-5, 10) ...
def pad(b): """ Follows Section 5.1: Padding the message """ b = bytearray(b) # convert to a mutable equivalent l = len(b) * 8 # note: len returns number of bytes not bits # append but "1" to the end of the message b.append(0b10000000) # appending 10000000 in binary (=128 in decimal) # follow ...
def terminal_side_effect(state, depth_remaining, time_remaining): """ Side effect returns true if we reach a terminal state :param state: the state of the game to evaluate :param depth_remaining: true if there is depth remaining :param time_remaining: true if there is time remaining :return: true i...
def exclude_deprecated_entities(script_set, script_names, playbook_set, playbook_names, integration_set, integration_ids): """Removes deprecated entities from the affected entities sets. :param script_set: The set of existing scripts within Conten...
def float_parameter(level, maxval): """Helper function to scale `val` between 0 and maxval. Args: level: Level of the operation that will be between [0, `PARAMETER_MAX`]. maxval: Maximum value that the operation can have. This will be scaled to level/PARAMETER_MAX. Returns: A float that ...
def flatten_rules(rules): """ Convenience function to flatten lists which may contain lists of rules to a list with only rules. """ result = [] for rule in rules: if type(rule) is list: result.extend(rule) else: result.append(rule) return result
def get_email_properties(indicator: dict) -> tuple: """ Extract the email properties from the indicator attributes. Example: Indicator: { "attributes": [ { "createdAt": "2019-05-13T16:54:18Z", "id": "abc", "name": "email-body", "value":...
def e_m(val): """energy multiplier""" if val == 5: return 10 elif val >= 6: return 100 else: return None
def check_set(card_set): """ Decide whether the three cards meet the criteria for a set :param card_set: should contain three cards :return: True/False """ allowed = 1, 3 colors = set([]) numbers = set([]) shades = set([]) shapes = set([]) for card in card_set: ...
def spin(x, dancers): """ Remove x characters from the end of the string and place them, order unchanged, on the front. Parameters ---------- x : int Number of characters to be moved from end of dancers to the front of dancers. dancers : str A mutable sequence of cha...
def SanitizeSQL(sql): """Convert singled quotes to dual single quotes, so SQL doesnt terminate the string improperly""" sql = str(sql).replace("'", "''") return sql
def is_float4x4(items): """Verify that the sequence contains 4 sequences of each 4 floats. Parameters ---------- items : sequence The sequence of items. Returns ------- bool """ return ( len(items) == 4 and all( len(item) == 4 and al...
def get_computed_response_parameter_number(response): """ extract the number of parameters from the Dialogflow response, fallback: 0 """ try: return len(response.query_result.parameters) except: return 0
def binary_search(target, lst): """ Perform binary search over the specified list with the specified target. The type of the target should match the types of the elements of the list and the list should be sorted. Parameters ---------- target : Any The element to search for in the ...
def probs(pct): """ Return a human-readable string representing the probabilities. This scheme is shamelessly ripped from CIA's Words of Estimative Probability. https://www.cia.gov/library/center-for-the-study-of-intelligence/csi-publications/books-and-monographs/sherman-kent-and-the-board-of-nati...
def split_bits(word : int, amounts : list): """ takes in a word and a list of bit amounts and returns the bits in the word split up. See the doctests for concrete examples >>> [bin(x) for x in split_bits(0b1001111010000001, [16])] ['0b1001111010000001'] >>> [bin(x) for x in split_bits(...
def calc_piping_thermal_losses_cooling(Total_load_per_hour_W): """ This function estimates the average thermal losses of a distribution for an hour of the year :param Tnet_K: current temperature of the pipe :param m_max_kgpers: maximum mass flow rate in the pipe :param m_min_kgpers: minimum mass flo...
def parseFloat(value, ret=0.0): """ Parses a value as float. This function works similar to its JavaScript-pendant, and performs checks to parse most of a string value as float. :param value: The value that should be parsed as float. :param ret: The default return value if no integer could be pa...
def _deps_compare(package): """Compare deps versions.""" d_compare = None d_version = None for compare in [">=", "<=", ">", "<", "="]: c_idx = package.rfind(compare) if c_idx >= 0: d_compare = compare d_version = package[c_idx + len(compare):len(package)] ...
def max_mod(n, inlist): """Returns k in inlist with the maximum value for n%k""" currMax = 0 ret = inlist[0] #defaults to some item in inlist. for item in inlist: if currMax < n%item: currMax = n%item ret = item return ret
def split_reference_name(reference_name, at="_"): """ Split reference_name at the first `at`. This returns the TE family name if the TEs are named "$ID_$NAME_$SUPERFAMILY". >>> split_reference_name('FBti0019298_rover_Gypsy') 'rover' """ if at in reference_name: return "_".join(refe...
def str_to_array_of_int(value): """ Convert a string representing an array of int into a real array of int """ return [int(v) for v in value.split(",")]
def is_env_var(s): """Environmental variables have a '$$' prefix.""" return s.startswith('$$')
def remove_prefix(string: str, prefix: str) -> str: """ Remove prefix from string. Parameters ---------- string Given string to remove prefix from. prefix Prefix to remove. Raises ------ AssertionError If string doesn't start with given prefix. """ i...
def shift(string: str, shift_num: int) -> str: """ :param shift_num: can be passed as a negative int or a positive one. :return: shifts the string characters by shift_num """ encrypted = "" for let in string: encrypted += chr(ord(str(let)) + shift_num) retur...
def flip_alt_week( alt_week: str, ) -> str: """Flip an alternate week value.""" return 'B2' if alt_week == 'B1' else 'B1'
def check_set(set_playable: list, expected: list ) -> bool: """ helperfunction for testing playable sets **Params**: ------------------------ set_playable: A set of cards Description """ return all(True for card in set_playable if card in expected)
def ppi2microns(val): """convert LCD display resolution in PPI to microns, which is the size of each display pixel. """ return 1000*25.4/val
def median(xs, sort=True): """Returns the median of an unsorted or sorted numeric vector. @param xs: the vector itself. @param sort: whether to sort the vector. If you know that the vector is sorted already, pass C{False} here. @return: the median, which will always be a float, even if the vector...
def list_to_str(l, commas=True): """Converts list to string representation""" if commas: return ','.join(l) else: return ''.join(l)
def get_choice_files(files): """ Adapted from http://stackoverflow.com/questions/4558983/slicing-a-dictionary-by-keys-that-start-with-a-certain-string :param files: :return: """ # return {k:v for k,v in files.iteritems() if k.startswith('choice')} return dict((k, files[k]) for k in files.key...
def getattribute(objeto, name: str): """Returns the attribute matching passed name.""" # Get internal dict value matching name. value = objeto.__dict__.get(name) if not value: # Raise AttributeError if attribute value not found. return None # Return...
def get_dict(post, key): """ Extract from POST PHP-like arrays as dictionary. Example usage:: <input type="text" name="option[key1]" value="Val 1"> <input type="text" name="option[key2]" value="Val 2"> options = get_dict(request.POST, 'option') options['key...
def aread8(np, input, output): """ command: aread8 -p demp.tif -ad8 demad8.tif [-o outletfile.shp] [-wg demwg.tif] [-nc], pfile: input flow directions grid, ad8file: output contributing area grid, Outletfile: input outlets shapefile, wgfile: input weight grid file """ aread8 = "mpirun -np {} aread8 -p {} -ad8 ...
def deg_to_dms(deg): """Convert decimal degrees to (deg,arcmin,arcsec)""" d = int(deg) deg-=d m = int(deg*60.) s=deg-m//60 return d,m,s
def basis_function_ders(degree, knot_vector, span, knot, order): """ Computes derivatives of the basis functions for a single parameter. Implementation of Algorithm A2.3 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math...