content
stringlengths
42
6.51k
def posting_lists_union(pl1, pl2): """ Returns a new posting list resulting from the union of the two lists passed as arguments. """ pl1 = sorted(list(pl1)) pl2 = sorted(list(pl2)) union = [] i = 0 j = 0 while (i < len(pl1) and j < len(pl2)): if (pl1[i] == pl2[j]): union.append(pl1[i]) i += 1 j += 1 elif (pl1[i] < pl2[j]): union.append(pl1[i]) i += 1 else: union.append(pl2[j]) j += 1 for k in range(i, len(pl1)): union.append(pl1[k]) for k in range(j, len(pl2)): union.append(pl2[k]) return union
def as_string(my_val, error_msg=False): """Helper function for returning a single value from MySQL. Convert from [(my_val,)] to string. """ if not my_val or not my_val[0][0]: return error_msg else: return str(my_val[0][0])
def difficult_n_terminal_residue(amino_acids): """ Is the N-terminus one of {Gln, Glu, Cys}? --- Priority I: avoid N-terminal Gln, Glu, Cys """ return amino_acids[0] in {"Q", "E", "C"}
def clipboard_to_url(clipboard_txt): """ Returns url if the clipboard text starts with http otherwise, returns None """ if clipboard_txt.startswith('http'): return clipboard_txt else: print('Clipboard content is not a url:') print(f'{clipboard_txt}') return None
def validate_query_date(datestr): # noqa """Validates a user provided date that can be compared using date_key(). Returns True id the date is valid. """ parts = datestr.split("-") if len(parts) > 3: return False if len(parts) > 2: try: v = int(parts[2]) except ValueError: return False else: if not 1 <= v <= 31: return False if len(parts) > 1: try: v = int(parts[1]) except ValueError: return False else: if not 1 <= v <= 12: return False try: int(parts[0]) except ValueError: return False return True
def luhn_checksum(card_number): """ Compute the Luhn checksum algorithm on all digits of the card number, and return whether or not the card number is constructed correctly. :param card_number: 16-digit card number to verify :return: True or False """ def digits_of(n): return [int(d) for d in str(n)] digits = digits_of(card_number) odd_digits = digits[-1::-2] even_digits = digits[-2::-2] checksum = 0 checksum += sum(odd_digits) for d in even_digits: checksum += sum(digits_of(d*2)) return checksum % 10
def is_ipv4(addr): """return true if addr looks like an ipv4 address, false otherwise""" if addr == '0/0' or '.' in addr: return True else: return False
def _linear_interpolation(l_v, r_v, slope): """linear interpolation between l_v and r_v with a slope""" return l_v + slope * (r_v - l_v)
def wrap_fn(fn, ids, i, j, **kwargs): """ A wrapper for the QCA batch downloader """ # out_str = kwargs["out_str"] # kwargs.pop("out_str") # prestr = "\r{:20s} {:4d} {:4d} ".format(out_str, i, j) # elapsed = datetime.now() objs = [obj for obj in fn(ids, **kwargs)] # objs = [obj for obj in fn(ids, **kwargs)] # elapsed = str(datetime.now() - elapsed) # N = len(objs) # poststr = "... Received {:6d} | elapsed: {:s}".format(N, elapsed) # out_str = prestr + poststr return objs
def deleteSymbol(command, mySymbols): """ Check if command is to delete stock symbol (d | delete [SYM/#]). """ expression = command.strip().lower() words = expression.split() return (len(mySymbols) > 0 and ("d " in expression or "delete " in expression) and (words[0] == "d" or words[0] == "delete") and len(words) == 2)
def convert_to_int(s) -> int: """ Converts a string to int Args: s (str): a string containg numbers and periods Returns: int: """ allowed_chars = "0123456789." num = s.strip() try: temp = int(num) return temp except: res = "".join([i for i in num if i in allowed_chars]) return int(float(res)) if res != "" else 0
def _get_period(member): """Get period for which an artist is/was part of a group, orchestra or choir. Args: member (Dict): Dictionary containing the artist information. Returns: Tuple containing the begin and end year during which an artist was part of a group. """ begin_date = member.get('begin-year', '') end_date = member.get('end-year', '') if not (begin_date or end_date): return None return str(begin_date), str(end_date)
def to_bytes(strlike, encoding="latin-1", errors="backslashreplace"): """Turns a str into bytes (Python 3) or a unicode to a str (Python 2)""" if strlike is None: return if not isinstance(strlike, bytes): return strlike.encode(encoding, errors) return strlike
def get_id_list(dict_list): """returns a list of all IDs of the items in a list of dictionaries :param dict_list: a list of entities in form of dictionaries :return: a list of all the entities id's """ values_array = [] items_array = dict_list.get('value') for x in items_array: values_array.append(x.get('@iot.id')) return values_array
def parse_postgre_sql_connection_string_as_string(connection_string): """Parse a PostgreSQL connection string to a dictionary in accordance with http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING""" fields = {} while True: connection_string = connection_string.strip() if not connection_string: break if "=" not in connection_string: raise ValueError("Expect key=value format in connection string fragment {!r}".format(connection_string)) key, rem = connection_string.split("=", 1) if rem.startswith("'"): as_is, value = False, "" for i in range(1, len(rem)): if as_is: value += rem[i] as_is = False elif rem[i] == "'": break elif rem[i] == "\\": as_is = True else: value += rem[i] else: raise ValueError("Invalid connection string fragment {!r}".format(rem)) connection_string = rem[i + 1:] else: res = rem.split(None, 1) if len(res) > 1: value, connection_string = res else: value, connection_string = rem, "" fields[key] = value return fields
def clean_input(text): """ Text sanitization function :param text: User input text :return: Sanitized text, without non ascii characters """ # To keep things simple at the start, let's only keep ASCII characters return str(text.encode().decode("ascii", errors="ignore"))
def build_sub_housenumber(hausnrzahl3, hausnrbuchstabe3, hausnrverbindung2, hausnrzahl4, hausnrbuchstabe4, hausnrverbindung3): """This function takes all the different single parts of the input file that belong to the sub address and combines them into one single string""" hausnr3 = hausnrzahl3 hausnr4 = hausnrzahl4 compiledHausNr = "" if hausnrbuchstabe3 != "": hausnr3 += hausnrbuchstabe3 if hausnrbuchstabe4 != "": hausnr4 += hausnrbuchstabe4 # ignore hausnrverbindung2 if hausnrverbindung3 in ["", "-", "/"]: compiledHausNr = hausnr3 + hausnrverbindung3 + hausnr4 else: compiledHausNr = hausnr3 +" "+ hausnrverbindung3 +" "+ hausnr4 return compiledHausNr
def _bit_length(num): """Return number of bits needed to encode given number.""" return len(bin(num).lstrip('-0b'))
def f_rosenbrock(x): """ Define the benchmark Rosenbrock function. :param numpy.ndarray x: The function's argument array. :return: The evaluated function at the given input array. :rtype: float """ dim = len(x) f = 0.0 for i in range(dim-1): left_term = 100. * (x[i + 1] - x[i] * x[i]) * (x[i + 1] - x[i] * x[i]) right_term = (1. - x[i]) * (1. - x[i]) f += left_term + right_term return f
def get_char(data, index): """Return one byte from data as a signed char""" result = data[index] if result > 127: result -= 256 return result
def isInt(n_o): """parseInt polyfill""" try: return int(n_o) except ValueError: return False
def get_pubs(db): """ returns all the publication details """ try: return (db.child("TagRecords").get()).val() except Exception as e: return False
def is_float(value): """Determines whether or not the provided value is a float or not.""" try: float(value) return True except: return False
def _Repeat(func, times): """Returns the result of running func() n times.""" return [func() for _ in range(times)]
def get_index_from_tensor_name(tensor_name): """ Get the index of the tensor of a certain op. Args: tensor_name (str): The tensor name Returns: int: The index of the tensor """ return int(tensor_name.split(':')[1])
def iterative_replace_line (input_line: str, case: str, source: dict, add_line: str) -> str: """ Iterative replacer. Iteratively copy-pastes `input_line` each time with a new substitution of a templated variable depending on the `case`. Parameters: input_line (str) : input line case (str) : single trigger case (templated variable to be replaced) source (dict) : dictionary of variables with substitution details add_line (str) : special line to be added (e.g. for error handling) Returns: output_block (str) : processed (replaced) block of text """ output_block = "" for item in source.keys(): templine1 = input_line.replace(case.upper(), item.upper()) templine2 = templine1.replace(case, item) if add_line != None: templine2 += add_line output_block += templine2 return output_block
def format_field(val: int, show: bool) -> str: """ Format a field """ return f'{val:>8}' if show else ""
def parse_suppress_errors(params): """Returns a list with suppressed error codes.""" val = params.get('suppressErrors', None) if not val: return [] return val.split('|')
def null_terminated(string): """Extract the NULL-terminated C string from the given array of bytes.""" return string.split(b'\0', 1)[0].decode()
def _is_float(value): """ Check whether a value is a float or not. """ try: value = float(value) return True except (TypeError, ValueError): return False
def three_shouts(word1, word2, word3): """Returns a tuple of strings concatenated with '!!!'.""" # Define inner def inner(word): """Returns a string concatenated with '!!!'.""" return word + '!!!' # Return a tuple of strings return (inner(word1), inner(word2), inner(word3))
def is_interactive_shell_example_line( func_start_index: int, py_module_str: str) -> bool: """ Get a boolean value of whether the target function is docstring of interactive shell string (e.g., `>>> def sample():`). Parameters ---------- func_start_index : int The index of the string at the start of the function. py_module_str : str String of target module. Returns ------- result_bool : bool If the target function is a interactive shell docstring string, True will be set. """ pre_str: str = py_module_str[func_start_index - 20:func_start_index] pre_str = pre_str.split('\n')[-1] is_in: bool = '>>> ' in pre_str if is_in: return True is_in = '... ' in pre_str if is_in: return True return False
def getzeros(num): """get leading zeros for a number string `num`. return a tuple `(leadingzeros, otherdigits)` """ leadingzeros = '' otherdigits = '' for i in range(len(num)): if num[i] != '0': otherdigits = num[i:] break leadingzeros += num[i] return leadingzeros, otherdigits
def fix_actress_name(name): """Returns the updated name for any actress based on our replacement scheme""" """ if you want to ad any additional ways to fix names, simply add another elif line below elif name == 'name returned from javlibrary' return 'different name' """ if name == 'Kitagawa Eria': return 'Kitagawa Erika' elif name == 'Oshikawa Yuuri': return 'Oshikawa Yuri' elif name == 'Shion Utsonomiya': return 'Anzai Rara' elif name == 'Rion': return "Rara Anzai" return name
def shorten(uri): """Makes a given uri a 10-character string""" return '{}...{}'.format(uri[:5], uri[-2:])
def num_pattern(i: int) -> str: """ Tries to make an unique pattern that will not generate collisions """ return f"_.:{i}:._([{i}])_!?{i}?!_"
def remove_falseneg(negatives, positives): """this method removes any negative fasta sequences that contain one of the positive sample sequences (essentially making them false negatives.""" seqs = [] for n in negatives: if not any(p in n for p in positives): seqs.append(n) return seqs
def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: O(n) Space Complexity: O(n) """ if num == 0: raise(ValueError) if num == 1: return "1" if num == 2: return "1 1" answer = [None, 1, 1] i = 3 while i in range(3, (num + 1)): p = answer[answer[i - 1]] + answer[i - answer[i - 1]] answer.append(p) i += 1 almost = answer[1:] final_answer = " ".join(str(n) for n in almost) return final_answer
def get_shift_bit(char, var): """Returns the var argument if char is '1', otherwise (bvnot var). Args: char: A string, either '0' or '1' var: A string, representing a variable we've defined in the smt2 file. Returns: The value or its inversion. """ if char == "0": return f"(bvnot {var})" elif char == "1": return var else: raise ValueError("Bit string contained value that wasn't 0 or 1")
def jaccard(a, b): """ Calculate Jaccard similarity. :param a: sentence1, list of segmented words :param b: sentence2 :return: similar score """ a = set(a) b = set(b) c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c))
def make_error_string(msg, args_str): """ - msg: string, an error message - args_str: string, original arguments RETURN: string, an error message """ return ("\n---\nERROR\n" + msg + f"\nin call to `add_schema_table({args_str})`\n---\n")
def confusion_matrix(rater_a, rater_b, min_rating=None, max_rating=None): """ Returns the confusion matrix between rater's ratings """ assert len(rater_a) == len(rater_b) if min_rating is None: min_rating = min(rater_a + rater_b) if max_rating is None: max_rating = max(rater_a + rater_b) num_ratings = int(max_rating - min_rating + 1) conf_mat = [[0 for i in range(num_ratings)] for j in range(num_ratings)] for a, b in zip(rater_a, rater_b): conf_mat[a - min_rating][b - min_rating] += 1 return conf_mat
def _get_type_name(klass): """ _get_type_name(KeyError) -> 'exceptions.KeyError' """ return klass.__module__ + '.' + klass.__name__
def rgb2rgba(rgb, max_val=1): """Convert color code from ``rgb`` to ``rgba``""" return (*rgb, 1)
def valid(parentheses): """ Validates if a string of only parenthetical characters (aka those in the set of {'(', ')', '[', ']', '{', '}'}) is in a valid order. Parameters: parentheses: str Return: int: 0 means False, and 1 means True """ # early exits: if there's an odd number of characters if len(parentheses) % 2 > 0: # O(n) return 0 # the string must be invalid # convert the string to a list parentheses = list(parentheses) # map each closing parentheses to the appropiate opening closing_opening = {")": "(", "]": "[", "}": "{"} # O(1) # iterate over the input index = 0 # precondition for while loop is that the string has even number of characters # best case: n/2, if the parentheses not enclosed, # worst is n, when they are all enclosed, e.g. ((((((((((())))))))))) while index < len(parentheses): # n iterations symbol = parentheses[index] # if it's a closing parentheses if symbol in closing_opening: # check that the opener is there, and in the right spot if index > 0 and parentheses[index - 1] == closing_opening[symbol]: # then delete both parentheses parentheses.pop(index) parentheses.pop(index - 1) # O( 2 * n/2 * n) # move on to the next iteration break # if the opening is not there, invalidate the string else: return 0 # otherwise if we see an opening parentheses, just iterate else: index += 1 # validate the string return 1
def get_date(*args, debug=0): """ Example: import cmglam as cm year, doy = cm.get_date(year, month, day) or year, month, day = cm.get_date(year, doy) """ # def help(): # print(""" # Example: # import cmglam as cm # year, doy = cm.get_date(year, month, day) # or # year, month, day = cm.get_date(year, doy)) # """) import datetime if len(args) == 2: y = int(args[0]) #int(sys.argv[1]) d = int(args[1]) #int(sys.argv[2]) yp1 = datetime.datetime(y+1, 1, 1) y_last_day = yp1 - datetime.timedelta(days=1) if d <= y_last_day.timetuple().tm_yday: date = datetime.datetime(y, 1, 1) + datetime.timedelta(days=d-1) return date.month, date.day else: print("error") print("Michael says, \"There aren't {} days in {}. Git good.\"".format(d, y)) # help() elif len(args) == 3: y, m, d = args date = datetime.datetime(y, m, d) doy = int(date.timetuple().tm_yday) # print("doy = {}".format(date.timetuple().tm_yday)) return str(y), str(doy).zfill(3) else: print("error: incorrect number of args") # help()
def choices_zip(choices): """ Creates a container compatible with Django's modelField.choices when both the databa :param choices: An iterable of the choices for the modelField :return: An iterable of two-item tuples, both items identical """ return [(c, c) for c in choices]
def set_xpath( data_base) -> dict: """ Sets the xpath based on which data base the user wants to search. :param data_base: The data base to search. :return: the xpath (search parameters in dict form) and db. (a magic string that tells the browser what database to search) """ if data_base == "Vulnerability Database": db = 'v' xpath = {'name': "//div/section/article/h4[@class='clearfix']/a/text()[1]", 'link': "//div/section/article/h4[@class='clearfix']/a/@href[1]", 'severity': "//*[@id='torso']/div/section/article[@class='vbResultItem']/ul[1]/li[1]/text()", 'type': '//*[@id="torso"]/div/section/article/h4/span/text()', 'summary': '//*[@id="torso"]/div/section/article/p[1]/text()', 'published': "//*[@id='torso']/div/section/article/ul[1]/li[2]/text()[1]"} elif data_base == "Metasploit Modules": db = 'm' xpath = {'name': '//*[@id="torso"]/div/section/div/h4/a/text()[1]', 'link': '//*[@id="torso"]/div/section/div/h4/a/@href[1]', 'module': '//*[@id="torso"]/div/section/div/h4/a/@href[1]', 'type': '//*[@id="torso"]/div/section/div/h4/span/text()', 'summary': '//*[@id="torso"]/div/section/div/p[2]/text()', 'published': '//*[@id="torso"]/div/section/div/p[1]/text()'} else: db = 'a' xpath = {'name': '//h4[@class]/a/text()', 'severity': "//*[@id='torso']/div/section/article[@class='vbResultItem']/ul[1]/li[1]/text()", 'type': '//*[@id="torso"]/div/section/article/h4/span/text()', 'summary': '//*[@id="torso"]/div/section/article/p/text()', 'published': "//*[@id='torso']/div/section/article/ul/li[2]/text()"} return {'xpath': xpath, 'db': db}
def isSymbolNumber(command, sortedSymbols): """ isSymbolNumber checks whether given command has Stock Symbol number and it is in the loaded Stock Symbols. """ return ((len(command.strip()) > 0) and command.strip().isdigit() and int(command.strip()) < len(sortedSymbols))
def tour_from_path(path): """Append the first city in a path to the end in order to obtain a tour""" path.append(path[0]) return path
def total_hazard_perceived_by_town(hazards: list, town_id: int, facilities: list) -> int: """ For the specified town retrieve the total risk caused by opened facility :param hazards: list of list, describe every hazard for the couple (town,facility) :param town_id: the town of interest :param facilities: list of the facility :return: the amount of risk perceived by the specified town """ hazard = hazards[town_id] tot_hazard = 0 for facility in facilities: if facility.is_open: tot_hazard += hazard[facility.facility_id] return tot_hazard
def get_stylesheets_for_decorator(decorator: dict, count: int) -> list: """ Gets stylesheets for a decorator. Args: decorator (dict): Decorator config object. count (int): Current page count. Returns: list: List of CSS documents that apply to current usage of decorator. """ stylesheets = [decorator['css']] if 'evenCss' in decorator and count % 2 == 0: stylesheets.append(decorator['evenCss']) elif 'oddCss' in decorator and count % 2 != 0: stylesheets.append(decorator['oddCss']) return stylesheets
def clamp(x, low, high): """ Ensures that x is between the limits set by low and high. For example, * clamp(5, 10, 15) is 10. * clamp(15, 5, 10) is 10. * clamp(20, 15, 25) is 20. @param x: the value to clamp. @param low: the minimum value allowed. @param high: the maximum value allowed. @returns: the clamped value """ return min(max(x, low), high)
def intersect_ranges(range_1, range_2): """If > 0: ranges intersect.""" range_1 = range_1 if range_1[1] > range_1[0] else range_1[::-1] range_2 = range_2 if range_2[1] > range_2[0] else range_2[::-1] return min(range_1[1], range_2[1]) - max(range_1[0], range_2[0])
def prettyprint_error(data: dict) -> str: """ Print generic errors returned from the API. """ error = 'Could not execute command\n' if 'message' in data: if type(data['message']) == list: error += ', '.join(data['message']) elif type(data['message']) == str: error += data['message'] else: error += 'Unknown error' return '\n\033[91m%s\033[0m\n\n' % error
def xobj_getattr(obj, attrName, *args): """ Return the value for the attr given following any .attrs """ checkExists = len(args) > 0 value = obj attrs = attrName.split('.') for attr in attrs: if not checkExists or hasattr(value, attr): value = getattr(value, attr) else: return args[0] return value
def stop_count_records(stream, summary=None, comp_id="stop_count_records"): """Only count the records from the incoming stream.""" rec_counter = 0 for rec in stream: rec_counter += 1 if summary is not None: summary[comp_id] = rec_counter return rec_counter
def b_distance_function(x): """Returns the function :math:`f(x)= \frac{1}{1+x}`. The function is used to transform the distance between two countries to a measure between zero and one that is used to regulate the probability of meeting an individual from a certain country. Parameters ---------- x : float Distance between two countries. Returns ------- float Function value evaluated at :math:`x` """ return 1 / (1 + x)
def _can_broadcast(shape1, shape2): """Whether two shapes can broadcast together using numpy rules""" for i, j in zip(reversed(shape1), reversed(shape2)): if i != j and i != 1 and j != 1: return False return True
def events_from_json(json_dict): """ simply accesses the events in a single json """ if not json_dict: return [] events = [] for group in json_dict: group_events = group["events"] events += group_events return events
def signum(x): """Return the sign of each entry of an array""" return (x < 0.) * -1. + (x >= 0) * 1.
def autocorrect(user_word, valid_words, diff_function, limit): """Returns the element of VALID_WORDS that has the smallest difference from USER_WORD. Instead returns USER_WORD if that difference is greater than or equal to LIMIT. """ # BEGIN PROBLEM 5 list_diff = [] list_words = [] for i in range(0, len(valid_words)): list_diff.append(diff_function(user_word, valid_words[i], limit)) for k in range(0, len(valid_words)): if diff_function(user_word, valid_words[k], limit) == min(tuple(list_diff)): list_words.append(valid_words[k]) if min(tuple(list_diff)) >= limit: return user_word elif user_word in valid_words: return user_word else: return list_words[0] # END PROBLEM 5
def calculate_opt_dt(a, D): """Calculates the optimal dt based on size of pore and diffusion coefficent returns a value for dt """ return (a*1e-3) / (6*D)
def translator(data): """This provides a function that hashes the flight times a second time with a per user hash.""" #also no hashing #issue: security return(data)
def _error_msg_routes(iface, option, expected): """ Build an appropriate error message from a given option and a list of expected values. """ msg = "Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]" return msg.format(iface, option, expected)
def round_to_step(x, parts=4): """ rounds to the step given, 4 is a quarter step, because 1.0 / 4 = 0.25. :param x: input value. :param parts: divisible by this many parts. :return: <float> to the rounded part. """ return round(x*parts)/parts
def get_atol(tol, atol, bnrm2, get_residual, routine_name): """ Parse arguments for absolute tolerance in termination condition. Parameters ---------- tol, atol : object The arguments passed into the solver routine by user. bnrm2 : float 2-norm of the rhs vector. get_residual : callable Callable ``get_residual()`` that returns the initial value of the residual. routine_name : str Name of the routine. """ if atol is None: atol = 'legacy' tol = float(tol) if atol == 'legacy': resid = get_residual() if resid <= tol: return 'exit' if bnrm2 == 0: return tol else: return tol * float(bnrm2) else: return max(float(atol), tol * float(bnrm2))
def linearstep(edge0: float, edge1: float, x: float) -> float: """A linear transition function. Returns a value that linearly moves from 0 to 1 as we go between edges. Values outside of the range return 0 or 1. """ return max(0.0, min(1.0, (x - edge0) / (edge1 - edge0)))
def ngrams_you_are(data): """Extract special features from data corresponding to "you are" experssion. Args: data: list of text samples Returns: list of special expressions """ g = [x.lower() .replace("you are", " SSS ") .replace("you're", " SSS ") .replace(" ur ", " SSS ") .replace(" u ", " SSS ") .replace(" you ", " SSS ") .replace(" yours ", " SSS ") .replace(" u r ", " SSS ") .replace(" are you ", " SSS ") .replace(" urs ", " SSS ") .replace(" r u ", " SSS ").split("SSS")[1:] for x in data] f = [] for x in g: fts = " " for y in x: w = y.strip().replace("?",".").split(".") fts = fts + " " + w[0] f.append(fts) return f
def is_dataclass_type(cls: type) -> bool: """Like dataclasses.is_dataclass(), but works correctly for a non-dataclass subclass of a dataclass.""" try: return "__dataclass_fields__" in cls.__dict__ except Exception: return False
def get_watershed_subbasin_from_folder(folder_name): """ Get's the watershed & subbasin name from folder """ input_folder_split = folder_name.split("-") watershed = input_folder_split[0].lower() subbasin = input_folder_split[1].lower() return watershed, subbasin
def set_output_path(folder, protocol, fprefix, particip, output_file, sess): """ Define pathway of output files """ output_path = folder + '/' + protocol + '/' + fprefix + '-' + \ '%02d' % particip + '/' + output_file + '_' + protocol + \ '_' + fprefix + '-' + '%02d' % particip + '_' + 'run' + \ str(sess) + '.tsv' return output_path
def point_to_geojson(lat, lng): """ Converts a single x-y point to a GeoJSON dictionary object of coordinates :param lat: latitude of point :param lng: longitude of point :return: dictionary appropriate for conversion to JSON """ feature = { 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': [lat, lng] } } return feature
def dict_find(in_dict, value): """ Helper function for looking up directory keys by their values. This isn't robust to repeated values Parameters ---------- in_dict : dictionary A dictionary containing `value` value : any type What we wish to find in the dictionary Returns ------- key: basestring The key at which the value can be found Examples -------- >>> dict_find({'Key1': 'A', 'Key2': 'B'}, 'B') 'Key2' """ # Todo: make this robust to repeated values # Todo: make this robust to missing values return list(in_dict.keys())[list(in_dict.values()).index(value)]
def check_rows(board: list) -> bool: """ Checks if ther are no duplicates in each row of the board. >>> check_rows(['**12', '1234', '2231']) False >>> check_rows(['**12', '1234', '2431']) True """ for row in range(len(board)): row_nums = set() for elem in board[row]: try: if isinstance(int(elem), int): if int(elem) in row_nums: return False else: row_nums.add(int(elem)) except ValueError: pass return True
def sort_score_by_event_times(score): """Sorts events by start time and returns new score""" return list(map( lambda index: score[index], sorted( list(range(len(score))), key=lambda indx: score[indx][0]) ))
def _private_call(method, args, prefix='_'): """Determine if a call's first argument is a private variable name.""" if method.__name__ in ('__getattribute__', '__setattr__'): assert isinstance(args[0], str) return args[0].startswith(prefix) else: return False
def encode_letters(name): """ Encode the letters in a string.""" # Character codes. codes = [] codes.append("aeiouy") # Vowels map to 0. codes.append("bfpv") # 1 codes.append("cgjkqsxz") # 2 codes.append("dt") # 3 codes.append("l") # 4 codes.append("mn") # 5 codes.append("r") # 6 # Encode the letters. result = "" for ch in name: for i in range(len(codes)): if ch in codes[i]: result += f"{i}" break return result
def add(a, b): """ Function to add two values """ c = a + b return c
def parse_float(value): """ Convert string to amount (float) :param value: string value :return: float value if the parameter can be converted to float, otherwise None """ try: return float(value) except (ValueError, TypeError): return None
def joinStrs(strlist): """Join a list of strings into a single string (in order).""" return ''.join(strlist)
def _format_page_object_string(page_objects): """Format page object string to store in test case.""" po_string = '' for page in page_objects: po_string = po_string + " '" + page + "',\n" + " " * 8 po_string = "[{}]".format(po_string.strip()[:-1]) return po_string
def generate_changelog(releases): """Generates a changelog from GitHub release notes""" changelog = "" for release in releases: changelog += "\n## [{tag}]({url}) - {date}\n{body}\n".format( tag=release['tag_name'], url=release['html_url'], date=release['published_at'].split('T')[0], body=release['body'].replace('\r\n', '\n').replace('##', '###') ) return changelog
def q_matrix(q): """return the rotation matrix based on q""" m = [0.0]*16 m[0*4+0] = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2]) m[0*4+1] = 2.0 * (q[0] * q[1] - q[2] * q[3]) m[0*4+2] = 2.0 * (q[2] * q[0] + q[1] * q[3]) m[0*4+3] = 0.0 m[1*4+0] = 2.0 * (q[0] * q[1] + q[2] * q[3]) m[1*4+1] = 1.0 - 2.0 * (q[2] * q[2] + q[0] * q[0]) m[1*4+2] = 2.0 * (q[1] * q[2] - q[0] * q[3]) m[1*4+3] = 0.0 m[2*4+0] = 2.0 * (q[2] * q[0] - q[1] * q[3]) m[2*4+1] = 2.0 * (q[1] * q[2] + q[0] * q[3]) m[2*4+2] = 1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0]) m[2*4+3] = 0.0 m[3*4+0] = 0.0 m[3*4+1] = 0.0 m[3*4+2] = 0.0 m[3*4+3] = 1.0 return m
def is_stupid_mkr(name: str) -> bool: """ Stupid mkr Parameters ----------- name: str Name of user, maybe stupid mkr """ if name is None: return False return name.lower() == "mkr"
def format(value, format_spec=''): """Return value.__format__(format_spec) format_spec defaults to the empty string. See the Format Specification Mini-Language section of help('FORMATTING') for details.""" return value.__format__(format_spec)
def get_formatted_percentage(x, tot): """ Return a percentage to one decimal place (respecting ) """ return "{0:.1f}".format((float(x) / tot * 100)) if tot else '0'
def per_capita_TED(sum_12_mo): """Calculates final Peak Hour Excessive Delay number. Args: sum_12_mo, the integer sum of all TED values. Returns: A value for Peak Hour Excessive Delay per capita. """ print(sum_12_mo) pop_PDX = 1577456 return sum_12_mo / pop_PDX
def tabular2dict(tabular, keys): """ Utility function to turn tabular format CONLL data into a sequence of dictionaries. @param tabular: tabular input @param keys: a dictionary that maps field positions into feature names @rtype: C{list} of featuresets """ tokendicts = [] lines = tabular.splitlines() for line in lines: line = line.strip() line = line.split() if line: tokendict = {} for i in range(len(line)): key = keys[i] tokendict [key] = line[i] tokendicts.append(tokendict ) return tokendicts
def add_spaces(amount): """ should only work if more then 6 Players are there, to make sure the embed looks good(still looks shit on mobile). """ spaces = "\t|\n\t|\n\t|\n\t|\n\t|\n" i = 6 amount = int(amount) while i <= amount: spaces += "\t|\n" return spaces
def measure_prf(num_TP, num_FN, num_FP): """Compute P, R, and F from size of TP, FN, and FP [FMP, Section 4.5.1] Notebook: C4/C4S5_Evaluation.ipynb""" P = num_TP / (num_TP + num_FP) R = num_TP / (num_TP + num_FN) if (P + R) > 0: F = 2 * P * R / (P + R) else: F = 0 return P, R, F
def f(a, b): """ f @param a: @param b: @return: """ a += b return a
def walk_json(obj, *fields): """ for example a=[{"a": {"b": 2}}] walk_json_field_safe(a, 0, "a", "b") will get 2 walk_json_field_safe(a, 0, "not_exist") will get None """ try: for f in fields: obj = obj[f] return obj except: return None
def getNumberDecomposition(numberString): """Decomposes the number in its digits. Returns a list of strings [units, tens, hundreds, thousands]. """ number = int(numberString) decomposition = [numberString[len(numberString) - 1]] for i in range(1, 4): if (number >= pow(10, i)): decomposition.append(numberString[len(numberString) - (i + 1)]) return decomposition
def gtir(registers, opcodes): """gtir (greater-than immediate/register) sets register C to 1 if value A is greater than register B. Otherwise, register C is set to 0""" test_result = int(opcodes[1] > registers[opcodes[2]]) return test_result
def convert_seconds_to_video_time_string(seconds): """ Converting elapsed seconds from the beginning of a video to video time's string representation Arguments: seconds (int): Time for the beginning of a video. Examples: >>> convert_seconds_to_video_time_string(16) "00:16" >>> convert_seconds_to_video_time_string(210) "03:30" Returns: str: string representation of the video time """ minute = int((seconds / 60)) seconds = seconds % 60 return "%02d" % minute + ":" + "%02d" % seconds
def minimum(a,b): """ UNUSED: return the smallest value of a and b """ if(a < b): return a else: return b
def s(word, seq, suffix="s"): """Adds a suffix to ``word`` if some sequence has anything other than exactly one element. Parameters ---------- word : str The string to add the suffix to. seq : sequence The sequence to check the length of. suffix : str, optional. The suffix to add to ``word`` Returns ------- maybe_plural : str ``word`` with ``suffix`` added if ``len(seq) != 1``. """ if len(seq) == 1: return word return word + suffix
def uniqueValues(aDict): """ Write a Python function that returns a list of keys in aDict that map to integer values that are unique (i.e. values appear exactly once in aDict). The list of keys you return should be sorted in increasing order. (If aDict does not contain any unique values, you should return an empty list.) """ keep, already_seen = {}, set() for k, v in aDict.items(): if v in already_seen: if v in keep: # remove it, we have already see this del keep[v] else: # add it for now and store the key, keep track of what seen keep[v] = k already_seen.add(v) lista = list(keep.values()) return sorted(lista)
def lib_utils_oo_chomp_commit_offset(version): """Chomp any "+git.foo" commit offset string from the given `version` and return the modified version string. Ex: - chomp_commit_offset(None) => None - chomp_commit_offset(1337) => "1337" - chomp_commit_offset("v3.4.0.15+git.derp") => "v3.4.0.15" - chomp_commit_offset("v3.4.0.15") => "v3.4.0.15" - chomp_commit_offset("v1.3.0+52492b4") => "v1.3.0" """ if version is None: return version else: # Stringify, just in case it's a Number type. Split by '+' and # return the first split. No concerns about strings without a # '+', .split() returns an array of the original string. return str(version).split('+')[0]