content
stringlengths
42
6.51k
def mycmp(a,b): """Wrap function of cmp in py2""" if a < b: return -1 elif a > b: return 1 else: return 0
def polynomial_power_combinations(degree): """ Combinations of powers for a 2D polynomial of a given degree. Produces the (i, j) pairs to evaluate the polynomial with ``x**i*y**j``. Parameters ---------- degree : int The degree of the 2D polynomial. Must be >= 1. Returns -----...
def str2bool(v): """ Converts a string to boolean Args: v (str) : string to be percieved as true or false Returns: (bool) : True or false based on string """ return v.lower() in ("yes", "True", "true", "t", "1")
def string_between( text, begin_str, end_str, incl_begin=False, incl_end=False, greedy=True): """ Isolate the string contained between two tokens Args: text (str): String to parse begin_str (str): Token at the beginning end_str (str): ...
def _TokenizeQuotedList(arg_value): """Tokenize an argument into a list. Args: arg_value: str, The raw argument. Returns: [str], The tokenized list. Raises: ArgumentTypeError: If the list is malformed. """ if arg_value: if not arg_value.endswith(','): arg_value += ',' return arg...
def _get_property_dict(property_list): """ Helper method to get a dictionary from list of property dicts with keys, values """ property_dict = {} for property in property_list: property_dict[property['key']] = property['value'] return property_dict
def get_clean_text(text: str) -> str: """ Preprocess text for being used in the model, including lower-casing, standardizing newlines and removing junk. Parameters ---------- text : str A string to be cleaned Returns ------- clean_text : str String after being clean...
def line_separated(value): """ Return a list of values from a `value` string using line as list delimiters. """ if not value: return [] return list(value.splitlines(False))
def cubrt(x): """Returns the cubed root of x""" return round(x ** (1/3), 12)
def clean_normalise_text_lines(input_text_lines): """Clear and normalise text Includes case lowering and strip (right & left) for whitespace. Also replace comma with dots to ease the search of float number Args: input_text_lines [(str)]: lines of text to be cleaned Returns: cle...
def rebuild_year_dict(raw_list): """ Converts raw dictionary (json) obtained by a wikidata query to a more useful dictionary with years as keys, and category item ID as values. """ new_dict = {} for elem in raw_list: year = elem['itemLabel'] if 'AD' in year: year ...
def module_importable(module): """Without importing it, returns whether python module is importable. Args: module (string): Name of module. Returns: bool """ import sys if sys.version_info >= (3, 4): from importlib import util plug_spec = util.find_spec(module)...
def fluid_properties(fluid_str): """ Return the physical density and kinematic viscosity for the prescribed fluid. """ fluid_lib = {'water':(1000., 1.0e-6), 'glycol':(965.3,0.06/965.3), 'glycerin':(1260.0,1.49/1260.0)} if fluid_str in list(fluid_lib.keys()): ...
def UnicodeToCLiteral(s): """Converts a unicode string to a C-style escaped string (e.g. "\xe1\x84").""" s = s.encode('utf8') out = ['"'] for c in s: if ord(c) > 127: out.append(r'\x%.2x' % ord(c)) # To prevent the C++ compiler from interpreting subsequent characters as # part of the hex c...
def aggregate_reviews(review_list): """Combine all review tokens into one string.""" reviews = "" for i in review_list: reviews += i[0] return reviews.lower()
def sn2order(scenario: list) -> str: """ Extract scenario item to order Parameters ---------- scenario: list use only index 1 0: number, 1: items (order and recipe), 2:judge Returns ---------- str order of scenario """ return str(scena...
def polynomial(a0,a1,a2,a3,a4,x): """ Up to x4 """ return a0 + x*(a1+x*(a2+x*(a3+x*a4)))
def _make_divisible(ch, divisor=8, min_ch=None): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py """ i...
def merge_dicts(*dicts: dict) -> dict: """Merge dictionaries into first one.""" merged_dict = dicts[0].copy() for dict_to_merge in dicts[1:]: for key, value in dict_to_merge.items(): if key not in merged_dict or value == merged_dict[key]: merged_dict[key] = value ...
def set_alarm(employed, vacation): """ A function named setAlarm which receives two parameters. The first parameter, employed, is true whenever you are employed and the second parameter, vacation is true whenever you are on vacation. The function should return true if you are employed and n...
def sort_nested(data): """ Return a new dict with any nested list sorted recursively. """ if isinstance(data, dict): new_data = {} for k, v in data.items(): if isinstance(v, list): v = sorted(v) if isinstance(v, dict): v = sort_nest...
def _start_string(num_total, tag, num_processes): """Returns a string to be displayed before processing begins. It contains the number of total items and the number of processes. It is prefixed by the `tag`. Where information are not available or a division by zero would occur, a `-` or `0ms` is returned f...
def uidIsValid(uid): """UID Validation.""" if len(uid) == 32: try: int(uid, 16) return True except ValueError: return False else: return False
def build_collection_representation(model, description): """Enclose collection description into a type-describing block.""" # pylint: disable=protected-access collection = { model.__name__: description, } return collection
def pyha_to_python(simulation_output): """ Convert simulation output (e.g fixed-point value) to Python value (e.g. float). It can be possible that model returns multiple values! """ def handle_one(output): try: # some Pyha type? return output._pyha_to_python_value() ...
def parse_logs(logs): """Load previous ... """ import json if isinstance(logs, str): print(len(logs)) logs = [logs] timings = [] for log in logs: with open(log, "r") as j: while True: try: iteration = next(...
def lcp(string,i,j): """ Longest-Common-Prefix """ l=0; n = len(string) while (l+max(i,j)<n) and (string[i+l]==string[j+l]): l+=1 return l
def adamatch_hyperparams(lr=3e-3, tau=0.9, wd=5e-4, scheduler=True): """ Return a dictionary of hyperparameters for the AdaMatch algorithm. Arguments: ---------- lr: float Learning rate. tau: float Weight of the unsupervised loss. wd: float Weight decay for the opt...
def calc_sum(num1, num2): """Returns the sum of num1 and num2. This one has been done for you. Use it as a gide for the funstions below. """ result = num1 + num2 return result
def generate_initials(text): """ Extract initials from a string Args: text(str): The string to extract initials from Returns: str: The initials extracted from the string """ if not text: return None text = text.strip() if text: split_text = text.split(" ...
def get_bit_bucket_url(contribution_urls): """ This Function finds the bit bucket url from a list of urls :param contribution_urls: list of urls :return: url - bit bucket url """ for url in contribution_urls: if 'bitbucket.com' in url or 'bitbucket.org' in url: return url ...
def is_reverse(x,y): """ If two ages are the reverse of eachother, returns True.""" stringx = str(x).zfill(2) stringy = str(y).zfill(2) if (stringx[0] == stringy[1] and stringx[1] == stringy[0]): return True else: return False
def null_handler(data: list) -> list: """ handles value types from sql.NullString `attribute_value_name` is type NullString, therefore contains (String, bool) """ for prod in data: prod["attribute_value_name"] = ( prod["attribute_value_name"]["String"] if prod["attrib...
def code_quoted(s): """ Internally user-provided `None` and non `literal_eval`uatable input is quoted with ``` This function checks if the input is quoted such :param s: The input :type s: ```Any``` :returns: Whether the input is code quoted :rtype: ```bool``` """ return ( ...
def make_course_id(year, term, a_lvl, campus, dept, code, delim, is_file=True): """Creates unique identifier out of course data. Multiple courses with the same ID can exist. Such as MATH121 for main campus, bader campus, or online. In order for a course listing to be unique, these 6 datapoints must be ...
def extract_unique_words(list_of_tup): """ :param list_of_tup: list of tuples :return: The unique words from all the reviews """ unique_wrs = set() for review in list_of_tup: for pair in review: unique_wrs.add(pair[0]) return sorted(list(unique_wrs))
def is_string_int(string): """ Checks if the string is a valid representation of an integer Examples -------- > is_string_int('12') > True > > is_string_int('a') > False """ try: int(string) return True except ValueError: return False
def get_info_dict(info_string): """Convert a info string to a dictionary Args: info_string(str): A string that contains the INFO field from a vcf variant Returns: info_dict(dict): The input converted to a dictionary """ info_dict = {} if not info_string: return info_dic...
def hailstone(n): """Print the hailstone sequence starting at n and return its length. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 """ "*** YOUR CODE HERE ***" length = 1 while n != 1: print(n) if n % 2 == 0: n = n // 2 ...
def sample_name_to_blasted_path(sample_name, dest_dir): """ Create a path to put a blast result in, using a sample name and destination directory. :param sample_name: e.g. '70_HOW9' :param dest_dir: directory to place file in :return: file path string """ return dest_dir + '/blast_resu...
def numberToVarint(n): """ Converts a number into a variable length byte array (using 7 bits per byte, big endian encoding, highest bit is info if last length-byte (0) or not (1)). Start at the lower byte (right) and work the way up :) """ value = int(n) if value == 0: ...
def zern_to_noll(n, m): """ Convert a Zernike index pair, (n,m) to a Linear Noll index. :param n: Zernike `n` index. :param m: Zernike `m` index. """ j = (n * (n+1))/2 + (n+m)/2 if not int(j) == j: raise ValueError("This should never happen, j={:f} should be an int...
def to_timestamp(ts: int) -> str: """returns a [(h*):mm:]ss timestamp string from `ts: int`""" if ts == 0: return "0" _mm = ts // 60 hh = _mm // 60 mm = _mm - hh * 60 ss = ts % 60 return ":".join( [str(u).rjust(2, "0") for u in (hh, mm) if u != 0] + [str(ss).rjust(2, "0")] ...
def value_str_filter(value, *, str_quote="", bool_is_str=False, bool_type=None): """ Convert a value to string that is suitable to be passed to an Backend Internally, this filter use the str() function. :param str_quote: enclosed the given str with this given str_quote :param bool_is_str: whether ...
def extract_overall_coverage(function_coverage): """Extract overall coverage from function coverage data.""" if not function_coverage: return {} hit = 0 total = 0 # file name -> function data for _, function_data in function_coverage.items(): # function name -> coverage data ...
def calculate_distance(p1, p2): """Calculates the distance between two points Args: p1 (tuple): (x ,y) of first point p2 (tuple): (x, y) of second point >>> calculate_distance((1,1), (1,1)) 0.0 >>> calculate_distance((52, 3), (26, 77)) 78.43468620451031 """ x1, y1 ...
def ccw_2d(A, B, C): """ Check if the points are listed in counter-clockwise order """ return((C[1] - A[1]) * (B[ 0] - A[0]) > (B[1] - A[1]) * (C[ 0] - A[0]))
def get_google_maps_url(data): """ It builds a google map url which will point to your lat lon. :param data: dictionary with lat and lon information :return: """ return "http://maps.google.com/maps?q=loc:{}+{}".format(data['lat'], data['lon'])
def _removed_nodes(steps): """Based on the steps, find node ids that were removed.""" added = set() for step in steps: if step['entity_type'] == 'node' and step['action'] == 'remove': added.add(step['entity_id']) return list(added)
def _make_divisible(v, divisor, min_value=None): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py """ i...
def is_theme(labels, zen_issue): """Check If Issue Is a Release Theme. Use the input Github Issue object and Zenhub Issue object to check: * if issue is an Epic (Zenhub) * if issue contains a `theme` label """ if zen_issue['is_epic']: if 'theme' in labels: return True
def trim(align, trans): """ Given a result from the aligning with Kalign, trims residues from longer 2nd sequence so it matches the 1st """ count = 0 for i in align[0]: if i != '-': break else: count += 1 start = count count = 0 for i in revers...
def prune(url, browse_boolean): """ This function will return true when the graph should continue searching and false when the graph should stop. """ url = url.lower().strip() if 'linkedin'in url: return False elif 'twitter' in url: return False elif 'socrata' in url: ...
def dms_to_dd(d, m, s): """Converts degrees, minutes and decimal seconds to decimal degrees. Example: (41, 24, 12.2) -> 41.4034 :param int d: degrees :param int m: minutes :param float s: decimal seconds :rtype: float """ return d + (m / 60) + (s / 3600)
def is_palindrome(yarn): """Return whether or not a string is a palindrome. A palindrome is a word/phrase that's the same in both directions. """ return yarn == yarn[::-1]
def average(v): """ :param v: a list of numerical values :return: average for a list of values expressed as a float """ return sum(v) * 1.0 / len(v)
def pe28(d=1001): """ >>> pe28() 669171001 """ n = (d - 1) >> 1 """ ld = [(2*i+1)**2 + 4*(i + 1) for i in range(n)] rd = [(2*i+1)**2 + 2*(i + 1) for i in range(n)] ru = [(2*i+3)**2 for i in range(n)] lu = [(2*i+3)**2 - 2*(i + 1) for i in range(n)] return 1 + sum(ld) + sum(rd)...
def _get_vulnerable_configs(full_cve): """Return the vulnerable configurations as a list from CVE JSON. Args: full_cve (dict): Full CVE data as a JSON dictionary from API call. Returns (list): list of vulnerable configuration details """ if 'vulnerable_configuration' in full_cve: r...
def list2str(args): """ Convert list[str] into string. For example: [x, y] -> "['x', 'y']" """ if args is None: return '[]' assert isinstance(args, (list, tuple)) args = ["'{}'".format(arg) for arg in args] return '[' + ','.join(args) + ']'
def adjust_price_bucket_by_price_multiplier(price_bucket, price_multiplier): """ Args: price_bucket (object): the price bucket configuration price_multiplier (int): the price_multiplier to adjust price bucket :return: updated price_bucket """ new_price_buckets = { 'precision': price_bucket['precis...
def snake_case_to_pascal_case(input_string): """ Converts the input string from snake_case to PascalCase :param input_string: (str) a snake_case string :return: (str) a PascalCase string """ input_list = input_string.split('_') input_list = [i.capitalize() for i in input_list] output = '...
def get_region_name(region_code): """Returns region name corresponding to the region abbreviation.""" try: region_mapping = {'us-east-1': 'US East (N. Virginia)', 'us-east-2': 'US East (Ohio)', 'us-west-1': 'US West (N. California)', 'us-west-2': 'US West (Oregon)', ...
def annotconflict(annotations, annotation): """ Checks to see if annotation is already in annotations :param annotations: a list of annotations :type annotations: list :param annotation: an annotation :type annotation: list :return: True if annotation is already in the list, otherwise...
def looks_like_heap_pointer(pointer: int) -> bool: """ Returns true if pointer could plausibly be a heap chunk :param pointer: Address to interrogate :return: True if the pointer could be a heap chunk, False otherwise """ # Make sure it is in userspace if pointer > 0x00007fffffffffff: ...
def buildKey(ids, dataLine): """ Concatenate a set of fields together to build an overall key This is a simple approach to determining k-anonymity, in which all of the fields of interest are concatenated as a single key. The ids coming in should be a list of indexes into the fields in the dataLine...
def _is_string_like(obj): """ Return True if object acts like a string. """ # From matplotlib cbook.py John D. Hunter # Python 2.2 style licence. See license.py in matplotlib for details. if hasattr(obj, 'shape'): return False try: obj + '' except (TypeError, ValueError): return False ...
def get_perm_key(action, class_name, field_name): """ Generate django permission code name. :Example: >> perm = get_perm_key('change', 'baseobject', 'remarks') change_baseobject_remarks_field :param action: Permission action (change/view) :type action: str :param class_name: D...
def _add_dicts(*dictionaries): """Adds a list of dictionaries into a single dictionary.""" # If keys are repeated in multiple dictionaries, the latter one "wins". result = {} for d in dictionaries: result.update(d) return result
def interval_to_freq(time_interval: str) -> str: """ Convert the natural language-based time period into freq char in order to standardize user input. Parameters ---------- time_interval : Natural lanaguage time period. Returns ------- freq : Appropriate frequency char, see: https:...
def dc(di, element_name): """ returns the child element `element_name' if any. returns None otherwise (when di is null or there is no such child element """ if di is None: return None if element_name in di: return di[element_name] return None
def all_subsets(s): """returns all the subsets included in this set.""" r = [set()] for i in s: for j in r[:]: r.append(j | set([i])) return r
def getRGB3(color, to_color, val, cmin, cmax): """ Return a tuple of floats between 0 and 1 for the red, green and blue amplitudes. Colormap: color tuple -> to_color tuple source: http://awesome.naquadah.org/wiki/Gradient """ red, green, blue = color to_red, to_green, to_blue = to_color ...
def pp_peername(peername): """Prettily format a peername tuple (host, port)""" return f"{peername[0]}:{peername[1]}"
def pow_mod(base, exponent, modulus): """ Computing Modular exponentiation: base ^ exponent (mod modulus) Parameters ---------- base : integer exponent : integer modulus : unsigned integer Returns ------- int Result of calculation """ return pow(base, exponent,...
def key_value_string_value(key_value_string, key): """Extract value for key from Zotero key-value-string. Zotero 'Extra'' field stores data as a space separated string: 'key1: value1 key2: value2 key3: value3'. This function extracts a value for a key from such a string. """ if key_value_strin...
def _filter_distance(results, return_distance): """For a list of tuples [(distance, value), ...] - optionally filter out the distance elements. Args: tuple_list: List of tuples. (distance, value) return_distance: boolean to determine if distances should be returned. """ if return_dis...
def get_id_from_url(url): """ param: url https://ns.adobe.com/salesvelocity/classes/f412489610bf750ad40b30e0b7804a13 """ url = url.replace("https://ns.adobe.com/", "") url = url.replace("/", ".") return "_" + url
def toggle_bits(S, *positions): """ Returns a new set from set `S` with bits toggled (flip the status of) in the given `positions`. Examples ======== Toggle the 2-nd item and then 3-rd item of the set >>> S = int('0b101000', base=2) >>> S = toggle_bits(S, 2, 3) >>> bin(S) '0b100100...
def taxon_cmd_line_checker(argv): """Checks command line arguments for correctness. Returns dictionary of taxon, name pairs or empty dictionary. Written by Phil Wilmarth, OHSU, 2009. """ tax_dict = {} if argv[0].endswith('.py'): argv = argv[1:] # need to have an even number of (...
def additive_hash(key): """Hash string by adding up the values of the characters.""" if not isinstance(key, str): raise TypeError("Key must be a string.") hv = sum(ord(letter) for letter in key) return hv
def is_iterable(x): """True if x can be iterated over""" return hasattr(x, '__iter__')
def cross(A, B): """ Cross product of elements in A and elements in B """ return [a+b for a in A for b in B]
def zipf_to_freq(zipf): """ Convert a word frequency from the Zipf scale to a proportion between 0 and 1. The Zipf scale is a logarithmic frequency scale proposed by Marc Brysbaert, who compiled the SUBTLEX data. The goal of the Zipf scale is to map reasonable word frequencies to understandable...
def response_payload_handler(token, user=None, request=None): """ Returns the response data for both the login and refresh views. Override to return a custom response such as including the serialized representation of the User. Example: def jwt_response_payload_handler(token, user=None, request=...
def parse_cardinality(val): """ Parses an odml specific cardinality from a string. If the string content is valid, returns an appropriate tuple. Returns None if the string is empty or the content cannot be properly parsed. :param val: string :return: None or 2-tuple """ if not val:...
def _combine_results(source_results: list, new_results: list) -> list: """Combines the specified dictionaries Arguments: source_results: the source dictionary to merge into new_results: the dictionary to add Return: Returns the combined dictionary Notes: Runtime parameter...
def isleap(year): """Verify if year is a leap year. :param int `year`: the year to check :return: True or False """ return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def event_at_sol(t, func, interpolate, rhs, cache, *args): """Helper function to find the root for the event function along the solution. Parameters ---------- t : float timepoint func : callable jitted event function. interpolate : callable jitted interpolation function...
def apply_fn_over_range(fn, start_time, end_time, arglist): """Apply a given function per second quanta over a time range. Args: fn: The function to apply start_time: The starting time of the whole duration end_time: The ending time of the whole duration arglist: Additional argument list Returns...
def get_threshold(rows, bands): """Approximate threshold from bandwidth and number of rows :param rows: rows per band :param bands: number of bands :return: threshold value :rtype: float """ return (1. / bands) ** (1. / rows)
def parse_rule(rule): """ Parses the rule and returns a dict describing the rule >>> parse_rule('1-3 a') {'start': 1, 'end': 3, 'char': 'a'} >>> parse_rule('1-3 b') {'start': 1, 'end': 3, 'char': 'b'} >>> parse_rule('2-9 c') {'start': 2, 'end': 9, 'char': 'c'} >>> parse_rule('2-99 c...
def asBinary(i): """ Produces a string from an integer's binary representation. (preceding zeros removed). """ if i > 1: if i % 2 == 1: return asBinary(i >> 1) + '1' else: return asBinary(i >> 1) + '0' else: return str(i)
def get_status(field): """Removes all values of arg from the given string""" if field == '+': return 'Created' elif field == '~': return 'Modified' elif field == '-': return 'Deleted' else: return 'Unknown'
def create_header(conf): """Creates a header based on the configuration file dictionary.""" head = [] colnames = conf['column_names'] for colkey in colnames.keys(): head.append(colnames[colkey]) return head
def key_by_tollbooth_month(element): """ Most Beam combiners are designed to work on a (key, value) tuple row. Input rows are normalized into a tuple where the first element contains the keys and second elements contains the values for combiners Beam allows for multi keys and values by accepting a...
def fib(n): """nth fibonacci number (recursive)""" if n == 0 or n == 1: return n #base case return fib(n-1) + fib(n-2)
def getFirstPlist(textString): """Gets the next plist from a set of concatenated text-style plists. Returns a tuple - the first plist (if any) and the remaining string""" plistStart = textString.find('<?xml version') if plistStart == -1: # not found return ("", textString) plistE...
def verify_configuration_types(config): """Verify the types of configuration attributes. Args: config (map): Configuration to verify. Returns: bool: True when types are valid, False when invalid. """ if not isinstance(config["count"], int): return False return True
def get_dict_nested_value(x, *keys): """ Get a value nested inside a dict :param x: The dict to extract the value from :param keys: Any number of string arguments representing the nested keys to search through :return: The value at the nested location or None if not found """ if not x: ...
def get_occurances(haystack,needle,l=[],start=0,end=-1): """ return a list with all indices of needle in haystack """ i = haystack.find(needle,start) if i == -1: return l return get_occurances(haystack,needle,l+[i],i+1)