content
stringlengths
42
6.51k
def get_aspects(labels): """ Get aspect expressions from a label sequence Parameters ---------- labels: ATE labels (list). Returns ------- List of aspect expression """ aspects = [] curr_aspect = [] prev_label = '' for i in range(len(labels)): if labels[i] == 'B-ASPECT': if 'ASPECT' in prev_label: aspects.append(curr_aspect) curr_aspect = [] curr_aspect.append(i) elif labels[i] == 'I-ASPECT' and ('ASPECT' in prev_label): curr_aspect.append(i) else: # 'O' if curr_aspect: aspects.append(curr_aspect) curr_aspect = [] prev_label = labels[i] if 'ASPECT' in prev_label: aspects.append(curr_aspect) return aspects
def add_it_up(num1: int, num2: int) -> int: """Example callable. Delete this function if copy/pasting this module for use as a template. """ if not isinstance(num1, int): raise TypeError('num1 must be an int') if not isinstance(num2, int): raise TypeError('num2 must be an int') return num1 + num2
def sanitize_string(output): """Removes unwanted characters from output string.""" return output.replace("\t", " ")
def _env_to_bool(val): """ Convert *val* to a bool if it's not a bool in the first place. """ if isinstance(val, bool): return val val = val.strip().lower() if val in ("1", "true", "yes", "on"): return True return False
def _caller_name_and_arg(frame): """Extract information about name and arguments of a function call from a *frame* object""" if frame is None: return None, None caller_name = frame.f_code.co_name caller_varnames = frame.f_code.co_varnames caller_arg = None if len(caller_varnames) > 0: try: loc = frame.f_locals except: loc = {} if caller_varnames[0] in loc: caller_arg = loc[caller_varnames[0]] return caller_name, caller_arg
def range2d(n, m): """ Returns a list of values in a 2d range Arguments: n: The number of rows in the 2d range m: The number of columns in the 2d range Returns: A list of values in a 2d range """ return [(i, j) for i in range(n) for j in range(m)]
def parse_USEARCH_cigar(cigar, seq_len): """Parses usearch specific cigar and return appropriate tuple output USEARCH uses an alternative output format option in which I and D are interchanged 0123456 MDINSHP """ DECODE = 'MDINSHP' _ENCODE = dict( (c,i) for (i, c) in enumerate(DECODE) ) result = [] n = '' total_M = 0 #to keep track of total matching characters to not exceed limit. pos = 0 for c in cigar: if c.isdigit(): n += c elif c in _ENCODE: pos += 1 if n == '': n='1' if pos > 1: if total_M +int(n) > seq_len: n = seq_len - total_M total_M += int(n) else: if c != 'I': total_M += int(n) elif c in 'DM': if total_M +int(n) > seq_len: n = seq_len - total_M total_M += int(n) else: total_M += int(n) result.append( (_ENCODE[c], int(n)) ) if int(n) == seq_len and c == 'M': return result n = '' return result
def make_html(info, tag='h3'): """write infos in simple html tag, return string""" html = '' for key, value in info.items(): line = f"<{tag}>{key} : {value}</{tag}>\n" html += line return html
def seq_strip(seq, stripper=lambda x: x.strip()): """ Strip a sequence of strings. """ if isinstance(seq, list): return map(stripper, seq) if isinstance(seq, tuple): return tuple(map(stripper, seq)) raise ValueError("%s of unsupported sequencetype %s" % (seq, type(seq)))
def _spec_attachment(name_or_type): """ Returns a query item matching messages that have attachments with a certain name or file type. Args: name_or_type (str): The specific name of file type to match. Returns: The query string. """ return f"filename:{name_or_type}"
def expand_qgrams_word_list(wlist, qsize, output, sep='~'): """Expands a list of words into a list of q-grams. It uses `sep` to join words :param wlist: List of words computed by :py:func:`microtc.textmodel.get_word_list`. :type wlist: list :param qsize: q-gram size of words :type qsize: int :param output: output :type output: list :param sep: String used to join the words :type sep: str :returns: output :rtype: list Example: >>> from microtc.textmodel import expand_qgrams_word_list >>> wlist = ["Good", "morning", "Mexico"] >>> expand_qgrams_word_list(wlist, 2, list()) ['Good~morning', 'morning~Mexico'] """ n = len(wlist) for start in range(n - qsize + 1): t = sep.join(wlist[start:start+qsize]) output.append(t) return output
def update_line(line): """ Takes a string line representing a single line of code and returns a string with print updated """ # Strip left white space using built-in string method lstrip() # If line is print statement, use the format() method to add insert parentheses # Note that solution does not handle white space/comments after print statememt if "print" in line: idx_print = line.find("print") return line[:idx_print] + line[idx_print:idx_print+5] + "(" + line[idx_print+6:] + ")" return line
def additionner_deux_nombres(premier_nombre, second_nombre): """ Additionne deux nombres inputs: Deux nombres outputs: Un nombre """ total = premier_nombre + second_nombre return total
def solution(X, A): """ For this task, we simply need to record where the leaves have fallen. As soon as we have a bridge, we cross. """ # initialise variables to keep track of the leaves leaves = [False] * X leaves_count = 0 for idx, val in enumerate(A): # leaf has fallen on an empty spot if not leaves[val - 1]: # increase counter leaves_count += 1 # bridge is complete, we can cross if leaves_count == X: return idx # record the space as filled leaves[val - 1] = True # the frog is stuck on this side I'm afraid return -1
def bspline_cython(p, j, x): """Return the value at x in [0,1[ of the B-spline with integer nodes of degree p with support starting at j. Implemented recursively using the de Boor's recursion formula""" assert (x >= 0.0) & (x <= 1.0) assert (type(p) == int) & (type(j) == int) if p == 0: if j == 0: return 1.0 else: return 0.0 else: w = (x - j) / p w1 = (x - j - 1) / p return w * bspline_cython(p - 1, j, x) + (1 - w1) * bspline_cython(p - 1, j + 1, x)
def filter_words(words, skip_words): """This function takes a list of words and returns a copy of the list from which all words provided in the list skip_words have been removed. For example: >>> filter_words(["help", "me", "please"], ["me", "please"]) ['help'] >>> filter_words(["go", "south"], skip_words) ['go', 'south'] >>> filter_words(['how', 'about', 'i', 'go', 'through', 'that', 'little', 'passage', 'to', 'the', 'south'], skip_words) ['go', 'passage', 'south'] """ return [word for word in words if word not in skip_words]
def row_check_conflict(row1, row2): """Returns False if row1 and row2 have any conflicts. A conflict is where one position in a row is True while the other is False.""" assert len(row1) == len(row2) for i, v1 in enumerate(row1): v2 = row2[i] # The solution can't conflict if either row is "None" (unknown). if v1 is None or v2 is None: continue if v1 != v2: return False # No conflicts in the entire row. We must be good. return True
def parse_int(text: str) -> int: """ Small postprocessing task to parse a string to an int. """ return int(text.strip())
def color_RGB_to_xy(R, G, B): """Convert from RGB color to XY color.""" if R + G + B == 0: return 0, 0 var_R = (R / 255.) var_G = (G / 255.) var_B = (B / 255.) if var_R > 0.04045: var_R = ((var_R + 0.055) / 1.055) ** 2.4 else: var_R /= 12.92 if var_G > 0.04045: var_G = ((var_G + 0.055) / 1.055) ** 2.4 else: var_G /= 12.92 if var_B > 0.04045: var_B = ((var_B + 0.055) / 1.055) ** 2.4 else: var_B /= 12.92 var_R *= 100 var_G *= 100 var_B *= 100 # Observer. = 2 deg, Illuminant = D65 X = var_R * 0.4124 + var_G * 0.3576 + var_B * 0.1805 Y = var_R * 0.2126 + var_G * 0.7152 + var_B * 0.0722 Z = var_R * 0.0193 + var_G * 0.1192 + var_B * 0.9505 # Convert XYZ to xy, see CIE 1931 color space on wikipedia return X / (X + Y + Z), Y / (X + Y + Z)
def efficientnet_params(model_name): """Get efficientnet params based on model name.""" params_dict = { # (width_coefficient, depth_coefficient, resolution, dropout_rate) 'efficientnet-b0': (1.0, 1.0, 224, 0.2), 'efficientnet-b1': (1.0, 1.1, 240, 0.2), 'efficientnet-b2': (1.1, 1.2, 260, 0.3), 'efficientnet-b3': (1.2, 1.4, 300, 0.3), 'efficientnet-b4': (1.4, 1.8, 380, 0.4), 'efficientnet-b5': (1.6, 2.2, 456, 0.4), 'efficientnet-b6': (1.8, 2.6, 528, 0.5), 'efficientnet-b7': (2.0, 3.1, 600, 0.5), } return params_dict[model_name]
def verify_newimage(filename, files): """ Checks existence of filename Args: filename: Image name ID: Username Returns: x: Boolean value. If x is true, image does not exist in database """ x = True cursor = files if cursor == []: x = True else: for i in cursor: if i == filename: x = False return x
def validate_team(all_boards, calender, team, glob=False): """ Helper function to validate if a team should be synced or not. :param Dict all_boards: All boards :param Dict calender: Calender created for the team :param String team: Team name :param Bool glob: Are we checking for the global board :return: True/False if the team should be synced :rtype: Bool """ # Gather all quarters quarters = [] for quarter, value in calender.items(): if value: if value[0]['quarter_string'] not in quarters: quarters.append(value[0]['quarter_string']) if not glob: # Check if the boards are in JIRA already for quarter in quarters: if f'{quarter} - {team} Board' in all_boards.keys(): return False return True else: # Check if the boards are in JIRA already for quarter in quarters: if f'{team} - {quarter} Board' in all_boards.keys(): return False return True
def unescape(s): """ replace Tumblr's escaped characters with ones that make sense for saving in an HTML file """ if s is None: return "" # html entities s = s.replace("&#13;", "\r") # standard html s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") s = s.replace("&amp;", "&") # this has to be last return s
def to_bool(s: str) -> bool: """Return bool converted from string. bool() from the standard library convert all non-empty strings to True. """ return s.lower() in ['true', 't', 'y', 'yes'] if s is not None else False
def flatten_dict(d, parent_key=''): """ Return array of flattened dict keys """ keys = [] for k in d: combined_key = k if parent_key: combined_key = "{}.{}".format(parent_key, k) if type(d[k]) == dict: keys.extend(flatten_dict(d[k], parent_key=combined_key)) else: keys.append(combined_key) return keys
def _sort_orders(orders): """Sort a list of possible orders that are to be tried so that the simplest ones are at the beginning. """ def weight(p, d, q, P, D, Q): """Assigns a weight to a given model order which accroding to which orders are sorted. It is only a simple heuristic that makes it so that the simplest models are sorted first. """ cost = 0 if P + D + Q: cost += 1000 cost += p**2 + d**2 + q**2 cost += P**3 + 2*d**3 + 3*q**3 return cost orders = [(weight(*o), o) for o in orders] orders.sort() orders = [x[1] for x in orders] return orders
def is_stopword(morpheme, trie): """ Returns the presence or absence of stopword in stopword dictionary. - input : morpheme string, trie instance - output : boolean (Ture, False) """ if morpheme in trie: return True return False
def trianglePoints(x, z, h, w): """ Takes the geometric parameters of the triangle and returns the position of the 3 points of the triagles. Format : [[x1, y1, z1], [x2, y2, z2], [x3, y3, z3]] """ P1 = [x, 0, z+h] P2 = [x, w/2, z] P3 = [x, -w/2, z] return [P1, P2, P3]
def simple_square_brackets(s, fmt_spec): """ Surrounds the string with [ ] characters. Useful when verifying string truncation i.e. when checking the UI these characters should be visible. :param s: String to surround :param fmt_spec: Regex for placeholders. :returns: String surrounded with [ ] """ return u'[{0}]'.format(s)
def lremove(s, prefix): """Remove prefix from string s""" return s[len(prefix):] if s.startswith(prefix) else s
def hex_to_long(hex_string: str): """Convert hex to long.""" return int(hex_string, 16)
def taputil_find_header(headers, key): """Searches for the specified keyword Parameters ---------- headers : HTTP(s) headers object, mandatory HTTP(s) response headers key : str, mandatory header key to be searched for Returns ------- The requested header value or None if the header is not found """ for entry in headers: if key.lower() == entry[0].lower(): return entry[1] return None
def powerOfN(x=2,n=3): """this function is completely useless, it just calculates x^n)""" y = x**n return y
def selection_sort_dec(array): """ it looks for largest value for each pass, after completing the pass, it places it in the proper position it has O(n2) time complexity larger numbers are sorted first """ for i in range(len(array)): # print(array) large = i for j in range(i+1,len(array)): if array[large] < array[j]: large = j array[i], array[large] = array[large], array[i] return array
def _get_app_domain(project_id): """ Return String App Engine Domain to send data to """ app_domain = "https://{project_id}.appspot.com".format(project_id=project_id) return app_domain
def chunks(list_, num_items): """break list_ into n-sized chunks...""" results = [] for i in range(0, len(list_), num_items): results.append(list_[i:i+num_items]) return results
def insertion_sort(my_list): """ Performs an insertion sort. Args: my_list: a list to be sorted. Returns: A sorted list Raises: TypeError: There are mixed types in the list which are not orderable """ for location in range(1, len(my_list)): # Skip the first item - so range starts at 1 current_item = my_list[location] # this is the first item which has not been sorted yet working_location = location # now work backwards through the sorted items to find the correct location # for the current_item for sorted_location in range(location - 1, -1, -1): compare_with = my_list[sorted_location] if current_item < compare_with: # then swap items at sorted_location and working_location my_list[sorted_location] = current_item my_list[working_location] = compare_with working_location -= 1 # here we could print the list to show the progress so far # print(my_list) return my_list
def get_capability(capabilities, capability_name): """Search a set of capabilities for a specific one.""" for capability in capabilities: if capability["interface"] == capability_name: return capability return None
def find_all(srcstr, substr): """ to find all desired substring in the source string and return their starting indices as a list Args: srcstr(str): the parent string substr(str): substr Returns: list: a list of the indices of the substrings found """ indices = [] gotone = srcstr.find(substr) while (gotone != -1): indices.append(gotone) gotone = srcstr.find(substr, gotone + 1) return indices
def pairT_impairF(x): """renvoit Vrai si pair Faux si impair""" assert type(x) is int if x%2 == 0 : return True else : return False
def _get_browser(buildername): """Gets the browser type to be used in the run benchmark command.""" if 'android' in buildername: return 'android-chromium' # pragma: no cover elif 'x64' in buildername: return 'release_x64' # pragma: no cover return 'release'
def get_train_test_modifiers(modifier=None): """Append the modifier to 'train' and 'test'""" modifier_train = 'train' modifier_test = 'test' if modifier is not None: modifier_train = modifier_train + '_' + modifier modifier_test = modifier_test + '_' + modifier return modifier_train, modifier_test
def extract_history_ztf(alert: dict, key: str) -> list: """Extract data field from alert candidate and previous linked alerts. Parameters ---------- candidate: dict Correspond to the key "candidate" in the alert dictionary. previous: list of dicts Correspond to the key "prv_candidates" in the alert dictionary. key: str Dictionary key for which values have to be extracted Returns ---------- out: list List containing values corresponding to the key. First element is from the candidate, and other elements from the previous alerts. """ data = [i[key] for i in alert["prv_candidates"]] data.insert(0, alert["candidate"][key]) return data
def len_eq(value, other): """Length Equal""" return len(value) == other
def fibonacci(number): """Calculate Fibonacci numbers fib_n The Fibonacci numbers are 1, 2, 3, 5 ,8, 12, 21, ... fib_n = fib_n-1 + fib_n-2 """ if number < 2: return 1 return fibonacci(number-1) + fibonacci(number-2)
def to_red(string): """ Converts a string to bright red color (16bit) Returns: str: the string in bright red color """ return f"\u001b[31;1m{string}\u001b[0m"
def line_width( segs ): """ Return the screen column width of one line of a text layout structure. This function ignores any existing shift applied to the line, represended by an (amount, None) tuple at the start of the line. """ sc = 0 seglist = segs if segs and len(segs[0])==2 and segs[0][1]==None: seglist = segs[1:] for s in seglist: sc += s[0] return sc
def get_hourly_rate(target_count, cycle_minutes): """Get hourly rate of emails sent.""" cycle_hours = cycle_minutes / 60 return target_count / cycle_hours
def rounddown_20(x): """ Project: 'ICOS Carbon Portal' Created: Tue May 07 09:00:00 2019 Last Changed: Tue May 07 09:00:00 2019 Version: 1.0.0 Author(s): Karolina Description: Function that takes a number as input and floors it to the nearest "20". Input parameters: Number (var_name: 'x', var_type: Integer or Float) Output: Float """ #Import module: import math import numbers #Check if input parameter is numeric: if(isinstance(x, numbers.Number)==True): #If the 2nd digit from the decimal point is an even number: if(int(x/10.0)%2==0): return(int(x / 10.0) * 10) - 20 #If the 2nd digit from the decimal point is an odd number: else: return(int(x / 10.0) * 10) - 10 #If input parameter is not numeric, prompt an error message: else: print("Input parameter is not numeric!")
def optional(flag=True): """When this flag is True, an exception should be issued if the related keyword/element is defined and the constraint fails. If the keyword/element is not defined or `flag` is False, the constraint should be ignored. Returns "O" or False >>> optional(True) 'O' >>> optional(False) False """ return "O" if flag else False
def singularize(name): """ This is a total hack that will only work with ESP resources. Don't use this for anything else. """ n = str(name) if n[-1:] == 's': return n[:-1] return n
def is_number(s): """ Determine if a string is a number :param s: :return: """ try: float(s) return True except ValueError: pass return False
def parse_vid(proto_vid): """Turn rm0 into RM000 etc""" letters = proto_vid[:2].upper() numbers = proto_vid[2:] numbers = "0" * (3 - len(numbers)) + numbers return letters + numbers
def part2(input): """ >>> part2([199, 200, 208, 210, 200, 207, 240, 269, 260, 263]) 5 """ window = lambda i, list : list[i] + list[i+1] + list[i+2] return sum(1 if window(i, input) < window(i+1, input) else 0 for i in range(len(input)-3))
def split_compound(compound): """Split a possibly compound format string into segments. >>> split_compound('bold_underline_bright_blue_on_red') ['bold', 'underline', 'bright_blue', 'on_red'] """ merged_segs = [] # These occur only as prefixes, so they can always be merged: mergeable_prefixes = ['on', 'bright', 'on_bright'] for s in compound.split('_'): if merged_segs and merged_segs[-1] in mergeable_prefixes: merged_segs[-1] += '_' + s else: merged_segs.append(s) return merged_segs
def compare_versions(old_version, new_version): """ Compare specified version and return True if new version is strictly greater than old one Args: old_version (string): old version new_version (string): new version Returns: bool: True if new version available """ #check versions old_vers = tuple(map(int, (old_version.split(u'.')))) if len(old_vers)!=3: raise Exception('Invalid version "%s" format, only 3 digits format allowed' % old_version) new_vers = tuple(map(int, (new_version.split(u'.')))) if len(new_vers)!=3: raise Exception('Invalid version "%s" format, only 3 digits format allowed' % new_version) #compare version if old_vers<new_vers: return True return False
def get_tenant_headers(webhook_api_key: str) -> dict: """Return HTTP headers required for tenant lob webhook call.""" headers = {"accept": "application/json", "Content-Type": "application/json"} if webhook_api_key: headers["X-API-Key"] = webhook_api_key return headers
def removeAdjacentsInArray(contourArray): """ removeAdjacentsInArray. remove adjacents in array :param contourArray: (Array) all contours :returns noAdjacentsArray: (Array) adjacents removed and with last array value """ noAdjacentsArray = [] if(len(contourArray)> 0): #r = [a for a,b in zip(contourArray, contourArray[1:]+[not contourArray[-1]]) if a != b] #fixed - included last array value noAdjacentsArray = [a for a,b in zip(contourArray, contourArray[1:]+[not contourArray[-1]]) if a != b]+[contourArray[-1]] else: noAdjacentsArray = [] return noAdjacentsArray
def _LookupKind(kinds, spec, scope): """Tries to find which Kind a spec refers to, given the scope in which its referenced. Starts checking from the narrowest scope to most general. For example, given a struct field like Foo.Bar x; Foo.Bar could refer to the type 'Bar' in the 'Foo' namespace, or an inner type 'Bar' in the struct 'Foo' in the current namespace. |scope| is a tuple that looks like (namespace, struct/interface), referring to the location where the type is referenced.""" if spec.startswith('x:'): mojom_name = spec[2:] for i in range(len(scope), -1, -1): test_spec = 'x:' if i > 0: test_spec += '.'.join(scope[:i]) + '.' test_spec += mojom_name kind = kinds.get(test_spec) if kind: return kind return kinds.get(spec)
def helper_parse_UniProt_dump_other_functions(list_of_string): """ e.g. input [['EMBL; AY548484; AAT09660.1; -; Genomic_DNA.'], ['RefSeq; YP_031579.1; NC_005946.1.'], ['ProteinModelPortal; Q6GZX4; -.'], ['SwissPalm; Q6GZX4; -.'], ['GeneID; 2947773; -.'], ['KEGG; vg:2947773; -.'], ['Proteomes; UP000008770; Genome.'], ['GO; GO:0046782; P:regulation of viral transcription; IEA:InterPro.'], ['InterPro; IPR007031; Poxvirus_VLTF3.'], ['Pfam; PF04947; Pox_VLTF3; 1.']] EnsemblPlants; AT3G09880.1; AT3G09880.1; AT3G09880. """ # GO, InterPro, Pfam, KEGG, Reactome, STRING, Proteomes = [], [], [], [], [], [], [] GO, InterPro, Pfam, Reactome = [], [], [], [] for row in list_of_string: row_split = row.split(";") func_type = row_split[0] try: annotation = row_split[1].strip() except IndexError: continue # if func_type == "KEGG": # KEGG.append(annotation) if func_type == "GO": GO.append(annotation) elif func_type == "InterPro": InterPro.append(annotation) elif func_type == "Pfam": Pfam.append(annotation) elif func_type == "Reactome": # DR Reactome; R-DME-6799198; Complex I biogenesis. if annotation.startswith("R-"): # R-DME-6799198 --> DME-6799198 annotation = annotation[2:] Reactome.append(annotation) # elif func_type == "STRING": # funcs_2_return = [] # try: # for func in [func.strip() for func in row_split[1:]]: # if func.endswith("."): # func = func[:-1] # if func == "-": # continue # funcs_2_return.append(func) # except IndexError: # continue # STRING += funcs_2_return # elif func_type == "Proteomes": # Proteomes.append(annotation) # return [GO, InterPro, Pfam, KEGG, Reactome, STRING, Proteomes] return GO, InterPro, Pfam, Reactome
def factorial2(num): """ return factorial without recursion :param num: the number :return: factorial """ product = 1 for n in range(2, num + 1): product *= n return product
def reverse_boolean(boolean): """Invert boolean.""" if boolean == True: return False else: return True
def ret_class(beta, p, pthre=0.05): """ tp = 0 : prediction 1, real 1 fp = 1 : prediction 1 ,real 0 fn = 2 : prediction 0 , real 1 tn = 3 : prediction 0, real 0 """ pred = 1 if p < pthre else 0 real = 1 if beta != 0 else 0 if pred == 1 and real == 1: return 0 elif pred == 1 and real == 0: return 1 elif pred == 0 and real == 1: return 2 else: return 3
def reformat_text(text: str) -> str: """Replace shadowverse-portal's formatting markup with markdown.""" return ( text.replace("<br>", "\n") .replace("[/b][b]", "") .replace("[b]", "**") .replace("[/b]", "**") )
def display_list(l): """Returns a comma-punctuated string for the input list with a trailing ('Oxford') comma.""" length = len(l) if length <= 2: return " and ".join(l) else: # oxford comma return ", ".join(l[:-1]) + ", and " + l[-1]
def is_function(s: str) -> bool: """Checks if the given string is a function name. Parameters: s: string to check. Returns: ``True`` if the given string is a function name, ``False`` otherwise. """ return 'f' <= s[0] <= 't' and s.isalnum()
def gnomad_link(variant_obj, build=37): """Compose link to gnomAD website.""" if build == 38: url_template = ( "http://gnomad.broadinstitute.org/variant/{this[chromosome]}-" "{this[position]}-{this[reference]}-{this[alternative]}?dataset=gnomad_r3" ) else: url_template = ( "http://gnomad.broadinstitute.org/variant/{this[chromosome]}-" "{this[position]}-{this[reference]}-{this[alternative]}" ) return url_template.format(this=variant_obj)
def byte_literal(b): """ If b is already a byte literal, return it. Otherwise, b is an integer which should be converted to a byte literal. This function is for compatibility with Python 2.6 and 3.x """ if isinstance(b, int): return bytes([b]) else: return b
def getAttributes(tag): """Convert non-nested key/vals in dict into dict on their own """ return dict([(k,v) for k,v in tag.items() if type(v) == type("") and '__' not in k ])
def questionize_label(word): """Convert a word to a true/false style question format. If a user follows the convention of using `is_something`, or `has_something`, for a boolean value, the *property* text will automatically be converted into a more human-readable format, e.g. 'Something?' for is_ and Has Something? for has_. Args: word (str): The string to format. Returns: word (str): The formatted word. """ if word is None: return '' if word.startswith('is_'): return '{0}?'.format(word[3:]) elif word.startswith('has_'): return '{0}?'.format(word[4:]) return word
def IsIntString(string): """ Return whether the supplied string contains pure integer data. """ try: intVal = int(string) except ValueError: return False strip = string.strip().lstrip("0") return len(strip) == 0 or str(intVal) == strip
def join_tkn_func(x: tuple, idx1: int, idx2: int): """ idx1: token(0) or lemma token(1) idx2: pos(2) or tag(3) - pos: coarse-grained tags, https://universaldependencies.org/docs/u/pos/ - tag: fine-grained part-of-speech tags """ return f"{x[idx1]}__{x[idx2]}"
def tokenize(list_nd: list) -> list: """Tokenize a list. :param list_nd: :return: """ if not list_nd: return [] if isinstance(list_nd, list): return ['('] + [tokenize(s) for s in list_nd] + [')'] return list_nd
def compute_middle(low: float, high: float): """"Returns the middle point of the interval [low, high].""" return low + (high - low) / 2
def make_profit(actions): """Calculate profit""" total_profit = 0 for action in actions: action_profit = action[2] total_profit += action_profit return total_profit
def sigfig(number, places): """ Round `number` to `places` significant digits. Parameters: number (int or float): A number to round. places (int): The number of places to round to. Returns: A number """ # Passing a negative int to round() gives us a sigfig determination. # Example: round(12345, -2) = 12300 ndigits = -int(len(str(abs(number)).split('.')[0]) - places) return round(number, ndigits)
def ish(s): """based on func reverse""" def reverse(m): if len(m) == 0: return '' return reverse(m[1:]) + m[0] return reverse(s) == s
def filter_positive_even_numbers(numbers): """Receives a list of numbers, and returns a filtered list of only the numbers that are both positive and even (divisible by 2), try to use a list comprehension.""" return [i for i in numbers if (int(i) % 2 == 0 and int(i)>0)]
def un_div(text): """Remove wrapping <div...>text</div> leaving just text.""" if text.strip().startswith("<div ") and text.strip().endswith("</div>"): text = text.strip()[:-6] text = text[text.index(">") + 1:].strip() return text
def tuples_to_geojson(bounds): """ Given bounding box in tuple format, returns GeoJSON polygon Input bounds: (lat(y) min, lat(y) max, long(x) min, long(x) max) """ lat_min = bounds[0] lat_max = bounds[1] long_min = bounds[2] long_max = bounds[3] bounding_box = {} bounding_box["type"] = "Polygon" bounding_box["coordinates"] = [ [lat_max, long_min], # NW [lat_max, long_max], # NE [lat_min, long_max], # SE [lat_min, long_min] # SW ] return bounding_box
def identify_block_children(block: dict) -> list: """Extract the blocks IDs of the given block's children. Presumably, order matters here, and the order needs to be maintained through text concatenation to get the full key text. """ child_ids = [] if "Relationships" in block.keys(): child_ids = [ ix for link in block["Relationships"] if link["Type"] == "CHILD" for ix in link["Ids"] ] return child_ids
def matches_only(entry, only) -> bool: """Return True if all variables are matched""" ret = False for val in only: if val["key"] in entry and entry[val["key"]] == val["value"]: ret = True else: ret = False break return ret
def create_loss_map(model_config: dict) -> dict: """ Creates a dictionary mapping loss names to loss functions. Args: model_config: The configuration dictionary. Returns: A dictionary mapping loss names to emtpy lists. """ losses = {'loss': []} if model_config['single_channel_module']['enabled']: losses['sc'] = [] if model_config['mixed_channel_module']['enabled']: losses['mc'] = [] if model_config['calibration_module']['enabled']: losses['calib'] = [] return losses
def uniquify(seq, idfun=None): """ Order-preserving uniquify of a list. Lifted directly from http://www.peterbe.com/plog/uniqifiers-benchmark """ if idfun is None: idfun = lambda x: x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue seen[marker] = 1 result.append(item) return result
def djb2(key): """ Classic hashing function by Bernstein. This algorithm (k=33) was first reported by dan bernstein many years ago in comp.lang.c. """ hash = 5381 for letter in str(key): hash = ((hash << 5) + hash) + ord(letter) return hash
def getMonthNumber(month): """ Change the months from string to int. """ months = { "Jan":1, "Feb":2, "Mar":3, "Apr":4, "May":5, "Jun":6, "Jul":7, "Aug":8, "Sep":9, "Oct":10, "Nov":11, "Dec":12 } return months[month]
def denormalized_age(age): """ :param age: age in range [-1, 1] :return: age in range [0, 240] (months) """ return (age + 1) * 120
def norm_spaces(s): """Normalize spaces, splits on all kinds of whitespace and rejoins""" return s # return " ".join((x for x in re.split(r"\s+", s) if x))
def __highlight_function__(feature): """ Function to define the layer highlight style """ return {"fillColor": "#ffaf00", "color": "green", "weight": 3, "dashArray": "1, 1"}
def exception_to_message(ex): """Get the message from an exception.""" return ex.args[0]
def isNumber(string): """ check if a string can be converted to a number """ try: number = float(string) return True except: return False
def cheating_matrix(seating_chart): """ Calculate and return the probabilities of cheating for each position in a rxc grid :param seating_chart: A nested list representing a rxc grid :return: A nested list, the same size as seating_chart, with each element representing that position's cheating probability """ # Create matrix of probabilities by location prob_matrix = [[.025, .3, .025], [.2, 0, .2], [.025, .2, .025]] # Create blank nested list for saving calculated probabilities (same size as seating_chart) calc_prob = [] for ch_row in range(len(seating_chart)): new_row = [] for ch_col in range(len(seating_chart[ch_row])): new_row.append(seating_chart[ch_row][ch_col]) calc_prob.append(new_row) # calculate probabilities for each spot in seating_chart, store in calc_prob for row in range(len(seating_chart)): for col in range(len(seating_chart[row])): calc_prob[row][col] = 0 for r_adj in range(-1, 2): for c_adj in range(-1, 2): if 0 <= row + r_adj < len(seating_chart): if 0 <= col + c_adj < len(seating_chart[row]): if seating_chart[row][col] == seating_chart[row + r_adj][col + c_adj]: calc_prob[row][col] += prob_matrix[1 + r_adj][1 + c_adj] return calc_prob
def ispowerof2(num): """ Is this number a power of 2?""" # see http://code.activestate.com/recipes/577514-chek-if-a-number-is-a-power-of-two/ return (num & (num-1) == 0)
def _plus(left: str, right: str) -> str: """Convenience function Takes two string representations of regular expressions, where the empty string is considered as matching the empty langage, and returns a string representation of their sum. """ if len(left) > 0 and len(right) > 0: return left + '+' + right if len(left) > 0: return left return right
def normalize(value): """ Simple method to always have the same kind of value """ if value and isinstance(value, bytes): value = value.decode('utf-8') return value
def _find_all_meta_group_vars(ncvars, meta_group_name): """ Return a list of all variables which are in a given meta_group. """ return [k for k, v in ncvars.items() if 'meta_group' in v.ncattrs() and v.meta_group == meta_group_name]
def _retrieve_links(link_data): """Auxiliary function to collect data on links. Returns list of lists in the form of [linkname, link]. """ out = [] for l in link_data: try: out.append([l['@ref'], l.get('@href')]) except KeyError: continue return out or None
def _remove_titles(text, ignore): """ Old Implementation This function just removes wrappers tags in the beginning of the XML text. Parameters: text - The XML text as string. ignore - List of tag to remove (ignore). This list has to be of only wrappers tags and in the order they appear in the XML text. It can be list, tuple or string (if only removing one tag). Returns: (String) The XML text without the wrappers tags. """ # This is not a completely correct implementation, but it is not very useful # function either if not isinstance (ignore, list) and not isinstance (ignore, tuple): ignore = [ignore] for x in ignore: text = text.strip() if text.startswith("<" + x): text = text[text.find(">")+1:] i = text.rfind("</" + x + ">") if i != -1: text = text[:i] return text
def spherical_index_k(degree: int, order: int = 0) -> int: """returns the mode `k` from the degree `degree` and order `order` Args: degree (int): Degree of the spherical harmonics order (int): Order of the spherical harmonics Raises: ValueError: if `order < -degree` or `order > degree` Returns: int: a combined index k """ if not -degree <= order <= degree: raise ValueError("order must lie between -degree and degree") return degree * (degree + 1) + order
def format_text(text): """Formata o texto relativo ao nome das promotorias. Arguments: text {string} -- Texto a ser formatado. Returns: string -- Texto formatado. """ return ' '.join( [ t.capitalize() if len(t) > 3 or t == "rio" else t for t in text.lower().split() ] )