content
stringlengths
42
6.51k
def _truncate_string_left(strg, maxlen): """ Helper function which truncates the left hand side of a string to the given length and adds a continuation characters, "...". """ if len(strg) > maxlen: lhs = maxlen - 4 strg = "... %s" % strg[-lhs:] else: ret...
def unstructured_size(dim_data): """ Get a size from an unstructured dim_data. """ return len(dim_data.get('indices', None))
def resolve_projects(single_project_filter): """Return source and destination project names from a src:dst string""" mapping = single_project_filter.split(':') src_project = mapping[0] dst_project = mapping[1] if len(mapping) > 1 else src_project return src_project, dst_project
def round_to(value: float, target: float) -> float: """ Round price to price tick value. """ return int(round(value / target)) * target
def createBackyard(width, height): """ This function initializes an empty 'backyard'. It takes as parameters the width and height of the desired backyard. It returns the empty backyard (grid of dots). """ row = int(height) column = int(width) backyard = [ [ ' . ' for i in range(c...
def is_improvement( best_value: float, current_value: float, larger_is_better: bool, relative_delta: float = 0.0, ) -> bool: """ Decide whether the current value is an improvement over the best value. :param best_value: The best value so far. :param current_value: The cur...
def readprocessingTime(pfile): """ Read processing time from a file """ try: f = open(pfile) s = f.readline().strip() # = f.read() f.close() T = float(s) except: T = None pass return T
def min_max_x_y(coordinates): """Returns min and max X and Y coordinates of the original set of points""" min_x = coordinates[0][0] max_x = coordinates[0][0] min_y = coordinates[0][1] max_y = coordinates[0][1] for i in coordinates: if i[0] < min_x: min_x = i[0] if ...
def f1_semeval(pred_spans, true_spans): """ F1 (a.k.a. DICE) operating on two lists of offsets (e.g., character). >>> assert f1([0, 1, 4, 5], [0, 1, 6]) == 0.5714285714285714 :param predictions: a list of predicted offsets :param gold: a list of offsets serving as the ground truth :return: a sco...
def unlist(listed, d=','): """takes a list and converts to delimiter-separated string; comma delimited by default""" unlisted=(d.join(a for a in listed)) return unlisted
def mean(lst): """Compute and return mean of numbers in a list The numpy average function has horrible performance, so implement our own mean function. Args: lst: The list of numbers to average. Return: The mean of members in the list. """ return sum(lst) / len(lst)
def short_stat(decoded_diff): """Get the commit data from git shortstat.""" added = None deleted = None changes = decoded_diff.split(",") for i in changes: if "+" in i: added = [int(s) for s in i.split() if s.isdigit()][0] if "-" in i: deleted = [int(s) for s ...
def scale_to(x, from_max, to_min, to_max): """Scale a value from range [0, from_max] to range [to_min, to_max].""" return x / from_max * (to_max - to_min) + to_min
def check_answer(user_guess, start_a_followers, start_b_followers): """Take user guess and follwer count and return it they guess right""" if start_a_followers > start_b_followers: return user_guess == 'a' else: return user_guess == "b"
def nextpow2(i): """ Find 2^n that is equal to or greater than. code taken from the website: http://www.phys.uu.nl/~haque/computing/WPark_recipes_in_python.html """ n = 2 while n < i: n = n * 2 return n
def get_obs_exp_ratio(seq): """ Obs/Exp CpG = Number of CpG * N / (Number of C * Number of G) :param seq: :return: """ cpg = seq.count('cg') # fudge factors to avoid ZeroDivision c = max(1, seq.count('c')) g = max(1, seq.count('g')) return round((cpg * len(seq)) / (c * g), 3)
def group(sequence): """ Groups items of a sequence according to default comparer and creates result values as (key, group) pairs. Args: sequence: iterable Sequence of items to go through. Returns: ((any, (any,)),) Grouped items as (key, group) pairs...
def sum_to_k(nums, k): """Solution to exercise C-4.21. Suppose you are given an n-element sequence, S, containing distinct integers that are listed in increasing order. Given a number k, describe a recursive algorithm to find two integers in S that sum to k, if such a pair exists. What is the runni...
def sanitize_cfn_resource_name(name): """ Sets Logical Name in CloudFormation """ name = ''.join([n.title() for n in name.split('-')]) return name
def _check_object_types(source, target, prop): """Check if objects with same name have different types. In such a case we need to subclass from one higher level. """ if 'type' in source: if source['type'] != 'array': return source['type'] != target[prop] else: # ...
def pep8_filter(line): """ Standard filter for pep8. """ if 'argweaver/bottle.py' in line: return False return True
def subtractFrom(acc, curr): """Subtraction formatter""" return "{} - {}".format(acc, curr)
def solve(seats): """Find the missing seat from the occupied <seats>. I used my own implementation of insertion sort to solve this one. """ sort_s = [False] * 2**10 for i in seats: sort_s[i] = True our_s = 0 for i, _ in enumerate(sort_s): if not sort_s[i] and sort_s[i - 1] a...
def parse(message): """Parse a message.""" message_parts = message.split(";") message_type = message_parts[0] content = message_parts[1].strip() return message_type, content
def str2bool(s): """ Convert a string to a boolean value. The supported conversions are: - `"false"` -> `False` - `"true"` -> `True` - `"f"` -> `False` - `"t"` -> `True` - `"0"` -> `False` - `"1"` -> `True` - `"n"` -> `False` - `"y"` -> `True` - `"no"` -> `False` - `"yes...
def list_filter(function, iterable): """my_filter(function or None, iterable) --> filter object Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.""" if function is None: return (item for item in iterable if...
def rescale_linear(array, minimum, maximum): """Rescale back to pytorch format.""" new_min, new_max = -1, 1 m = (new_max - new_min) / (maximum - minimum) b = new_min - m * minimum return m * array + b
def filter_sentences_by_mentions(sentences,names): """ Recieves a list of sentences and a list of names. Returns the sentences in which at leas one of the mentioned names appear. """ # filter(lambda x: any(name in sentence for name in names),sentences) sents = [] for sentence in sentenc...
def _get_score_(psm): """ :param psm: peptide to spectrum match dictionairy :return: XCorr score (if not available XCorr = 0) """ hit=0 hit_key='' score={} #print psm.keys() for key in psm: if "score" in key.lower(): hit=1 hit_key=key if hit==1: ...
def signum(x): """ Give info about the sign of the given int. :param int x: Value whose sign is asked :return: -1 if the given value is negative, 0 if it is null, 1 if it is positive :rtype: int """ return -1 if x < 0 else 0 if x == 0 else 1
def check_joint_limits_respected(lower_joint_limits, upper_joint_limits, joints_configuration_query): """ Generates a circle trajectory :param lower_joint_limits: upper joint limits :param upper_joint_limits: lower joint limits :param joints_configuration_query: joints configuration to be checked ...
def roessler(XYZ, t, a=0.2, b=0.2, c=5.7): """ The Roessler Attractor. x0 = (1,1,1) """ x, y, z = XYZ x_dt = -(y + z) y_dt = x + a * y z_dt = b + z * (x - c) return x_dt, y_dt, z_dt
def FASTEP_to_mm(vals, delta_val=False): """ Use CXC calibration value to convert from focus assembly steps to mm. """ fastep = (1.47906994e-3 * vals + 3.5723322e-8 * vals**2 + -1.08492544e-12 * vals**3 + 3.9803832e-17 * vals**4 + 5.29336e-21 * vals**5 + 1.020064e-25 * vals**6) return ...
def remove_empty_els(t_v): """ Returns a list that doesn't contain empty strings. :param list t_v: list of elements :return list t_parsed_v: list of elements (no empty strings) """ t_parsed_v = [] for el in t_v: if el.strip() != "": t_parsed_v.append(el.strip()) retu...
def token_start(token, ending, start_min_length): """Given an ending, returns the start of a token if possible""" if token.endswith(ending) and len(token) > len(ending): start = token[:-len(ending)] if len(start) >= start_min_length: return start return None
def _ignore_old_dead_container(container, created_before=None): """ Returns True or False to determine whether we should ignore the logs for a dead container, depending on whether the create time of the container is before a certain threshold time (specified in seconds since the epoc...
def lc_valid_number(x): """ From https://leetcode.com/problems/valid-number Validate if a given string is numeric. Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. Examples: >>> lc_valid_number("0") Tru...
def binary_search_for_right_range(mz_values, right_range): """ Return the index in the sorted array where the value is smaller or equal than right_range :param mz_values: :param right_range: :return: """ l = len(mz_values) if mz_values[0] > right_range: raise ValueError("No value...
def get_intf_ids(apic, args, switch_attributes): """ Get the list of Physical Interface IDs from the command line arguments. If none, get all of the node ids :param apic: Session instance logged in to the APIC :param args: Command line arguments :return: List of strings containing Interface ids ...
def set_or_callable(value): """Convert single str or None to a set. Pass through callables and sets.""" if value is None: return frozenset() if callable(value): return value if isinstance(value, (frozenset, set, list)): return frozenset(value) return frozenset([str(value)])
def starmap(function, argument_list): """Apply a univariate function to a list of arguments in a serial fashion. Uses the starmap() function from itertools in Python's standard library and Python's built-in zip() function. Args: function: A callable object that accepts one argument arg...
def check_typename(arg_name, arg_type, valid_types): """Does it contain the _name_ attribute.""" def get_typename(t): return t.__name__ if hasattr(t, '__name__') else str(t) if arg_type in valid_types: return arg_type type_names = [get_typename(t) for t in valid_types] if len(valid_...
def _scrub_links(links, name): """ Remove container name from HostConfig:Links values to enable comparing container configurations correctly. """ if isinstance(links, list): ret = [] for l in links: ret.append(l.replace("/{}/".format(name), "/", 1)) else: ret ...
def get_duplicate_emails(participants): """ Creates a list of duplicate emails in the db. Emails need to be unique, so these users will be handled separately. """ email_list = [] for participant in participants: email_list.append(participant.get('attributes').get('email')) return [email...
def compute_iou(rec1, rec2): """ computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ # computing area of each rectangles S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]) S_r...
def cleanArray(arr): """ Simply util that removes empty items from an array and returns cleaned array """ return list(filter(None, arr))
def point2ituple(point): """ Returns an integer tuple for a floating point point. """ return tuple([int(x) for x in point])
def formatted_float(f, precision=2): """ Returns formatted float value to given precision (or less). :param float f: Float value. :return: Formatted float value. :rtype: str """ return "{:.{precision}f}".format(f, precision=precision).rstrip("0").rstrip(".")
def get_text_documents(mmif_obj): """Returns a dictionary of all text documents, indexed on the identifier.""" docs = {} for view in mmif_obj['views']: for annotation in view['annotations']: if 'TextDocument' in annotation['@type']: full_id = "%s:%s" % (view['id'], annota...
def clean_votes(candidates, votes): """ params: - candidates (list 'a): The list of candidates - votes (list (dict {'a : Ord 'b})): The list of votes, which are candidates mapped to a preference returns: - cleaned votes (list (dict {'a : Ord 'b})) Cleans votes by adding a 0 for each non-present candidate...
def mock_event(player1: dict, player2: dict) -> dict: """ Fixture to create an AWS Lambda event dict :param player1: Input character 1 see above :param player2: Input character 2 see above :return: Mock event dict """ return {"body": {"Player1": player1, "Player2": player2}}
def cc_to_cb(s, enc, cc): """convert char count to byte count arguments: s -- unicode string enc -- encoding name cc -- char count """ if cc == -1: return -1 s = s.encode('UTF-32LE') clen = cc * 4 if clen > len(s): raise IndexError return len(s[:cle...
def texmrm(string): """Format given string into mathmode with mathrm r"\\$\mathrm{string}$" :string: str :returns: str """ return r"$\mathrm{"+string+"}$"
def minimum_absolute_difference(arr): """Hackerrank Problem: https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem Given an array of integers, find and print the minimum absolute difference between any two elements in the array. Solve: Sort the array, and then compa...
def _is_under_dir(file_name: str, dir_name: str) -> bool: """ Return whether a file is under the given directory. """ subdir_names = file_name.split("/") return dir_name in subdir_names
def make_member_decls(members): """Semicolon-terminated type name list used in member declaration. int i; char j; """ return "\n".join("{} {};".format( type.as_member, name ) for type, name in members)
def prepare_service(data): """Prepare service for catalog endpoint Parameters: data (Union[str, dict]): Service ID or service definition Returns: Tuple[str, dict]: str is ID and dict is service Transform ``/v1/health/state/<state>``:: { "Node": "foobar", ...
def compute_precision(true_positives, false_positives): """Compute precision >>> compute_precision(0, 10) 0.0 >>> compute_precision(446579, 13932) 0.969747 """ return true_positives / (true_positives + false_positives)
def rprpet_point(pet, snowmelt, avh2o_3, precip): """Calculate the ratio of precipitation to ref evapotranspiration. The ratio of precipitation or snowmelt to reference evapotranspiration influences agdefac and bgdefac, the above- and belowground decomposition factors. Parameters: ...
def make_download_status(queue, pieces): """ Make a queue readable. """ def get_status(pieces, piece, downloading): """ Nicely looking status. """ status = "[ ]" if pieces[piece] is True: status = "[#]" if piece in downloading: ...
def update(event, context): """ Place your code to handle Update events here To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events. """ physical_resource_id = event['PhysicalResourceId'] response_data = {} return physica...
def interleave(list_a, list_b): """ >>> interleave([0, 2, 4, 6], [1, 3, 5]) [0, 1, 2, 3, 4, 5, 6] https://stackoverflow.com/a/7947461 """ size_a, size_b = len(list_a), len(list_b) if size_a - size_b not in (0, 1): raise ValueError("The lists' sizes are too different: ({}, {})" ...
def fmt_states(device: str, indent: str) -> str: """Format state entries for the given device. Args: device: Device name. indent: Intentation. Returns: State entries to be appended to the device. """ return "\n".join( ( f"{indent}pinctrl-0 = <&{device}_...
def is_equal_or_contians(url1, url2): """ Check if two url is the same or contains each other Args: url1: url2: Returns: true or false """ return url1 == url2 or url1 in url2 or url2 in url1
def bbcMicro_partPhonemeCount(pronunc): """Returns the number of 'part phonemes' (at least that's what I'm calling them) for the BBC Micro phonemes in pronunc. The *SPEAK command cannot take more than 117 part-phonemes at a time before saying "Line too long", and in some cases it takes less than that (I'm not sure...
def indices_of_nouns(tokens): """Return indices of tokens that are nouns""" return [i for i, (_, pos) in enumerate(tokens) if pos.startswith('N')]
def last(sequence): """Get the last element of a sequence. Parameters ---------- sequence : Sequence[A] The sequence from which to extract an element. Returns ------- A The last element of the sequence. """ return sequence[-1]
def no_digit(s): """ Remove digits from string. Args ---- s: str String to remove digits from. """ return "".join((x for x in s if not x.isdigit()))
def parseCondaForOS(libs,opSys): """ Modifies the list of Conda for a particular operating system. @ In, libs, list, list of libraries as (lib,version) @ In, opSys, string, name of operating system (mac, windows, linux) @ Out, libs, updated libs list """ if opSys == 'windows': pass # nothing s...
def fasta_header(exp, N): """Generates random headers for the fasta file Parameters ---------- exp : str name of experiment (no spaces) N : int number of headers to be generated Returns ------- headers : list names for each sequence (arbritrary) """ ...
def _parse_kwargs_string(s): """ Parses string and returns a dictionary. All values are strings. :param s: string specifying key/value pairs in format: X=Y,A=10,B=hello :return: dictionary of parsed content """ if not s: return {} d = dict([item.split("=") for item in s.split(";")]) retu...
def tag(name, *content, class_=None, **attrs): """Generate one or more HTML tags""" if class_ is not None: attrs['class'] = class_ if attrs: attr_pairs = (f' {attr}="{value}"' for attr, value in sorted(attrs.items())) attr_str = ''.join(attr_pairs) else: ...
def _get_embl_key(line): """Return first part of a string as a embl key (ie 'AC M14399;' -> 'AC')""" # embl keys have a fixed size of 2 chars return line[:2]
def to_uint256(value: int) -> bytes: """Encodes an unsigned integer as a big endian uint256.""" return value.to_bytes(32, "big")
def addBinary(a, b): """ :type a: str :type b: str :rtype: str """ #If one of the strings is null, return the non null one if not a or not b: return a or b #If both strings end with a 1, add a 0 at the end, let the 1 overflow into the addition of the two strings again if a[-1] == '1'...
def get_table_name(full_qualified_table_name): """Extracts the table name form a full qualified table name. Parameters ---------- full_qualified_table_name : str, mandatory A full qualified table name (i.e. schema name and table name) Returns ------- The table name or None. """...
def newPipe(x, y, w, h): """ Create pipe object """ return { "type": "rectangle", "pos": [x,y], "dim": [w, h] }
def _escaped_str(text: str) -> str: """Escape the text and returns it as a valid Golang string.""" return '"{}"'.format( text.replace('\\', '\\\\').replace('"', '\\"').replace('\a', '\\a').replace('\f', '\\f').replace('\t', '\\t') .replace('\n', '\\n').replace('\r', '\\r').replace('\v', '\\v'))
def dict_get(item, *keys): """ nested dict `get()` >>> example={1: {2: 'X'}} >>> dict_get(example, 1, 2) 'X' >>> dict_get(example, 1) {2: 'X'} >>> dict_get(example, 1, 2, 3) is None True >>> dict_get(example, 'foo', 'bar') is None True >>> dict_get('no dict', 'no key') i...
def most_common(lst): """ This method returns the most frequent value in an array """ y = {} for i in lst: if i != "": if i in y: y[i] += 1 else: y[i] = 1 most_frequent_value = 0 most_frequent_key = "" for key in y.keys(): ...
def F(param): """Fitness function to be maximized, parameterized using the variables A and B. Has to return a float value, representative of the 'quality' of the parameters. The fitness is higher when better the parameters are chosen.""" A=param['A'] B=param['B'] f=(A**2 + B**2)/2.0...
def get_colors(classifications): """Take a list of classifications ("het", "hom", anythingElse) and returns corresponding list of colors for the coverage graphs. Returns: A list of colors ("red", "green", "purple"). """ colors = [] for cl in classifications: if(cl == 'he...
def defaults_add(dictionary, defaults): """if a value has not been defined in the dictionary add it from defaults""" if dictionary: for key in defaults.keys(): if not key in dictionary.keys(): dictionary[key] = defaults[key] return dictionary else: return ...
def first(nodes): """ Return the first node in the given list, or None, if the list is empty. """ if len(nodes) >= 1: return nodes[0] else: return None
def validate_list_of_numbers_from_csv(data): """ Converts a comma separated string of numeric values to a list of sorted unique integers. The values that do not match are skipped. :param (str, iterable) data: - str | iterable :return: - list(int) """ if isinstance(data, str): ...
def affine(x, W, b): """Apply affine transformation to `x` by computing `Wx + b` and return a list with the dimensions of `b`. Args: x (list): List that is to be transformed. 1 dimensional. W (list): List representing the transformation. 2 dimensional. b (list): List that is added t...
def about(topic): """Return a select function that returns whether a paragraph contains one of the words in TOPIC. >>> about_dogs = about(['dog', 'dogs', 'pup', 'puppy']) >>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup!'], about_dogs, 0) 'Cute Dog!' >>> choose(['Cute Dog!', 'That is a cat....
def remove_domain(hn): """Removes domain suffix from provided hostname string Args: hn (str): fully qualified dns hostname Returns: str: hostname left by removing domain suffix """ return hn.split(".")[0]
def trunc_end_of_file(name) -> str: """ Take only the start of the filename to avoid error with Python and Windows :param str name: Filename to truncate :return str: """ return name[:240]
def ngram_to_number(ngram: str) -> int: """ Assumes all letters are capitalized """ number = 0 for char in ngram: number = number * 26 + ord(char) - ord('A') return number
def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i
def zone_is_hot_water(zone): """ Is this a hot water zone """ return zone["ishotwater"]
def car_by_colour(parkingLot, inputColour): """ prints the registration number of the cars for the given colour ARGS: parkingLot(ParkingLot Object) inputColour(str) - given Colour """ returnString = '' if parkingLot: if not parkingLot.get_parked_cars(): retur...
def parse_credentials(creds): """ Parses a credentials string. The first part is the password which is separated by a forward-slash to the host-name. The host-name is separated by a double-colon to the port-name. Returns a tuple of ``(password, host, port)``. A *ValueError* is raised if the for...
def kv2dict(s, convertor=str): """Primitive ad-hoc parser of a key-value record list. * The string *s* should contain each key-value pair on a separate line (separated by newline). The first white space after the key separates key and value. * Empty lines are allowed. * Comment lines (sta...
def formatbytes(bytes: float): """ Return the given bytes as a human friendly KB, MB, GB, or TB string """ bytes_float = float(bytes) KB = float(1024) MB = float(KB ** 2) # 1,048,576 GB = float(KB ** 3) # 1,073,741,824 TB = float(KB ** 4) # 1,099,511,627,776 if bytes_float < KB: ...
def process_predicted_qdmr(predicted_qdmr): """Converts a predicted qdmr string to standard qdmr E.g., from "the writer of The Bet born @@SEP@@ In what year was @@1@@"" to "the writer of The Bet born ; In what year was #1" Parameters ---------- predicted_qdmr : str String repres...
def errs_tab(n): """Generate list of error rates for qualities less than equal than n.""" return [10**(q / -10) for q in range(n + 1)]
def y_dot(time, x): """ function to test algorithm """ return -x[0]
def clear_empty_strings(data): """ Remove empty string values from data structs. For dict, deletes the empty string value and any corresponding key. Since dicts are passed as references, dict changes are also in-place. Returns the modified version of the data. """ if isinstance(data, dict):...