content
stringlengths
42
6.51k
def expand_from_middle(string: str, left: int, right: int) -> str: """Return the longest palindrome centred around the indices left and right. left == right for palindrome of odd length left == right + 1 for even length """ max_palindrome = "" while left >= 0 and right < len(string) and string[...
def read_file(path): """Returns contents of a given file or None if not readable.""" try: with open(path, 'rb') as f: return f.read() except IOError: return None
def whatMajor(fName, listOfStudents): """ return the major of first student in listOfStudents with first name fName, False if none found >>> whatMajor("FRED",[Student("MARY","KAY","MATH"), Student("FRED","CRUZ","HISTORY"), Student("CHRIS","GAUCHO","UNDEC")]) 'HISTORY' >>> """ for i in ran...
def serialise_version(version): """ Convert a version tuple back to a string. """ return '.'.join(str(v) for v in version)
def getList(x): """ Convert any input object to list. """ if isinstance(x, list): return x elif isinstance(x, str): return [x] try: return list(x) except TypeError: return [x]
def is_file_type(file, extension=["psd", "tga"]): """ Returns True if the file has a given extension. Args: file (str): File name or full path. extension (list, optional): example: [ "PSD", "MB", "MAX", "TGA", "BMP", "GIF", "JPEG", "MNG", "PBM", "PGM", "PNG", "PPM", "XBM", "...
def chunks(file_names, threads): """Yield successive n-sized chunks from l.""" chunks = [] for i in range(0, len(file_names), threads): chunks.append(file_names[i:i + threads]) return chunks
def reversed_complement(string): """ Given: A DNA string s of length at most 1000 bp. Return: The reverse complement sc of s.""" complements = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A' } return "".join([complements[string[i]] for i in range(len(string))][::-1])
def reverse_by_index(string): """Reverses a string via indexing. :param string: The string to be reversed :type string: str :return: string reversed :rtype: str """ reverse_string = string[::-1] return reverse_string
def first_occurrence_of_tag(sequence, tag_type_or_types): """ Returns the position of the first tag with type tag_type_or_types in the sequence tag_type_or_types can be a string (exact match) or a list of strings (exact match any in the list) """ for i in range(0, len(sequence)): if isinsta...
def update_query_object(query, data, exceptions=[]): """Iterates over given data object. Set attributes to SQLAlchemy query. Args: query (obj): SQLAlchemy query object data (obj): Given request's arguments from JSON exceptions (list): Keys for which iteration ...
def _scale_annots_dict(annot, new_sz, ann_im_sz): """Scale annotations to the new_sz, provided the original ann_im_sz. :param annot: bounding box in dict format :param new_sz: new size of image (after linear transforms like resize) :param ann_im_sz: original size of image for which the bounding boxes we...
def chunkInto64CharsPerLine(data, separator=b'\n'): """Chunk **data** into lines with 64 characters each. :param basestring data: The data to be chunked up. :keyword basestring separator: The character to use to join the chunked lines. :rtype: basestring :returns: The **data**, as a string,...
def quickSort(array): """Apply quick sort to an array. Returns a sorted array.""" array.sort() return array
def is_end_of_group(string): """Determine if the given string should be interpreted as the end of a docstring identifier :param string: The string to use to determine if it's the end :returns: True if the string is the end of a group, otherwise false """ return string.strip() == "" or string.s...
def build_ngram_dict(words): """ Key: ngram (currently 2-word tuples) Values: A list of words that follow the ngram """ ngram_dict = {} for i, word in enumerate(words): try: first, second, third = words[i], words[i+1], words[i+2] except IndexError: break ...
def _comment(scanner, token): """token for a comment, this also captures any whitespace in front of the comment and newlines in the comment, so the indentation of the comment, and linebreaks are preserved without creating / parsing indent tokens. Any are also captured because """ return "comment", token
def epsilon(ab_eps, bb_eps): """ Perform combining rule to get A+A epsilon parameter. Output units are whatever those are of the input parameters. :param ab_eps: A+B epsilon parameter :type ab_eps: float :param ab_eps: B+B epsilon parameter :type ab_eps: float :rtype...
def gc(DNA): """This command takes a seq as a string and returns the gc percentage of it.""" for i in DNA: if i not in 'AGCTN': return 'Invalid Seq' DNA = DNA.upper() nBases = DNA.count('N') gcBases = DNA.count('G') + DNA.count('C') precantage = (gcBases / (len(DNA) - nBases)...
def onlyeven_idx(i, x): """For keep indexed: needs to return None.""" if i%2 == 0: return x
def vect3_cross(u, v): """ Cross product. u, v (3-tuple): 3d vectors return (3-tuple): 3d vector """ return (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0])
def _process_ups(ups): # pragma: no cover """This function processes the UpdateInfo instances of the two undo stacks (clustering and cluster metadata) and concatenates them into a single UpdateInfo instance.""" if len(ups) == 0: return elif len(ups) == 1: return ups[0] elif len(...
def CoapOptionDelta(v): """To be used as n=CoapOptionDelta(v).""" if v < 13: return (0xFF & v) elif v <= 0xFF + 13: return 13 else: return 14
def count_change(total): """Return the number of ways to make change for total. >>> count_change(7) 6 >>> count_change(10) 14 >>> count_change(20) 60 >>> count_change(100) 9828 >>> from construct_check import check >>> # ban iteration >>> check(HW_SOURCE_FILE, 'count_cha...
def safe_str(obj): """ Return the byte string representation of obj """ try: return str(obj) except UnicodeEncodeError: # obj is unicode return str(obj).encode('unicode_escape')
def binary_search_iterative(lst, value): """ Searches for an value within a given list. This algorithm uses binary search in an iterative way. @param lst: a list containing numbers @param value: value to be found @return: True if the value has been found. Otherwise, False. """ ...
def parseTrackLog(line): """Parse trackLog line and return important fields: db, year, month, hgsid, and a list of tracks""" #### Sample line being processed #### # [Sun Mar 05 04:11:27 2017] [error] [client ###.###.###.##] trackLog 0 hg38 hgsid_### cytoBandIdeo:1,cloneEndCTD:2 #### spli...
def is_dotted_module_path(module_path): """ Returns whether given module path is a dotted one (tpDcc.libs.python.modules) or not :param module_path: str :return: bool """ return len(module_path.split('.')) > 2
def format_key(key: str, title: bool = True) -> str: """Return formatted key.""" key = ' '.join(key.split('_')) return key.title() if title and key.islower() else key
def file_ready_string(string): """ Change a string from 'Something Like This" to "something_like_this" for ease of saving it as a filename or directory name. Args: string: Returns: """ return string.replace(' ', '_').lower()
def do_rstrip(s): """ Removes all whitespace (tabs, spaces, and newlines) from the right side of a string. https://github.com/Shopify/liquid/blob/b2feeacbce8e4a718bde9bc9fa9d00e44ab32351/lib/liquid/standardfilters.rb#L100 """ return s.rstrip()
def get_mentions(mention_entity): """ - gets the user mentions and their string ids if available """ mentions = {'screen_names': [], 'string_id': []} if mention_entity is not None: for user in mention_entity: mentions['screen_names'].append(user['screen_name']) ...
def getTypeStringOrConversion(stringOrTypeOrClassOrFnOrObj): """Return a type string (for lookup) from type name (already a string), a type object, class object, or implicit conversion function; or compute the type of the object. Also return the conversion fn. if present. """ obj = stringOrTyp...
def negative_to_front(arr): """ Time Complexity : O(n) Space Complexity : O(1) """ pointer1, pointer2 = 0, len(arr) - 1 while pointer1 < pointer2: if arr[pointer1] >= 0 and arr[pointer2] >= 0: pointer2 -= 1 elif arr[pointer1] < 0 and arr[pointer2] < 0: ...
def is_string_empty(string: str) -> bool: """ Checks if a string is empty. :param string: The string to check :return: True if the string is empty; False otherwise """ return string is None or len(string) == 0
def parse_id_list(id_list) -> str: """ Converts a list of IDs to a comma-delimited string """ if isinstance(id_list, list): returned = "" for s in id_list: if len(returned) > 1: returned += "," returned += str(s) else: returned = id_list r...
def parse_visitor(d): """ Used to parse name of visiting team. """ return str(d.get("tUNaam", ""))
def stderr_stdout_captured(func): """Capture stderr and stdout Args: func: A function Returns: str, str, any: stderr output, stdout output, return of function """ import sys from io import StringIO old_stdout = sys.stdout old_stderr = sys.stderr captured_stderr = s...
def not_important(row, required_fields): """ Finds out if a row is important based based on the presence of data in all the required table columns. :param row: Input row :param required_fields: List of indices of required fields :rtype: bool """ return all([value for index, value in enu...
def clean_game(game: str, game_type: str): """Clean game string. These vary over the years, hence all the if-else's. """ clean_game = ( game_type + "_" + str(game) .strip() .lower() .replace(" ", "_") .replace("-", "_") .replace("dollars",...
def safe_equals(x,y): """ Handle "x = y" where x and y could be some combination of ints and strs. """ # Handle NULLs. if (x == "NULL"): x = 0 if (y == "NULL"): y = 0 # Easy case first. if (type(x) == type(y)): return x == y # Booleans and ints can be d...
def dict_to_obj(our_dict): """ Function that takes in a dict and returns a custom object associated with the dict. This function makes use of the "__module__" and "__class__" metadata in the dictionary to know which object type to create. """ if "__class__" in our_dict: # Pop ensures we ...
def rtd(raw_value): """Converts platinum RTD (resistance thermometer) output to degrees C. The temperature resolution is 0.1C per ADU, and the temperature range is -273C to +850C. The 16-bit digital number wraps below 0C to 2^16-1 ADU. This handles that conversion. """ tempRes = 0.1 # Module...
def multiply_odd(num): """ Return sum of multiple of all odd number below user specified range """ result = 1 for i in range(1,num, 2): result*=i return result
def expand_bar(bar): """ Expand a bar into 4 notes """ missing = 4-len(bar) # log.debug("Expanding bar %s, missing %s elements" % (bar,missing)) if missing == 1: return bar.append(bar[2]) elif missing == 2: return bar + [bar[0], bar[1]] elif missing == 3: return bar + [ba...
def get_floor(directions): """ Get the floor for Santa. Parameters ---------- directions : str A string of parentheses representing directions. An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor. R...
def escape(pattern): """escape(string) -> string Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. """ result = list(pattern) for i in range(len(pattern)): cha...
def take_while(predicate, collection): """Returns a list corresponding to the longest prefix of the original list for which all the values when tested against the given predicate return True >>> take_while(lambda x: x<=10, range(10000)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] """ payload = [] ...
def cache_resolved_get(reference): """ :param reference: :return: """ # for experiment disable cache return None try: reference_md5 = md5(reference.encode('utf-8')).hexdigest() resolved = redis_db.get(name=current_app.config['REDIS_NAME_PREFIX'] + reference_md5).decode('utf-...
def pipe_commands(commands): """Pipe commands together""" return ' | '.join(commands)
def motor_resistance_from_no_load_current( no_load_current ): """ Estimates the internal resistance of a motor from its no_load_current. Gates quotes R^2=0.93 for this model. Source: Gates, et. al., "Combined Trajectory, Propulsion, and Battery Mass Optimization for Solar-Regen..." https://s...
def mult_vec_mat(a, b): """Multiply vector times matrix for any indexable types.""" return [sum(ae*be for (ae, be) in zip(a, b_col)) for b_col in zip(*b)]
def StrippedStr(obj, maxlen=80): """Strings too long are useless anyway.""" if isinstance(obj, str): # Quote strings. b = "'%s'" % obj else: b = str(obj) if len(b) > maxlen: b = b[0:maxlen] + '...' return b
def make_iterable(arg): """Checks if ``arg`` is iterable. If not, makes it a one-element list. Otherwise returns ``arg``.""" try: iterator = iter(arg) return arg except TypeError: return [arg]
def mac_str_to_bytes(mac_str): """Convert mac address AA:BB:CC:DD:EE:FF to byte representation.""" return b"".join([bytes.fromhex(x) for x in mac_str.split(":")])
def join_key(*args): """ Examples -------- >>> join_key('building1', 'elec', 'meter1') '/building1/elec/meter1' >>> join_key('/') '/' >>> join_key('') '/' """ key = '/' for arg in args: arg_stripped = str(arg).strip('/') if arg_stripped: key ...
def reverse_order(array) -> list: """This function reverse array.""" return array[::-1]
def update(existing_aggregate, new_value): """ for a new value, compute the new count, new mean, the new M2. mean accumulates the mean of the entire dataset M2 aggregates the squared distance from the mean count aggregates the number of samples seen so far """ (count, mean, M2) = existing_ag...
def _get_query_variables(repo_owner, repo_name, family_name, reference='refs/heads/main'): """ call like: get_query_variables('google', 'fonts', 'gelasio') reference: see $ git help rev-parse and git help revisions and https://git-scm.com/book/en/v2/Git-Internals-Git-References For a br...
def merge_options(options): """preprocess options to remove duplicate""" alloptions = {} options = list(options) for i in range(len(options)-1, -1, -1): optname, optdict = options[i] if optname in alloptions: options.pop(i) alloptions[optname].update(optdict) ...
def keyword_set(kw): """ only true if ``kw`` is defined AND different from zero. here, ``None`` is used for non-defined keyword. """ return kw is not None and kw!=0
def compute_iou(bbox0, bboxes0): """ bbox0 is (cx, cy, scale, score, x, y, h, w) last 4 bit is the standard bbox. For this ignore score. """ def iou(boxA, boxB): boxA_area = boxA[2] * boxA[3] boxB_area = boxB[2] * boxB[3] min_x = max(boxA[0], boxB[0]) min_y = max...
def si(i): """ Sum of i-th square corners from the center Eg: si(1) = 9 + 7 + 5 + 3 """ return 4*((1 + 2*i)**2) - 12*i
def remove_version_from_guid(guid): """ Removes version from toolshed-derived tool_id(=guid). """ if "/" not in guid: return None last_slash = guid.rfind("/") return guid[:last_slash]
def IsConfigUserInputValid(user_input, valid_el): """Determines if user input within configuration scripts is valid. Each time a choice is presented to the user, a set of allowed values specific to that interaction is passed into this function. Args: user_input: The string of user input. valid_el: A l...
def checksum(string): """ Compute the Luhn checksum for the provided string of digits. Note this assumes the check digit is in place. """ digits = list(map(int, string)) odd_sum = sum(digits[-1::-2]) even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]]) return (odd_sum + even_...
def format_function_call(func_name, *args, **kwargs): """ Formats a function of a PipelineStage or Dataset object to ensure proper recording of the function and its arguments. args and kwargs should be exactly those passed to the function. Parameters ---------- func_name : str Name ...
def norm_text(textstring): """Takes a string of text and returns a string of normalized text.""" return "".join([c.lower() for c in textstring if c.isalnum() or c.isspace()])
def split_namespace(clark_name): """Return (namespace, localname) tuple for a property name in Clark Notation. Namespace defaults to ''. Example: '{DAV:}foo' -> ('DAV:', 'foo') 'bar' -> ('', 'bar') """ if clark_name.startswith("{") and "}" in clark_name: ns, localname = clark_name...
def all_equal(seq): """Return True iff all elements of the input are equal.""" fst, *rest = seq if not rest: return True return all(r == fst for r in rest)
def hamming(n): """Returns the nth hamming number""" hamming = [1] x = 1 while len(hamming) <= n * 3.5: new_hamming = [] print(len(hamming)) length = len(hamming) s = hamming if length >= 1000: s = hamming[int(length / 2) : length] for i in s...
def format_excludes(path, excludes): """ Format the excluded directory list. (verify that the path is not from the root of the volume or the root of the package) """ f_excludes = [] for exclude in excludes: if exclude[0] != '/' and exclude[:len(path)] != path: exclude = '...
def decodemeta(data): """Return string to string dictionary from encoded version.""" d = {} for l in data.split('\0'): if l: key, value = l.split(':') d[key] = value return d
def validate_predictivescalingmode(predictivescalingmode): """ Validate PredictiveScalingMode for ScalingInstruction Property: ScalingInstruction.PredictiveScalingMode """ VALID_PREDICTIVESCALINGMODE = ("ForecastAndScale", "ForecastOnly") if predictivescalingmode not in VALID_PREDICTIVESCALING...
def brute_force(numbers: list) -> int: """ Brute force for counting invertions This aproach not work for a large n :param numbers: list of numbers :return: number of invertions """ count = 0 for i, number in enumerate(numbers[:-1]): for compare in numbers[i+1:]: if n...
def extended_gcd(a, b): """ The function extended_gcd(a,b) returns three values: the greatest common divisor of a and b: d=gcd(a,b); and two numbers x and y such that d = ax + by """ # assert a >= b and b >= 0 and a + b > 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = exte...
def startNamespace(moduleConfig): """String for the start the header namespace""" string = [ 'namespace ' + s + '\n{\n' for s in moduleConfig['Namespace'] ] string = ''.join(string) return string
def cap_text(text): """capitalize() upper cases the first letter of a string.""" return text.capitalize()
def info_from_api_key(api_key: str, required_scopes: None) -> dict: """ Check and retrieve authentication information from api_key. Returned value will be passed in 'token_info' parameter of your operation function, if there is one. 'sub' or 'uid' will be set in 'user' parameter of your operation functi...
def calculate_tco_for_each_asset(capex, opex, discount_rate, current_year, year_deployed, asset_lifetime, end_year, repeating): """ - capex - opex - discount rate - current year - year deployed - asset lifetime - end_year - repeating """ repeating_capex_cost_year1 = capex / ...
def _id(value: str) -> str: """Coerce id by removing '-'.""" return value.replace("-", "")
def generic_cmp(value1, value2): """ Generic comparator of values which uses the builtin '<' and '>' operators. Assumes the values can be compared that way. Args: value1: The first value value2: The second value Returns: -1, 0, or 1 depending on whether value1 is less, equa...
def _is_num(data): """Verify if data is either int or float. Could be replaced by: from numbers import Number as number isinstance(data, number) but that requires Python v2.6+. """ return isinstance(data, int) or isinstance(data, float)
def any_in(collection, values): """ Check if any of a collection of values is in `collection`. Returns boolean. """ for value in values: if value in collection: return True return False
def modify_authors_state_dict(state_dict): """The state dicts prefixes don't match (ours is bert.xyz, their's is model.model.xyz. This function alters the naming in their state_dict to match""" from collections import OrderedDict new_state_dict = OrderedDict() for x in state_dict.items(): ...
def build_url( group_id, artifact_id, version, filename=None, base_url='https://repo1.maven.org/maven2', ): """ Return a download URL for a Maven artifact built from its POM "coordinates". """ filename = filename or '' if group_id: group_id = group_id.replace('.', '/') ...
def int_to_hex(i: int, length: int=1) -> str: """Converts int to little-endian hex string. `length` is the number of bytes available """ if not isinstance(i, int): raise TypeError('{} instead of int'.format(i)) range_size = pow(256, length) if i < -(range_size//2) or i >= range_size: raise OverflowError('cann...
def _discard_newlines(parm: str, start: int) -> int: """Discard any newline characters. :param parm: The parameter data. :param start: The start index. :return: The start index offset to discard any newlines """ pos = start while pos < len(parm): if parm[pos] not in ("\r", "\n"): ...
def get_sweep_parameters(parameters, env_config, index): """ Gets the parameters for the hyperparameter sweep defined by the index. Each hyperparameter setting has a specific index number, and this function will get the appropriate parameters for the argument index. In addition, this the indices wi...
def pathStepToPosGroupType(spot): """ Takes a substring from a pos field defining a single tree node and returns its position and group type (if it's an inner node). E.g. "0-all" """ pos_gtype_stc = spot.split("-") if len(pos_gtype_stc) == 3: pos = pos_gtype_stc[0] gtype = pos_...
def app_config(app_config): """Get app config.""" tests_config = { "APP_ALLOWED_HOSTS": "localhost", "CELERY_TASK_ALWAYS_EAGER": True, "CDS_ILS_LITERATURE_UPDATE_COVERS": False, "SQLALCHEMY_DATABASE_URI": "postgresql+psycopg2://invenio:invenio@localhost/invenio", ...
def parse_academic_year(year): """ Parses an academic year eg 2014/15 into an int with the first year """ return int(year.split("/")[0])
def uint8_to_float(uint8_color): """ Converts a uint8 color (0 to 255) to float (0 to 1.0) """ return tuple(map(lambda x: float(x) / 255.0, uint8_color))
def _get_phonopy_postprocess_info(phonon_settings): """Return phonopy postprocess parameters.""" valid_keys = ("mesh", "fc_calculator") params = {} for key in valid_keys: if key in phonon_settings.keys(): params[key] = phonon_settings[key] if "mesh" not in phonon_settings.keys()...
def _FormatSummary(value): """Formats a job's summary. Takes possible non-ascii encoding into account. """ return ','.encode('utf-8').join(item.encode('utf-8') for item in value)
def last(list): """Returns the last element of the given list or string""" for x in reversed(list): return x
def emf(w, q): """ Calculate and return the value of electromotive force using given values of the params How to Use: Give arguments for w and q params, *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE HARD TO UNDERSTAND AND USE.' Parameters: q (int):cha...
def calculate_time_fold(t, t0, p): """Function to get time-fold""" hp = 0.5 * p return (t - t0 + hp) % p - hp
def determineCard(playedCards, currentTrick, cardLed, hand): """ Determines a card to play based on the card led and the player's hand. Currently determines card to play according to the rules with some strategy. """ suit = cardLed[2] cardsOfSuit = [] # flags for if player has queen of spade...
def parse_date(val=None, return_timestamp=True, ms=False): """ Parse date from string or float/integer Input date can be either timestamp or date-time string If input value is integer and greater than 3000, it's considered as a timestamp, otherwise - as a year Args: val: value to pars...