content
stringlengths
42
6.51k
def get_index_of_feature(feature_list, item): """ Gets the index of the feature in the provided feature list :rtype : int :param feature_list: List of features to search from :param item: The feature to search :return: The index where the feature was founded, -1 otherwise """ # getting...
def _prepare_string_to_sign(req_tgt, hdrs): """ :param req_tgt : Request Target as stored in http header. :param hdrs: HTTP Headers to be signed. :return: instance of digest object """ signature_string = '(request-target): ' + req_tgt.lower() + '\n' for i, (key, value) in enumerate(hdrs.it...
def numberToZigZag(n): """ ZigZag-Encodes a number: -1 = 1 -2 = 3 0 = 0 1 = 2 2 = 4 """ return (n << 1) ^ (n >> 31)
def get_window_ids(tabs): """ gets tab objects and returns a list of window IDs """ window_ids = [tab.window for tab in tabs] window_ids = list(set(window_ids)) return window_ids
def _pack_asn1_octet_number(num): # type: (int) -> bytes """ Packs an int number into an ASN.1 integer value that spans multiple octets. """ num_octets = bytearray() while num: # Get the 7 bit value of the number. octet_value = num & 0b01111111 # Set the MSB if this isn't ...
def chebyshev(vector_1, vector_2): """ compute CHEBYSHEV metric """ return max([abs(vector_1[i] - vector_2[i]) for i in range(len(vector_1))])
def mantissa_int_part(n): """convert the integral part of a decimal number to mantissa digits""" result = [] n = int(n) while n > 0: q = n / 2 rem = n % 2 if rem == 0: result.append('0') else: result.append('1') n = int(q) result.revers...
def max_or_zero(iterable): """ Return max of an iterable or zero if not iterable. >>> max_or_zero([]) 0 >>> max_or_zero([1,2,3]) 3 """ if iterable: return max(iterable) return 0
def packageParameters(gK, gNa, gL, Cm, EK, ENa, EL, Vm_0, adjacencyMatrix, AP_times, timeConstants, AP_threshold, T): """ Takes all HH class parameters, packages and returns a dictionary class object; the keys are hardcoded in the Hodgkin Huxley class definition """ parameterDictionary = { ...
def count_syllables_in_word(word): """This function takes a word in the form of a string and returns the number of syllables. Note this function is a heuristic and may be not 100% accurate. """ count = 0 endings = '!,;.?:' last_char = word[-1] if last_char in endings: pr...
def finddefault(f): """return the default value given a format""" if f.count('A'): default="UNKNOWN" elif f.count('I'): default=-999 else: default=-999.99 return default
def merge(left, right): """ Merge two sorted arrays in a resulting array of size len(left) + len(right) """ result = [] while len(left) != 0 and len(right) != 0: if left[0] < right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) if len(l...
def calc_auc(raw_arr): """Summary Args: raw_arr (TYPE): Description Returns: TYPE: Description """ # sort by pred value, from small to big arr = sorted(raw_arr, key=lambda d:d[2]) auc = 0.0 fp1, tp1, fp2, tp2 = 0.0, 0.0, 0.0, 0.0 for record in arr: fp2 += r...
def SubpArgs(args): """ According to subcommand, when using shell=True, its recommended not to pass in an argument list but the full command line as a single string. That means in the argument list in the configuration make sure to provide the proper escapements or double-quotes for paths with spaces :...
def color565(r, g, b): """Convert 24-bit RGB color to 16-bit.""" return (r & 0xf8) << 8 | (g & 0xfc) << 3 | b >> 3
def _find_duplicates(iterable): """Returns a list of duplicate entries found in `iterable`.""" duplicates = [] seen = set() for item in iterable: if item in seen: duplicates.append(item) else: seen.add(item) return duplicates
def solution(a: list) -> int: """ >>> solution([-3, 1, 2, -2, 5, 6]) 60 >>> solution([6, 5, 4]) 120 """ a.sort() return max(a[0] * a[1] * a[-1], a[-3] * a[-2] * a[-1])
def frexp10(x): """ e.g. 1.3E5 ~= (1.3, 5) 1.32894632e-06) ~= (0.13, -5) """ import math try: exp = int(math.log10(x)) return x / 10**float(exp), exp except (OverflowError,ValueError): return x,0 except NameError: print( "You forg...
def add(X, Y): """Add two vectors.""" return X[0]+Y[0], X[1]+Y[1]
def format_time(time): """Turn a time value in seconds into hh:mm:ss or mm:ss.""" if time < 0: time = abs(time) prefix = "-" else: prefix = "" if time >= 3600: # 1 hour # time, in hours:minutes:seconds return "%s%d:%02d:%02d" % (prefix, time // 3600, ...
def sanitize_filename(s): """Sanitizes a string so it could be used as part of a filename.""" def replace_insane(char): if char in u' .\\/|?*<>:"' or ord(char) < 32: return '_' return char return u''.join(map(replace_insane, s)).strip('_')
def isinrectbnd(x: int, y: int, xmin: int, ymin: int, xmax: int, ymax: int) -> bool: """Checks if the x and y values lie within the rectangular area defined by xmin, ymin and xmax, ymax Args: x, y: (x,y) coordinates to test xmin, ymin...
def memoize(f): """ Memoization decorator for functions taking one or more arguments. """ class memodict(dict): def __init__(self, f): self.f = f def __call__(self, *args): return self[args] def __missing__(self, key): ret = self.f(*key) ...
def c_to_f(tempe): """Receives a temperature in Celsius and returns in Fahrenheit""" return 1.8 * tempe + 32
def _list_of_bytes_singletons(bytes_alphabet): """Convert to list of bytes, or the function will return ints instead of bytes""" return list(map(lambda x: bytes([x]), bytes_alphabet))
def parse_winner(turn, log, attacker, defender): """ parses round winner from log :param turn: simulation round :param log: log file :param attacker: attacker nation id :param defender: defender nation id :return: dictionary with the nation that won the turn """ p_loc = log.find('go...
def Color(red, green, blue, white=0): """Convert the provided red, green, blue color to a 24-bit color value. Each color component should be a value 0-255 where 0 is the lowest intensity and 255 is the highest intensity. """ return (white << 24) | (red << 16) | (green << 8) | blue
def convert_to_mixed_fraction(number, denominators): """ Convert floats to components of a mixed fraction representation Returns the closest fractional representation using the provided denominators. For example, 4.500002 would become the whole number 4, the numerator 1 and the denominator 2 ...
def Perp2(a, b): """Return a sort of 2d cross product.""" return a[0] * b[1] - a[1] * b[0]
def md_link(display: str, real_url: str) -> str: """Make Markdown link from the given URL.""" return f"[{display}]({real_url})"
def is_array_of(obj, classinfo): """ Check if obj is a list of classinfo or a tuple of classinfo or a set of classinfo :param obj: an object :param classinfo: type of class (or subclass). See isinstance() build in function for more info :return: flag: True or False """ flag = False if is...
def _RunCallbacks(*callbacks): """Run the provided callbacks. Return the value from the last one.""" retval = None for callback in callbacks: retval = callback() return retval
def delete_type(rows, msg_content): """ Function: delete_type Description: A existing event type is deleted from the user's calendar file Input: rows: lsit of lines in calendar msg_content: event type to be deleted Output: - A existing event type ...
def listify(items): """Puts each list element in its own list. Example: Input: [a, b, c] Output: [[a], [b], [c]] This is needed for tabulate to print rows [a], [b], and [c]. Args: * items: A list to listify. Returns: A list that contains elements that are listifie...
def _IndexToLineColumn( text, index ): """Get (line_number, col) of `index` in `string`.""" lines = text.splitlines( True ) curr_pos = 0 for linenum, line in enumerate( lines ): if curr_pos + len( line ) > index: return linenum + 1, index - curr_pos + 1 curr_pos += len( line ) assert False
def calculate_area(length, width, height): """Calculates the area + slack based on dimensions""" area_of_sides = [length*width, width*height, height*length] return sum(2*area_of_sides, min(area_of_sides))
def denormalize(x_point: float, mean: float, width: float) -> float: """de-normalize the data point Args: x (float): the data point mean (float): the mean value width (float): the width Returns: float: the de-normalized value """ return 0.5 * width * x_point + mean
def capture_in_dir(board, player, x, y, i, j, size): """ captures pieces in a certain direction """ captures = 1 other_player = -player xc = x+i yc = y+j while size > xc >= 0 and size > yc >= 0 and board[yc][xc] == other_player: xc += i yc += j captures += 1 i...
def page_to_offset(page: int, per_page: int, zero_offset: int = 1) -> int: """Calculate offset from ``page`` and ``per_page`` Args: page (int): page number (1 based) per_page (int): items per page zero_offset (int, optional): Offset from zero, e.g. if your engine starts cou...
def canonical_message_builder(content, fmt): """ Builds the canonical message to be verified. Sorts the fields as a requirement from AWS Args: content (dict): Parsed body of the response fmt (list): List of the fields that need to go into the message Returns (str): ...
def insertion_sort(array): """ For Shorting the Array, this would take an Average time complexity of O(n2) And space complexity of O(1) :param array: Array to be Shorted :return: Shorted Array """ # Running a loop from the 1st pos to the length of the array for i in range(1, len(array)):...
def avg_values(buildings_buf, building_data, road): """ Get some really simple statistics on a set of buildings given a road segment. Return average building height and average distance from the buildings to the road. """ if not buildings_buf: return 0, 0 avg_dist = 0 avg_heigh...
def _check_correct(names, values, check, transform=None): """ Transforms the values of given fields from the uploaded file and check if they end up in the desired format :param names: names of the fields to check :param values: values of the fields to transform and check if they are in the ri...
def skewed_lorentzian(x, bkg, bkg_slp, skw, mintrans, res_f, Q): """ Skewed Lorentzian """ return bkg + bkg_slp*(x-res_f)-(mintrans+skw*(x-res_f))/\ (1+4*Q**2*((x-res_f)/res_f)**2)
def isSequence(arg): """Check if input is iterable.""" if hasattr(arg, "strip"): return False if hasattr(arg, "__getslice__"): return True if hasattr(arg, "__iter__"): return True return False
def get_requirements(requirements_file): """ Parse the specified requirements file and return a list of its non-empty, non-comment lines. The returned lines are without any trailing newline characters. """ with open(requirements_file, 'r') as f_p: lines = f_p.readlines() reqs = [] ...
def url_form(url): """Takes the SLWA photo url and returns the photo url. Note this function is heavily influenced by the format of the catalogue and could be easily broken if the Library switches to a different url structure. """ if url[-4:] != '.png' and url[-4:] != '.jpg': url = url + '...
def _base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'): """Converts an integer to a base36 string.""" if not isinstance(number, int): raise TypeError('number must be an integer') base36 = '' sign = '' if number < 0: sign = '-' number = -number if 0 ...
def split_user_input(inp): """ convert comma separated string into list of items """ return list(map(lambda x: x.strip(), inp.split(',')))
def extension_checker(extensions, file_name): """Check given file names with extensions""" for extension in extensions: # if extension is not matched pass this loop if (file_name.endswith(extension)) == True: return True # if extensions not matched with the file's exte...
def name_item_info(mosaic_info, item_info): """ Generate the name for a mosaic metadata file in Azure Blob Storage. This follows the pattern `metadata/quad/{mosaic-id}/{item-id}.json`. """ return f"metadata/quad/{mosaic_info['id']}/{item_info['id']}.json"
def calc_padding(img_width, stride, dilation, filter_width): """ calculate pixels to padding in order to keep input/output size same. """ filter_width = dilation * (filter_width - 1) + 1 if img_width % stride == 0: pad_along_width = max(filter_width - stride, 0) else: pad_along_width = ...
def _get_auth_kwargs(config): """Generate the kwargs for the AWS keys from a configuration dictionary. If credentials are not present in the config, then assume that we're using IAM roles with instance profiles. :mod:`boto` will automatically take care of using the credentials from the instance met...
def _encoded_cookies(cookies): """Encode dict of cookies to ascii string""" return ('&'.join('{0}={1}'.format(k, v) for k, v in cookies.items())).encode("ascii")
def alive_and_well(xml_obj): """ Simple conversion function that uses 'deceased' and 'aw' fields from the xml person object to determine Individual 'life_status' Args: xml_obj (dict): xml data for the individual Returns: str: life_status """ if xml_obj['deceased'] == '1': ...
def parse_ref_words(argstr): # address: (expect, mask) """ All three of thse are equivilent: ./solver.py --bytes 0x31,0xfe,0xff dmg-cpu/rom.txt ./solver.py --bytes 0x00:0x31,0x01:0xfe,0x02:0xff dmg-cpu/rom.txt ./solver.py --bytes 0x00:0x31:0xFF,0x01:0xfe:0xFF,0x02:0xff:0xFF dmg-cpu/rom.txt ...
def get_git_version(git='git'): """Use ``git describe`` to generate a version string. Parameters ---------- git : :class:`str`, optional Path to the git executable, if not in :envvar:`PATH`. Returns ------- :class:`str` A :pep:`386`-compatible version string. Notes ...
def point_in_polygon(x, y, polygon): """ Check if a point is inside a polygon - x,y - Coordinates of the point - polygon - List of the vertices of the polygon [(x1, x2), (x2, y2), ..., (xn, yn)]""" i = 0 j = len(polygon) - 1 res = False for i in range(len(polygon)): i...
def to_d(l): """ Converts list of dicts to dict. """ _d = {} for x in l: for k, v in x.items(): _d[k] = v return _d
def trapezoidal_command(CurrTime, Distance, Vmax, Accel, StartTime=0.): """ Function to generate a trapezoidal velocity command Arguments: CurrTime : The current timestep or an array of times Distance : The distance to travel over Vmax: The maximum velocity to reach Accel: The a...
def _search_string(username): """ Construct the search string to be used for creating the recent tiddlers for this username. """ return 'modifier:%s _limit:20' % username
def _safe_str_cmp(a, b): """ Internal function to efficiently iterate over the hashes Regular string compare will bail at the earliest opportunity which allows timing attacks """ if len(a) != len(b): return False rv = 0 for x, y in zip(a, b): rv |= ord(x) ^ ord(y) ...
def listize(x): """Returns a list with a thing in it, unless the thing is already a list""" return [x] if type(x) is not list else x
def persistent_connection(obj): """An adapter which gets a ZODB connection from a persistent object We are assuming the object has a parent if it has been created in this transaction. Raises ValueError if it is impossible to get a connection. """ cur = obj while not getattr(cur, '_p_jar', ...
def calculate_total_emisisons(clinker_emissions, power_emissions, capture_ratio=0.0): """ Calculate the added emissions of the cement production unit :param clinker_emissions: emissions related to the clinker production :param power_emissions: emissions related to the energy production :param captur...
def color_string(color_number, text): """Return the text with color codes for the given color.""" return '\x1b[{0}m{1}\x1b[0m'.format(color_number, text)
def doc_key(locale, doc_slug): """The key for a document as stored in client-side's indexeddb. The arguments to this function must be strings. """ return locale + '~' + doc_slug
def awesome(text): """- Prints a webpage to show <nick> how awesome they are.""" link = 'http://is-awesome.cool/{}' nick = text.split(' ')[0] return "{}: I am blown away by your recent awesome action(s). Please read \x02{}\x02".format( nick, link.format(nick) )
def merge(list1, list2): """ Merge two sorted lists. Returns a new sorted list containing those elements that are in either list1 or list2. This function is iterative. """ first_list = list(list1) second_list = list(list2) merged_list = [] # iterating until one of the lists is...
def format_name(s): """ Converts VPR parenthesized name to just name. """ assert s[0] == '(' assert s[-1] == ')' return s[1:-1]
def _get_default_setuptools_abi(platform_string, pyver): """ Try to guess the ABI for setuptools eggs from the platform_string and pyver parts. Parameters ---------- platform_string: str The platform part of the setuptools egg filename as a string. If None, understood as a cross pla...
def stringToBool(string): """ Converts a string with the contents 'true' or 'false' to the appropriate boolean value. Examples: >>> stringToBool( 'true' ) True >>> stringToBool( 'false' ) False >>> stringToBool( 'True' ) Traceback (most recent call last): ... ValueErr...
def flatten_(structure): """Combine all leaves of a nested structure into a tuple. The nested structure can consist of any combination of tuples, lists, and dicts. Dictionary keys will be discarded but values will ordered by the sorting of the keys. Args: structure: Nested structure. Returns: F...
def encode_number(number): """ Encodes the number as a symbol. The buckets are: (-inf, 0.001, 0.01, 0.1, 1.0, 10.0, 25.0, 50.0, 75.0, 100.0, +inf) :param float number: a float number :return str: the encoded number """ if number < 0.001: return '>number_0001' elif number < 0.01:...
def mask_ip(addr): """Mask a given IP address to the beginning bit """ if addr is None: return '' # ipv6 or IPv4 mapped IPv6 if ':' in addr: data = addr.split(':', maxsplit=5)[:4] return "{}:{}:{}:{}:xxxx:xxxx:xxxx:xxxx".format(*data) # ipv4 elif '.' in addr: ...
def levenshtein(s1, s2, weights=(1, 1, 1)): """ python implementation of a generic Levenshtein distance this is much less error prone, than the bitparallel C implementations and is therefor used to test the C implementation However this makes this very slow even for testing purposes """ row...
def feb2(n): """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a + b return result
def polygon_area(polygon): """ Computes the area of a polygon. polygon: list of tuples representing points (x, y). first and last point should be the same. return: the polygon area """ w=0 for count in range(len(polygon)-1): y = polygon[count+1][1] + polygon[count][1] ...
def calculate_mm_volumes(num_rxns): """ calculate_mm_volumes Description: Calculates volumes of reagents needed to make master mix depending on number of reactions (num_rxns) Parameters: num_rxns: (int) number of rxns to perform (1-96) Output: mm_volumes_dict: dictionatry of maste...
def relpath(path, start): """Return a relative version of a path""" from os.path import abspath, sep, pardir, commonprefix from os.path import join as path_join if not path: raise ValueError("no path specified") start_list = abspath(start).split(sep) path_list = abspath(path).split(sep) ...
def detect_format_from_location(location): """Try to detect the format from the given location and return None if it fails.""" fmt = None location_lower = location.lower() known_formats = ['jpeg', 'jpg', 'png', 'gif', 'webp', 'svg', 'pdf', 'eps', 'ps'] for candidate in known_formats: if loca...
def SUB_STR_CP(string, index, count): """ Returns the substring of a string. The substring starts with the character at the specified UTF-8 code point (CP) index (zero-based) in the string for the number of code points specified. https://docs.mongodb.com/manual/reference/operator/aggregation/substrC...
def RestrictDict( aDict, restrictSet ): """Return a dict which has the mappings from the original dict only for keys in the given set""" restrictSet = frozenset( restrictSet ) return dict( item for item in aDict.items() if item[0] in restrictSet )
def float_parameter(level, maxval): """Helper function to scale `val` between 0 and maxval. Args: level: Level of the operation that will be between [0, `PARAMETER_MAX`]. maxval: Maximum value that the operation can have. This will be scaled to level/PARAMETER_MAX. Returns: A float that result...
def clean_other_names(name_list): """ cleaning birthday entries where the year is not a link (2nd, 3rd, 4th birthdays in a year) :param name_list: list of names :return: """ # throw anything out with a length <5, exception for 4 letter names # throw out end wikipedia info at the end # ma...
def fibonacci(n): """ Return the n_th Fibonnaci number $F_n$. The Fibonacci sequence starts 0, 1, 1, 2, 3, 5, 8, ..., and is defined as $F_n = F_{n-1} + F_{n-2}.$ >>> fibonacci(0) 0 >>> fibonacci(5) 5 >>> fibonacci(10) 55 """ fibs = [1, 1] for i in range(2, n+1): ...
def parse_msgid_article(obj): """Parse a message-id or article number argument. Args: str: Message id or article as a string. Returns: The message id as a string or article number as an integer. """ try: return int(obj) except ValueError: pass return obj
def _normalize_encoding(encoding): """returns normalized name for <encoding> see dist/src/Parser/tokenizer.c 'get_normal_name()' for implementation details / reference NOTE: for now, parser.suite() raises a MemoryError when a bad encoding is used. (SF bug #979739) """ if encoding is ...
def data_to_toml(data, filetype='toml', filter_fields=[], taxonomy_fields=[]): """ Takes a list of pairs and turns it into TOML format """ content = "" fields = {} for a,b in data: if a not in filter_fields: fields[a] = b if filetype=="md": ...
def get_arxiv_id_or_ascl_id(result_record): """ :param result_record: :return: """ identifiers = result_record.get("identifier", []) for identifier in identifiers: if "arXiv:" in identifier: return identifier.replace("arXiv:", "") if "ascl:" in identifier: ...
def get_modified(raw): """ Extract last modification date of Libris post. To be used as 'published' date in reference note on Wikidata. @param raw: json object of a Libris edition @type raw: dictionary """ return raw["modified"]
def sim_lorentz_gamma(x, x0, gamma): """ Simulate a Lorentzian lineshape with unit height at the center. Simulates discrete points of the continuous Cauchy-Lorentz (Breit-Wigner) distribution with unit height at the center. Gamma (the half-width at half-maximum, HWHM) is used as the scale paramet...
def _cmplx_div_ ( s , o ) : """divide complex values >>> r = v / other """ return ( 1.0 / o ) * complex ( s )
def get_variants(perfyaml): """ Return a list of strings with the variant names for the project :param dict perfyaml: Input perf.yml file :rtype list: List of variant names """ return [variant["name"] for variant in perfyaml["buildvariants"]]
def ordinal(n): """Get the ordinal format of an integer number.""" # Source: https://stackoverflow.com/a/20007730 return "{:d}{:s}".format( n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10 :: 4] )
def char_half_to_full_width(uchar): """Convert half width chars to full width chars.""" inside_code = ord(uchar) if inside_code < 0x0020 or inside_code > 0x7e: return uchar if inside_code == 0x0020: inside_code = 0x3000 else: inside_code += 0xfee0 return chr(inside_code)
def are_users_same(users): """True if all users are the same and not Nones""" x = set(u.get('seq') for u in users) return len(x) == 1 and None not in x
def is_printable(char): """Determines whether a character can be displayed directly. Used for testing if some content should be treated as text or binary. :param char: Character to be tested :type char: str :rtype: bool """ char_code = ord(char) return (char_code >= 32) or (9 <= char_c...
def parse_none_or_string(value): """ This function is primarily used to parse command-line arguments. Whenever the string 'None' is passed, it will return it as None, otherwise it will return whatever it was passed as a string. """ if value == 'None': return None return value
def application_id(config): """Returns the application_id from the configuration. :param config: Configuration to extract the application_id from. :type config: dict :returns: The application_id from the configuration. :rtype: str """ return config['application_id']