content
stringlengths
42
6.51k
def add_filter(modifiers, new_filter): """Add filter to the modifiers. :param dict modifiers: modifiers :param sqlalchemy.sql.expression.BinaryExpression new_filter: filter :return dict modifiers: new modifiers """ if modifiers is None: modifiers = {} if 'filter' not in modifiers: modifiers['filter'] = [] modifiers['filter'].append(new_filter) return modifiers
def utc_to_gps(utcsec): """ Convert UTC seconds to GPS seconds. Parameters ---------- utcsec: int Time in utc seconds. Returns ------- Time in GPS seconds. Notes ----- The code is ported from Offline. Examples -------- >>> utc_to_gps(315964800) # Jan 6th, 1980 0 """ import time def seconds(year, month, day): return time.mktime((year, month, day, 0, 0, 0, 0, 0, 0)) - time.timezone kUTCGPSOffset0 = (10 * 365 + 7) * 24 * 3600 kLeapSecondList = ( (seconds(1981, 7, 1), 1), # 1 JUL 1981 (seconds(1982, 7, 1), 2), # 1 JUL 1982 (seconds(1983, 7, 1), 3), # 1 JUL 1983 (seconds(1985, 7, 1), 4), # 1 JUL 1985 (seconds(1988, 1, 1), 5), # 1 JAN 1988 (seconds(1990, 1, 1), 6), # 1 JAN 1990 (seconds(1991, 1, 1), 7), # 1 JAN 1991 (seconds(1992, 7, 1), 8), # 1 JUL 1992 (seconds(1993, 7, 1), 9), # 1 JUL 1993 (seconds(1994, 7, 1), 10), # 1 JUL 1994 (seconds(1996, 1, 1), 11), # 1 JAN 1996 (seconds(1997, 7, 1), 12), # 1 JUL 1997 (seconds(1999, 1, 1), 13), # 1 JAN 1999 # DV: 2000 IS a leap year since it is divisible by 400, # ie leap years here are 2000 and 2004 -> leap days = 6 (seconds(2006, 1, 1), 14), # 1 JAN 2006 (seconds(2009, 1, 1), 15), # 1 JAN 2009, from IERS Bulletin C No. 36 (seconds(2012, 7, 1), 16), # 1 JUL 2012, from IERS Bulletin C No. 43 # 1 JUL 2015, from IERS Bulletin C No. 49 # (https://hpiers.obspm.fr/iers/bul/bulc/bulletinc.49) (seconds(2015, 7, 1), 17), (seconds(2017, 1, 1), 18) # 1 JAN 2017, from IERS Bulletin C No. 52 ) leapSeconds = 0 for x in reversed(kLeapSecondList): if utcsec >= x[0]: leapSeconds = x[1] break return utcsec - kUTCGPSOffset0 + leapSeconds
def interpret_distribution(key, value): """ interpret input distribution descriptions into usable entries """ dist_name, args = value.split('(') # uniform(a, b) to ['Uniform', 'a, b)'] dist_name = dist_name.strip() # clear whitespace args = args.strip(')').split(',') # 'a, b)' to ['a', 'b'] converted = {} # storage for distribution information if dist_name not in ['uniform', 'normal', 'constant']: raise IOError('Variable distributions can only be "uniform", "normal", or "constant"; '+ 'got "{}" for "{}"'.format(dist_name, key)) converted['dist'] = dist_name # always store the distribution type if dist_name == 'uniform': # interpret uniform distributions converted['lowerBound'] = float(args[0]) converted['upperBound'] = float(args[1]) elif dist_name == 'normal': # interpret normal distributions converted['mean'] = float(args[0]) converted['std'] = float(args[1]) if len(args) > 2: converted['lowerBound'] = float(args[2]) # note that normal distributions can be truncated converted['upperBound'] = float(args[3]) elif dist_name == 'constant': # constants are simple! converted['value'] = float(args[0]) return converted
def load_items(data): """ Loading items into the game. Parameters: data(dict): Nested dictionaries containing all information of the game. Returns: items_name(list): Returns list of item names. """ items_name = list(data['Items'].keys()) return items_name
def is_palindrome(input): """ Return True if input is palindrome, False otherwise. Args: input(str): input to be checked if it is palindrome """ # Termination / Base condition if len(input) <= 1: return True else: first_char = input[0] last_char = input[-1] # sub_input is input with first and last char removed sub_input = input[1:-1] # recursive call, if first and last char are identical, else return False return (first_char == last_char) and is_palindrome(sub_input)
def cubic(x, a, b, c, d): """ @type x: number @type a: number @type b: number @type c: number @type d: number Calculates cubic function a*x^3+b*x^2+c*x+d @rtype: number @return: result of cubic function calculation """ return a * (x ** 3) + b * (x ** 2) + c * x + d
def bfs_visited(node, graph): """BFS: Return visited nodes""" queue = [node] visited = [] while queue: current = queue.pop() # Enqueue unvisited neighbors queue[0:0] = [neighbor for neighbor in graph[current] if neighbor not in visited] visited.append(current) return visited
def get_search_params(url_path): """ From the full url path, this prunes it to just the query section, that starts with 'q=' and ends either at the end of the line of the next found '&'. Parameters ---------- url_path : str The full url of the request to chop up Returns ------- str The pruned query string, with any other replaced string """ # Remove the '/search.json' part to get the given options query_params = url_path[len('/search.json?'):] # Find the 'q=' section, what we care about queryPos = query_params.find('q=') if queryPos == -1: # There's no 'q=' to grab items from, fail return [] query_params = query_params[queryPos+2:] # Find the end of the search terms, if not the end of the string endPos = query_params.find('&') if endPos != -1: query_params = query_params[:endPos] return query_params
def get_nodes_ordered_balance_keys(src, edge_data): """ This functions gets the source node in the route and return which node is it (node1 ot node2 in the channel) :param src: src node in the route :param edge_data: dictionary containing the edge's attributes. :return: the order of the nodes in the money transformation """ if edge_data['node1_pub'] == src: return 'node1_balance', 'node2_balance' return 'node2_balance', 'node1_balance'
def get_rate_from_actset(action, actset): """ Returns rate from actset returned from solver """ for act in actset: if act[0] == action: return float(act[1])
def _around_mean(prmsl, i: int, j: int): """_around_mean. Args: prmsl: i: j: """ sum_data = 0 for i in range(-1, 2, 1): for j in range(-1, 2, 1): if i == 0 and j == 0: continue sum_data += prmsl[i+i][j+i] return sum_data / 8
def _cast_none(value: str) -> None: """Cast None""" if value == "": return None raise ValueError(f"Expect `@none`, got `{value}`")
def is_positive(number): """ The is_positive function should return True if the number received is positive and False if it isn't. """ if number > 0: return True else: return False
def _get_node(root, name): """ Find xml child node with given name """ for child in root: if child.get('name') == name: return child raise ValueError(f'{name} not found')
def find_next_tip(remaining_id_lst, s, s_values): """find the next tip on the same contour, encoded in s_values. Supposes remaining_id_lst is a sorted list of spiral tip indices, Example Usage: j_nxt=find_next_tip(remaining_id_lst, s, s_values) """ j_nxt=-9999;k=1 kmax=len(remaining_id_lst) while (j_nxt<0)&(k<=kmax): jj=remaining_id_lst[-k] #positive integer valued s_nxt=s_values[jj] if s_nxt==s: #the tips are on the same contour j_nxt=jj else: k+=1 # if k>kmax: # #a circular path is made with the first tip available # j_nxt=0 return j_nxt
def uleb128Encode(num): """ Encode int -> uleb128 num -- int to encode return -- bytearray with encoded number """ arr = bytearray() length = 0 if num == 0: return bytearray(b"\x00") while num > 0: arr.append(num & 127) num = num >> 7 if num != 0: arr[length] = arr[length] | 128 length+=1 return arr
def first_not_none(obj, default): """ returns obj if it is not None, otherwise returns default """ return default if obj is None else obj
def word_list_to_long(val_list, big_endian=True): """Word list (16 bits int) to long list (32 bits int) By default word_list2long() use big endian order. For use little endian, set big_endian param to False. :param val_list: list of 16 bits int value :type val_list: list :param big_endian: True for big endian/False for little (optional) :type big_endian: bool :returns: 2's complement result :rtype: list """ # allocate list for long int long_list = [None] * int(len(val_list)/2) # fill registers list with register items for i, item in enumerate(long_list): if big_endian: long_list[i] = (val_list[i*2]<<16) + val_list[(i*2)+1] else: long_list[i] = (val_list[(i*2)+1]<<16) + val_list[i*2] # return long list return long_list
def is_err(p4filename): """ True if the filename represents a p4 program that should fail. """ return "_errors" in p4filename
def check_is_iterable(py_obj): """ Check whether a python object is a built-in iterable. Note: this treats unicode and string as NON ITERABLE Args: py_obj: python object to test Returns: iter_ok (bool): True if item is iterable, False is item is not """ # Check if py_obj is an accepted iterable and return return(isinstance(py_obj, (tuple, list, set)))
def recall(overlap_count, gold_count): """Compute the recall in a zero safe way. :param overlap_count: `int` The number of true positives. :param gold_count: `int` The number of gold positives (tp + fn) :returns: `float` The recall. """ if gold_count == 0: return 0.0 return overlap_count / float(gold_count)
def render_svg(pixels): """ Converts a sense hat pixel picture to SVG format. pixels is a list of 64 smaller lists of [R, G, B] pixels. """ svg = '<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80">' for y in range(8): for x in range(8): color = pixels[(y*8)+x] if color[0] == 0 and color[1] == 0 and color[2] == 0: continue # Skip black pixels so they are rendered transparent svg += '<rect x="{x}" y="{y}" width="10" height="10" style="fill:rgb({r},{g},{b})" />'.format(x=x*10, y=y*10, r=color[0], g=color[1], b=color[2]) svg += '</svg>' return svg
def _assemble_mif(sim_object): """ assemble_mif(sim_object, output) Function to take a simulation instance and return a string which can be used as a MIF file. Parameters ---------- sim_object : instance A simulation instance. Returns ------- string The constructed MIF string for the simulation.. """ mif = "# MIF 2.1\n\nset pi [expr 4*atan(1.0)]\nset mu0 [expr 4*$pi1e-7]\n" return mif
def xor(a, b): """Return the XOR of two byte sequences. The length of the result is the length of the shortest.""" return bytes(x ^ y for (x, y) in zip(a, b))
def dict_to_json_keys(pydict: dict) -> dict: """this converts a dict using the python coding style to a dict where the keys are in JSON format style :pydict dict keys are strings in python style format :returns dict """ d = {} for key in pydict.keys(): new_key = key.title().replace('_', '') new_key = new_key[:1].lower() + new_key[1:] d[new_key] = pydict[key] return d
def r_capitalize(l: list) -> list: """Recursively calls str.capitalize on each string in l.""" result = [] if not l: return [] result.append(l[0].capitalize()) return result + r_capitalize(l[1:])
def float_nsf(num, precision=17): """n-Significant Figures""" return ('{0:.%ie}' % (precision - 1)).format(float(num))
def fibonacci(n): """Returns the n th fibonacci number""" if n in [0, 1]: # The special case of n being 0 or 1 return 1 a = 1 b = 0 fib_sequence=[] for i in range(n - 1): temp = b # A temporary variable to remember the value of b b = a + b # New value of b fib_sequence.append(b) a = temp # New value of a (old value of b) return fib_sequence
def identify_exclusive_feature_groups(entries): """ Identifies exclusive FASM features and creates groups of them. Returns a dict indexed by group names containing sets of the features. """ groups = {} # Scan entries, form groups for entry in entries: # Get the feature and split it into fields feature = entry.signature parts = feature.split(".") # Check if this feature may be a part of a group. # This is EOS-S3 specific. Each routing mux is encoded as one-hot. # A mux feature has "I_pg<n>" suffix. if parts[1] == "ROUTING" and parts[-1].startswith("I_pg"): # Create a group group = ".".join(parts[:-1]) if group not in groups: groups[group] = set() # Add the feature to the group groups[group].add(feature) return groups
def non_exp_repr(x): """Return a floating point representation without exponential notation. Result is a string that satisfies: float(result)==float(x) and 'e' not in result. >>> non_exp_repr(1.234e-025) '0.00000000000000000000000012339999999999999' >>> non_exp_repr(-1.234e+018) '-1234000000000000000.0' >>> for e in xrange(-50,51): ... for m in (1.234, 0.018, -0.89, -75.59, 100/7.0, -909): ... x = m * 10 ** e ... s = non_exp_repr(x) ... assert 'e' not in s ... assert float(x) == float(s) """ s = repr(float(x)) e_loc = s.lower().find('e') if e_loc == -1: return s mantissa = s[:e_loc].replace('.', '') exp = int(s[e_loc+1:]) assert s[1] == '.' or s[0] == '-' and s[2] == '.', "Unsupported format" sign = '' if mantissa[0] == '-': sign = '-' mantissa = mantissa[1:] digitsafter = len(mantissa) - 1 # num digits after the decimal point if exp >= digitsafter: return sign + mantissa + '0' * (exp - digitsafter) + '.0' elif exp <= -1: return sign + '0.' + '0' * (-exp - 1) + mantissa ip = exp + 1 # insertion point return sign + mantissa[:ip] + '.' + mantissa[ip:]
def get_neighbor_pos(pos): """ Helper function to get right sibling -- no guarantee it exists in tree """ neighbor = list(pos) neighbor[-1] += 1 return neighbor
def format_answers(project, form_data): """ """ if project is None: return {} answers = project.answers keys = [k for k, v in form_data.items() if 'answers' in k] if len(keys) == 0: return answers for k in keys: splt = k.split('_') aspect_id = splt[1] order = splt[2] if order == "None": answers[aspect_id][0] = form_data[k] else: answers[aspect_id][int(order)] = form_data[k] return answers
def del_elements(ele: int, lst: list) -> list: """Remove an element from a list""" new_lst = lst.copy() new_lst.remove(ele) return new_lst
def csv_safe(obj): """Puts quotes around strings with commas in them. """ string = str(obj) return '"' + string + '"' if "," in string else string
def _KindsListToTuple(get_schema_kinds_list): """Called to return default tuple when no datastore statistics are available. """ results = [] if get_schema_kinds_list: for kind_str in sorted(get_schema_kinds_list): results.append({'kind_name': kind_str}) return '', results
def rgb2cmyk(r, g, b): """ Convert rgb color to cmyk color. """ c = 1 - r m = 1 - g y = 1 - b k = min(c, m, y) c = min(1, max(0, c - k)) m = min(1, max(0, m - k)) y = min(1, max(0, y - k)) k = min(1, max(0, k)) return c, m, y, k
def mac_addr_convert(mac_address=u""): """ Function for providing single format for MAC addresses. :param str mac_address: MAC address to be converted. :return: MAC address in format `XX:XX:XX:XX:XX:XX`. """ try: mac = mac_address.replace(".", "") mac = [mac[i:i + 2].upper() for i in range(0, len(mac), 2)] mac = ":".join(mac) return mac except Exception as e: return mac_address
def format_serial(serial_int): """Format the volume serial number as a string. Args: serial_int (long|int): The integer representing the volume serial number Returns: (str): The string representation xxxx-xxxx """ serial_str = None if serial_int == 0: return serial_str if serial_int is not None: serial_str = hex(serial_int)[2:-1].zfill(8) serial_str = serial_str[:4] + '-' + serial_str[4:] return serial_str
def get_hamming_mismatch(genome1, genome2): """returns the number of mismatches between strings""" count = 0 for idx, item in enumerate(genome1): if genome1[idx] != genome2[idx]: count += 1 return count
def get_useful_information(info): """Extracts useful information from video.""" result = {} result['description'] = info['description'] result['id'] = info['id'] result['thumbnail'] = info['thumbnail'] result['title'] = info['title'] result['uploader'] = info['uploader'] return result
def string_to_index(needle, columns): """Given a string, find which column index it corresponds to. :param needle: The string to look for. :param columns: The list of columns to search in. :returns: The index containing that string. :raises ValueError: Value "`needle`" not found in columns "`columns`" """ for index, value in enumerate(columns): if needle == value: return index + 1 raise ValueError("Value \"{0}\" not found in columns \"{1}\"".format(needle, columns))
def instrumentLookup(instrument_df, symbol): """Looks up instrument token for a given script from instrument dump""" try: return instrument_df[instrument_df.tradingsymbol == symbol].instrument_token.values[0] except: return -1
def key(d, key_name): """ Performs a dictionary lookup. """ try: return d[key_name] except KeyError: return 0
def txtToDict(txtfile): """Read vertices from a text file of (Lon, Lat) coords. Input file represents a single polygon with a single line list of comma-separated vertices, e.g.: "<lon>, <lat>, <lon>, <lat>, ...". """ with open(txtfile) as f: polygon = f.readline() if not polygon: return None vertices = [float(val) for val in polygon.strip().split(",")] d = {} d["Lon"] = vertices[::2] d["Lat"] = vertices[1::2] if len(d["Lon"]) != len(d["Lat"]): raise RuntimeError("Invalid input.") return d
def getPrediction(neighbors, weights): """ Computes the weighted vote of each of the k-neighbors Adds up all votes of each entry. And retruns the key of the entry with the highest number of votes. """ import operator votes = {} for x in range(len(neighbors)): response = neighbors[x][-1] # value exists # weight = 0 => add 1 # weight != 0 => add 1/weights[x] if response in votes: if weights[x] == float(0): votes[response] += 1 else: votes[response] += 1/weights[x] # value doesn't exist yet # weight = 0 => add 1 # weight != 0 => add 1/weights[x] else: if weights[x] == float(0): votes[response] = 1 else: votes[response] = 1/weights[x] # Sort the keys in the dictionary of entries in desc order # according the the entry with the highest # of votes sortedVotes = sorted(votes.items(), key=operator.itemgetter(1),reverse=True) # return the entry with the highest vote return sortedVotes[0][0]
def popget(d, key, default=None): """ Get the key from the dict, returning the default if not found. Parameters ---------- d : dict Dictionary to get key from. key : object Key to get from the dictionary. default : object Default to return if key is not found in dictionary. Returns ------- object Examples --------- >>> d = {'ABC': 5.0} >>> popget(d, 'ZPF', 1.0) == 1.0 True >>> popget(d, 'ABC', 1.0) == 5.0 True """ try: return d.pop(key) except KeyError: return default
def phone_edit_distance(predicted_str, ref_str): """ Estimate the edit distance between predicted and ref phone sequences. """ predicted_list = predicted_str.split(" ") ref_list = ref_str.split(" ") m, n = len(predicted_list), len(ref_list) dp = [[0] * (m+1) for _ in range(n+1)] dp[0][0] = 0 for i in range(1, m+1): dp[0][i] = i for i in range(1, n+1): dp[i][0] = i for i in range(1, m+1): for j in range(1, n+1): if predicted_list[i-1] == ref_list[j-1]: dp[j][i] = dp[j-1][i-1] else: dp[j][i] = min(dp[j-1][i] + 1, dp[j][i-1] + 1, dp[j-1][i-1] + 1) return dp[n][m]
def filter_by_type(lst, type_of): """Returns a list of elements with given type.""" return [e for e in lst if isinstance(e, type_of)]
def calc_new_dimensions(max_size: int, width, height): """ Calculate new minimum dimensions and corresponding scalar :param max_size: int :param width: int :param height: int :return: tuple - new dimensions and minimum scalar """ width_scalar = max_size / width height_scalar = max_size / height best_fit_scalar = min(width_scalar, height_scalar) dimensions = (int(width * best_fit_scalar), int(height * best_fit_scalar)) return dimensions, best_fit_scalar
def convert_to_numeric(score): """Convert the score to a float.""" converted_score = float(score) return converted_score
def unpack_tupla(tupla): """unpack_tupla""" (word1, word2) = tupla final = word1 + " " + word2 return final
def get_str_dates_from_dates(dates): """ function takes list of date objects and convert them to string dates :param dates: list of date objects :return str_dates: list of string dates """ str_dates = [] for date in dates: str_dates.append(str(date)) return str_dates
def check_indices(indices_size, index): """Checks indices whether is empty.""" if indices_size < 1: raise IndexError( "The tensor's index is unreasonable. index:{}".format(index)) return indices_size
def revcomp(seq, ttable=str.maketrans('ATCG','TAGC')): """Standard revcomp """ return seq.translate(ttable)[::-1]
def get_macs(leases): """ get list of macs in leases leases is a dict from parse_dhcpd_config return macs as list for each host in leases dict """ return [leases[host]['mac'] for host in leases]
def dbuv_to_uV(dbuv): """ dBuv (dB microvolts) to V (volts) @param dbuv : dB(uV) @type dbuv : float @return: uV (float) """ return (10**(dbuv/20.))
def _get_value(cav, _type): """Get value of custom attribute item""" if _type == 'Map:Person': return cav["attribute_object_id"] if _type == 'Checkbox': return cav["attribute_value"] == '1' return cav["attribute_value"]
def validate_message_prop_value(prop, value): """Check if prop and value is valid.""" if prop not in ["Direction", "Speed", "Status"]: return False if prop == "Direction": if value not in ["E", "W", "N", "S"]: return False if prop == "Speed": if not value.isdigit(): return False if prop == "Status": if value not in ["Off", "Active"]: return False return True
def mid_point(bboxes): """ Method to find the bottom center of every bbox Input: bboxes: all the boxes containing "person" Returns: Return a list of bottom center of every bbox """ mid_values = list() for i in range(len(bboxes)): #get the coordinates coor = bboxes[i] (x1, y1), (x2, y2) = (coor[0], coor[1]), (coor[2], coor[3]) #compute bottom center of bbox x_mid = int(x1 - ((x1 - (x1 + x2)) / 2)) y_mid = int(y1 + y2) mid_values.append((x_mid, y_mid)) return mid_values
def match_asset(asset_name, goos, goarch): """ Compate asset name with GOOS and GOARCH. Return True if matched. """ asset_name = asset_name.lower() goarch = { "386": ["386"], "amd64": ["amd64", "x86_64"] }[goarch] match_goos = goos in asset_name match_goarch = any([word in asset_name for word in goarch]) return match_goos and match_goarch
def get_tags_from_string(tags_string): """Return list of tags from given string""" if tags_string: tags = tags_string.split(', ') else: tags = [] return [ tag for tag in tags if tag ]
def b64_validator(*payload): """Checks if base64 string is a multiple of 4 and returns it unchanged if so, otherwise it will trim the tail end by the digits necessary to make the string a multiple of 4 Args: encodedb64: Base64 string. Returns: decoded Base64 string. """ date, encodedb64 = payload overflow = (len(encodedb64) % 4) if (overflow != 0): trimmed = encodedb64[: len(encodedb64) - overflow] return trimmed else: return (date, encodedb64)
def linear_extrap(x1, x2, x3, y1, y2): """ return y3 such that (y2 - y1)/(x2 - x1) = (y3 - y2)/(x3 - x2) """ return (x3-x2)*(y2-y1)/(x2-x1) + y2;
def decode_response(rec): """ Decodes a response from the server """ return rec.decode().split(",")
def class_to_name(class_label): """ This function can be used to map a numeric feature name to a particular class. """ class_dict = { 0: "Hate Speech", 1: "Offensive Language", 2: "Neither", } if class_label in class_dict.keys(): return class_dict[class_label] else: return "No Label"
def convert_postag(pos): """Convert NLTK POS tags to SentiWordNet's POS tags.""" if pos in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']: return 'v' elif pos in ['JJ', 'JJR', 'JJS']: return 'a' elif pos in ['RB', 'RBR', 'RBS']: return 'r' elif pos in ['NNS', 'NN', 'NNP', 'NNPS']: return 'n' else: return 'u'
def multy(b: int) -> int: """2**b via naive recursion. >>> multy(17)-1 131071 """ if b == 0: return 1 return 2*multy(b-1)
def path_exists(source, path, separator='/'): """Check a dict for the existence of a value given a path to it. :param source: a dict to read data from :param path: a key or path to a key (path is delimited by `separator`) :keyword separator: the separator used in the path (ex. Could be "." for a json/mongodb type of value) """ if path == separator and isinstance(source, dict): return True parts = path.strip(separator).split(separator) if not parts: return False current = source for part in parts: if not isinstance(current, dict): return False if part not in current: return False current = current[part] return True
def convert_uint16_to_array(value): """ Converts a int to an array of 2 bytes (little endian) :param int value: int value to convert to list :return list[int]: list with 2 bytes """ byte0 = value & 0xFF byte1 = (value >> 8) & 0xFF return [byte0, byte1]
def format_indentation(string): """ Replace indentation (4 spaces) with '\t' Args: string: A string. Returns: string: A string. """ return string.replace(" ", " ~ ")
def c2t(c): """Make a complex number into a tuple""" return c.real, c.imag
def check_word(p, tok = None, dep = None, up_tok = None, up_dep = None, precede = None): """ Returns an indicator and a marker If parameters match any word in the sentence: returns 1, markers for each occurance Else: returns 0, [] """ toks = [] for ind, x in enumerate(p): if tok != None and x["tok"].lower() not in tok: continue if dep != None and x["dep"] not in dep: continue if up_tok != None and ("up" not in x or p[x["up"]]["tok"].lower() not in up_tok): continue if up_dep != None and p[x["up"]]["dep"] not in up_dep: continue if precede != None and (len(p) <= ind + 1 or p[ind + 1]["tok"] not in precede): continue if up_tok != None: toks += [[(x["tok"], ind), (p[x["up"]]["tok"].lower() , x["up"])]] else: toks += [[(x["tok"], ind)]] if toks != []: return 1, toks else: return 0, []
def lower(word: str) -> str: """ Will convert the entire string to lowecase letters >>> lower("wow") 'wow' >>> lower("HellZo") 'hellzo' >>> lower("WHAT") 'what' >>> lower("wh[]32") 'wh[]32' >>> lower("whAT") 'what' """ # converting to ascii value int value and checking to see if char is a capital letter # if it is a capital letter it is getting shift by 32 which makes it a lower case letter return "".join( chr(ord(char) + 32) if 65 <= ord(char) <= 90 else char for char in word )
def sum_sequence(sequence): """ What comes in: A sequence of integers. What goes out: Returns the sum of the numbers in the given sequence. Side effects: None. Examples: sum_sequence([8, 13, 7, -5]) returns 23 sum_sequence([48, -10]) returns 38 sum_sequence([]) returns 0 Type hints: :type sequence: list or tuple (of integers) """ # ------------------------------------------------------------------------- # DONE: 3. Implement and test this function. # Tests have been written for you (above). # # RESTRICTION: # You may NOT use the built-in sum function # in IMPLEMENTING this function. # -- The TESTING code above does use built_ins.sum # as an ORACLE in TESTING this function, however. # ------------------------------------------------------------------------- total = 0 for k in range(len(sequence)): total = total + sequence[k] return total
def Hubble(Om, z): """ LCDM AP parameter auxiliary function (from pybird) """ return ((Om) * (1 + z)**3. + (1 - Om))**0.5
def _cyclic_permutations(lst): """Return the list of cyclic permutations of the list lst""" if lst == []: return [[]] plst = [] for _ in range(len(lst)): plst.append(lst) lst = lst[1:] + [lst[0]] return plst
def asym_peak_L(t, pars): """ Lorentizian function. Parameters ------------- t : 'array' pars : 'array' Parameters used in the decomposition. E.g. heigh, center, width. Returns ------------- function """ a0 = pars[0] # height a1 = pars[1] # center a2 = pars[2] # width of gaussian # f = a0*np.exp(-(t - a1)**2/(2*a2**2)) #GAUSSIAN # f = (a0/np.pi)*(0.5*a2)/((t-a1)**2 + (0.5*a2)**2) #LORENTZIAN f = a0 * ((a2 ** 2) / ((t - a1) ** 2 + (1.0 * a2) ** 2)) # LORENTZIAN return f
def limit_ordered_from_domain(domain): """ Testdata: ("3", "2c", "2b", "2a", "1") or ("ORIGIN", "not ok", "LIMIT_VALUE", "ok") yield domain[len(domain) // 2] -> "2b" or "LIMIT_VALUE" in domain -> "LIMIT_VALUE" """ if not domain: return "NULL" if "LIMIT_VALUE" in domain: return "LIMIT_VALUE" return domain[len(domain) // 2]
def throw_empty_pairs(src_tgt_pairs): """Filter [src,tgt] tuple from input list of pairs if either element is empty. Args: src_tgt_pairs: list of (src,tgt) pairs Returns: subset of input pair list for which all elements are non-empty """ return [x for x in src_tgt_pairs if x[0] and x[1]]
def sum_digits(n): """Sum the digits of N.""" L = [] for s in str(n): L.append(int(s)) return sum(L)
def indent(lines, amount, ch=" "): """ Indent the lines in a string by padding each one with proper number of pad characters """ padding = amount * ch return padding + ("\n" + padding).join(lines.split("\n"))
def top(list_to_truncate, number): """ Returns top n elements of a list. """ return list_to_truncate[0:number]
def fix_wg_name(wgname): """Check no non-alphanumerics and convert to lowercase.""" wgname = wgname.lower() if wgname.isalnum(): return wgname raise SystemExit('Non-alphanumeric in WG name: "%s"' % (wgname,)) return wgname
def format_seconds(seconds): """ Takes in a number of seconds and returns a string representing the seconds broken into hours, minutes and seconds. For example, format_seconds(3750.4) returns '1 h 2 min 30.40 s'. """ minutes = int(seconds // 60) hours = int(minutes // 60) remainder_sec = seconds % 60 remainder_min = minutes % 60 output_str = "" if hours != 0: output_str += f"{hours} h " if minutes != 0: output_str += f"{remainder_min} min " output_str += f"{remainder_sec:.2f} s" return output_str
def _is_domain_2nd_level(hostname): """returns True if hostname is a 2nd level TLD. e.g. the 'elifesciences' in 'journal.elifesciences.org'. '.org' would be the first-level domain name, and 'journal' would be the third-level or 'sub' domain name.""" return hostname.count(".") == 1
def UnicodeEscape(string): """Helper function which escapes unicode characters. Args: string: A string which may contain unicode characters. Returns: An escaped string. """ return ('' + string).encode('unicode-escape')
def and_field_filters(field_name, field_values): """AND filter returns documents that contain fields matching all of the values. Returns a list of "term" filters: one for each of the filter values. """ return [ { "term": { field_name: value, } } for value in field_values ]
def is_valid_int(s: str) -> bool: """ Return true if s can be converted into a valid integer, and false otherwise. :param s: value to check if can be converted into a valid integer :return: true if s can be converted into a valid integer, false otherwise >>> is_valid_int("hello") False >>> is_valid_int("506") True """ try: int(s) except ValueError: return False else: return True
def _d4rl_dataset_name(env_name): """Obtains the TFDS D4RL name.""" split_name = env_name.split('-') task = split_name[0] version = split_name[-1] level = '-'.join(split_name[1:-1]) return f'd4rl_adroit_{task}/{version}-{level}'
def format_time(t): """Format time for nice printing. Parameters ---------- t : float Time in seconds Returns ------- format template """ if t > 60 or t == 0: units = 'min' t /= 60 elif t > 1: units = 's' elif t > 1e-3: units = 'ms' t *= 1e3 elif t > 1e-6: units = 'us' t *= 1e6 else: units = 'ns' t *= 1e9 return '%.1f %s' % (t, units)
def norm_min_max_dict(dict1): """ min-max normalization for dictionary :param dict1: input dictionary :return: min-max normalized dictionary """ for key, value in dict1.items(): dict1[key] = round((dict1[key] - min(dict1.values())) / (max(dict1.values()) - min(dict1.values())), 3) return dict1
def _msg_prefix_add(msg_prefix, value): """Return msg_prefix with added value.""" msg_prefix = f"{msg_prefix}: " if msg_prefix else "" return f"{msg_prefix}{value}"
def calculateBallRegion(ballCoordinate, robotCoordinate) -> int: """ Ball region is the region of the ball according to robot. We assumed the robot as origin of coordinate system. Args: ballCoordinate (list): x, y, z coordinates of the ball. robotCoordinate (list): x, y coordinates of the robot. Returns: int: 1 = top-right, 2 = top-left, 3 = bottom-left, 4 = bottom-right """ ballRegion = 0 # Find the location of the ball according to the robot. if ballCoordinate[0] > robotCoordinate[0]: if ballCoordinate[1] > robotCoordinate[1]: ballRegion = 1 else: ballRegion = 4 else: if ballCoordinate[1] > robotCoordinate[1]: ballRegion = 2 else: ballRegion = 3 # print(ballRegion) return ballRegion
def no_space(x) -> str: """ Remove the spaces from the string, then return the resultant string. :param x: :return: """ return x.replace(' ', '')
def add_weights_to_postcode_sector(postcode_sectors, weights): """ Add weights to postcode sector """ output = [] for postcode_sector in postcode_sectors: pcd_id = postcode_sector['properties']['id'].replace(' ', '') for weight in weights: weight_id = weight['id'].replace(' ', '') if pcd_id == weight_id: output.append({ 'type': postcode_sector['type'], 'geometry': postcode_sector['geometry'], 'properties': { 'id': pcd_id, 'lad': postcode_sector['properties']['lad'], 'population_weight': weight['population'], 'area_km2': (postcode_sector['properties']['area'] / 1e6), } }) return output
def lazy_set_default(dct, key, lazy_val_func, *args, **kwargs): """ A variant of dict.set_default that requires a function instead of a value. >>> d = dict() >>> lazy_set_default(d, 'a', lambda val: val**2, 5) 25 >>> lazy_set_default(d, 'a', lambda val: val**3, 6) 25 >>> d {'a': 25} """ try: val = dct[key] except KeyError: val = lazy_val_func(*args, **kwargs) dct[key] = val return val
def parse_refs_json(data): """ Function to parse the json response from the references collection in Solr. It returns the results as a list with the annotation and details. """ # docs contains annotation, fileName, details, id generated by Solr docs = data['response']['docs'] # Create a list object for the results with annotation and details. Details is a list of # a single string, flatten it: remove the string from the list. results = [[docs[i].get('annotation'), docs[i].get('details')[0]] for i in range(len(data['response']['docs']))] #results = [result[0] for result in results] return results
def trapezoidal(f, x_min, x_max, n=1000) -> float: """input fx --> function, x_min, x_max. return hasil integrasi """ h = (x_max - x_min) / n # lebar grid jum = 0.5 * f(x_min) for i in range(1, n): xi = x_min + h * i jum = jum + f(xi) jum = jum + 0.5 * f(x_max) hasil = jum * h return hasil
def only_keys(d, *keys): """Returns a new dictionary containing only the given keys. Parameters ---------- d : dict The original dictionary. keys: list of keys The keys to keep. If a key is not found in the dictionary, it is ignored. """ result = dict() for key in keys: if key in d: result[key] = d[key] return result
def clean_chars_reverse(command: str) -> str: """ replaces mongodb characters format with standard characters :param command: discord command to be converted :type command: str :return: converted command :return type: str """ clean_freq_data = command if "(Dot)" in clean_freq_data: clean_freq_data = clean_freq_data.replace("(Dot)", ".") if "(Dollar_Sign)" in clean_freq_data: clean_freq_data = clean_freq_data.replace("(Dollar_Sign)", "$") return clean_freq_data