content
stringlengths
42
6.51k
def split_kwargs(original, anothers): """split a dict to 2 dicts. Args: original: original data. antohers: the elments will be put the other dict if its key in this tuple. Returns: (original, new) """ new = {} for key in anothers: try: new[key] = original.pop(key) except KeyError: pass return (original, new)
def get_tags_gff3(tagline): """Extract tags from given tagline""" tags = dict() for t in tagline.strip(';').split(';'): tt = t.split('=') tags[tt[0]] = tt[1] return tags
def patternToIndex(pattern): """ the index of the pattern in lexicographically ordered k-mers """ if len(pattern) == 1: if pattern == 'A': return 0 elif pattern =='C': return 1 elif pattern =='G': return 2 elif pattern =='T': return 3 lastChar = pattern[-1:] prefix = pattern[:-1] return 4 * patternToIndex(prefix) + patternToIndex(lastChar)
def addrstr(astr): """Parse string astr as a socket address. Return (addr, af) where af is a socket.AddressFamily and the type of addr depends on af (see documentation of the socket module). If astr contains a slash it is interpreted as the file name of a AF_UNIX socket. Otherwise the syntax is host:port for an AF_INET socket. """ from socket import AddressFamily as AF if "/" in astr: return astr, AF.AF_UNIX else: addr, ps = astr.split(":") return (addr, int(ps)), AF.AF_INET
def modify_eve_dict(eve_dict): """ Modify nested event dictionary to make it follow a more flattened approach so as to use full functionality of the run.py function `find_value(name, obj)`. The dictionaries of the format { "event_type":"http", "http":{ "hostname":"supportingfunctions.us.newsweaver.com", "http_port":443 } } will be converted to { "event_type":"http", "http.hostname":"supportingfunctions.us.newsweaver.com", "http.http_port":443 } """ modified = {} def flatten(x, name=''): """ Recursive function to flatten the nested dictionaries. """ if type(x) is dict: for val in x: flatten(x[val], name + val + '.') elif type(x) is list: i = 0 for val in x: name = name.rstrip('.') flatten(val, name + '[' + str(i) + ']' + '.') i += 1 else: if name[:-1] not in ["flow.start", "flow.end"]: modified[name[:-1]] = x flatten(eve_dict) return modified
def bit_invert(value, width=32): """! @brief Return the bitwise inverted value of the argument given a specified width. @param value Integer value to be inverted. @param width Bit width of both the input and output. If not supplied, this defaults to 32. @return Integer of the bitwise inversion of @a value. """ return ((1 << width) - 1) & (~value)
def get_ellipse_equation_coefficient_by_simplest_focus_add(x1, y1, x2, y2, add): """ [1/a^2, 0, 1/b^2, 0, 0, -1] """ if y1 == 0: a = add / 2 aa = a * a c = abs(x1) bb = aa - c ** 2 return [1 / aa, 0, 1 / bb, 0, 0, -1] b = add / 2 bb = b * b c = abs(y1) aa = bb - c ** 2 return [1 / aa, 0, 1 / bb, 0, 0, -1]
def palindrome_anagram(S): """Find an anagram of the string that is palindrome """ visited = set() for s in S: if s in visited: visited.remove(s) else: visited.add(s) return len(visited) <= 1
def filter_requirements(requirements: str) -> list: """Filter the requirements, exclude comments, empty strings Parameters: ----------- requirements: str, string of requirements Returns: -------- list list of filtered requirements """ list_requirements = requirements.split("\n") for entry in list_requirements: if "#" in entry or entry == "": list_requirements.remove(entry) return list_requirements
def __get_gnome_url(pkg_info): """ Get gnome repo url of package """ src_repos = pkg_info["src_repo"].split("/") if len(src_repos) == 1: url = "https://gitlab.gnome.org/GNOME/" + pkg_info["src_repo"] + ".git" else: url = "https://gitlab.gnome.org/" + pkg_info["src_repo"] + ".git" return url
def calculate_m_metric(flux_a: float, flux_b: float) -> float: """Calculate the m variability metric which is the modulation index between two fluxes. This is proportional to the fractional variability. See Section 5 of Mooley et al. (2016) for details, DOI: 10.3847/0004-637X/818/2/105. Args: flux_a (float): flux value "A". flux_b (float): flux value "B". Returns: float: the m metric for flux values "A" and "B". """ return 2 * ((flux_a - flux_b) / (flux_a + flux_b))
def is_same_sequence_sublist(child_list: list, parent_list: list) -> bool: """ Check if the parent list has a sublist which is identical to the child list including the sequence. Examples: - child_list = [1,2,3], parent_list=[5,1,2,3,9] -> ``True`` - child_list = [1,2,3], parent_list=[5,6,1,3,9] -> ``False`` Args: child_list (list): The child list (the pattern to search in the parent list). parent_list (list): The parent list. Returns: bool ``True`` if the sublist is in the parent list. """ if len(parent_list) < len(child_list): return False if any([item not in parent_list for item in child_list]): return False for index in range(len(parent_list) - len(child_list) + 1): if child_list == parent_list[index:index + len(child_list)]: return True return False
def entity_list(raw_entities_dict): """ Returns a list of tuples that preserves the qbbo_types and Id keys. (The input is what you get when you run quickbooks.transactions() or quickbooks.names()) Each item in list is a three-item tuple: (qbbo_type,Id,raw_entity_dict) """ e_list = [] for qbbo in raw_entities_dict: for Id in raw_entities_dict[qbbo]: raw_QBBO_dict = raw_entities_dict[qbbo][Id] e_list.append((qbbo, Id, raw_QBBO_dict)) return e_list
def username(email): """Keeps the username of an email address.""" return email and email.split('@', 1)[0]
def valid_cluster_header(ds, file): """ checks if colnames are comaptible with provided list :param ds: ds header name :param file: lsit of allowed header names :return: bool showing whether given colname is compatible with list """ return str(ds) in list(file)
def sgn(val): """Sign function. Returns -1 if val negative, 0 if zero, and 1 if positive. """ try: return val._sgn_() except AttributeError: if val == 0: return 0 if val > 0: return 1 else: return -1
def estimate_fee(estimated_size: int, fee_kb: int) -> int: """ Calculate fee based in the transaction size and the price per KiB. :param estimated_size: Estimated size for the transaction. :param fee_kb: Price of the transaction by KiB. :return: The estimated fee. """ return int(estimated_size * fee_kb / 1024.0 + 0.5)
def get_tool_name(header): """Gets the name of the tool that was used and that delivered the log.""" header = header.split(":") return header[1].strip(), ":".join(header[2:])
def none_of(pred, iterable): """ Returns ``True`` if ``pred`` returns ``False`` for all the elements in the ``iterable`` range or if the range is empty, and ``False`` otherwise. >>> none_of(lambda x: x % 2 == 0, [1, 3, 5, 7]) True :param pred: a predicate function to check a value from the iterable range :param iterable: an iterable range to check in :returns: ``True`` if all elements don't satfisfy ``pred`` """ return all((not pred(i) for i in iterable))
def get_last_index(dictionary: dict) -> int: """ Obtaining of the last index from the `dictionary`, functions returns `-1` if the `dict` is empty. """ indexes = list(dictionary) return indexes[-1] if indexes else -1
def is_google_registry_image(path: str) -> bool: """Returns true if the given Docker image path points to either the Google Container Registry or the Artifact Registry.""" host = path.partition('/')[0] return host == 'gcr.io' or host.endswith('docker.pkg.dev')
def make_diff_header(path, old_tag, new_tag, src_label=None, dst_label=None): """Generate the expected diff header for file PATH, with its old and new versions described in parentheses by OLD_TAG and NEW_TAG. SRC_LABEL and DST_LABEL are paths or urls that are added to the diff labels if we're diffing against the repository or diffing two arbitrary paths. Return the header as an array of newline-terminated strings.""" if src_label: src_label = src_label.replace('\\', '/') src_label = '\t(.../' + src_label + ')' else: src_label = '' if dst_label: dst_label = dst_label.replace('\\', '/') dst_label = '\t(.../' + dst_label + ')' else: dst_label = '' path_as_shown = path.replace('\\', '/') return [ "Index: " + path_as_shown + "\n", "===================================================================\n", "--- " + path_as_shown + src_label + "\t(" + old_tag + ")\n", "+++ " + path_as_shown + dst_label + "\t(" + new_tag + ")\n", ]
def genSubparts(string): """ Partition a string into all possible two parts, e.g. given "abcd", generate [("a", "bcd"), ("ab", "cd"), ("abc", "d")] For string of length 1, return empty list """ length = len(string) res = [] for i in range(1, length): res.append((string[0:i], string[i:])) return res
def _PerModeMini(x): """Takes Numeric Code and returns String API code Input Values: 1:"Totals", 2:"PerGame" Used in: """ measure = {1:"Totals",2:"PerGame"} try: return measure[x] except: raise ValueError("Please enter a number between 1 and "+str(len(measure)))
def binary_eval(op, left, right): """token_lst has length 3 and format: [left_arg, operator, right_arg] operator(left_arg, right_arg) is returned""" return op(left, right)
def get_custom_params_value(custom_params_list, key): """ :param List custom_params_list: :param str key: :rtype: str """ param = next(iter( filter(lambda x: x['name'] == key, custom_params_list)), None) if param: return param['value'] else: return None
def path_to_directions(l): """ as seen here: https://github.com/multinormal/ddsm/blob/master/ddsm-software/get_ddsm_groundtruth.m original documentation: http://marathon.csee.usf.edu/Mammography/DDSM/case_description.html#OVERLAYFILE rows and columns are swapped """ chain_code = {0: [-1, 0], 1: [-1, 1], 2: [0, 1], 3: [1, 1], 4: [1, 0], 5: [1, -1], 6: [0, -1], 7: [-1, -1]} return [chain_code[x] for x in l]
def soundex(name, len=4): """ Code referenced from http://code.activestate.com/recipes/52213-soundex-algorithm/ @author: Pradnya Kulkarni """ # digits holds the soundex values for the alphabet digits = "01230120022455012623010202" sndx = "" fc = "" # Translate alpha chars in name to soundex digits for c in name.upper(): if c.isalpha(): if not fc: # remember first letter fc = c d = digits[ord(c)-ord("A")] # duplicate consecutive soundex digits are skipped if not sndx or (d != sndx[-1]): sndx += d # replace first digit with first alpha character sndx = fc + sndx[1:] # remove all 0s from the soundex code sndx = sndx.replace("0", "") # return soundex code padded to len characters return (sndx + (len * "0"))[:len]
def to_internal_instsp(instsp): """Convert instantiation pair to assignments of internal variables.""" tyinst, inst = instsp tyinst2 = {"_" + nm: T for nm, T in tyinst.items()} inst2 = {"_" + nm: t for nm, t in inst.items()} return tyinst2, inst2
def dict2str(dictionary): """Helper function to easily compare lists of dicts whose values are strings.""" s = '' for k, v in dictionary.items(): s += str(v) return s
def is_valid_manifest(manifest_json, required_keys): """ Returns True if the manifest.json is a list of the form [{'k' : v}, ...], where each member dictionary contains an object_id key. Otherwise, returns False """ for record in manifest_json: record_keys = record.keys() if not set(required_keys).issubset(record_keys): return False return True
def convert_classes(raw_data, local_label_dict): """Convert the MC Land use classes to the specific things I'm interested in Args ---- raw_data (dict) : dictionary of raw data, returned from load_raw_data() local_label_dict (dict) : a dictionary that maps the datasets labels into the labels used by the model Returns ------- Similar dictionary but with labels of specific interest """ data = {} for label, images in raw_data.items(): local_label = local_label_dict[label] if label: data[local_label] = images return data
def multi_tmplt_1(x, y, z): """Tests Interfaces""" return x + y + z
def DeepSupervision(criterion, xs, y): """ Args: criterion: loss function xs: tuple of inputs y: ground truth """ loss = 0. for x in xs: loss += criterion(x, y) # loss /= len(xs) return loss
def max_nth_percent(n, data): """ A function that returns the nth percent top value, planned use is for plotting :param n: the percentile value desired for return :param data: the iterable object searched through :return: nth percent largest value """ import heapq data=list(data) n=float(n) return heapq.nlargest(int(len(data)*(n/100.0)), data)[-1]
def lennard_jones_potential(x): """ calculates the lennard-jones-potential of a given value x """ return 4 * ((x ** -12) - (x ** -6))
def find_migration_file_version(config, migrations, version, prior=False): """ Returns int (or None on failure) Finds the target migration version by its version string (not sortable version) in the list of migrations """ # find target ix = None for ix, m in enumerate(migrations): if m['version'] == version: return ix if prior: return ix return None
def add_params(value, arg): """ Used in connection with Django's add_preserved_filters Usage: - url|add_params:'foo=bar&yolo=no' - url|add_params:'foo=bar'|add_params:'motto=yolo' use only for admin view """ first = '?' if '?' in value: first = '&' return value + first + str(arg)
def have_mp3_extension(l): """Check if .mp3 extension is present""" if ".mp3" in str(l): return 1 else: return 0
def font_stretch(keyword): """Validation for the ``font-stretch`` property.""" return keyword in ( 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded')
def any_above(prices, threshold): """Determines if there are any prices above a threshold.""" for x in prices: if x > threshold: return True return False
def dice_counts(dice): """Make a dictionary of how many of each value are in the dice """ return {x: dice.count(x) for x in range(1, 7)}
def _getParameterRange(key): """ Returns fur's default parameter range as 2-tuple (min, max). key: fur attribute (string) """ if "Density" ==key: return (10000.0, 30000.0) ## geometry attributes (1) for single strand if "Length" ==key: return (1.00, 5.00) if "BaseWidth"==key: return (0.01, 0.10) if "TipWidth" ==key: return (0.00, 0.10) ## geometry attributes (2) for strand root distribution if "Inclination" ==key: return (0.0, 0.9) # 1.0 makes extrusion if "PolarNoise" ==key: return (0.0, 0.5) if "PolarNoiseFreq"==key: return (1.0, 20.0) if "BaseCurl"==key: return (0.5, 1.0) # [0.0:0.5] usually makes extrusion if "TipCurl" ==key: return (0.0, 1.0) ## geometry attributes (4) for noise in fields if "Scraggle" ==key: return (0.0, 0.5) if "ScraggleCorrelation"==key: return (0.0, 0.5) if "ScraggleFrequency" ==key: return (1.0, 10.0) ## geometry attributes (3) for clumping if "Clumping" ==key: return ( 0.0, 0.5) if "ClumpingFrequency"==key: return ( 1.0, 50.0) if "ClumpShape" ==key: return (+1.0, +5.0) ## color attributes: special if "SpecularSharpness" ==key: return (0.0, 100.0) # otherwise, all values should be [0.0:1.0] return (0.0, 1.0)
def get_content_values_by_name(content, name): """ :type content: dict :param content: A dictionary as returned by KairosDB with timestamps converted to seconds since the epoch :type name: str :param name: The name of the entry in the results whose values will be returned :rtype: list :return: a list of resulting [timestamp, value] pairs When you've got content, but only want to look at a piece of it, specifically the values that are provided for a particular name, then use this function. return the dict(s) whose name matches the argument "name" """ r_list = list() for q in content["queries"]: for r in q["results"]: if r["name"] == name: r_list.append(r) return r_list
def sort_spec(spec): """Helper to provide a key function for `sorted` Provide key to sort by type first and by whatever identifies a particular type of spec dict Parameters ---------- spec: dict study specification dictionary Returns ------- string """ if spec['type'] == 'dicomseries': return 'dicomseries' + spec['uid'] else: # ATM assuming everything else is identifiable by its location: return spec['type'] + spec['location']
def recall_at(targets, scores, k): """Calculation for recall at k.""" for target in targets: if target in scores[:k]: return 1.0 return 0.0
def generate_predefined_split(n=87, n_sessions=3): """Create a test_fold array for the PredefinedSplit function.""" test_fold = [] for s in range(n_sessions): test_fold.extend([s] * n) return test_fold
def assert_not_equal(other, obj, msg=None): """Fail if the two objects are equal as determined by the '==' operator. """ if obj == other: raise AssertionError(msg or '%r == %r' % (obj, other)) return obj
def decode_dict(source): """ docstring for """ if type(source) in [str, int, float, bool]: return source if type(source) == bytes: return source.decode() if type(source) in [list, set]: decode_list = [] for item in source: decode_list.append(decode_dict(item)) return decode_list target = {} for key, value in list(source.items()): key = decode_dict(key) value = decode_dict(value) target[key] = value return target
def reverse(graph): """Reverse the direction of edges in a graph.""" reverse_graph = [[] for _ in range(len(graph))] for node, children in enumerate(graph): for child in children: reverse_graph[child].append(node) return reverse_graph
def is_std_logic(value): """Returns whether the given value is the Python equivalent of an std_logic.""" return value is True or value is False
def has_at_least_one_models_key(lc_keys): """Check if there is at least one optional Models dict key in lowercase keys """ model_keys = {"paper", "code", "weights", "config", "readme", "metadata", "results", "incollection"} return len(model_keys.intersection(set(lc_keys))) >= 1
def erb_bandwidth(fc): """Bandwidth of an Equivalent Rectangular Bandwidth (ERB). Parameters ---------- fc : ndarray Center frequency, or center frequencies, of the filter. Returns ------- ndarray or float Equivalent rectangular bandwidth of the filter(s). """ # In Hz, according to Glasberg and Moore (1990) return 24.7 + fc / 9.265
def _swap_endian(val, length): """ Swap the endianness of a number """ if length <= 8: return val if length <= 16: return (val & 0xFF00) >> 8 | (val & 0xFF) << 8 if length <= 32: return ((val & 0xFF000000) >> 24 | (val & 0x00FF0000) >> 8 | (val & 0x0000FF00) << 8 | (val & 0x000000FF) << 24) raise Exception('Cannot swap endianness for length ' + length)
def check_dht_value_type(value): """ Checks to see if the type of the value is a valid type for placing in the dht. """ typeset = [int, float, bool, str, bytes] return type(value) in typeset
def mVPD( vpd, vpdclose, vpdopen ): """VPD dependent reduction function of the biome dependent potential conductance""" if vpd <= vpdopen: return 1.0 elif vpd >= vpdclose: return 1.0 else: return ( ( vpdclose - vpd ) / ( vpdclose - vpdopen ) )
def pseudo_quoteattr(value): """Quote attributes for pseudo-xml""" return '"%s"' % value
def is_valid_section_format(referenced_section): """ referenced_section - a list containing referenced chapter and paragraph. """ return referenced_section is not None and len(referenced_section) == 2
def row_to_dict(row): """ This takes a row from a resultset and returns a dict with the same structure :param row: :return: dict """ return {key: value for (key, value) in row.items()}
def _zero_forward_closed(x, y, c, l): """convert coordinates to zero-based, both strand, open/closed coordinates. Parameters are from, to, is_positive_strand, length of contig. """ y += 1 if not c: x, y = l - y, l - x return x, y
def get_backgroundcolor(window, defalut=0xeeeeee): """ Get background color through accesibility api. """ import sys try: acc = window.getAccessibleContext() if sys.platform.startswith("win"): return acc.getAccessibleChild(0).getBackground() else: return acc.getBackground() except: pass return defalut
def parse_user(line, sep=','): """ Parses a user line Returns: tuple of (user_id, gender) """ fields = line.strip().split(sep) user_id = int(fields[0]) # convert user_id to int gender = fields[1] return user_id, gender
def create_one_hot_v(selected_set, reference): """ :param selected_set: :param reference: list/dict, is full set list or a item2id dict :return: """ v = [0 for i in range(len(reference))] # print('************** debug *************** create one hot v', selected_set, reference, ) if type(reference) == list: for x in selected_set: v[reference.index(x)] = 1 elif type(reference) == dict: # item2id dict for x in selected_set: v[reference[x]] = 1 else: raise TypeError return v
def parse_line(line, file_type, verboseprint): """Parse a scan file line, returns state, proto, port, host, banner.""" result = [] if line[0] == "#": return result if file_type == "masscan": state, proto, port, host, _ = line.split() result = ["open", proto, port, host, ""] elif file_type == "nmap": # Ignore these lines: # Host: 10.1.1.1 () Status: Up if "Status:" not in line: # Host: 10.1.1.1 () Ports: 21/filtered/tcp//ftp///, 80/open/tcp//http///, # 53/open|filtered/udp//domain///, 137/open/udp//netbios-ns/// Ignored State: filtered (195) # Ports: 25/open/tcp//smtp//Microsoft Exchange smtpd/ host_info, port_info = line.split("Ports:") host = host_info.strip().split(' ')[1] # get the port information port_info = port_info.strip() if "Ignored State" in port_info: port_info, _ = port_info.split('Ignored State:') port_info = port_info.strip() port_list = port_info.split(',') port_list = [ x.strip() for x in port_list ] for p in port_list: try: port, state, proto, _, _, _, banner, _ = p.split('/') result.append([state, proto, port, host, banner]) except ValueError as err: print("[-] Error occurred: %s" % str(err)) print("[-] offending line: %s" % p) verboseprint("[*] parse line result: %s" % result) return result
def encode_bool(value): """Encode booleans to produce valid XML""" if value: return "true" return "false"
def _modify_instance_state_response(response_type, previous_state, new_state): """ Generates a response for a Start, Stop, Terminate requests. @param response_type: Cloudstack response. @param previous_state: The previous state of the instance. @param new_state: The new state of the instance. @return: Response. """ response = { 'template_name_or_list': 'change_instance_state.xml', 'response_type': response_type, 'previous_state': previous_state, 'new_state': new_state } return response
def minutes_readable(minutes): """ convert the duration in minutes to a more readable form Args: minutes (float | int): duration in minutes Returns: str: duration as a string """ if minutes <= 60: return '{:0.0f} min'.format(minutes) elif 60 < minutes < 60 * 24: minutes /= 60 if minutes % 1: fmt = '{:0.1f} h' else: fmt = '{:0.0f} h' return fmt.format(minutes) elif 60 * 24 <= minutes: minutes /= 60 * 24 if minutes % 1: fmt = '{:0.1f} d' else: fmt = '{:0.0f} d' return fmt.format(minutes) else: return str(minutes)
def find_first_list_element_above(a_list, value): """ Simple method to return the index of the first element of a list that is greater than a specified value. Args: a_list: List of floats value: The value that the element must be greater than """ if max(a_list) <= value: ValueError('The requested value is greater than max(a_list)') for i, val in enumerate(a_list): if val > value: return i # return next(x[0] for x in enumerate(a_list) if x[1] > value)
def get_id(state): """ Assigns a unique natural number to each board state. :param state: Two dimensional array containing the state of the game board :return: Id number of the state """ cell_id = 0 exponent = 8 for row in state: for column in row: if column == 1: cell_id += pow(2, exponent) exponent -= 1 return cell_id
def remove_text_inside_brackets(text, brackets="()[]{}"): """Removes all content inside brackets""" count = [0] * (len(brackets) // 2) # count open/close brackets saved_chars = [] for character in text: for idx, brack in enumerate(brackets): if character == brack: # found bracket kind, is_close = divmod(idx, 2) count[kind] += (-1)**is_close # `+1`: open, `-1`: close if count[kind] < 0: # unbalanced bracket count[kind] = 0 # keep it else: # found bracket to remove break else: # character is not a [balanced] bracket if not any(count): # outside brackets saved_chars.append(character) return ''.join(saved_chars)
def multAll(lst): """Multiplies a list of variables together""" if len(lst) == 0: return 0 out = lst[0] for i in range(1,len(lst)): out *= lst[i] return out
def _shell_quote(word): """Use single quotes to make the word usable as a single commandline argument on bash, so that debug output can be easily runnable. """ return "'" + word.replace("'", "'\"'\"'") + "'"
def base_expansion(num: int, base: int = 2): """ return a base expansion """ q = int(num) b = int(base) count = 0 expansion = [] while q != 0: expansion.append(q % b) q = q//b count += 1 expansion.reverse() res = "".join(map(str, expansion)) return int(res)
def commandLine(Argv): """ Method converting a list of arguments/parameter in a command line format (to include in the execution of a program for exemple). list --> str """ assert type(Argv) is list, "The argument of this method are the arguments to convert in the command line format. (type List)" commandLine = '' for i in Argv[1::]: commandLine += i+" " return(commandLine)
def _get_job_string(ii, jj, ii_zfill, jj_zfill, protocol): """Returns the job string used in `generate_job_indexes`.""" _s_ii = str(ii).zfill(ii_zfill) _s_jj = str(jj).zfill(jj_zfill) return "p%s-%s-%s" % (str(protocol), _s_ii, _s_jj)
def truncate(base, length, ellipsis="..."): """Truncate a string""" lenbase = len(base) if length >= lenbase: return base return base[:length - len(ellipsis)] + ellipsis
def _tokenize_string(formula): """ Converts a string formula into a series of tokens for evaluation Takes a string and divides it into a list of individual string tokens. Special tokens include ``"(", ")", "+", "^", "[", "]", "=", "~"``, where these have the expected Python behavior, with ``"="`` and ``"~"`` separating the LHS and RHS of the formula. All other special characters are considered to be non-special in this language and will only be split up based on whitespace. The LHS and all white space are removed. Note also that ``"call"`` is a protected keyword here, as it is used to designate a function call operation. :param formula: string formula to be parsed :type formula: str :returns: list of parsed string tokens :rtype: list """ assert isinstance(formula, str) token_list = [] accumulated = "" for char in formula: if char in ["(", ")", "+", "^", " ", "[", "]", "=", "~"]: if not accumulated == "": token_list.append(accumulated) token_list.append(char) accumulated = "" elif char == "*": if accumulated == "*": token_list.append("^") accumulated = "" elif not accumulated == "": token_list.append(accumulated) accumulated = "*" else: accumulated = "*" else: if accumulated == "*": token_list.append(accumulated) accumulated = "" accumulated += char if not accumulated == "": token_list.append(accumulated) outlist = [] for item in token_list: if not item in [" ", "[", "]"]: outlist.append(item) elif item == "[": outlist.append(outlist.pop()+item) elif item == "]": if len(outlist) < 2: raise SyntaxError("error in using square brackets in formula input") outlist.append(outlist.pop(-2)+outlist.pop()+item) if outlist[0] == "y": outlist.pop(0) if outlist[0] in ["=", "~"]: outlist.pop(0) for item in outlist: if (not "[" in item and "]" in item) or (not "]" in item and "[" in item): raise SyntaxError("cannot nest operators in square brackets in formula input") if item == "call": raise SyntaxError("'call' cannot be used as a variable name in formula input") if item in ["=", "~"]: raise SyntaxError("LHS in formula is not correctly specified") return outlist
def zip_object(keys, values=None): """Creates a dict composed from lists of keys and values. Pass either a single two dimensional list, i.e. ``[[key1, value1], [key2, value2]]``, or two lists, one of keys and one of corresponding values. Args: keys (list): either a list of keys or a list of ``[key, value]`` pairs values (list, optional): list of values to zip Returns: dict: Zipped dict. Example: >>> zip_object([1, 2, 3], [4, 5, 6]) {1: 4, 2: 5, 3: 6} See Also: - :func:`zip_object` (main definition) - :func:`object_` (alias) .. versionadded:: 1.0.0 """ if values is None: zipped = keys else: zipped = zip(keys, values) return dict(zipped)
def assignment_no_params_with_context(context): """Expected assignment_no_params_with_context __doc__""" return "assignment_no_params_with_context - Expected result (context value: %s)" % context['value']
def unhappy_point(list, index): """ Checks if a point is unhappy. Returns False if happy. """ if list[index] == list[index - 1] or list[index] == list[(index + 1) % len(list)]: return False return True
def process_coordinate_string(str): """ Take the coordinate string from the KML file, and break it up into [[Lat,Lon,Alt],[Lat,Lon,Alt],...] """ long_lat_alt_arr = [] for point in str.split('\n'): if len(point) > 0: long_lat_alt_arr.append( [float(point.split(',')[0]), float(point.split(',')[1]), float(point.split(',')[2])]) return long_lat_alt_arr
def find_ngrams(token_dict, text, n): """ See: https://github.com/facebookresearch/ParlAI/blob/master/parlai/core/dict.py#L31 token_dict: {'hello world', 'ol boy'} text: ['hello', 'world', 'buddy', 'ol', 'boy'] n: max n of n-gram ret: ['hello world', 'buddy', 'ol boy'] """ # base case if n <= 1: return text # tokens committed to output saved_tokens = [] # tokens remaining to be searched in sentence search_tokens = text[:] # tokens stored until next ngram found next_search = [] while len(search_tokens) >= n: ngram = ' '.join(search_tokens[:n]) if ngram in token_dict: # first, search previous unmatched words for smaller ngrams sub_n = min(len(next_search), n - 1) saved_tokens.extend(find_ngrams(token_dict, next_search, sub_n)) next_search.clear() # then add this ngram saved_tokens.append(ngram) # then pop this ngram from the remaining words to search search_tokens = search_tokens[n:] else: next_search.append(search_tokens.pop(0)) remainder = next_search + search_tokens sub_n = min(len(remainder), n - 1) saved_tokens.extend(find_ngrams(token_dict, remainder, sub_n)) return saved_tokens
def badhash(x): """ Just a quick and dirty hash function for doing a deterministic shuffle based on image_id. Source: https://stackoverflow.com/questions/664014/what-integer-hash-function-are-good-that-accepts-an-integer-hash-key """ x = (((x >> 16) ^ x) * 0x045d9f3b) & 0xFFFFFFFF x = (((x >> 16) ^ x) * 0x045d9f3b) & 0xFFFFFFFF x = ((x >> 16) ^ x) & 0xFFFFFFFF return x
def find_between(string, first, last): """Return substring between 'first' and 'last'.""" try: start = string.index(first) + len(first) end = string.index(last, start) return string[start:end] except ValueError: return ""
def getsize(data): """Return the smallest possible integer size for the given array.""" maxdata = max(data) if maxdata < (1 << 8): return 1 if maxdata < (1 << 16): return 2 return 4
def l2_loss(x: float, y: float) -> float: """ Compute the L2 loss function. Return the square difference between the inputs. https://www.bitlog.com/knowledge-base/machine-learning/loss-function/#l2-error Parameters ---------- x : float The estimate y : float The actual value """ return (x - y) ** 2
def action_get_into_bash(image_name, image_tag, user_name): """The function action_get_into_bash takes into the bash shell running in the container. Arguments: image_name: Name of the image to be used to build the container. image_tag: The tag of the image which is used to build the container. user_name: The user name which logins into the container. """ image_name_with_tag = image_name + ":" + image_tag get_bash_command_list = [ "docker", "run", "-it", image_name_with_tag, "/usr/bin/su", "-l", user_name, "-s", "/usr/bin/bash", ] return get_bash_command_list
def escape_html_chars(str_val): """ Escape special HTML characters (& <>) @type str_val: string @return: formatted string @rtype: string """ if str_val is None: return None output = str_val output = output.replace('&', '&amp;') output = output.replace(' ', '&nbsp;') output = output.replace('>', '&gt;') output = output.replace('<', '&lt;') return output
def convert_to_int(str_byte: str) -> int: """Take string representation of byte and convert to int""" return int(str_byte, 2)
def count_ballots(ballots): """ Counts the "for" and "against" ballots :param ballots: Vote ballots :return: A tuple of dictionaries: for and against votes """ # Count the number of votes for each candidate results_for = {} results_against = {} blanks = [] for name, ballot in ballots.items(): if not ballot['for'] and not ballot['against']: # Blank vote blanks.append(name) continue for candidate in ballot['for']: results_for[candidate] = results_for.get(candidate, 0) + 1 for candidate in ballot['against']: results_against[candidate] = results_against.get(candidate, 0) - 1 return results_for, results_against, tuple(sorted(blanks))
def pkcs7_unpad(bytes_, len_): """Unpad a byte sequence with PKCS #7.""" remainder = bytes_[-1] pad_len = remainder if remainder != 0 else len_ msg = bytes_[:-pad_len] pad = bytes_[-pad_len:] if remainder >= len_ or any(p != remainder for p in pad): raise ValueError("Invalid padding") return msg
def permutation(s): """ @s: list of elements, eg: [1,2,3] return: list of permutations, eg: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]] """ ret = [] length = len(s) if length == 0: return ret if length == 1: return [s] curr = s[0] for prev in permutation(s[1:]): for i in range(length): ret.append(prev[:i] + [curr] + prev[i:]) return ret
def global2local(gobal_coord, start, end, strand): """Returns local coordinate in a global region""" # swap if strands disagree if strand == 1: return gobal_coord - start else: return end - gobal_coord
def split_line(line): """Split a line read from file into a name/sequence tuple Arguments: line: line of text with name and sequence separated by tab. Returns: (name,sequence) tuple. """ name = line.strip('\n').split('\t')[0] seq = line.strip('\n').split('\t')[-1] return (name,seq)
def get_keys(dictionary): """ :param dictionary: python dict obj :return: sorted list of keys of dictionary """ keys = sorted(list(dictionary.keys())) print("length of keys: ", len(keys)) return keys
def rgbu8_size(width, height): """Calculate rgb 24bit image size Args: width: image width height: image height Returns: rgb 24bit image data size """ return int(width * height * 3)
def parse_author_and_permlink(url): """ Parses a typical steem URL and returns a tuple including the author and permlink. Ex: http://steemit.com/@author/permlink """ try: author = url.split("@")[1].split("/")[0] permlink = url.split("@")[1].split("/")[1] except IndexError as e: raise ValueError("This is not valid Steem permlink.") return author, permlink
def get_smiles(res): """ Get a list of SMILES from function results """ smiles = set() for smi in res: try: smiles.add( "{}\t{}".format( smi["molecule_structures"]["canonical_smiles"], smi["molecule_chembl_id"], ) ) except TypeError: continue return smiles
def _is_private(name: str) -> bool: """Return true if the name is private. :param name: name of an attribute """ return name.startswith('_')
def barxor(a, b): # xor two strings of different lengths """XOR the given byte strings. If they are not of equal lengths, right pad the shorter one with zeroes. """ if len(a) > len(b): return [ord(x) ^ ord(y) for (x, y) in zip(a[:len(b)], b)] else: return [ord(x) ^ ord(y) for (x, y) in zip(a, b[:len(a)])]