content
stringlengths
42
6.51k
def binary_search(numbers, look): """Binary Search algorithm""" # Split at the start start = 0 # Start is beginning mid = len(numbers) // 2 # the middle end = len(numbers) - 1 # end found = -2 # temp not found # is it empty? if not numbers: return -1 def check_val(_start, _mid, _end): """Checks if the value is equal""" if numbers[_start] == look: # is the start found? return _start elif numbers[_end] == look: # is the end found? return _end elif numbers[_mid] == look: # is the middle found? return _mid elif _mid == _end or _mid == _start: # Is there no middle? return -1 else: return -2 # Nothing found while 1: # Start looping found = check_val(start, mid, end) # do the check if found > -2: # is the value finally found break # Split the list. if numbers[mid] > look: # Split from the start, to middle. [left] end = mid # Set end to middle mid = int(end / 2) # Find the new middle else: start = mid # Set start to middle mid = int(start + ((end - mid) / 2)) # Find the new middle return found
def is_valid_uni(uni): """ Validate the syntax of a uni string """ # UNIs are (2 or 3 letters) followed by (1 to 4 numbers) # total length 3~7 if not isinstance(uni,str): return False if len(uni) < 3 or len(uni) > 7: return False if uni[:3].isalpha(): # 3 letters return uni[3:].isnumeric() elif uni[:2].isalpha(): # 2 letters return uni[2:].isnumeric() else: return False
def format_dir_space(dirpath): """REMOVE ESCAPED SPACES FROM DIRECTORY PATH Args: dirpath: Str, directory path to be corrected Returns: dirpath: Str, directory path with plain spaces and appended backslash """ dirpath = dirpath.replace("\ ", " ") if dirpath[-1] != '/': dirpath = dirpath + '/' return dirpath
def tetrahedral(number): """ Returns True if number is tetrahedral """ # n-th tetrahedral number is n * (n + 1) * (n + 2) / 6 n = 1 while True: p = n * (n + 1) * (n + 2) / 6 if p == number: return True elif p > number: return False n = n + 1
def api_repo_url(org_name): """ With the supplied organization name, constructs a GitHub API URL :param org_name: GitHub organization name :return: URL to GitHub API to query org's repos """ return 'https://api.github.com/orgs/{}/repos'.format(org_name)
def as_twos_comp(value: int) -> int: """Interpret number as 32-bit twos comp value.""" if value & 0x8000_0000 != 0: # negative flipped_value = (~value) & 0xFFFF_FFFF return -(flipped_value + 1) else: # positive return value
def isString( obj ): """ Returns a boolean whether or not 'obj' is of type 'str'. """ return isinstance( obj, str )
def build_config(column): """Return router configuration with values from row. :param column: mapping of values from csv columns for router_id :type column: dict :return: router configuration (list) """ # > > > Paste configuration *BELOW* the next line ("return \") < < < return \ [ { "system": { "system_id": column["B"] }, "wlan": { "radio": { "0": { "bss": { "0": { "ssid": column["d"] } } }, "1": { "bss": { "0": { "ssid": column["d"] } } } } } }, [] ] # > > > Paste configuration ^ ABOVE HERE ^ < < < # > > > Replace config values with corresponding csv column letters < < <
def slashescape(err): """ codecs error handler. err is UnicodeDecode instance. return a tuple with a replacement for the unencodable part of the input and a position where encoding should continue""" #print(err, dir(err), err.start, err.end) thebyte = err.object[err.start:err.end] repl=u'' for i in thebyte:#Sett MODED repl=repl+u'\\x'+hex(ord(chr(i)))[2:]#Sett MODED return (repl, err.end)
def part2(allergens): """Part 2 wants the list of unsafe ingredients, sorted by their allergen alphabetically, joined together into one string by commas. """ return ",".join( ingredient for (allergen, ingredient) in sorted(allergens.items()) )
def list_format(lst): """ Unpack a list of values and write them to a string """ return '\n'.join(lst)
def _init_well_info(well_info, wname): """Initialize well info dictionary for well """ if wname not in well_info.keys(): winfo = dict() winfo['welltype'] = 'Producer' winfo['phase'] = 'Oil' well_info[wname] = winfo return well_info
def get_num_tablets_per_dose(dose, strength, divisions=1): """Calculates the number of tablets to give based on the dose given and the strength of the tablets. Tablets can be divided in quarters. :params: dose (Float) - The dose in mg of what the patient should be receiving strength (Float) - The strength in mg of the chosen tablets. divisions (Int) - the number of sections you can divide your tablet into :returns: Number of tablets per dose (Float) - fixed to one of the points of the divisions >>> get_num_tablets_per_dose(120, 100, 2) 1.0 >>> get_num_tablets_per_dose(240, 100, 2) 2.5 #Divide into quarters >>> get_num_tablets_per_dose(120, 100, 4) 1.25 """ num_tabs = dose/strength return round(num_tabs * divisions)/divisions
def from_camelcase(s): """ convert camel case to underscore :param s: ThisIsCamelCase :return: this_is_camel_case """ return ''.join(['_' + c.lower() if c.isupper() else c for c in s]).lstrip('_')
def hex_to_rgb(color): """Convert a hex color code to an 8 bit rgb tuple. Parameters ---------- color : string, must be in #112233 syntax Returns ------- tuple : (red, green, blue) as 8 bit numbers """ if not len(color) == 7 and color[0] == "#": raise ValueError("Color must be in #112233 format") color = color.lstrip("#") return tuple(int(color[i : i + 2], 16) for i in (0, 2, 4))
def horizontal_plate_natual_convection_1(Gr, Pr): """hot side upward, or cold side downward """ """ 1e4 < Ra < 1e11 """ Ra = Gr * Pr if Ra < 1.0e7: return 0.54 * Ra**0.25 else: return 0.15 * Ra**0.25
def dnfcode_key(code): """Return a rank/dnf code sorting key.""" # rank [rel] '' dsq hd|otl dnf dns dnfordmap = { u'rel':8000, u'':8500, u'hd':8800,u'otl':8800, u'dnf':9000, u'dns':9500, u'dsq':10000,} ret = 0 if code is not None: code = code.lower() if code in dnfordmap: ret = dnfordmap[code] else: code = code.strip(u'.') if code.isdigit(): ret = int(code) return ret
def to_name_key_dict(data, name_key): """ Iterates a list of dictionaries where each dictionary has a `name_key` value that is used to return a single dictionary indexed by those values. Returns: dict: Dictionary keyed by `name_key` values having the information contained in the original input list `data`. """ return dict((row[name_key], row) for row in data)
def unify_walk(l1, l2, U): """ Tries to unify each corresponding pair of elements from l1 and l2. """ if len(l1) != len(l2): return False for x1, x2 in zip(l1, l2): U = unify_walk(x1, x2, U) if U is False: return False return U
def trash_file(drive_service, file_id): """ Move file to bin on google drive """ body = {"trashed": True} try: updated_file = drive_service.files().update(fileId=file_id, body=body).execute() print(f"Moved old backup file to bin.") return updated_file except Exception: print(f"!!! did not find old bkp file with id {file_id}")
def cross(a, b): """The cross product between vectors a and b. This code was copied off of StackOverflow, but it's better than making you download numpy.""" c = (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]) return c
def extract_stat_names(dict_of_stats): """ Extracts all the names of the statistics Args: dict_of_stats (dict): Dictionary containing key-alue pair of stats """ stat_names = [] for key, val in dict_of_stats.items(): stat_names += [key] return stat_names
def weighted_uniform_strings(s, queries): """Given a string s, and a list of weight queries return a list indicating if query is possible.""" weights = [] last_char, repetitions = None, 1 for c in s: val = ord(c) - 96 if last_char == val: repetitions += 1 else: repetitions = 1 weights.append(val * repetitions) last_char = val weights = set(weights) results = [] for q in queries: results.append('Yes' if q in weights else 'No') return results
def short_method_name(method_name: str) -> str: """ This function takes a long method name like "class_name::method_name" and return the short method name without the class prefix and the "::" separator. """ if "::" not in method_name: return method_name return method_name.split("::",1)[1]
def check_path(dirs): """Check if directory path has '/' at the end. Return value is either '/' or empty string ''. """ if dirs[-1] != "/": return "/" else: return ""
def get_water_info(data: dict, hostname: str, path: str): """ Use in ows_cfg.py as below: "feature_info": { "include_custom": { "function" : "datacube_ows.feature_info_utils.get_water_info", "kwargs" : { "hostname" : "https://data.dea.ga.gov.au", "path" : "projects/WaterBodies/feature_info/" } } } Returns: [dict] -- Timeseries feature info """ return { 'timeseries': f"{hostname}/{path}" f"{int(data['dam_id']) // 100:04}/{int(data['dam_id']):06}.csv" }
def bubble_sort_rc(array): """perform bubble search recursively""" # Check whether all values in list are numbers if all(isinstance(x, (int,float)) for x in array): for ind, val in enumerate(array): try: if array[ind+1] < val: array[ind] = array[ind+1] array[ind+1] = val bubble_sort_rc(array) except IndexError: pass return array else: print("all values in array needs to be a number")
def preproc_space(text): """line preprocessing - removes first space""" return text.replace(" ", "", 1) if text.startswith(" ") else text
def expandCall(kargs): """SNIPPET 20.10 PASSING THE JOB (MOLECULE) TO THE CALLBACK FUNCTION Expand the arguments of a callback function, kargs['func'] """ func=kargs['func'] del kargs['func'] out=func(**kargs) return out
def wrap_angle(x): """Wraps an angle between 0 and 360 degrees Args: x: the angle to wrap Returns: a new angle on the interval [0, 360] """ if x < 0: x = 360 - x elif x > 360: x = x - 360 return x
def get_suitable_astropy_format(outputFormat): """ Reason for change ----------------- Translate the right file extension to one astropy would recognize """ if "csv" == outputFormat: return "ascii.csv" if "tsv" == outputFormat: return "ascii.fast_tab" return outputFormat
def get_total(alist, digits=1): """ get total sum param alist: list param digits: integer [how many digits to round off result) return: float """ return round(sum(alist), digits)
def parser_data_broadcast_id_Descriptor(data,i,length,end): """\ parser_data_broadcast_id_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). Parses a descriptor containing a list of alternative frequences on which the multiplex may be carried. The dict returned is: { "type" : "data_broadcast_id", "id" : numeric identifier for the way in which the data is being broadcast "selectors" : string data specific to the data broadcast type } The id specifies the kind of data broadcast. For example, 0x106 has been registered by TDN for use in the United Kingdom Digital Terrestrial network for 'interactive' applications. The selectors are data specific to the particular kind of data broadcast, generally used to specify an 'interactive app' to be loaded when the channel or data broadcast is tuned to by the user. (Defined in ETSI EN 300 468 specification and "The D book") """ d = { "type" : "data_broadcast_id", "id" : (ord(data[i+2])<<8) + ord(data[i+3]), "selectors" : data[i+4:end], } return d
def splitCentersByBeats(centers, splitter_dict): """ Split list of note centers by beats """ # Sort by columns column_sorted_centers = sorted(centers, key=lambda x: x[0]) beats = {} current_offset = 0 total_counter = 0 counter = 0 for key in sorted(splitter_dict.keys()): beat = [] counter = 0 for note_center in column_sorted_centers[current_offset:]: beat.append(note_center) counter += 1 if counter == splitter_dict[key]: break if beat: beats[key] = beat current_offset += counter total_counter += counter assert total_counter == len( centers), "Number of notes in the measure doesn't match the expectation" return beats
def normalize_string(str_input: str): """ Given a string, remove all non alphanumerics, and replace spaces with underscores """ str_list = [] for c in str_input.split(" "): san = [lo.lower() for lo in c if lo.isalnum()] str_list.append("".join(san)) return "_".join(str_list)
def replace_all(text, dic): """ https://stackoverflow.com/a/6117042 """ for i, j in dic.items(): text = text.replace(i, j) return text
def messageSend(num, text): """ :param num : Notification number (1: 'danger', 2: 'info', 3: 'success') :param text: Message text :return: Message """ alert = {1: 'danger', 2: 'info', 3: 'success'} if num != 1 and num != 2 and num != 3: num = 1 text = "Error. Wrong number of alert!" message = ''' <div class="alert alert-{} alert-dismissible fade show" role="alert" align="center"> <b>{}</b>: {} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> '''.format(alert[num], alert[num].title(), text) return message
def ksi_of_t_discrete(x_func, T, y0, g): """ Local regressor. Discrete system """ return x_func(T) * (g - y0)
def prudent(lst): """ :param lst: list :return: int """ mins = dict() for j in range(len(lst)): mins[j] = min(lst[j]) for j in mins: if mins[j] == max([mins[key] for key in mins]): return j
def transparency2float(value: int) -> float: """ Returns transparency value as float from 0 to 1, 0 for no transparency (opaque) and 1 for 100% transparency. Args: value: DXF integer transparency value, 0 for 100% transparency and 255 for opaque """ # Transparency value 0x020000TT 0 = fully transparent / 255 = opaque # 255 -> 0.0 # 0 -> 1.0 return 1.0 - float(int(value) & 0xFF) / 255.0
def subtract_dict(whole_dict, sub_dict): """ Creates a dictionary with a set of keys, that only present in the 'greater' dictionary. :param whole_dict: dict, the dictionary to be reduced. :param sub_dict: dict, the dictionary with the required keys. :return: dict, the reduced dict. """ reduced_dict = {} for parameter in [key for key in whole_dict.keys() if key not in sub_dict.keys()]: reduced_dict[parameter] = whole_dict[parameter] return reduced_dict
def _format(link): """ Give nice format to dict with alleles and reads supporting """ cell = '' for allele in link: cell += "%s=%s;" % (allele, link[allele]) return cell
def calculate(digits): """Returns the index of the first term in the Fibonacci sequence to contain the specified number of digits.""" answer = 0 prev = 1 cur = 1 while len(str(prev)) < digits: answer += 1 next_term = prev + cur prev = cur cur = next_term answer += 1 return answer
def bullet_list(inp): """Convienience function that joins elements of a list into a bullet formatted list.""" return '\n' + '\n'.join(['- ' + z for z in inp])
def round_up_to_power_of_two(n): """ From http://stackoverflow.com/a/14267825/1958900 """ if n < 0: raise TypeError("Nonzero positive integers only") elif n == 0: return 1 else: return 1 << (n-1).bit_length()
def active_mode_english(raw_table, base_index): """ Convert mode to English """ value = raw_table[base_index] if value == 0: return "Vacation" if value == 2: return "Night" if value == 4: return "Day" return "Unknown"
def sep(*args): """join strings or list of strings ignoring None values""" return ' '.join(a for a in args if a)
def create_required(variable, window, in_options=False, var_type='numeric', var_length='11'): """ Returns the required `dict` to be used by lottus :param variable `str`: the variable of that will be stored in the session :param window `str`: the name of the window that this required object points to :param in_options `bool`: indicates whether the value to be stored will be found in the options list :param var_type `str`: indicates the type of the variable :param var_length `str`: indicates the length of the variable """ return { 'var': variable, 'window': window, 'in_options': in_options, 'type': var_type, 'length': var_length }
def items_key(params): """Return a hashable object (a tuple) suitable for a cache key A dict is not hashable, so we need something hashable for caching the items() function. """ def hashable(thing): if isinstance(thing, list): return ','.join(sorted(thing)) else: return thing # A tuple of dict items() plus a token to prevent collisions with # keys from other functions that might use the same cache items = [(k, hashable(v)) for (k, v) in params.items()] return tuple(sorted(items)) + ('v2_items',)
def parse_command_line_name_and_range(name_and_range_arg): """ Parse command line argument that looks like "phage:0:80000,prok:0:70000" into { phage_dset_name: "phage", phage_range: (0,80000), prok_dset_name: "prok", prok_range: (0,70000) } :param name_and_range: (str) "phage:0:80000,prok:0:70000" :return: (dict) """ phage_arg, prok_arg = name_and_range_arg.split(',') phage_dset_name, phage_start, phage_stop = phage_arg.split(':') prok_dset_name, prok_start, prok_stop = prok_arg.split(':') names_and_ranges = { 'phage_dset_name': phage_dset_name, 'phage_range': (int(phage_start), int(phage_stop)), 'prok_dset_name': prok_dset_name, 'prok_range': (int(prok_start), int(prok_stop)) } return names_and_ranges
def word_at(match, word_index): """A utility function that gets the word with index word_index""" assert 0 <= word_index < len(match["words"]), "word_index out of range of words" return match["words"][word_index]
def get_post_context(resp): """ Prepare context data for forum post :param resp: forum post api response :return: dict object """ post_ec = { 'PostId': resp['id'], 'PublishedAt': resp.get('published_at', ''), 'Url': resp.get('url', ''), 'PlatformUrl': resp.get('platform_url', ''), 'Forum': resp['embed']['forum'], 'Room': resp['embed']['room'], 'User': resp['embed']['author'] } return post_ec
def xor(a, b): """xor bits together. >>> assert xor(0, 0) == 0 >>> assert xor(0, 1) == 1 >>> assert xor(1, 0) == 1 >>> assert xor(1, 1) == 0 """ assert a in (0, 1) assert b in (0, 1) if a == b: return 0 else: return 1
def _string_or_float_to_integer_python(s): """ conda-build 2.0.4 expects CONDA_PY values to be integers (e.g., 27, 35) but older versions were OK with strings or even floats. To avoid editing existing config files, we support those values here. """ try: s = float(s) if s < 10: # it'll be a looong time before we hit Python 10.0 s = int(s * 10) else: s = int(s) except ValueError: raise ValueError("{} is an unrecognized Python version".format(s)) return s
def deploy_dashboard(db_json_url, wf_url, api_token): """Deploy a dashboard in wavefront.""" print("Deploying Dashboard with %s, %s, %s" % (db_json_url, wf_url, api_token)) return True
def get_piece(gameBoard: tuple, x: int, y: int) -> int: """ Returns the state of the given location """ max_x = len(gameBoard[0]) - 1 max_y = len(gameBoard) - 1 # Check for wraps if x > max_x: x = x - max_x - 1 if x < 0: x = max_x + x + 1 if y > max_y: y = y - max_y - 1 if y < 0: y = max_y + y + 1 # print(x, y) return gameBoard[y][x]
def unique(ngb): """Return unique values from vector.""" uni = list() for n in ngb: if n not in uni: uni.append(n) return uni
def group_words(words): """Takes a list of words, and groups them, returning a list-of-lists. The idea is that each word starting with '*' is a synonym for the previous word, and we group these synonyms together with their base word. The word '.' is padding, and we discard it if found. """ grouped = [] buffer = [] for word in words: if word not in (".", "*."): # This must be the padding, I think if word == "": pass elif word[0] == "*": buffer.append(word[1:]) elif len(buffer) == 0: buffer.append(word) else: grouped.append(buffer) buffer = [word] if len(buffer) > 0: grouped.append(buffer) return grouped
def get_2comp(val_int, val_size=16): """Get the 2's complement of Python int val_int :param val_int: int value to apply 2's complement :type val_int: int :param val_size: bit size of int value (word = 16, long = 32) (optional) :type val_size: int :returns: 2's complement result :rtype: int :raises ValueError: if mismatch between val_int and val_size """ # avoid overflow if not -1 << val_size-1 <= val_int < 1 << val_size: err_msg = 'could not compute two\'s complement for %i on %i bits' err_msg %= (val_int, val_size) raise ValueError(err_msg) # test negative int if val_int < 0: val_int += 1 << val_size # test MSB (do two's comp if set) elif val_int & (1 << (val_size - 1)): val_int -= 1 << val_size return val_int
def approx_Q_linear(B: float, T: float): """ Approximate rotational partition function for a linear molecule. Parameters ---------- B - float Rotational constant in MHz. T - float Temperature in Kelvin. Returns ------- Q - float Rotational partition function at temperature T. """ Q = 2.0837e4 * (T / B) return Q
def remove_comments(input_string): """ Helper function for import_test. Removes all parts of string that would be commented out by # in python paramters --------- input_string: string returns ------- string where all parts commented out by a '#' are removed from input_string """ split_lines = input_string.split("\n") return ''.join([line.split('#')[0] for line in split_lines])
def name_mosaic_info(mosaic_info): """ Generate the name for a mosaic metadata file in Azure Blob Storage. This follows the pattern `metadata/mosaic/{mosaic-id}.json`. """ return f"metadata/mosaic/{mosaic_info['id']}.json"
def extract_data(drug, statuses): """Extracts the desired data from a list of twitter responses. Arguments: drug {str} -- the drug name that corresponds to the statuses. statuses {list} -- twitter statuses that were the result of searching for 'drug'. Returns: [list] -- a list of dictionaries containing the desired data for each tweet. """ tweets = [] for status in statuses: tweet = { 'drug': drug, 'tweet_id': status['id'], 'user_id': status['user']['id'], 'username': status['user']['screen_name'], } if status['retweeted'] == True: tweet['text'] = status['retweeted_status']['full_text'] else: tweet['text'] = status['full_text'] tweets.append(tweet) return tweets
def dpq(states, actions, initial_value=0): """dynamic programming definition for Q-learning This implementation returns a table like, nested dict of states and actions -- where the inner values q[s][a] reflect the best current estimates of expected rewards for taking action a on state s. See [1] chapter 3 for details. PARAMETERS ---------- * states: list, tuple or any other enumerable Where each state in the collection is representated by any other immutable type i.g int or tuple. * actions: list, tuple or any other enumerable Where each action in the collection is representated by any other immutable type i.g int or tuple. * initial_value: numeric Initial a priori guess for the Q function RETURNS ------- * q: dictionary Where q is a nested dictionary where the outer keys are states and the inner keys are the actions REFERENCE --------- [1] Sutton et Barto, Reinforcement Learning 2nd Ed 2018 """ return { s: { a: initial_value for a in actions } for s in states }
def _singularize(string): """Hacky singularization function.""" if string.endswith("ies"): return string[:-3] + "y" if string.endswith("s"): return string[:-1] return string
def get_pf_input(spc, spc_str, global_pf_str, zpe_str): """ prepare the full pf input string for running messpf """ # create a messpf input file spc_head_str = 'Species ' + spc print('pf string test:', global_pf_str, spc_head_str, spc_str, zpe_str) pf_inp_str = '\n'.join( [global_pf_str, spc_head_str, spc_str, zpe_str, '\n']) return pf_inp_str
def base_url(host, port): """build scrapyd host url :param host: scrapyd host ip :param port: scrapyd host port :return scrapyd host url """ return 'http://{host}:{port}'.format(host=host, port=port)
def solve(puzzle_input): """Solve a puzzle input""" # print("solve(%s)" % puzzle_input) direction = 0 # 0 up, 1 left, 2 down, 3 right # initialise a starting grid with the first ring aka square 1 # The size is known to be big enough to solve my input grid_size = 13 grid = [[0 for x in range(grid_size)] for y in range(grid_size)] grid[int(grid_size/2)][int(grid_size/2)] = 1 csx = int(grid_size/2)+1 # current square x co-ordinates within the grid csy = int(grid_size/2) # current square y co-ordinates within the grid while True: # set the square value based on our neighboughs grid[csy][csx] = ( grid[csy-1][csx-1] + grid[csy-1][csx] + grid[csy-1][csx+1] + grid[csy][csx-1] + grid[csy][csx] + grid[csy][csx+1] + grid[csy+1][csx-1] + grid[csy+1][csx] + grid[csy+1][csx+1] ) if grid[csy][csx] > puzzle_input: break # do we need to change direction? # if we are going up and there is nothing left, turn left if direction == 0: if not grid[csy][csx-1]: direction = 1 # if we are going left and there is nothing below, turn down elif direction == 1: if not grid[csy+1][csx]: direction = 2 # if we are going down and there is nothing right, turn right elif direction == 2: if not grid[csy][csx+1]: direction = 3 # if we are going right and there is nothing above, turn up elif direction == 3: if not grid[csy-1][csx]: direction = 0 # move to the next square if direction == 0: csy -= 1 elif direction == 1: csx -= 1 elif direction == 2: csy += 1 elif direction == 3: csx += 1 # for row in grid: # print(row) return grid[csy][csx]
def precip_to_energy(prec): """Convert precip to W/m2 Parameters --------- prec : (mm/day) """ density_water = 1000 Lv = 2.51e6 coef = density_water / 1000 / 86400 * Lv return coef * prec
def sortByLabels(arr, labels): """ intended use case: sorting by cluster labels for plotting a heatmap """ return [x[1] for x in sorted(enumerate(arr), key=lambda x: labels[x[0]])]
def is_float(value): """ Reports whether the value represents a float. """ try: float(value) return True except ValueError: return False
def _align32b(i): """Return int `i` aligned to the 32-bit boundary""" r = i % 4 return i if not r else i + 4 - r
def NONS(s): """ strip NS """ return s[32:]
def unchurch(c) -> int: """ Convert church number to integer :param c: :return: """ return c(lambda x: x + 1)(0)
def decode_to_string(toDecode): """ This function is needed for Python 3, because a subprocess can return bytes instead of a string. """ try: return toDecode.decode("utf-8") except AttributeError: # bytesToDecode was of type string before return toDecode
def maybeint(x): """Convert x to int if it has no trailing decimals.""" if x % 1 == 0: x = int(x) return x
def _codeStatusSplit(line): """ Parse the first line of a multi-line server response. @type line: L{bytes} @param line: The first line of a multi-line server response. @rtype: 2-tuple of (0) L{bytes}, (1) L{bytes} @return: The status indicator and the rest of the server response. """ parts = line.split(b' ', 1) if len(parts) == 1: return parts[0], b'' return parts
def to_string(data): """Convert data to string. Works for both Python2 & Python3. """ return '%s' % data
def test_shadowing(x, y, z): """Test an expression where variables are shadowed.""" x = x * y y = y * z z = x * z return x + y + z
def expand_abbreviations(template, abbreviations) -> str: """Expand abbreviations in a template name. :param template: The project template name. :param abbreviations: Abbreviation definitions. """ if template in abbreviations: return abbreviations[template] # Split on colon. If there is no colon, rest will be empty # and prefix will be the whole template prefix, sep, rest = template.partition(':') if prefix in abbreviations: return abbreviations[prefix].format(rest) return template
def replace_items(lst, old, new): """ :param lst: [] List of items :param old: obj Object to substitute :param new: obj New object to put in place :return: [] List of items """ for i, val in enumerate(lst): if val == old: lst[i] = new return lst
def acl_represent(acl, options): """ Represent ACLs in tables for testing purposes, not for production use! """ values = [] for o in options.keys(): if o == 0 and acl == 0: values.append("%s" % options[o][0]) elif acl and acl & o == o: values.append("%s" % options[o][0]) else: values.append("_") return " ".join(values)
def kgtk_date(x): """Return True if 'x' is a KGTK date literal. """ return isinstance(x, str) and x.startswith('^')
def compression_ratio(width, height, terms): """ Parameters ---------- width : int Width of the image in pixels. height : int Width of the image in pixels. terms : int The number of terms in the singular value expansion. Returns ------- float The of the compressed image relative to non-compressed. """ return terms * (1 + width + height) / (width * height)
def aic_measure(log_likelihood, params_num): """ Returns the Akaike information criterion value, that is AIC = -2ln(L) + 2m, where L is the likelihood in the optimum and m is the number of parameters in the model. :param log_likelihood: optimized log-likelihood. :param params_num: number of model parameters. :return: AIC value. """ return -2*(log_likelihood - params_num)
def parse_entry_helper(node, item): """ Create a numpy list from value extrated from the node :param node: node from each the value is stored :param item: list name of three strings.the two first are name of data attribute and the third one is the type of the value of that attribute. type can be string, float, bool, etc. : return: numpy array """ if node is not None: if item[2] == "string": return str(node.get(item[0]).strip()) elif item[2] == "bool": try: return node.get(item[0]).strip() == "True" except Exception: return None else: try: return float(node.get(item[0])) except Exception: return None
def get_multi_machine_types(machinetype): """ Converts machine type string to list based on common deliminators """ machinetypes = [] machine_type_deliminator = [',', ' ', '\t'] for deliminator in machine_type_deliminator: if deliminator in machinetype: machinetypes = machinetype.split(deliminator) break if not machinetypes: machinetypes.append(machinetype) return machinetypes
def unique_items(seq): """Return the unique items from iterable *seq* (in order).""" seen = set() return [x for x in seq if not (x in seen or seen.add(x))]
def int_min(int_a, int_b): """ min(a, b) """ if int_a < int_b: return int_a else: return int_b
def evaluate_subcategories(list1, list2, max_score): """returns a numerical representation of the similarity of two lists of strings Args: list1(list): a list of strings (this is a list of items from the query patient) list2(list): another list of strings (list of items from the patients in database) max_score(float): the maximum value to return if the lists are identical Returns: matching_score(float): a number reflecting the similarity between the lists """ matching_score = 0 if len(list1) > 0: list_item_score = max_score / len( list1 ) # the max value of each matching item between lists n_shared_items = len( set(list1).intersection(list2) ) # number of elements shared between the lists matching_score = n_shared_items * list_item_score return matching_score
def next_run_iso_format(next_run): """ Convert next run timestamp object to the ISO format """ if isinstance(next_run, bool): next_run = None else: next_run = next_run.isoformat() return next_run
def generate_one_test_data_set_1D( random_generator, pixels_per_clock: int, image_size: int, ): """Generate a 2D-list of test data suitable for testing a 1D line buffer with the given pixels/clock and image size parameters. Populate the test data using values from the random_generator function passed. """ cycle_count = image_size//pixels_per_clock assert cycle_count * pixels_per_clock == image_size, \ "Expected pixels/clock to evenly divide pixel count." return [ [random_generator() for i in range(pixels_per_clock)] for s in range(cycle_count) ]
def _is_dunder(name): """Returns True if a __dunder__ name, False otherwise.""" return ( len(name) > 4 and name[:2] == name[-2:] == "__" and name[2] != "_" and name[-3] != "_" )
def parse_escaped_hierarchical_category_name(category_name): """Parse a category name.""" result = [] current = None index = 0 next_backslash = category_name.find('\\', index) next_slash = category_name.find('/', index) while index < len(category_name): if next_backslash == -1 and next_slash == -1: current = (current if current else "") + category_name[index:] index = len(category_name) elif next_slash >= 0 and (next_backslash == -1 or next_backslash > next_slash): result.append((current if current else "") + category_name[index:next_slash]) current = '' index = next_slash + 1 next_slash = category_name.find('/', index) else: if len(category_name) == next_backslash + 1: raise Exception("Unexpected '\\' in '{0}' at last position!".format(category_name)) esc_ch = category_name[next_backslash + 1] if esc_ch not in {'/', '\\'}: raise Exception("Unknown escape sequence '\\{0}' in '{1}'!".format(esc_ch, category_name)) current = (current if current else "") + category_name[index:next_backslash] + esc_ch index = next_backslash + 2 next_backslash = category_name.find('\\', index) if esc_ch == '/': next_slash = category_name.find('/', index) if current is not None: result.append(current) return result
def gcd(a, b): """Computes the greatest common divisor of integers a and b using Euclid's Algorithm. """ while b != 0: a, b = b, a % b return a
def construct_backwards_adjacency_list(adjacency_list): """ Create an adjacency list for traversing a graph backwards The resulting adjacency dictionary maps vertices to each vertex with an edge pointing to them """ backwards_adjacency_list = {} for u in adjacency_list: for v in adjacency_list[u]: try: backwards_adjacency_list[v].add(u) except: backwards_adjacency_list[v] = {u} return backwards_adjacency_list
def modelVariance(fn,xs,ys,yerrs=None): """takes a function and returns the variance compared to some data""" if yerrs is None: yerrs=[1]*len(xs) return sum([(fn(x)-ys[i])**2./yerrs[i]**2. for i,x in enumerate(xs)])
def save_params(net, best_metric, current_metric, epoch, save_interval, prefix): """Logic for if/when to save/checkpoint model parameters""" if current_metric > best_metric: best_metric = current_metric net.save_parameters('{:s}_best.params'.format(prefix, epoch, current_metric)) with open(prefix+'_best.log', 'a') as f: f.write('\n{:04d}:\t{:.4f}'.format(epoch, current_metric)) if save_interval and (epoch + 1) % save_interval == 0: net.save_parameters('{:s}_{:04d}_{:.4f}.params'.format(prefix, epoch, current_metric)) return best_metric
def count_values(in_list): """ Return the count of the number of elements in an arbitrarily nested list """ # Deep copy of in_list if type(in_list) is dict: mod_list = list(in_list.values()) else: mod_list = list(in_list) count = 0 while mod_list: entry = mod_list.pop() if isinstance(entry, list): mod_list += entry else: count += 1 return count
def make_xml_name(attr_name): """ Convert an attribute name to its XML equivalent by replacing all '_' with '-'. CamelCase names are retained as such. :param str attr_name: Name of the attribute :returns: Attribute name in XML format. """ return attr_name.replace('_', '-')