content
stringlengths
42
6.51k
def get_dict_ordered_values_from_keys(d): """ Returns a list of dictionary values, ordered based on their keys :param d: dict, dictionary to construct list from :return: list<variant> """ return [d[key] for key in sorted(list(d.keys()))]
def same_module(cls1: type, cls2: type) -> bool: """Return if two classes come from the same module via the ``__module__`` attribute.""" return cls1.__module__.split(".")[0] == cls2.__module__.split(".")[0]
def docstring(func): """Split and strip function docstrings into a list of lines.""" try: lines = func.__doc__.strip().split("\n") return [line.strip() for line in lines] except AttributeError: return None
def measure_var_int(number): """ Returns the length of the bytearray returned by encode_var_int(). """ length = 0 shift = 1 while True: length += 1 number -= (number & 0x7F) if number == 0: break number -= shift number >>= 7 shift += 7 return length
def num_groups_2(payload): """This function returns the a list of 24 numbers representing the payload""" num_groups = [] read_count = 0 num = 0 for byte in payload: bit = 0 while bit < 8: bit_enabled = byte & 128 == 128 read_count += 1 bit += 1 ...
def generate_fizz_buzz_sequence(n_max): """Function to generate fizz buzz sequence """ output_list = [] for number in range(1, n_max + 1): if number % 15 == 0: output_list.append("fizzbuzz") elif number % 3 == 0: output_list.append("fizz") elif number % 5 ...
def num_alpha(n, N): """ Counts the number of alpha electrons in a Fock representation. Assumes that the orbitals are sorted by spin first. :param n: any positive integer :param N: number of bits/qubits used in representing the integer `n` :returns: an integer giving the number of alpha electro...
def GreedyMatching(edges, max_count: int): """Find matching greedily. Edges are picked sequentially from top of input. So, useful for greedy matching with weights as well.""" M = set() matched_nodes = set() for u, v in edges: if u not in matched_nodes and v not in matched_nodes: ...
def commaspace(member, memberList): """ Just like comma, but returns a comma+space """ if member is memberList[-1]: return '' else: return ', '
def comma_format(value): """Formats value with commas and returns new value.""" return f"{value:,}"
def deep_delete(target, value, parent): """Recursively search for then delete ``target`` from ``parent``. :param target: Target value to remove. :param value: Current value in a list or dict to compare against ``target`` and removed from ``parent`` given match. :param parent: Tracks the parent ...
def minimaldescriptives(inlist): """this function takes a clean list of data and returns the N, sum, mean and sum of squares. """ N = 0 sum = 0.0 SS = 0.0 for i in range(len(inlist)): N = N + 1 sum = sum + inlist[i] SS = SS + (inlist[i] ** 2) mean = sum / float(N) ...
def parse_authors(auth_str): """returns list of all author last names from a string with `last_name, first_initial and last_name, first_inital and etc` :param auth_str: string containing all author names as exported by EndNoteX9 default BibTex export :type auth_str: str :return: list of auth...
def _is_oldstyle_rt(tweet): """Determine whether ``tweet`` is an old-style retweet.""" return tweet['text'].startswith('RT @')
def _(value: bytearray) -> str: """Convert ``bytearray`` to ``str``""" return bytes(value).decode('utf-8')
def format_subject(subject: str) -> str: """ Escape CR and LF characters. """ return subject.replace('\n', '\\n').replace('\r', '\\r')
def _tag(s, tag): """Return string wrapped in a tag.""" return "<{0}>{1}</{0}>".format(tag, s)
def hex_reflect_x(x, y, z): """Reflects the given hex through the y-axis and returns the co-ordinates of the new hex""" return -x, -z, -y
def multi_match_query(query, fields, size=10, fuzziness=None): """Returns the body of the multi_match query in Elasticsearch with possibility of setting the fuzziness on it""" query = { "query": { "multi_match": { "query": query, "fields": fields ...
def factorial(n): """ Returns the factorial of a number """ if n == 0: return 1 else: return n * factorial(n-1) if x <= 0: return -x else: return x
def calc_metric(y_true, y_pred, num_flag=False): """ :param y_true: [(tuple), ...] :param y_pred: [(tuple), ...] :return: """ num_proposed = len(y_pred) num_gold = len(y_true) y_true_set = set(y_true) num_correct = 0 for item in y_pred: if item in y_true_set: ...
def charsToBin(chars): """ convert a sequence of chars to binary """ return chars.encode("utf-8", "backslashreplace")
def cp(i): """ Input: { } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ return {'return': 1, 'error': 'copying CK repositories is f...
def ticket_name(branch_name): """ Assume the naming convention <ticket_no><underscore><description> and return <ticket_no> Where: <underscore> -> "_" The delimiter is an <underscore> In case this is not respected it will return the token up to the first <underscore>, or everything if none...
def fsplit(text, delimiter, multi=False): """split text, but keep split character attached to first part """ if multi: data = text.split(delimiter) else: data = text.split(delimiter, 1) for idx, _ in enumerate(data[:-1]): data[idx] += delimiter.strip() return data
def _find_dependent_monitors(monitors, monitor_names): """ Used to find all the monitors that re dependent on those in the original monitor_names to the list. """ last_iteration_count = 0 while len(monitor_names) != last_iteration_count: # May need to loop through the list mutiple times ...
def parse_instruction(instruction): """Removes whitespace and commas from the instruction tokens""" tokens = filter( lambda x: len(x) > 0, [str(token).strip().replace(",", "") for token in str(instruction).split(" ")], ) return list(tokens)
def _detect_fully_listened_track(remaining_duration, end_of_track_buffer) -> bool: """Performs the detection logic for whether a track was fully listened through Args: remaining_duration: The remaining duration of the track in milliseconds end_of_track_buffer: T...
def compare(x, y): """ tries to fuzzy match process names """ if x.lower() == y.lower(): return True y = '.'.join(y.split('.')[:-1]) if x.lower() == y.lower(): return True return False
def horizontal_validation(board: list) -> bool: """ Return if the horiontal requerments are satisfied. """ board_set = set() board_lst = [] for line in board: board_set |= set(line) board_lst.append(list(line)) for elem in board_set: for line in board_lst: ...
def intersect_lines(line1, line2): """ https://stackoverflow.com/questions/3838329/how-can-i-check-if-two-segments-intersect/3838357#3838357 Thank you @ Martijn Pieters! """ max_f = 1.8e+300 if line2 is None: # Empty hitboxes return False X1, Y1 = line1[0] X2, Y2 = line1[1] ...
def padded(a_list, n, value=None): """ Return a copy of `a_list` with length `n`. """ a_list = list(a_list) padding_length = n - len(a_list) if padding_length <= 0: return a_list padding = [value] * padding_length return a_list + padding
def AddToCRC(b, crc): """ computes crc iteratively by returning updated crc input""" if b < 0: b += 256 for i in range(8): odd = ((b ^ crc) & 1) == 1 crc >>= 1 b >>= 1 if odd: crc ^= 0x8C # this means crc ^= 140 return crc
def _tag_matches_pattern(tag, pattern): """Returns true if MARC 'tag' matches a 'pattern'. 'pattern' is plain text, with % as wildcard Both parameters must be 3 characters long strings. For e.g. >> _tag_matches_pattern("909", "909") -> True >> _tag_matches_pattern("909", "9%9") -> True >>...
def bin2dec(x): """ Convert binary string to decimal number. For instance: '11' -> 3 """ return int(x, 2)
def isZero(x, atol): """Determine if a floating point number is equal to zero. Args: x (float): a number atol (float): absolute tolerance from zero Returns: (bool) true if the number is sufficiently close to zero """ return atol > x > -atol
def _no_tiebreak(winners): """ Given an iterable of `winners`, return None if there is a tie. """ if len(winners) == 1: return winners[0] else: return None
def is_interested_source_code_file(afile): """ If a file is the source code file that we are interested. """ tokens = afile.split(".") if len(tokens) > 1 and tokens[-1] in ("c", "cpp", "pl", "tmpl", "py", "s", "S"): # we care about C/C++/perl/template/python/assembly source code files ...
def powln(n, m): """Power of number in log space""" return sum([n] * m)
def extract_7z_singlefile(archive, compression, cmd, verbosity, interactive, outdir): """Extract a singlefile archive (eg. gzip or bzip2) with '7z e'. This makes sure a single file and no subdirectories are created, which would cause errors with patool repack.""" cmdlist = [cmd, 'e'] if not interact...
def _calculate_amount_of_steps(scope_len, horizon): """ Method return amount of iterations which must be done for multistep time series forecasting :param scope_len: time series forecasting length :param horizon: forecast horizon :return amount_of_steps: amount of steps to produce """ amoun...
def get_si(simpos): """ Get SI corresponding to the given SIM position. """ if ((simpos >= 82109) and (simpos <= 104839)): si = 'ACIS-I' elif ((simpos >= 70736) and (simpos <= 82108)): si = 'ACIS-S' elif ((simpos >= -86147) and (simpos <= -20000)): si = ' HRC-I' elif ...
def validate_transaction(spend_amounts, tokens_amounts): """ A transaction is considered valid here if the amounts of tokens in the source UTXOs are greater than or equal to the amounts to spend. :param spend_amounts: amounts to spend :param tokens_amounts: existing amounts to spend from :retur...
def find_missing(*args): """ If True then missing value is there """ for value in args: if value == None or value == '': return True else: return False
def remove(value, node): """ Remove first element that matches value in linked list :param value: value to look for :param node: value of head node, start of list :return: node: linked list head """ if node is not None and node.value == value: # skip over value to remove from list ...
def assure_tuple_or_list(obj): """Given an object, wrap into a tuple if not list or tuple """ if isinstance(obj, list) or isinstance(obj, tuple): return obj return (obj,)
def ip_key(ip): """ Return an IP address as a tuple of ints. This function is used to sort IP addresses properly. """ return tuple(int(part) for part in ip.split('.'))
def yes_no_conditions(node_conditions): """ :param node_conditions: :return: """ return set(node_conditions) == {"yes", "no"}
def split_interwiki(wikiurl): """ Split a interwiki name, into wikiname and pagename, e.g: 'MoinMoin:FrontPage' -> "MoinMoin", "FrontPage" 'FrontPage' -> "Self", "FrontPage" 'MoinMoin:Page with blanks' -> "MoinMoin", "Page with blanks" 'MoinMoin:' -> "MoinMoin", "" can also be used for: '...
def round_to_place(x, decimal_place=-1): """ >>> round_to_place(12345.6789, -3) # doctest: +ELLIPSIS 12000.0 >>> round_to_place(12345, -2) # doctest: +ELLIPSIS 12300 >>> round_to_place(12345.6789, 2) # doctest: +ELLIPSIS 12345.68 """ t = type(x) return t(round(float(x), decima...
def round_filters(filters, width_coefficient, divisor=8): """Round number of filters based on depth multiplier.""" filters *= width_coefficient new_filters = max(divisor, int(filters + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_filters < ...
def get_synapse_data(S,e,cpartners=set([]),screen=None,remove_partners = False): """ Formats the synapse data. Returns list synapse (syn) and neighbors (neigh) where cell names have been converted to cell indicies Parameters: ----------- S : dictionary Dictionary synapse data e : expr...
def get_book_number(book_name): """ Find appropriate book number for book name. This is used in situations where local bibles are used, or to determine if a translation supports a book (mostly the deuterocanon). :param book_name: The book to get the book number for """ book_numbers = { ...
def merge_policies_dict(non_report_only_policies_dict, report_only_policies_dict): """ Method to merge 2 Policies dictionaries to a single. :param non_report_only_policies_dict: A dictionary with all non REPORT-ONLY Policies ...
def bool_to_str(value): """Converts bool value to string.""" assert isinstance(value, bool) return "TRUE" if value is True else "FALSE"
def sum_ac21(n): """Write a fruitful function sumTo(n) that returns the sum of all integer numbers up to and including n. So sumTo(10) would be 1+2+3...+10 which would return the value 55. Use the equation (n * (n + 1)) / 2.""" #~ return sum(i for i in range(1, n+1)) return (n*(n+1))*0.5
def precision_conf(conf): """compute precision""" TN, FP, FN, TP = conf if (TP + FP) == 0: return float('nan') return TP / float(TP + FP)
def _try_divide(x, y, val=0.0): """try to divide two numbers""" if y != 0.0: val = float(x) / y return val
def parse_address(address): """ Take a Tor-formatted v4 or v6 IP address with a port, returns a cleaned-up version. :param str address: input address to be processed :returns: a tuple (address, port, guessed-type) where port is an integer and guessed-type is 4 or ...
def makeDigitString(string): """Gathers all digits and returns them in a continuous string (Helper for count909AreaCode)""" newString = '' for char in string: if char in '0123456789': newString += char return newString
def validate_command_string(input_str): """Validates that the command line includes the type of the geometry object""" val = input_str.split() if not val or (len(val[0]) > 1) or (not val[0].isalpha()): print('Wrong type format. Command must start with Type') return False return Tru...
def isValid(s): """ :type s: str :rtype: bool """ stack = [] dict = {')': '(', ']': '[', '}': '{'} for char in s: if char in dict.values(): stack.append(char) elif char in dict.keys(): if stack == [] or dict[char] != stack.pop(): return False else: return False return stack == []
def merge_trees(tree1, tree2): # """ """ if tree1 is None: return tree2 if tree2 is None: return tree1 tree1.value = tree1.value + tree2.value tree1.left = merge_trees(tree1.left, tree2.left) tree2.right = merge_trees(tree1.left, tree2.left) return tree1
def obj_checked(words, defaultset): """ Selecting the prechecked checkboxes for the objects. :rtype: list """ checked = [] stringed = [] for word in words: if word['name'].split()[-1] in defaultset: checked.append('checked') else: checked.append('') ...
def to_idx(item, mapper, unknown="@@@UNKNOWN@@@"): """ :param item: Object Object to be encoded :param mapper: dict Dictionary from item to idx :param unknown: int Index of unknown item. If None, use len(mapper) It returns ---------- idx : int Index of item """ if item in mapp...
def afis_succesori_cost(l): """ o functie folosita strict in afisari - poate fi modificata in functie de problema """ sir="" for (x, cost) in l: sir+="\nnod: "+str(x)+", cost arc:"+ str(cost) return sir
def modify_disks(data, state, facts, prefix='_'): """ Replace disk definitions by filename from facts """ if isinstance(data, list) and len(data) == len(facts): ret = [] for i, disk in enumerate(data): record = {} if isinstance(disk, dict): user...
def get_kaggle_path(kaggle_link): """ This functin grabs the path of the dataset from the kaggle url of the dataset ex. Link: https://www.kaggle.com/mikhailgaerlan/spongebob-squarepants-completed-transcripts Path: mikhailgaerlan/spongebob-squarepants-completed-transcripts @params: ...
def ent_to_plain(e): """ :param e: "@entityLeft_hand" :return: "Left hand" """ return " ".join(e[len("@entity"):].split("_"))
def with_suffix(form, suffix): """ Return a new form with ``suffix`` attached """ word, tag, normal_form, score, methods_stack = form return (word+suffix, tag, normal_form+suffix, score, methods_stack)
def get_repos(section): """TK""" repos = {} repo = {} for line in section: line = line.strip() if line.startswith('repo.url'): if repo.get('url'): repos[repo['url']] = repo url = line.split('=', 1)[1].strip() repo = {'url' : url} ...
def _nested_update(document, key, value): """ Method to update a key->value pair in a nested document. If the number of passed values is less than the number of key matches when scanning for updates, use last value as default. Args: document: Might be List of Dicts (or) Dict of Lists (or) ...
def convert_number_to_meter(unit: str, number: int) -> int: """ Converts input number into meter :param unit Unit of number :param number Integer to be converted """ # meters is default unit if unit == "m": return number # convert miles to meters if unit == "miles": ...
def matrixtodict(matrix): """ convert a word matrix(which is generated in getMatirx() method in ModelClass.py) to the one that is used in the test() method in this file. :param matrix: the count matrix generated by getMatrix method :return: a Result Array(each element is a dict) that test method ca...
def has_ghosts(string): """ Returns True if there is a ghost/auxiliary field in the interaction. """ for i in range(0, len(string)): if (string[i].endswith(".f") or string[i].endswith(".c") or string[i].endswith(".C") or string[i].endswith(".t")): return Tr...
def normalize_hex(hex_color): """Transform a xxx hex color to xxxxxx. """ hex_color = hex_color.replace('#', '').lower() length = len(hex_color) if length in (6, 8): return '#' + hex_color if length not in (3, 4): return None strhex = u'#%s%s%s' % ( hex_color[0] * 2, ...
def process_string(instring, year, month, day): """ Process a string replacing placeholder occurrences of YYYY with year, MMMM with month and DDDD with day. :param instring: string to be converted :param year: year to replace in input string :param month: month to replace in input string :param...
def _make_valid_param_dicts(arg_dict): """Unpack dictionary of lists of numbers into dictionary of numbers. Ex: turn {'a': [0, 1], 'b':[2, 3]} into [{'a': 0, 'b': 2}, {'a': 1, 'b': 3}] """ return [dict(zip(arg_dict, val)) for val in zip(*arg_dict.values())]
def is_total_slice(item, shape): """Determine whether `item` specifies a complete slice of array with the given `shape`. Used to optimize __setitem__ operations on the Chunk class.""" # N.B., assume shape is normalized if item == Ellipsis: return True if item == slice(None): re...
def find_metadata_end(raw_file): """Extract the metadata from the raw file.""" lines = raw_file.split("\n") start = None end = None for idx, line in enumerate(lines): if "---" in line and start is None: start = idx elif "---" in line and start is not None: re...
def get_weighted_loss(loss_coeff, all_loss): """ calculate the weighted loss """ output_loss = 0 for i in range(len(loss_coeff)): temp = loss_coeff[i]*all_loss[i] output_loss = output_loss + temp return output_loss
def poly_smooth(x: float, n: float = 3) -> float: """Polynomial easing of a variable in range [0, 1]. Args: x (float): variable to be smoothed n (float, optional): polynomial degree. Defaults to 3. Returns: float: _description_ """ if x > 1: return 1 if x < 0: ...
def get_variant_name(nm, prevs): """Create a name starting at nm, to avoid any of the prevs.""" if nm not in prevs: return nm i = 1 while True: if nm + str(i) not in prevs: return nm + str(i) i += 1
def perpend_to_line(p1, p2, p3): """Return the perpendicular line of a point to a line segment """ x1, y1 = p1 x2, y2 = p2 x3, y3 = p3 px = x2 - x1 py = y2 - y1 sqr = float(px * px + py * py) if sqr == 0: return x1, y1 u = ((x3 - x1) * px + (y3 - y1) * py) / sqr if u ...
def inv_luminance(lum: float) -> float: """Convert gamma-expanded (linear) value into gamma-compressed value.""" if lum < 0.0028218390804597704: return lum * 12.92 return lum ** (1 / 2.4) * 1.055 - 0.055
def small(text: str) -> str: """ Return the *text* surrounded by small HTML tags. >>> small("foo") '<small>foo</small>' """ return f"<small>{text}</small>"
def detect_robot_context(code, cursor_pos): """Return robot code context in cursor position.""" code = code[:cursor_pos] line = code.rsplit("\n")[-1] context_parts = code.rsplit("***", 2) if len(context_parts) != 3: return "__root__" else: context_name = context_parts[1].strip()....
def is_valid_int(value: str): """ Checks whether the input is an integeral value or not """ try: int(value) return True except: return False
def word_score(word): """ (str) -> int Return the point value the word earns. Word length: < 3: 0 points 3-6: 1 point per character for all characters in word 7-9: 2 points per character for all characters in word 10+: 3 points per character for all chara...
def jsonify(records): """ Parse database record response into JSON format """ return [dict(r.items()) for r in records]
def color2gray(x): """Convert an RGB or RGBA (Red Green Blue Alpha) color tuple to a grayscale value.""" if len(x) == 3: r, g, b = x a = 1 elif len(x) == 4: r, g, b, a = x else: raise ValueError("Incorrect tuple length") return (r * 0.299 + 0.587*g + 0.114*b) *...
def get_author(author): """Extract author of PR or comment from GitHub API response""" # handle deleted GitHub accounts if author is None: return 'ghost' return author['login']
def sort_files(file_collection): """ Return list of files sorted by date File names are sorted by name, which, if the pattern is suitable, will cause the file names to be sorted by creation date. Another option might be to sort on mtime followed by name as a tie-breaker. ctime is not an option bec...
def getMYOP(rawEMGSignal, threshold): """ The myopulse percentage rate (MYOP) is an average value of myopulse output. It is defined as one absolute value of the EMG signal exceed a pre-defined thershold value. :: MYOP = (1/N) * sum(|f(xi)|) for i = 1 --> N f(x) = { ...
def mk_opt_args(keys, kwargs): """ Make optional kwargs valid and optimized for each backend. :param keys: optional argument names :param kwargs: keyword arguements to process >>> mk_opt_args(("aaa", ), dict(aaa=1, bbb=2)) {'aaa': 1} >>> mk_opt_args(("aaa", ), dict(bbb=2)) {} """ ...
def spot_adjacent(spot1, spot2): """checks if 2 spots are adjacent returns True or False""" adjacentSpots = {1: [2, 5, 6], 2: [1, 3, 5, 6, 7], 3: [8, 2, 4, 6, 7], 4: [8, 3, 7], 5: [1, 2, 10, 6, 9], 6:...
def _get_switch_str(opt): """ Output just the '-r, --rev [VAL]' part of the option string. """ if opt[2] is None or opt[2] is True or opt[2] is False: default = "" else: default = "[VAL]" if opt[0]: # has a short and long option return "-%s, --%s %s" % (opt[0], op...
def non_strict_neq(a, b): """Disequality between non-strict values Arguments: - `a`: a value or None - `b`: a value of a type comparable to a or None """ if a == None or b == None: return None else: return a != b
def format_mapping(mapping): """ Given a str-str mapping, formats it as a string. """ return ", ".join( ["'%s'='%s'" % (k, v) for k, v in mapping.items()])
def _indent_genbank(information, indent): """Write out information with the specified indent (PRIVATE). Unlike _wrapped_genbank, this function makes no attempt to wrap lines -- it assumes that the information already has newlines in the appropriate places, and will add the specified indent to the start...