content
stringlengths
42
6.51k
def dict_value_add(dict1, dict2): """Add values with same keys from two dictionaries.""" result = {key: dict1.get(key, 0) + dict2.get(key, 0) for key in set(dict1) | set(dict2)} ''' # This has an issue of only keeping track of >0 values! from collections import Counter result = dic...
def invite_more_women(arr: list) -> bool: """ Arthur wants to make sure that there are at least as many women as men at this year's party. He gave you a list of integers of all the party goers. Arthur needs you to return true if he needs to invite more women or false if he is all set. An a...
def ClockUsToTimestamp(clock_us, reference_clock_us, reference_timestamp): """Converts a reported clock measurement (in us) to a timestamp. Args: clock_us: Measured clock [us]. reference_clock_us: Measured clock at a reference moment [us]. reference_timestamp: Seconds after 1/1/1970 at the reference mo...
def chunkify(sequence, chunk_size): """Utility method to split a sequence into fixed size chunks.""" return [sequence[i: i + chunk_size] for i in range(0, len(sequence), chunk_size)]
def get_labels(voice_list, face_list): """ Take intersection between VoxCeleb1 and VGGFace1, and reorder pair with number starting from 0 :param voice_list: :param face_list: :return: x_dict format: { (int) label_id : {'filepath': (str) filepath, 'name': (str) celeb_name, 'label_id': (int) label...
def is_blank(line): """ Returns true iff the line contains only whitespace. """ return line.strip() == ""
def subfolders_in(whole_path): """ Returns all subfolders in a path, in order >>> subfolders_in('/') ['/'] >>> subfolders_in('/this/is/a/path') ['/this', '/this/is', '/this/is/a', '/this/is/a/path'] >>> subfolders_in('this/is/a/path') ['this', 'this/is', 'this/is/a', 'this/is/a/path']...
def keyExtract(array, key): """Returns values of specific key from list of dicts. Args: array (list): List to be processed. key (str): Key to extract. Returns: list: List of extracted values. Example: >>> keyExtract([ {'a': 0, ...}, {'a': 1, ...}, {'a': 2, ...}...
def get_expert_output(expert_preds, free_expert_vals): """ :param expert_preds: (B x nexperts x max_forecast_steps) or [] :param free_expert_vals: (nexperts x max_forecast_steps) -> (1 x nexperts x max_forecast_steps), or None :return: expert_vals. Size: (* x nexperts x max_forecast_steps) :meta p...
def Get_nongap_uppstream(topo, begin_TM):#{{{ """ Get the first non gap state uppstream Input: topo topology sequence of the protein begin_TM sequence position at the beginning of the TM helix (begin_TM, end_TM) defines the location of the TM helix ...
def isdigit(char): """Return True iff char is a digit. """ return char.isdigit()
def get_x_bits(num: int, max_bits: int, num_bits: int, right_bits: bool = True) -> int: """ensure the correct number of bits and pull the upper x bits""" bits = bin(num).lstrip("0b") bits = bits.zfill(max_bits) if right_bits: return int(bits[-num_bits:], 2) return int(bits[:num_bits], 2)
def convert_command(input_filename, output_filename, vcodec='libx264'): """Convert to H.264 format""" cmd = ['ffmpeg', '-i', input_filename, '-vcodec', vcodec, output_filename, '-loglevel', 'error'] return cmd
def neg_poly(p): """Returns a negation of a polynomial""" result = [m.copy() for m in p] for m in result: m.c = -m.c return result
def format_time(t): """Return human-readable interval of time. Assumes t is in units of seconds. """ minutes = int(t / 60) seconds = t % 60 r = "" if minutes > 0: r += "%d minute%s " % (minutes, "" if minutes == 1 else "s") r += "%.3f seconds" % seconds return r
def _filter_relevant_datasets(datasets, load_columns): """ Filter datasets so only ones that actually load columns are left. Parameters ---------- datasets: Dict[str, kartothek.core.dataset.DatasetMetadata] Datasets to filter. load_columns: Dict[str, Set[str]] Columns to load. ...
def extract_label(predictions): """ extract the predicted label without the following prediction :param predictions: list of Strings / complete predicted output :return: list of Strings / only labels """ # extract the predicted label without the following prediction array = [] for pred i...
def rot(a, n): """ Renvoie a <<< n. """ return a[n:] + a[:n]
def sum_of_minimums(numbers: list) -> int: """ This function returns the sum of minimum value in each row. """ return sum([min(i) for i in numbers])
def convertVoltage(raw_voltage): """ Ground is 1 1.8 is 4095 """ converted_voltage = (raw_voltage/4095)*1.8 return "%.3f" % converted_voltage
def null_condition_attribute(obj, attribute) : """ Return the value of the item with key equals to attribute. Args: obj (:obj:`dict`) : Dictionary object. attribute (:obj:`str`) : Attribute name of obj. Returns: The value of the item. If obj is None, return None. ""...
def getBoundsOverlap(bb1, bb2): """Returns the intersection of two bounding boxes""" minX = max(bb1[0], bb2[0]) minY = max(bb1[1], bb2[1]) maxX = min(bb1[2], bb2[2]) maxY = min(bb1[3], bb2[3]) return (minX, minY, maxX, maxY)
def compare_flavors(flavor_item): """ Helper function for sorting flavors. Sorting order: Flavors with lower resources first. Resource importance order: GPUs, CPUs, RAM, Disk, Ephemeral. :param flavor_item: :return: """ return ( flavor_item.get("Properties", {}).get("Accelerato...
def get_item_properties(item, columns): """Get specified in columns properties, with preserved order. Required for correct cli table generation :param item: dict :param columns: list with arbitrary keys """ properties = [] for key in columns: properties.append(item.get(key, '')) ...
def flatten_routes(routes): """Flatten the grouped routes into a single list of routes. Arguments: routes {list} -- This can be a multi dementional list which can flatten all lists into a single list. Returns: list -- Returns the flatten list. """ route_collection = [] for rout...
def utf8_bytes(text): """ Ensures that text becomes utf-8 bytes. :param text: strings or bytes. :return: a bytes object. """ if not isinstance(text, bytes): return text.encode('utf-8') return text
def NPL_indicator (row): """ Determine the indicator of NPL as one of five indicators """ if row < 37: return "Excellent" elif row <= 48: return "Good" elif row < 61: return "Fair" elif row < 93: return "Poor" else: return "Hazard"
def collapse_sided_value(value): """Inverses `expand_sided_value`, returning the most optimal form of four-sided value. """ if not isinstance(value, (tuple, list)): return value elif len(value) == 1: return value[0] elif len(value) == 2: if value[0] == value[1]: return value[0] else: ...
def serialize_uint256(n: int) -> bytes: """ Serialize an unsigned integer ``n`` as 32 bytes (256 bits) in big-endian order. Corresponds directly to the "ser_256(p)" function in BIP32 (https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#conventions). :param n: The integer to be seria...
def brensenham_line(x, y, x2, y2): """Modified to draw hex sides in HexCheckImage. Assumes dy > dx, x>x2 and y2>y which is always the case for what it's being used for.""" coords = list() dx = abs(x2 - x) dy = abs(y2 - y) d = (2 * dx) - dy for i in range(0, dy): coords.append((x...
def get_volume_of_runoff(runoff, cell_count, cell_resolution): """ Calculate the volume of runoff over the entire modeled area Args: runoff (number): Q from TR55, averaged amount of runoff in inches per cell over a number of cells. cell_count (integer): The number of cells included...
def compare_and_get_name(a, b): """ If both a & b have name attribute, and they are same return the common name. Else, return either one of the name of a or b, whichever is present. Parameters ---------- a : object b : object Returns ------- name : str or None """ ...
def classify(op): """ Given an operation name, decide whether it is a constructor or an annihilator. The convention is that constructors are operations starting with 'c', and all other operations are annihilators. >>> classify("c") 'C' >>> classify("c2df") 'C' >>> classify("a") ...
def OverrideToImplementCustomLogic(obj): """Users should override this in their sub-classes to implement custom logic. Used in Trainer and Policy to tag methods that need overriding, e.g. `Policy.loss()`. Examples: >>> from ray.rllib.policy.torch_policy import TorchPolicy >>> @override...
def stream_copy(read, write, size, chunk_size): """ Copy a stream up to size bytes using the provided read and write methods, in chunks of chunk_size :note: its much like stream_copy utility, but operates just using methods""" dbw = 0 # num data bytes written # WRITE ALL DATA UP TO SIZE while Tru...
def identity(size): """ @brief Return Identity matrix. """ assert size > 0, "A size should be > 0" M = [[0 for i in range(size)] for j in range(size)] for i in range(size): M[i][i] = 1 return M
def Number_Pad(Number): """Format Dollars amounts to strings & Pad Right 10 Spaces""" Number_Display = f"{Number:,}" Number_Display = f"{Number_Display:>10}" return Number_Display
def humantime(timedelta): """Converts time durations to human readable time""" seconds = int(timedelta) years, seconds = divmod(seconds, (3600 * 24 * 365)) days, seconds = divmod(seconds, (3600 * 24)) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) if years > 0:...
def expand_places_from_index(placename_list, idx): """Searches up and down from the index, collecting places with the same name.""" if idx == -1: return [] # Find and save the initial value word = placename_list[idx][0] matched_places = [] matched_places.append(placename_list[id...
def get_app_instances_ids(instances): """ Accepts a dictionary of id: AppInstance and returns a set of keys """ return set(instances.keys())
def parse_numbers(numbers, dtype=float, sep=','): """Return list of numbers from string of separated numbers.""" if not numbers: return [] try: return [dtype(i) for i in numbers.split(sep)] except Exception as exc: raise ValueError(f"not a '{sep}' separated list of numbers") from...
def to_string(todos): """Convert a list of todos to a string. :param list todos: List of :class:`todotxtio.Todo` objects :rtype: str """ return '\n'.join([str(todo) for todo in todos])
def cut_lines(info_str, start, end): """Cut a number of lines from the start and the end. Args: info_str (str): command output from arcconf start (int): offset from start end (int): offset from end Returns: str: cutted info_str """ return '\n'.join(info_str.split('\n...
def convertPressureToPascals(mpressure): """ Convert pressure given in kg/cm2 to Pascals """ ppas = 98066.5 * mpressure return ppas
def compute_xi_t(return_t, risk_free_rate, sigma_t): """ Compute innovation xi at time t as a function of return t, rf rate, and sigma t """ return return_t - risk_free_rate + 1/2 * sigma_t
def sum_dicts_values(dict1, dict2): """Sums the value between tow dictionnaries (with the same keys) and return the sum""" dict = {} for k in dict1.keys(): try: dict[k] = int(dict1[k]) + int(dict2[k]) except: dict[k] = int(dict1[k]) return dict
def merge(L1, L2): """(list, list) -> list Merge sorted lists L1 and L2 into a new list and return that new list. >>> merge([1, 3, 4, 6],[1, 2, 5, 7]) [1, 1, 2, 3, 4, 5, 6, 7] """ newL = [] i1 = 0 i2 = 0 while i1 != len(L1) and i2 != len(L2): if L1[i1] <= L2[i2]: ...
def str_2_list(del_str, fld_del): """Function: str_2_list Description: Converts a string delimited field to a list. Arguments: (input) del_str -> Delimited string. (input) fld_del -> Field delimiter. (output) List of values from the string. """ return del_str.split(fld...
def jobparams_postfiltering(value, exclusions={}): """ Perform post-filtering of raw job parameters. Any items in the optional exclusion list will be added (space separated) at the end of the job parameters. :param value: job parameters (string). :param optional exclusion: exclusion dictionary from...
def normalize(name): """ Normalizes text from a Wikipedia title/segment by capitalizing the first letter, replacing underscores with spaces, and collapsing all spaces to one space. :Parameters: name : string Namespace or title portion of a Wikipedia page name. :Return: string Normalized text """ r...
def scale_factor(redshift): """ Calculates the scale factor, a, at a given redshift. a = (1 + z)**-1 Parameters ---------- redshift: array-like The redshift values. Returns ------- a: array-like The scale factor at the given redshift. Examples -------- ...
def trans_rot_affine(matrix, u_vec, v_vec): """ Args: matrix (matrix): rotation matrix u_vec (float): x coordinate v_vec (float): y coordinate Returns: int: rotated x coordinate Returns: int: rotated y coordinate """ # rotation affine transformation ...
def get_rundir_name(d): """ Helper method to construct the result sub-directory name based on the experiment parameters :param d: dictionary of experiment parameters :return: string of the sub-directory name """ env_str = str(d['env.kwargs.env_name']) lr_fl = float(d['algo.kwargs.optim...
def extractPBestPos(particleList): """ Returns the pBestPos of all particles in particleList as a list. Parameters: particleList (list): A list of Particle objects. Returns: list: List of pBestPos of the Particle objects in particleList, in the same order as the input. """ ret...
def to_camel_case(snake_case): """Makes a snake case string into a camel case one Parameters ----------- snake_case : str Snake-cased string (e.g., "snake_cased") to be converted to camel-case (e.g., "camelCase") """ output_str = '' should_upper_case = False for c in snake_case:...
def _compute_colocation_summary_from_dict(name, colocation_dict, prefix=""): """Return a summary of an op's colocation stack. Args: name: The op name. colocation_dict: The op._colocation_dict. prefix: An optional string prefix used before each line of the multi- line string returned by this fu...
def image_round(image): """ :param image: a grayscale image represented as a list of list of floats :return: corresponding image, represented as a list of lists of integers, obtained by rounding the floats in the input image and taking their absolute values and replacing numbers greater than 255 wit...
def transformDiffCost(criterion, frRow, exRow): """Returns the absolute difference between their image through the 'transform' dict, normalized""" t = criterion['transform'] q = criterion['QLabel'] return abs(t[frRow[q]] - t[exRow[q]]) / max(t.values())
def calculate_mean(instance_count: int, items: list) -> float: """ Calculate given class mean :param instance_count: Number of instances in class :param items: items that related to specific class(data grouping) :return: calculated actual mean of considered class """ # the sum of all items d...
def make_feature_collection(data): """Return a feature collection.""" return {"type": "FeatureCollection", "features": data}
def GetProblemIoSetByName(problem, io_set_name): """Get a problem's index given its key and a problem list. Args: problem: Problem whose I/O set must be retrieved. io_set_name: String with the name of the I/O set to retrieve. Returns: The problem I/O set with the specified name, or None if no I/O se...
def to_discord_description_safe(text: str) -> str: """Convert the given string to one that will be accepted by discord as a description for a channel. """ return text[:1024]
def format_instances(instances, features): """ Convert a list of instances into a header list and datarows list. `header` is just `features` e.g. ['username', 'email'] `datarows` is a list of lists, each sublist representing a row in a table e.g. [['username1', 'email1@email.com'], ['username2'...
def lin_comb(clist, vlist): """ Compute a linear combination :param clist: X len list of scalars :param vlist: X len list of vectors all of domain D :return: D domain vector whose values are summation of clist * vlist """ return sum([s * v for s, v in zip(clist, vlist)])
def amigos(x,y): """ amigos(x: int ,y:int) -> Boleano amigos(x,y) Parameters ---------- x : int Un numero entero. y : int Un numero entero. Returns ------- output : Buleano Verdadero si son amigos, Falso si no lo son E...
def icon(name=None, class_name="icon", title=None, wrapped=False): """ Abstracts away the actual icon implementation. Usage: {% load wagtailadmin_tags %} ... {% icon name="cogs" class_name="icon--red" title="Settings" %} :param name: the icon name/id, required (string) :par...
def floor(x) -> int: """ Return the floor of x as an Integral. :param x: the number :return: the largest integer <= x. >>> import math >>> all(floor(n) == math.floor(n) for n ... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000)) True """ return int(x) if x - int(x) >= 0...
def checksum2(data): """ Calculate Checksum 2 Calculate the ckecksum 2 required for the herkulex data packet Args: data (int): the data of which checksum is to be calculated Returns: int: The calculated checksum 2 """ return (~data)&0xFE
def make_paired_cycle_list(cycle_list): """Pairs up cycles together into tuples. cycle_list is the list of actions that need to be paired up.""" # [::2] are the even-indexed items of the list, [1::2] are the # odd-indexed items of the list. The python zip function puts # matching-index items from t...
def common_prefix(strings): """ Find the longest string that is a prefix of all the strings. """ if not strings: return '' prefix = strings[0] for s in strings: if len(s) < len(prefix): prefix = prefix[:len(s)] if not prefix: return '' for i in...
def get_smallwords(text, min_length=1, max_length=5): """ Computes the smallwords of a given text :rtype : list :param text: The text provided :param min_length: The minimum length of the smallwords :param max_length: The maximum length of the smallwords :return: The list of all the smallwo...
def strip_rule(line): """ Sanitize a rule string provided before writing it to the output hosts file. Some sources put comments around their rules, for accuracy we need to strip them the comments are preserved in the output hosts file. Parameters ---------- line : str The rule prov...
def get_reverted_rses_id_name_map(rses_id_name_map): """Revert k:v to v:k""" return {v: k for k, v in rses_id_name_map.items()}
def leap_year(year: int) -> bool: """Report if a year is leap. :param year: int - year. :return: bool """ return (year % 4 == 0 and not year % 100 == 0) or year % 400 == 0
def factors_to_dictionary(factors): """Transforms a list of factors into a dictionary Args: factors (list): List of factors Returns: dict: Dictionary of factors to count """ factor_dict = {} for factor in factors: if factor in factor_dict: factor_dict[facto...
def to_response(objects, not_found_msg): """ Convert namedtuple objects to dict form. If the specified sequence of objects is non-empty, return the dict version of them. Otherwise return 404 and the specified message. NamedTuple objects need to be converted to a dictionary for to be serialized to ...
def dump_data(ws,headings,data): """ Iterate over the data and write it out row by row. """ for i, colVal in enumerate(headings): ws.write(0,i,colVal) for i, row in enumerate(data): for j, colVal in enumerate(row): ws.write(i+1,j,colVal) return ws
def timestamp_str_to_seconds(timestamp): """Converts a timestamp string in "HH:MM:SS.XXX" format to seconds. Args: timestamp: a string in "HH:MM:SS.XXX" format Returns: the number of seconds """ return sum( float(n) * m for n, m in zip(reversed(timestamp.split(":"))...
def key_has_dot_or_dollar(d): """Helper function to recursively determine if any key in a dictionary contains a dot or a dollar sign. """ for k, v in d.items(): if ("." in k or k.startswith("$")) or ( isinstance(v, dict) and key_has_dot_or_dollar(v) ): return True
def makeHeader(seqs): """ Make a header for the BAM file given a dictionary of sequences and their lengths """ header = { 'HD': {'VN': '1.0'}, 'SQ': [] } for seqName in seqs: # {'LN': 1575, 'SN': 'chr1'}, header['SQ'].append({'LN': seqs[seqName], 'SN': seqName }) ...
def twod_to_oned(size, *coordinates): """Converts coordinates (x >= 0, y >= 0) to an int representation. :param size: Size of the grid that (x, y) is contained in :param coordinates: [(x0, y0), (x1, y1), ...] :return: (int0, int1, ...) """ x_axis = size[0] result = tuple(x + y * x_axis for ...
def get_title(this_title): """ xxx """ page_title = ''+\ '<title>' +\ this_title +\ '</title>' return_data = page_title return return_data
def valid_mapping(mention_start, mention_end, group_indices): """Determine if the mention can be mapped under merging rules.""" for group_start, group_end in group_indices: if mention_start == group_start and mention_end == group_end: # Exact match return True elif group_start <= me...
def tuple_to_string(date_tuple): """ Create a yyyy-mm(-dd) string from a tuple containing (yyyy, m) (or one with the day too) """ if len(date_tuple) == 2: # It's yyyy-mm return str(date_tuple[0]).zfill(4) + '-' + str(date_tuple[1]).zfill(2) # It's yyyy-mm-dd return str(date_tuple...
def sequence(find, numbers): """This function checks to see if an object is in a sequence >>> sequence(1, [1,2,3,4]) 1 >>> sequence("i", "Hello world") 'Nothing' >>> sequence(4, (2,4,6)) 4 """ for n in numbers: if find == n: return(n) ...
def find_amazon_id(link): """Find amazon item id from a passed link ONLY WORKS FOR BOOKS RIGHT NOW sample book url: http://www.amazon.com/Carbon-isotope-fractionation-trophic-transfer/dp/B000RR3CXS%3FSubscriptionId%3D1XJTRNMGKSD3T57YM002%26tag%3Dquasika-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165...
def current_green_or_left(before, after, current=None): """ Checks if green and left green lights works well. :param before: has to be None, "yellow" or "blink" :param after: has to be None or "blink" :param current: Set as default None, so it won't trigger tests as the colour is only relevant ...
def get_values(line): """ Returns the portion of an INSERT statement containing values """ return line.partition('` VALUES ')[2]
def rectContains(rect,pt): """ Count if Rect contains point @Param rect rectangle @Param pt point @Return boolean @source: https://stackoverflow.com/questions/33065834/how-to-detect-if-a-point-is-contained-within-a-bounding-rect-opecv-python """ return rect[0] < pt[0] < rect[0]+rect[2] a...
def remove_toffoli_from_line(local_qasm_line, qubit_1, qubit_2, target_qubit): """ Remove a specific Toffoli gate from a line of qasm. Args: local_qasm_line: The line of qasm qubit_1: The first control qubit of the Toffoli gate qubit_2: The second control qubit target_qubit:...
def fibonacci(n): """Return the nth fibonacci number""" if n < 2: return n return fibonacci(n - 1) + fibonacci(n - 2)
def check_true(string): """ Check if an English string seems to contain truth. Return a boolean Default to returning a False value unless truth is found. """ string = string.lower() if string in ['true', 'yes', 'y', '1', 'yep', 'yeah']: return True else: return False
def isNumber(arg) -> bool: """Returns True if the value can be converted to a floating point""" try: int(arg) return True except: return False
def bget(jdb,s): """Better get. Check for nonetype""" try: return jdb.get(s) except: pass return None
def convert_to_seconds(duration): """ Converts a ISO 8601 unicode duration str to seconds. :param duration: The ISO 8601 unicode duration str :return: int seconds """ duration_string = duration.replace('PT', '').upper() seconds = 0 number_string = '' for char in duration_string: ...
def MyGrep(hash_list, index_name, iname): """ hash_list: (list<subdict>) subdict: (dict) header -> value index_name: (str) key in subdict that maps to index names iname: (str) the index name we want. Returns: list<dict> minimized such that only dicts with wanted index na...
def sizeof_fmt(num): """ Returns the human readable version of a file size :param num: :return: """ for item in ['B', 'KB', 'MB', 'GB']: if num < 1024.0: return "%3.1f %s" % (num, item) num /= 1024.0 return "%3.1f%s" % (num, 'TB')
def check_guess(user_number,generated_number,count): """ check user guess number against with genrated number """ if(user_number == generated_number): return f"Great Job! The Correct number is {generated_number}. You have made {count} guesses.\n" elif(user_number > generated_number): return ...
def coordinates_list_to_BED(scaffold_name: str, coordinates: list) -> str: """ function to create BED format from a list of coordinates takes list [[start, stop], [start, stop]] """ result = "" for lst in coordinates: result += (scaffold_name + '\t' + str(lst[0]) + '\t' + str(lst[1]) + '...
def str_to_bool(val): """ Helper function to turn a string representation of "true" into boolean True. """ if isinstance(val, str): val = val.lower() return val in ["true", "on", "yes", True]