content
stringlengths
42
6.51k
def str2bool(text=None): """Parse a boolean stored as a string.""" if text is None: # default value return False text = text.lower() if text == "false": return False elif text == "true": return True else: raise ValueError("unknown string for bool '%s'" ...
def convert_parentheses(text: str): """Replaces -LRB- and -RRB- tokens present in SST with ( and )""" return text.replace("-LRB-", "(").replace("-RRB-", ")")
def format_percent(number): """Format percents for display. uses whole numbers, clipped to [0, 100] range. """ if number == 0: return "0" if number < 1: return "<1" return f"{min(round(number), 100):.0f}"
def format_set(s): """ Format a set of strings. """ max_el = 50 if len(s) == 0: return "" l = list(s) ret = "'" + "', '".join(l[:min(max_el, len(s))]) + "'" if len(s) > max_el: ret = ret + ", ..." return ret
def nbest_ascending_wins(limit, rlen, numdocs): """ Primitive curve-fitting to see if nbest ascending will beat timsort for a particular limit/rlen/numdocs tuple. XXX This needs work, particularly at small index sizes. It is currently optimized for an index size of about 32768 (98% accuracy); it g...
def log_differences(manual_data, scraped_data): """ Returns a list of differences between the manual and scraped data lists. """ return list(set(manual_data) - set(scraped_data))
def find_peak(list_of_integers): """That finds a peak in a list of unsorted integers. """ if list_of_integers: list_of_integers.sort() return list_of_integers[-1]
def matyas(X, Y): """constraints=10, minimum f(0, 0)=0""" return (0.26 * (X ** 2 + Y ** 2)) - (0.48 * X * Y)
def width_function_nataraj(filesize: int) -> int: """Set width depending on filesize. References: - Nataraj et al. 2011. Malware images: visualization and automatic classification. https://doi.org/10.1145/2016904.2016908 """ k = filesize // 1024 if k < 10: width = 32 ...
def make_header_id_unique(header_id, used_ids): """Make the given ID unique given a dictionary of used_ids Arguments: header_id - Slugified header ID used_id - Dictionary associating each header ID without suffixes to the number of times that such ID has been used. """ if header_id in used...
def pressureInFluid(f_perpendicular, A): """ variables: f_perpendicular = normal force A = area""" p=f_perpendicular/A return p
def make_scp_safe(string: str) -> str: """ Helper function to make a string safe for saving in Kaldi scp files. They use space as a delimiter, so any spaces in the string will be converted to "_MFASPACE_" to preserve them Parameters ---------- string: str Text to escape Returns ...
def parse_offsets(offsets): """Parse offsets file into list of offsets.""" return [int(offset) for offset in offsets.splitlines()]
def BC(x, y): """Used to set the boundary condition for the grid of points. Change this as you feel fit.""" return (x ** 2 - y ** 2)
def fixed_xor(a: bytearray, b: bytearray) -> bytearray: """Returns the xor of two equal length bytearrays. Arguments: a {bytearray} -- Bytearray to be used b {bytearray} -- Bytearray to be used Returns: bytearray -- a ^ b """ assert(len(a) == len(b)), "Bytearra...
def _set_conf_range(print_keyword_dct): """ ? """ cnf_range = print_keyword_dct['cnf_range'] # if cnf_range == 'all': # pass # elif cnf_range != 'min': # cnf_range = 'n{}'.format(cnf_range) # else: # cnf_range = print_keyword_dct['econfs'] # if cnf_range != 'min':...
def get_vuart_id(tmp_vuart, leaf_tag, leaf_text): """ Get all vuart id member of class :param tmp_vuart: a dictionary to store member:value :param leaf_tag: key pattern of item tag :param leaf_text: key pattern of item tag's value :return: a dictionary to which stored member:value """ if...
def get_geojson_bounds(geojson: dict): """Returns geojson bounds in format compatible with folium.Map.set_bounds() method. Returns two (lat, long) points: [southwest, northeast] """ # NOTE: bbox is given as: # 2D: [SW lat, SW long, NE lat, NE long] # 3D: [SW lat, SW long, SW elev, NE l...
def is_number(s): """ Check if a string is a number Parameters ---------- s: str The input string Returns ------- is_number: bool Is True if the input string is a number, otherwise False """ try: float(s) is_number = True except ValueError: ...
def json_to_dict(data): """ Convert serialized JSON to the custom structure I devised to handle everything. It's essentially a dictionary of lists of all the servers and their statuses. As functionality grows, this will become more functional. :param data: Data to parse :return: Parsed dictionary ...
def html_spam_guard(addr, entities_only=False): """Return a spam-protected version of email ADDR that renders the same in HTML as the original address. If ENTITIES_ONLY, use a less thorough mangling scheme involving entities only, avoiding the use of tags.""" if entities_only: def mangle(x): return...
def text_of_segments(segments): """ >>> segments = ['Hi there! ', 'My name is Peter.'] >>> text_of_segments(segments) 'Hi there! My name is Peter.' """ return "".join(segments)
def split_text(lines): """Split a text devided by newline into chunks of about 4000 characters.""" chunks = [] current_chunk = [] chars = 0 for line in lines: # Append the length of the line + a newline chars += len(line) + 1 if chars < 4000: current_chunk.append...
def binary_boundary(t, d): """ Return the last <t integer that is a multiple of 2^d >>> binary_boundary(11, 4) 0 >>> binary_boundary(11, 3) 8 >>> binary_boundary(11, 2) 8 >>> binary_boundary(11, 1) 10 >>> binary_boundary(15, 4) 0 >>> binary_boundary(16, 4) ...
def has_super(cls): """Returns True if input class `__super__` is not None. `__super__` is defined and not None for class trees having a main superclass and one or more inherited classes. Parameters ---------- cls : obj Any class or class isntance. """ return hasattr(cls, '__s...
def areStringsEqual(a, b): """ Returns if two strings are the same, disregarding cases. """ return a.upper() == b.upper()
def minWindow(s, t): """s, t all str""" from collections import defaultdict mem = defaultdict(int) for char in t: mem[char] += 1 t_len = len(t) minleft, minright = 0, len(s) left = 0 for right, char in enumerate(s): if mem[char] > 0: t_len -= 1 mem[cha...
def temporal_coverage(resource_name, datapkg_settings): """Extract start and end dates from ETL parameters for a given source. Args: resource_name (str): The name of the (potentially partitioned) resource for which we are enumerating the spatial coverage. Currently this is the o...
def extract_query_string_parameters(event): """ Returns the query string parameters from the request The format is: a sequence of two-element tuples (name, value) Supports regular and multivalue querystringparameters :param event: :return: """ query_string_params = event.get("queryStri...
def __min_birth_max_death(persistence, band=0.0): """This function returns (min_birth, max_death) from the persistence. :param persistence: The persistence to plot. :type persistence: list of tuples(dimension, tuple(birth, death)). :param band: band :type band: float. :returns: (float, float) -...
def iou(bb_a, bb_b): """Calculates the Intersection over Union (IoU) of two 2D bounding boxes. :param bb_a: 2D bounding box (x1, y1, w1, h1) -- see calc_2d_bbox. :param bb_b: 2D bounding box (x2, y2, w2, h2) -- see calc_2d_bbox. :return: The IoU value. """ # [x1, y1, width, height] --> [x1, y1, x2, y2] t...
def general_pool_fn(x): """ x[0]: function to call x[1] to x[n]: arguments of the function """ return x[0](*x[1:])
def FVIFA(i,n): """ interest years """ FVIFA=0 for t in range(n): FVIFA=FVIFA+(1+i)**t return FVIFA
def convert_to_int(var): """ Tries to convert an number to int. :param var :returns the value of the int or None if it fails """ try: return int(var) except ValueError: return None
def make_snake_case(text: str) -> str: """ A very basic way to converts some text into snake case. Strips out any non a-z, 0-9 characters. :param text: :return: a string which snake cases the text provided """ chars = 'abcdefghijklmnopqrstuvwxyz1234567890_' unclean = text.lower().strip()...
def greatest_common_div(A, B): """ Find the greatest common divisor of A and B. """ while B != 0: rem = A % B A = B B = rem return A
def solution_score_100(A, B, K): # write your code in Python 3.6 """ To get multiples of K from A - B. Get multiples of K in range B = B // K say kB get multiples of K before A: A - 1 // K asy kA return difference kB - kA. this gives the multiples of K from A to B """ return (B // K) - (...
def get_reference_file(changed_file, tool_dict): """ Lookup the file that the tool is generating in response to changing an interesting file """ return tool_dict['interesting_to_reference_file'](changed_file, tool_dict['reference_files'])
def clip(number, min_nb, max_nb): """ Clip a number between min and max inclusively """ return max(min_nb, min(number, max_nb))
def _get_master(cluster_spec, task_type, task_id): """Returns the appropriate string for the TensorFlow master.""" if not cluster_spec: return '' # If there is only one node in the cluster, do things locally. jobs = cluster_spec.jobs if len(jobs) == 1 and len(cluster_spec.job_tasks(jobs[0])) == 1: re...
def member_of2(x, val): """ member_of(x, val) Ensures that the value `val` is in the array `x`. """ print(f"member_of2({x},{val})") constraints = [sum([v == val for v in x]) > 0] return constraints
def pad_seq(seq): """Pad sequence to multiple of 3 with Ns""" return {0: seq, 1: seq+'NN', 2: seq+'N'}[len(seq) % 3]
def powerlaw_alpha(x, p, u_ref=10, z_ref=100): """ p = alpha """ return u_ref * (x / z_ref) ** p[0]
def optimal_points(segments): """ Example 1: >>> optimal_points([(1, 3), (2, 5), (3, 6)]) [3] Example 2: >>> optimal_points([(4, 7), (1, 3), (2, 5), (5, 6)]) [3, 6] """ segments.sort(key=lambda s: s[0]) end = segments[0][1] point = [] for i in range(1, len(segments)): ...
def P_bremsstrahlung(k, Te, ne): """ W m^3 """ return 1.53e-38 * Te**0.5 * (k + 1)**2
def convert_to_freq_string(date_str: str) -> str: """ Converts a conversational description of a period (e.g. 2 weeks) to a pandas frequency string (2W). Args: date_str: A period description of the form "{number} {period}" Returns: A corresponding pandas frequency string """ # ...
def format_list_of_seq(list_of_seq): """ :param list_of_seq: :return: removes \n and converts to uppercase """ for i, seq in enumerate(list_of_seq): list_of_seq[i] = seq.strip().upper() return list_of_seq
def convert_to_bool(value: str) -> bool: """Convert string to boolean.""" return value.lower() == 'true'
def compute_square_coordinates(height: int = 10, width: int = 10) -> list: """Compute coordinates of the bottom right corner for each square on the 10x10 grid, where each square is of size 10x10. This function will store the coordinate information of the bottom right corner of each square for subsequent use. ...
def _filter_config_dict_recursive_key(final_dict): """Filters the dict recursively, removing all $-entries. Not the best performance-solution right now.""" if not isinstance(final_dict, dict): return final_dict filtered = {k: v for k, v in final_dict.items() if not k.startswith('$')} # Recursion...
def to_int_iff_int(value): """ Returns int type number if the value is an integer value :param value: :return: """ try: if int(value) == value: return int(value) except (TypeError, ValueError): pass return value
def get_val_fn(x): """ get_val_fn """ ret = x + 3 return ret
def leap(year: int) -> bool: """ Given year X >= 1582, returns whether X is a leap year """ # Multiples of 100 must also be of 400 if year % 100 == 0: return year % 400 == 0 else: return year % 4 == 0
def get_direction_from_abbrev(abbrev): """Finds the direction of a metaedge from its abbreviaton""" if '>' in abbrev: return 'forward' elif '<' in abbrev: return 'backward' else: return 'both'
def parse_list_from_string(a_string): """ This just parses a comma separated string and returns an INTEGER list Args: a_string (str): The string to be parsed Returns: A list of integers Author: SMM Date: 10/01/2018 """ print("Hey pardner, I'm a gonna parse a string in...
def get_bin(x, n=0): """ Get the binary representation of x. Parameters ---------- x : int n : int Minimum number of digits. If x needs less digits in binary, the rest is filled with zeros. Returns ------- list of binary digits """ y = format(x, 'b').zfill(...
def S_difference_values(_data_lista, _data_listb): """ Returns new data samples where values are transformed by transformer values. """ d_data = [] dsa = len(_data_lista) dsb = len(_data_listb) if dsa != dsb: return [] for i in range(dsa): d_data.append(_data_lista[i] ...
def GetText(node): """Dig out node text Args: node: DOM node Returns: text: stripped concatenation of all TEXT_NODEs """ if not node: return None text = [] for child in node.childNodes: if child.nodeType == child.TEXT_NODE: text.append(child.data) elif child.nodeType == child...
def isHellaTemp(filename): """ Determine whether or not the specified file is a 'hellanzb-tmp-' file """ return filename.find('hellanzb-tmp-') == 0
def clip_colours(colour_value): """ This function ensures that our auto white balance module does not exceed the limits of our RGB spectrum. :param colour_value: The value of our colour channel. :return: The normalised value of our colour channel. """ if colour_value <= 0: # Value of ...
def template_vector_cumulative_luminosity_function(Eth,*params): """ Template for a cumulative luminosity function Returns fraction of cumulative distribution above Eth Luminosity function is defined by *params Eth is a 1D numpy array This example uses a cumulative power law """ #result=...
def remove_extension(filepath): """Removes all extensions of the filename pointed by filepath. :Example: >>> remove_extension('home/user/t1_image.nii.gz') 'home/user/t1_image' >>> remove_extension('home/user/t1_image.nii.gz') + '_processed.nii.gz' 'home/user/t1_image_processed.nii.gz' """ ...
def num_digits(n) -> int: """ Compute the number of digits of a number :return: number of digits """ if not isinstance(n, int): raise TypeError(f'Invalid n: not an integer {n}') count = 1 while (int(n / 10)) != 0: count += 1 n = int(n / 10) return count
def generate_dashboard_link(uuid: str) -> str: """Generate a MythX dashboard link for an analysis job. This method will generate a link to an analysis job on the official MythX dashboard production setup. Custom deployment locations are currently not supported by this function (but available at mythx.i...
def get_preproc_name(filename): """ Get the name of a .m4 file after preprocessing. """ return filename[:-3]
def flatten_nested_arrays(lst: list): """Creates a single flat list out of a given list containing nested lists. Examples: >>> nested_list = [1, [2], [[3], 4], 5]\n >>> flatten_nested_arrays(nested_list)\n [1, 2, 3, 4, 5] >>> more_nesting = [1, [2], [[3,[7,8,9]], 4], 5]\n ...
def shortest_path(grid): """This doesn't work for all inputs. It is possible to have a minimum-risk path that requires moving up or left. E.G. 19999 11999 91999 11999 19999 11111 """ rows, cols = len(grid), len(grid[0]) total_grid = [[0] * cols for _ in range(rows)] ...
def get_set_from_curs(cur_set): """ Get number set from boolean list :param cur_set: list :return: list """ result = [] for (idx, in_cur_set) in enumerate(cur_set): if in_cur_set: result.append(idx) return result
def fix_colwidth(n_columns, width_str="MAKE COLUMN THIS WIDE"): """adds a hidden row to the bottom of the table with text width_str, forcing each column to be at least as wide as width_str""" html = """<tr> <th class="colwidth" rowspan=1></th> <th></th> """ for _ in range(n_col...
def fix_oov(line: str): """ Args: line: transcript like "WORD1 WORD2 WORD3..." separated by space. Returns: OOV replaced. """ oov_dict = { "'EM": "EM", "MCVEIGH": "MC VEIGH", "MCFEE'S": "MC FEE'S", "DENNIN'S": "DENNING'S", "DAUGHTRY'S": "DAW T...
def to_preorder_iterative(root: dict, allow_none_value: bool = False) -> list: """ Convert a binary tree node to depth-first pre-order list (iteratively). """ node, node_list, stack = root, [], [] stack.append(node) # push root into the stack while len(stack) > 0: node = stack[-1] ...
def makeResult (page, endPage): """returns a list of the articles needed to go from startpage to endpage""" result = [endPage] while (page != None): result.append(page.Title) page = page.parent result.reverse() return result
def get_positions(entry): """ get the correct start and end position """ start_position = entry['pal_s'] end_position = entry['pal_e'] if start_position > end_position: _start_position = start_position start_position = end_position end_position = _start_position retur...
def swap_strategy(score, opponent_score): """This strategy rolls 0 dice when it would result in a beneficial swap and rolls BASELINE_NUM_ROLLS if it would result in a harmful swap. It also rolls 0 dice if that gives at least BACON_MARGIN points and rolls BASELINE_NUM_ROLLS otherwise. >>> swap_strat...
def gcd(num1: int, num2: int) -> int: """Computes the greatest common divisor of integers a and b using Euclid's Algorithm. """ while num2 != 0: num1, num2 = num2, num1 % num2 return num1
def parse_key_value_list(kv_string_list, error_fmt, error_func): """Parse a list of strings like ``KEY=VALUE`` into a dictionary. :param kv_string_list: Parse a list of strings like ``KEY=VALUE`` into a dictionary. :type kv_string_list: [str] :param error_fmt: Format string a...
def get_enum_key(key, choices): """Get an enum by prefix or equality""" if key in choices: return key keys = [k for k in choices if k.startswith(key)] if len(keys) == 1: return keys[0]
def merge_lists(src, dest, insert=True): """Merge lists avoiding duplicates""" if insert: for x in reversed(src): if x in dest: continue dest.insert(0, x) else: dest.extend([x for x in src if x not in dest]) return dest
def convert_nary_conditions(conditions, schemes): """Convert an NaryJoin map from global column index to local""" attr_map = {} # map of global attribute to local column index count = 0 for i, scheme in enumerate(schemes): for j, attr in enumerate(scheme.ascolumnlist()): attr_map[c...
def Join(iterable, separator=''): """ iterable >> Join(separator='') Same as Python's sep.join(iterable). Concatenates the elements in the iterable to a string using the given separator. In addition to Python's sep.join(iterable) it also automatically converts elements to strings. :param i...
def parse_worker_path(path, hostname, port): """Replace HOSTNAME & PORT to :param:`hostname` & :param:`port` respectively. """ return path.replace('HOSTNAME', hostname).replace('PORT', str(port))
def merge_sites_into_messages(found_sites): """ Join links to found accounts and make telegram messages list """ if not found_sites: return ['No accounts found!'] found_accounts = len(found_sites) found_sites_messages = [] found_sites_entry = found_sites[0] for i in range(l...
def _is_arraylike(arr): """Check if object is an array.""" return ( hasattr(arr, "shape") and hasattr(arr, "dtype") and hasattr(arr, "__array__") and hasattr(arr, "ndim") )
def fib(n): """ Fibonacci nth number definition based on Dijsktra's paper here: www.cs.utexas.edu/users/EWD/ewd06xx/EWD654.pdf """ # dictionary used for memoization fibs = {0: 0, 1: 1} if n in fibs: return fibs[n] if n % 2 == 0: fibs[n] = ((2 * fib((n / 2) - 1)) + fib(n ...
def request(url_request): """ Generate the URI to send to the THETA S. The THETA IP address is 192.168.1.1 All calls start with /osc/ """ url_base = "http://192.168.1.1/osc/" url = url_base + url_request return url
def _get_scope(node_name): """Extract the scope name from a node name. The scope name is everything before the final slash, not including any ^ prefix denoting a control dependency. Args: node_name: the full name of an Op or a Tensor in the graph. Returns: The deepest named scope containing the node...
def compute_viewport(window_width, window_height, scissor_x, scissor_y, scissor_width, scissor_height): """ Used on vtkCamera when you are trying to set the viewport to only render to a part of the total...
def openreadlines(filename, xform=None): """Open a file and return a list of all its lines. xform -- a function to run on all lines""" with open(filename, "r", encoding="utf-8") as infp: return [xform(x) if xform else x for x in infp]
def serialize_object(obj): """ Serialize the provided object. We look for "to_dict" and "to_serializable_dict" methods. If none of those methods is available, we fall back to "repr(obj)". :rtype: ``str`` """ # Try to serialize the object if getattr(obj, "to_dict", None): value ...
def pluralize(count: int, unit: str) -> str: """ Pluralize a count and given its units. >>> pluralize(1, 'file') '1 file' >>> pluralize(2, 'file') '2 files' >>> pluralize(0, 'file') '0 files' """ return f"{count} {unit}{'s' if count != 1 else ''}"
def searchForInsert(sortedList:list, value:float)->int: """Search for where to insert the value for the list to remain sorted Args: sortedList (list): a sorted list value (float): the value to insert into the sorted list Returns: int: the index where to insert the value """ ...
def ds_strip_empty(lDatasets): """Strip empty datasets from a list of datasets Args: lDatasets (list) : A list of Dataset Objects or None Returns: list Returns a list object containing all datasets that contained at least a single coordinate or data point. If the given list contains only empty datasets (o...
def numCompareTo(a,b): """compares two numbers by their numerical value""" if a>b: return 1 elif a==b: return 0 elif a<b: return -1
def hex_round(cord, radius): """Round to the nearest whole hex.""" # Convert from axial to cube cords. # https://www.redblobgames.com/grids/hexagons/#conversions-axial x = cord[0] z = cord[1] y = -x-z # Do the rounding. # https://www.redblobgames.com/grids/hexagons/#rounding rx = r...
def get_only_child(node): """ Returns the only child of a node which has only one child. Returns 'None' if node has 0 or >1 children """ child_count = 0 only_child = None for key in node: if isinstance(key, int): child_count += 1 only_child = node[key] return ...
def _delete_enhancement_git_data(enhancement): """Deletes the base GitHub data fields form an enhancement dictionary. Parameters: enhancement - The enhancement dictionary from which the GitHub data fields should be deleted. This dictionary must contain th...
def red(text): """ Print text in red to the console """ return "\033[31m" + text + "\033[0m"
def sort_params_by_block(parameters, mixings): """ Returns a dictionary of the LH blocks of a new model, with all entries. The dict looks like: { # A block with many entries SMINPUTS : { 1: alphainv, 2: GF, 3: alphaS, ... }, # A block with just one entry, i.e. matrices: ...
def extract_position_relations(qdmr_step): """Extract a relation regarding entity positions in a QDMR step. Relevant for VQA data Parameters ---------- qdmr_step : str string of the QDMR step containg relative position knowledge. Either a FILTER of BOOLEAN step. Returns ------- str strin...
def sort_lists(val_list, label_list, sort_order, top_n): """ Designed to take two lists: labels and values. Zips them together, sorts by values, then outputs two lists with matching indices. """ zipped = zip(val_list, label_list) ordered = sorted(zipped, reverse = True if sort_order == 'descendi...