content
stringlengths
42
6.51k
def bakhshali_sqrt(rough, n): """https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Bakhshali_method""" iterations = 10 for _ in range(iterations): a = (n - (rough ** 2)) / (2 * rough) b = rough + a rough = b - ((a ** 2) / (2 * b)) return rough
def factorial(num): """This is a recursive function that calls itself to find the factorial of given number""" if num == 1: return num else: # print("lofh") return num * factorial(num-1)
def resolve_args_and_kwargs(context, args, kwargs): """ Resolves arguments and keyword arguments parsed by ``parse_args_and_kwargs`` using the passed context instance See ``parse_args_and_kwargs`` for usage instructions. """ return ( [v.resolve(context) for v in args], {k: v.resolve(context) for k, v in kwargs.items()}, )
def list_cubes(path='.'): """ List all the cubefiles (suffix ".cube" ) in a given path Parameters ---------- path : str The path of the directory that will contain the cube files """ import os cube_files = [] isdir = os.path.isdir(path) if isdir: for file in os.listdir(path): if file.endswith('.cube'): cube_files.append(os.path.join(path, file)) if len(cube_files) == 0: print(f'load_cubes: no cube files found in directory {path}') else: print(f'load_cubes: directory {path} does not exist') return cube_files
def config_value(config, key): """ Return value of a key in config """ if key not in config: return None return config[key]
def compute_1d_offsets(off, n, target_dist): """Helper function to compute slices along one dimension. Args: off (int): The offset of the local data. n (int): The local number of elements. target_dist (list): A list of tuples, one per process, with the offset and number of elements for that process in the new distribution. Returns: (list): A list of slices (one per process) with the slice of local data that overlaps the data on the target process. If there is no overlap a None value is returned. """ out = list() for ip, p in enumerate(target_dist): toff = p[0] tend = p[0] + p[1] if toff >= off + n: out.append(None) continue if tend <= off: out.append(None) continue local_off = 0 target_off = 0 if toff >= off: local_off = toff - off else: target_off = off - toff tnum = n - local_off if tend < off + n: tnum = tend - local_off out.append(slice(local_off, local_off + tnum, 1)) return out
def ci_extractor(document): """Only records positive features""" features = {} for token in document.split(): features["contains_ci(%s)" % token.upper()] = True return features
def same(path1, path2): """ Compares two paths to verify whether they're the same. :param path1: list of nodes. :param path2: list of nodes. :return: boolean. """ start1 = path2.index(path1[0]) checks = [ path1[:len(path1) - start1] == path2[start1:], path1[len(path1) - start1:] == path2[:start1] ] if all(checks): return True return False
def get_row_sql(row): """Function to get SQL to create column from row in PROC CONTENTS.""" postgres_type = row['postgres_type'] if postgres_type == 'timestamp': postgres_type = 'text' return '"' + row['name'].lower() + '" ' + postgres_type
def linspace(start, stop, n): """ Generates evenly spaced values over an interval Parameters ---------- start : int Starting value stop : int End value n : int Number of values Returns ------- list Sequence of evenly spaced values """ if n < 0: raise ValueError('`n` must be a positive integer.') def __generate(): if n == 1: yield stop return h = (stop - start) / (n - 1) for i in range(n): yield start + h * i return list(__generate())
def f(n: int) -> int: """ Extract the digit value you like from a natural number. :param n: the natural number :return: the digit (as int) """ s = str(n) return int(s[0])
def get_row_col_channel_indices_from_flattened_indices(indices: int, num_cols: int, num_channels: int): """Computes row, column and channel indices from flattened indices. NOTE: Repurposed from Google OD API. Args: indices: An `int` tensor of any shape holding the indices in the flattened space. num_cols: `int`, number of columns in the image (width). num_channels: `int`, number of channels in the image. Returns: row_indices: The row indices corresponding to each of the input indices. Same shape as indices. col_indices: The column indices corresponding to each of the input indices. Same shape as indices. channel_indices. The channel indices corresponding to each of the input indices. """ # Avoid using mod operator to make the ops more easy to be compatible with # different environments, e.g. WASM. # all inputs and outputs are dtype int32 row_indices = (indices // num_channels) // num_cols col_indices = (indices // num_channels) - row_indices * num_cols channel_indices_temp = indices // num_channels channel_indices = indices - channel_indices_temp * num_channels return row_indices, col_indices, channel_indices
def find_min(a_para_list): """ Take in a list and return its minimum value :param a_para_list: a list of a wanted parameter :return: a_min: a minimum value """ num_lt = [float(i) for i in a_para_list] # Arjun Mehta min_val = min(num_lt) return min_val
def decode(text): """Decode text using Run-Length Encoding algorithm""" res = '' for i in range(len(text)): if text[i].isdigit(): res += text[i+1] * int(text[i]) return res
def even(value): """ Rounds a number to an even number less than or equal to original Arguments --------- value: number to be rounded """ return 2*int(value//2)
def normalize(numbers, total=1.0): """Multiply each number by a constant such that the sum is 1.0 (or total). >>> normalize([1,2,1]) [0.25, 0.5, 0.25] """ k = total / sum(numbers) return [k * n for n in numbers]
def fuel_to_launch_mass(module_mass: int) -> int: """Calculate the fuel to launch a module of the given mass.""" return max(module_mass // 3 - 2, 0)
def mult(m1,m2): """Matrix multiplication""" res = [len(m2[0])*[0] for i in range(len(m1))] for i in range(len(m1)): for j in range(len(m2[0])): for k in range(len(m2)): res[i][j] += m1[i][k]*m2[k][j] return res
def rotate_lambda(Lambda,clockwise=True): """ Rotate the Lambda tensors for the canonical PEPS representation """ if Lambda is not None: # Get system size (of rotated lambda) Ny = len(Lambda[0]) Nx = len(Lambda[1][0]) # Lambda tensors along vertical bonds vert = [] for x in range(Nx): tmp = [] for y in range(Ny-1): if clockwise: tmp += [Lambda[1][Ny-2-y][x].copy()] else: tmp += [Lambda[1][y][Nx-1-x].copy()] vert += [tmp] # Lambda tensors along horizontal bonds horz = [] for x in range(Nx-1): tmp = [] for y in range(Ny): if clockwise: tmp += [Lambda[0][Ny-1-y][x].copy()] else: tmp += [Lambda[0][y][Nx-2-x].copy()] horz += [tmp] # Combine vertical and horizontal lambdas rLambda = [vert,horz] return rLambda else: return None
def checker_multiple_newlines_at_end_of_file(physical_line, last_line=False, **args): """Multiple newlines at end of file.""" if not last_line: return if not physical_line.strip(): return 0, W205
def make_skills_string(position): """ Take a position dictionary and build the skills list. Ensure the list separator is not a comma if there is a comma in one of the skill items """ if not 'skills' in position.keys(): return '' # Seprator separator = ', ' # Default separator is comma skills = position['skills'] for skill in skills: if ',' in skill: separator = '; ' # If there is a comma in a skill then change to ; return separator.join(skills)
def diff_sequences(left, right): """ Compare two sequences, return a dict containing differences """ return { 'length_match': len(left) == len(right), 'differing': set([ i for i, (l, r) in enumerate(zip(left, right)) if l != r ])}
def gen_rowkey( sport_id: int, league_id: int, match_id: int, market: str, seq: int, period: str, vendor: str, timestamp: int) -> str: """Generate a row key based on the following format with ``#`` as the seperator. <sport_id>#<league_id>#<match_id>#<market>#<seq>#<period>#<vendor>#<timestamp>, Args: sport_id (int): The sport ID. league_id (int): The league ID. match_id (int): The match ID. market (str): The abbriviated market name, e.g., `1x2`, `ah`, `ou`, `ah_1st`, `ou_1st`, etc. seq (int): The sequence of the odd pair if more than 1 odd pairs exist in a market. period (str): The abbriviated current period, e.g., 1st half (`1h`)/2nd half (`2h`) in soccer, 1st quarter/2nd quarter/... etc. in basketball. vendor (str): The vendor from which the odd messages originate. timestamp (int): The epoch timestamp of the creation time included in the original odd message. Returns: str: The row key corresponds to the given input prarmeters. """ rowkey_list = [str(sport_id), str(league_id), str(match_id), market, str(seq), period, vendor, str(timestamp)] return ":".join(rowkey_list)
def boolean(_printer, ast): """Prints a boolean value.""" return f'{"true" if ast["val"] else "false"}'
def mean_parallel_B(rm=0.0, dm=100.0): """ Accepts a rotation measure (in rad/m^2) and dispersion measure (in pc/cm^3) and returns the approximate mean value for the paralelle magnetic field compoent along the line of sight, in Gauss. Conversion to Tesla is: 1 T = 10^4 G """ b_los = 1.23 * (rm / dm) return b_los / 1.0e6
def add_ssl_statement(bucket, policy): """Add SSL statement to policy.""" bucket_arn_obj = "arn:aws:s3:::" + bucket + "/*" ssl_statement = { "Effect": "Deny", "Principal": "*", "Action": "*", "Resource": bucket_arn_obj, "Condition": { "Bool": { "aws:SecureTransport": "false" } } } policy["Statement"].append(ssl_statement) return(policy)
def smallest_prime_factor(x): """Returns the smallest prime number that is a divisor of x""" # Start checking with 2, then move up one by one n = 2 while n <= x: if x % n == 0: return n n+=1
def get_options(options_str): """ Receives a string of 1's and 0's corresponding to different user settings 1 = True, 0 = False options_list[0]: "Enable Footnotes" options_list[1]: "Force Reprocess" """ options_list = [True if char == "1" else False for char in options_str] options = {"enable_footnotes": options_list[0], "force_reprocess": options_list[1]} return options
def float_round(val): """ Rounds a floating number Args: val: number to be rounded Returns: Rounded integer """ return round(float(val))
def cssname(value): """Replaces all spaces with a dash to be a valid id for a cssname""" return value.replace(' ', '-')
def round_to_mbsize(value, batch_size): """Round value to multiple of batch size, if required.""" if value % batch_size == 0: return value else: return value + batch_size - value % batch_size
def to_bool(v): """Converts the given argument to a boolean value""" return v is True or str(v).lower() in ['true', '1']
def build_tags_filter(tags): """Build tag filter based on dict of tags. Each entry in the match is either single tag or tag list. It if is a list, it is "or". """ filters = [] assert isinstance(tags, (list, dict)), 'tags must be either list or dict.' if isinstance(tags, list): tags_dict = {tag['name']: tag['value'] for tag in tags} else: tags_dict = tags for name, values in tags_dict.items(): if isinstance(values, str): values = [values] filters.append({'Name': 'tag:{}'.format(name), 'Values': values}) return filters
def isnull(val): """ Equivalent to isnan for floats, but also numba compatible with integers """ return not (val <= 0 or val > 0)
def get_page_url(year, month): """Get the 'wallpapers of the month' page URL. Arguments: year {int} -- year month {int} -- month Returns: str -- URL string """ template = "https://www.smashingmagazine.com/{:04}/{:02}/desktop-wallpaper-calendars-{}-{:04}/" months = [ "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december", ] prev_year = year if month > 1 else year - 1 prev_month = month - 1 if month > 1 else 12 return template.format(prev_year, prev_month, months[month - 1], year)
def wikidata_url(wikibase): """ returns Wikidata URL from wikibase """ if wikibase: return 'https://www.wikidata.org/wiki/' + wikibase
def get_value(line): """ - line: Line with QASM code to inspect """ return line.split(":")[1].strip()
def format_bytes(count): """ Format bytes in human-readable format """ for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB']: if abs(count) < 1024.0: return f"{count:3.1f} {unit}" count /= 1024.0 return f"{count:.1f} YiB"
def transition_soil_carbon(area_final, carbon_final, depth_final, transition_rate, year, area_initial, carbon_initial, depth_initial): """This is the formula for calculating the transition of soil carbon .. math:: (af * cf * df) - \ \\frac{1}{(1 + tr)^y} * \ [(af * cf * df) - \ (ai * ci * di)] where * :math:`af` is area_final * :math:`cf` is carbon_final * :math:`df` is depth_final * :math:`tr` is transition_rate * :math:`y` is year * :math:`ai` is area_initial * :math:`ci` is carbon_initial * :math:`di` is depth_initial Args: area_final (float): The final area of the carbon carbon_final (float): The final amount of carbon per volume depth_final (float): The final depth of carbon transition_rate (float): The rate at which the transition occurs year (float): The amount of time in years overwhich the transition occurs area_initial (float): The intial area of the carbon carbon_initial (float): The iniital amount of carbon per volume depth_initial (float): The initial depth of carbon Returns: float: Transition amount of soil carbon """ return (area_final * carbon_final * depth_final) - \ (1/((1 + transition_rate) ** year)) * \ ((area_final * carbon_final * depth_final) - \ (area_initial * carbon_initial * depth_initial))
def generate_constraint(category_id, user): """ generate the proper basic data structure to express a constraint based on the category string """ return {'year': category_id}
def is_threatening(x1: int, y1: int, x2: int, y2: int) -> bool: """ Check if the positions are threatening each other. Examples -------- >>> is_threatening(0, 1, 1, 0) True """ same_row = x1 == x2 same_col = y1 == y2 delta1 = min(x1, y1) major_coords1 = (x1 - delta1, y1 - delta1) delta2 = min(x2, y2) major_coords2 = (x2 - delta2, y2 - delta2) same_diagonal_major = major_coords1 == major_coords2 delta1 = x1 delta2 = x2 minor_coords1 = (x1 - delta1, y1 + delta1) minor_coords2 = (x2 - delta2, y2 + delta2) same_diagonal_minor = minor_coords1 == minor_coords2 same_diagonal = same_diagonal_major or same_diagonal_minor return same_row or same_col or same_diagonal
def take(l, indexes): """take(l, indexes) -> list of just the indexes from l""" items = [] for i in indexes: items.append(l[i]) return items
def stringToArgList(string): """Converts a single argument string into a list of arguments""" return string.split(" ")
def day_postfix(day): """Returns day's correct postfix (2nd, 3rd, 61st, etc).""" if day != 11 and day % 10 == 1: postfix = "st" elif day != 12 and day % 10 == 2: postfix = "nd" elif day != 13 and day % 10 == 3: postfix = "rd" else: postfix = "th" return postfix
def is_acceptable_multiplier(m): """A 61-bit integer is acceptable if it isn't 0 mod 2**61 - 1. """ return 1 < m < (2 ** 61 - 1)
def is_unique_chars(str): """returns True if every character in the string is unique""" s = [char for char in str] print(s, str) for x in set(s): if (s.count(x) > 1): print(x) return False return True
def _can_cast_to(value, cast_type): """Returns true if `value` can be casted to type `type`""" try: _ = cast_type(value) return True except ValueError: return False
def tobin(x): """ Serialize strings to UTF8 """ if isinstance(x, str): return bytes(x, 'utf-8') else: return x
def read_sensor_package(bytes_serial): """ Read a sensor from serial bytes. Expected format is 5 bytes: 1, 2 : Package start 0x59 for YY 3 : unsigned integer for sensor index 4, 5 : unsigned integer for reading :return: sensor_index, reading """ if bytes_serial[0] == 0x59 and bytes_serial[1] == 0x59: # check for 'YY' # print(bytes_serial) sensor_index = bytes_serial[2] # sensor index reading = bytes_serial[4] + bytes_serial[3] * 256 # 2 bytes for reading return sensor_index, reading else: return -1, None
def predict_species_impala(context, sepal_width, petal_length, petal_width): """ Predictor for species from model/52952081035d07727e01d836 Predictive model by BigML - Machine Learning Made Easy """ # 0 == Iris-virginica # 1 == Iris-versicolor # 2 == Iris-setosa if (petal_width > 0.8): if (petal_width <= 1.75): if (petal_length > 4.95): if (petal_width <= 1.55): return 0 if (petal_width > 1.55): if (petal_length > 5.45): return 0 if (petal_length <= 5.45): return 1 if (petal_length <= 4.95): if (petal_width <= 1.65): return 1 if (petal_width > 1.65): return 0 if (petal_width > 1.75): if (petal_length > 4.85): return 0 if (petal_length <= 4.85): if (sepal_width <= 3.1): return 0 if (sepal_width > 3.1): return 1 if (petal_width <= 0.8): return 2
def pull_instance_id(arn): """ pulls the ecs instance id from the full arn """ return arn.split('container-instance/', 1)[-1]
def u_func(z, theta): """ Agents utility of asset: Args: z (input array): input to utility function. theta (float): the degree of relative risk aversion (theta = -2). Returns: u (float): utility for given input. """ return (z ** (1 + theta))/(1 + theta)
def prepare_shortlistedFirms(shortlistedFirms): """ Make list with keys key = {identifier_id}_{identifier_scheme}_{lot_id} """ shortlistedFirms = shortlistedFirms if shortlistedFirms else [] all_keys = set() for firm in shortlistedFirms: key = "{firm_id}_{firm_scheme}".format( firm_id=firm["identifier"]["id"], firm_scheme=firm["identifier"]["scheme"] ) # if firm.get('lots'): # keys = set([u"{key}_{lot_id}".format(key=key, lot_id=lot['id']) for lot in firm.get('lots')]) # else: # keys = set([key]) keys = set([key]) all_keys |= keys return all_keys
def v0_group_by(iterable, key_func): """Group iterable by key_func. The simplest way to write the group_by function is to use a dictionary and an if statement. As we loop over the items in our iterable, we can check whether each item has a key in our dictionary or not. If the key in not yet in our dictionary, we'll add it with an empty list as the value. We'll always append to the list as we loop. """ groups = {} for item in iterable: key = key_func(item) if key not in groups: groups[key] = [] groups[key].append(item) return groups
def exact_log2(num): """Find and return an integer i >= 0 such that num == 2**i. If no such integer exists, this function raises ValueError. """ if not isinstance(num, int): raise TypeError("unsupported operand type: %r" % (type(num).__name__,)) n = int(num) if n <= 0: raise ValueError("cannot compute logarithm of non-positive number") i = 0 while n != 0: if (n & 1) and n != 1: raise ValueError("No solution could be found") i += 1 n >>= 1 i -= 1 assert num == (1 << i) return i
def flatten(list1): """ Simple function to flatten peers list Format: [((node1 endpoint1 tuple), (node1 endpoint2 tuple), ..., (node1 endpointm tuple)), ....] Example: [(("172.17.0.1",3000,None),), (("2001:db8:85a3::8a2e",6666,None), ("172.17.0.3",3004,None))] """ f_list = [] for i in list1: if isinstance(i[0], tuple): for j in i: f_list.append(j) else: f_list.append(i) return f_list
def get_per_difference(list1, list2): """list1 : quocient (base value)""" my_size = len(list1) my_range = list(range(0, my_size)) diff = [] if len(list2) != my_size: print('Error! lists have different sizes') exit() else: for i in my_range: diff.append([]) A = list1[i] B = list2[i] my_2_size = list(range(0, len(A))) for j in my_2_size: quo = A[j] per_ = abs(100*(A[j] - B[j]))/quo diff[i].append(per_) return diff
def smooth(x, y): """ Smooth a curve """ xs = x[:] ys = y[:] d = 0 for i in range(0, len(ys)): num = min(len(ys), i + d + 1) - max(0, i - d) _beg = max(0, i - d) _end = min(len(ys), i + d + 1) _ys = ys[_beg:_end] total = sum(_ys) ys[i] = total / float(num) return xs, ys
def alias(name): """ Create a filesystem-friendly alias from a string. Replaces space with _ and keeps only alphanumeric chars. """ name = name.replace(" ", "_") return "".join(x for x in name if x.isalnum() or x == "_").lower()
def rle(seq): """define the rle function""" zipped = [] count = 1 var = seq[0] for i in range(1, len(seq)): if seq[i] == var: count = count + 1 else: zipped.append([var, count]) var = seq[i] count = 1 zipped.append([var, count]) return zipped
def is_quoted_identifier(identifier, sql_mode=""): """Check if the given identifier is quoted. Args: identifier (string): Identifier to check. sql_mode (Optional[string]): SQL mode. Returns: `True` if the identifier has backtick quotes, and False otherwise. """ if "ANSI_QUOTES" in sql_mode: return ((identifier[0] == "`" and identifier[-1] == "`") or (identifier[0] == '"' and identifier[-1] == '"')) return identifier[0] == "`" and identifier[-1] == "`"
def exclusive_id(arg): """Return a regex that captures exclusive id""" assert isinstance(arg, str) return r"(?P<%s>\d+)" % (arg,)
def merge_gaps(gap_list): """ Merges overlapping gaps in a gap list. The gap list is in the form: [('3','4'),('5','6'),('6','7'),('8','9'),('10','11'),('15','16'),('17','18'),('18','19')] Returns a new list containing the merged gaps: [('3','4'),('5','7'),('8','9'),('10','11'),('15','16'),('17','19')] """ merged_gaps = [] while len(gap_list) > 0: try: if int(gap_list[0][1]) >= int(gap_list[1][0]): tmp = (gap_list[0][0], gap_list[1][1]) gap_list.pop(0) gap_list[0] = tmp else: merged_gaps.append(gap_list.pop(0)) except: merged_gaps.append(gap_list.pop(0)) return merged_gaps
def get_url_stripped(uri): """ :param uri: <uri> or uri :return: uri """ uri_stripped = uri.strip() if uri_stripped[0] == "<": uri_stripped = uri_stripped[1:] if uri_stripped[-1] == ">": uri_stripped = uri_stripped[:-1] return uri_stripped
def insertion_sort(a): """ The insertion sort uses another strategy: at the i-th pass, the i first terms are sorted and it inserts the i + 1 term where it belongs by shifting right all elements greater one notch right to create a gap to insert it. It also runs in O(n^2) """ length = len(a) for pass_number in range(1, length): value = a[pass_number] i = pass_number - 1 while i > -1 and value < a[i]: a[i + 1] = a[i] i -= 1 a[i + 1] = value return a
def func(*args): """Function that returns the provided tuple with 'A' prepended.""" return ('A',) + args
def idx_to_hue(idx, color_num=24): """ Convert color index to hue """ if not isinstance(idx, int) or idx < 0 or idx > color_num-1: raise ValueError('idx should be integer between 0 and color_num-1') used = [-1] * color_num used[0] = color_num - 1 i = 0 result = 0 while i < idx: maxi = 0 maxv = used[0] for j in range(color_num): if used[j] > maxv: maxi = j maxv = used[j] nexti = maxi + maxv // 2 + 1 nextv = maxi + maxv - nexti used[maxi] = nexti - maxi - 1 used[nexti] = nextv result = nexti i += 1 h = result / color_num * 360 return h
def steps_to_coords(hor_steps, vert_steps, start_x, start_y, wire_coords): """Add coordinates to a set of points that the wire passes through. They are defined as a number of steps horizontally or vertically from the starting point for this particular instruction. Parameters ---------- hor_steps : int number of steps to take along the x direction vert_steps : int number of steps to take along the y direction start_x : int x coordinate of starting point start_y : int y coordinate of starting point wire_coords : set set of coordinates that the wire passes through Returns ------- start_x : int x coordinate of end point (will be the starting point for the next instruction) start_y : int y coordinate of end point (will be the starting point for the next instruction) wire_coords : set set of coordinates that the wire passes through """ if hor_steps > 0: for x in range(1, hor_steps + 1): wire_coords.add((start_x + x, start_y)) elif hor_steps < 0: for x in range(1, (-1) * hor_steps + 1): wire_coords.add((start_x - x, start_y)) if vert_steps > 0: for y in range(1, vert_steps + 1): wire_coords.add((start_x, start_y + y)) elif vert_steps < 0: for y in range(1, (-1) * vert_steps + 1): wire_coords.add((start_x, start_y - y)) start_x, start_y = start_x + hor_steps, start_y + vert_steps return (start_x, start_y), wire_coords
def circ_square(length): """Calculates the circumference of a square. Calculates the circumference of a square based on the lenth of side. Args: length (float) : length is the length of side of a square. Returns: float: circumference of the square. """ if length < 0: raise ValueError("The length of side must be >= 0.") area_output = 4 * length return area_output
def reset_counts_nondeterministic(shots, hex_counts=True): """Reset test circuits reference counts.""" targets = [] if hex_counts: # Reset 0 from |++> targets.append({'0x0': shots / 2, '0x2': shots / 2}) # Reset 1 from |++> targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # Reset 0 from |++> targets.append({'00': shots / 2, '10': shots / 2}) # Reset 1 from |++> targets.append({'00': shots / 2, '01': shots / 2}) return targets
def listlist_and_matrix_to_listdict(graph, weight=None): """Transforms the weighted adjacency list representation of a graph of type listlist + optional weight matrix into the listdict representation :param graph: in listlist representation :param weight: optional weight matrix :returns: graph in listdict representation :complexity: linear """ if weight: return [{v:weight[u][v] for v in graph[u]} for u in range(len(graph))] else: return [{v:None for v in graph[u]} for u in range(len(graph))]
def any_lowercase5(s): """ incorrect - returns whether false if s contains any capital letters""" for c in s: if not c.islower(): return False return True
def size_to_kb_mb_string(data_size: int, as_additional_info: bool = False) -> str: """Returns human-readable string with kilobytes or megabytes depending on the data_size range. \n :param data_size: data size in bytes to convert :param as_additional_info: if True, the dynamic data appear in round bracket after the number in bytes. e.g. '12345678 bytes (11.7 MB)' if False, only the dynamic data is returned e.g. '11.7 MB' """ if data_size < 1024: as_additional_info = False dynamic = f'{data_size} bytes' elif data_size < 1048576: dynamic = f'{data_size / 1024:0.1f} kB' else: dynamic = f'{data_size / 1048576:0.1f} MB' if as_additional_info: return f'{data_size} bytes ({dynamic})' else: return dynamic
def kolmogorov_53_uni(k, epsilon, c=1.6): """ Universal Kolmogorov Energy spectrum Returns the value(s) of C \epsilon^{2/3} k^{-5/3} Parameters ---------- k: array-like, wavenumber epsilon: float, dissipation rate c: float, Kolmogorov constant c=1.6 (default) ... E(k) = c epsilon^(2/3) k^(-5/3) ... E11(k) = c1 epsilon^(2/3) k^(-5/3) ... E22(k) = c2 epsilon^(2/3) k^(-5/3) ... c1:c2:c = 1: 4/3: 55/18 ... If c = 1.6, c1 = 0.491, c2 = 1.125 ... Exp. values: c = 1.5, c1 = 0.5, c2 = ? Returns ------- e_k: array-like, Kolmogorov energy spectrum for a given range of k """ e_k = c * epsilon ** (2. / 3) * k ** (-5. / 3) return e_k
def absolute_difference(x:float, y:float) -> float: """ return the absolute value of the difference between x and y >>> absolute_difference(3, 5) 2 >>> absolute_difference(10, 7) 3 """ return abs(x - y)
def _conv_size_fcn(inp, padding, dilation, kernel, stride): """ Return the output size or a conv layer with the given params. """ numerator = inp + (2*padding) - (dilation*(kernel-1)) - 1 return int((numerator/stride) + 1)
def redirect_to_url(url): """ Return a bcm dictionary with a command to redirect to 'url' """ return {'mode': 'redirect', 'url': url}
def _parse_double_quotion_5(cur_char, cur_token, token_stack): """ a function that analyze character in state 5 of finite automaton that state means the finite automaton has just handled double quotion """ token_stack.append(''.join(cur_token)) del cur_token[:] return None
def damerau_levenshtein_distance(s1, s2, t1, t2): """ Compute the Damerau-Levenshtein distance between two given strings (s1 and s2) """ d = {} max_size = max(t1+t2) lenstr1 = len(s1) lenstr2 = len(s2) for i in range(-1,lenstr1+1): d[(i,-1)] = i+1 for j in range(-1,lenstr2+1): d[(-1,j)] = j+1 for i in range(0, lenstr1): for j in range(0, lenstr2): if s1[i] == s2[j]: cost = abs(t2[j]-t1[i])/max_size else: cost = 1 d[(i,j)] = min( d[(i-1,j)] + 1, # deletion d[(i,j-1)] + 1, # insertion d[(i-1,j-1)] + cost, # substitution ) if i and j and s1[i]==s2[j-1] and s1[i-1] == s2[j]: d[(i,j)] = min (d[(i,j)], d[i-2,j-2] + cost) # transposition return d[lenstr1-1,lenstr2-1]
def splitAtCapitalization(text): """ splits a string before capital letters. Useful to make identifiers which consist of capitalized words easier to read We should actually find a smarter algorithm in order to avoid splitting things like HLT or LW. """ retval = '' for ch in text: if ch.isupper() and len(retval) > 0: retval += ' ' retval += ch return retval
def gcd(a: int, b: int) -> int: """Greatest common divisor Returns greatest common divisor of given inputs using Euclid's algorithm. Args: a: First integer input. b: Second integer input. Returns: Integer representing GCD. """ # Return the GCD of a and b using Euclid's algorithm: while a != 0: a, b = b % a, a return b
def matchStrengthNoNoise(x, y, n): """Compute the match strength for the individual *x* on the string *y* excluding noise *n*. """ return sum(xi == yi for xi, yi, ni in zip(x, y, n) if ni != "#")
def convert_timeout(argument): """ Allow -1, 0, positive integers and None These are the valid options for the nbconvert timeout option. """ if argument.lower() == 'none': return None value = int(argument) if value < -1: raise ValueError('Value less than -1 not allowed') return value
def aggregator_utility(R,r,k,N): """ Calculates the aggregator's utility """ U_ag=[] # utility of aggregator for c in range(N): U_ag.append((R-r)*c + k) return U_ag
def parse_header( line ): """Parses a header line into a (key, value) tuple, trimming whitespace off ends. Introductory 'From ' header not treated.""" colon = line.find( ':' ) space = line.find( ' ' ) # If starts with something with no whitespace then a colon, # that's the ID. if colon > -1 and ( space == -1 or space > colon ): id = line[ 0: colon + 1 ] value = line[ colon + 1:] if value: value = value.strip() return ( id, value ) return ( None, None )
def ConcatAttr(scope, attr, slash=False): """Combine the SCOPE and ATTR to give the canonical name of the attribute.""" if scope: if slash: sep = '/' else: sep = '.' return '%s%s%s' % (scope, sep, attr) return attr
def fetch_tmin(dbname, dt, bbox): """Downloads minimum temperature from NCEP Reanalysis.""" url = "http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.DAILY/.Diagnostic/.above_ground/.minimum/dods" varname = "temp" return url, varname, bbox, dt
def clean_name(string): """Clean entity/device name.""" return string.replace("-", " ").replace("_", " ").title()
def filter_data(data, filter_keys): """Applies a key filter to a dictionary in order to return a subset of the key-values. The insertion order of the filtered key-value pairs is determined by the filter key sequence. Parameters: data (dict): key-value pairs to be filtered. filter_keys (tuple): sequence of key names that are used to select key-value pairs that match on the key name. Returns: dict: filtered collection of key-value pairs. """ return {key: data[key] for key in filter_keys if key in data.keys()} # record = {} # for key in filter_keys: # if key in data.keys(): # record[key] = data[key] # return record
def handle_generic_error(err): """ default exception handler """ return 'error: ' + str(err), 500
def intify(x): """Change to an int if it is equal to one.""" i = int(x) return i if x == i else x
def bytes_rfind(x: bytes, sub: bytes, start: int, end: int) -> int: """Where is the last location of a subsequence within a given slice of a bytes object? Compiling bytes.rfind compiles this function, when sub is a bytes object. This function is only intended to be executed in this compiled form. Args: x: The bytes object in which to search. sub: The subsequence to look for. start: Beginning of slice of x. Interpreted as slice notation. end: End of slice of x. Interpreted as slice notation. Returns: Highest index of match within slice of x, or -1 if not found. """ if start < 0: start += len(x) if start < 0: start = 0 if end < 0: end += len(x) if end < 0: end = 0 if end > len(x): end = len(x) len_sub = len(sub) if len_sub == 0: if start > len(x) or start > end: return -1 return end index = end - len_sub while index >= start: subindex = 0 while subindex < len_sub: if x[index+subindex] != sub[subindex]: break subindex += 1 if subindex == len_sub: return index index -= 1 return -1
def factorial(n: int) -> int: """Returns the factorial of n, which is calculated recursively, as it's usually defined mathematically.""" assert n >= 0 if n == 0: return 1 elif n == 1 or n == 2: return n else: return n * factorial(n - 1)
def first(l): """ Return the first item from a list, or None of the list is empty. :param l: The list :type l: list :return: The first list item (or None) :rtype: object | None """ return next(iter(l), None)
def generate_message(character, key, dictionary): """Generate Message.""" index = dictionary.find(character) if index > 0: return dictionary[index + key] else: return character
def is_chitoi(tiles): """ Returns True if the hand satisfies chitoitsu. """ unique_tiles = set(tiles) return (len(unique_tiles) == 7 and all([tiles.count(tile) == 2 for tile in unique_tiles]))
def calcGlycerolFractionByVolume(waterVolume, glycerolVolume): """ Calculates the volume fraction of glycerol in a water - glycerol mixture Args: waterVolume (float): volume of water in l glycerolVolume (float): volume of glycerol in l Returns: :class:`float` Fraction of glycerol by volume in [0, 1] """ gV = float(glycerolVolume) gW = float(waterVolume) try: Cv = gV / (gW + gV) except ZeroDivisionError: Cv = 0.0 volumeFractionGlycerol = Cv return volumeFractionGlycerol
def _format_field_name(attr): """Format an object attribute in a human-friendly way.""" # Split at ':' and leave the extension name as-is. parts = attr.rsplit(':', 1) name = parts[-1].replace('_', ' ') # Don't title() on mixed case if name.isupper() or name.islower(): name = name.title() parts[-1] = name return ': '.join(parts)
def reflect_angle_y_deg(a: float) -> float: """Returns reflected angle of `a` in y-direction in degrees. Angles are counter clockwise orientated and +y-axis is at 90 degrees. Args: a: angle to reflect in degrees """ return (360.0 - (a % 360.0)) % 360.0
def pretty_print(parsed_file): """ We just print so it looks decent in a terminal """ indented_uc = ' ' + parsed_file['uncommented_content'].replace('\n', '\n ') return '{origpath} ({artifact}):\n{indented_uc}'.format( origpath=parsed_file['origpath'], artifact=parsed_file['artifact'], indented_uc=indented_uc, ).strip()