content
stringlengths
42
6.51k
def to_list(x): """ :param x: :return: """ return x if type(x) == list else [x]
def min_platforms(arrival, departure): """ :param: arrival - list of arrival time :param: departure - list of departure time """ arrival.sort() departure.sort() events = [] i, j = 0, 0 while i < len(arrival) and j < len(departure): if arrival[i] < departure[j]: ev...
def known_letters(word_list: list, letters: list) -> list: """Make a new list if all the letters are in the world_list.""" return [word for word in word_list if all(letter in word for letter in letters)]
def _version_to_tuple(version): """Converts the version string ``major.minor`` to ``(major, minor)`` int tuple.""" major, minor = version.split('.') return (int(major), int(minor))
def build_bankruptcy_definition(years): """Build a bankruptcy definition Notes: This function is set according to a line of best fit from Year 0 at -10% ROI to 10% ROI by Year 7. Args: years (int): No. of years for analysis Returns: Bankruptcy definitio...
def use_dd_to_update_guess(dd): """ Uses Top Punts Dropdown to Update Guess Options """ if isinstance(dd, str): return {'guess':[c for c in dd]} elif isinstance(dd, list): return {'guess':[c for c in dd[0]]}
def nicebytes(n): """Convert a bytecount to a string like '<number> bytes' or '<number>K'. This is intended for inclusion in status messages that display things like '<number>% read of <bytecount>' or '<bytecount> read'. When the byte count is large, it will be expressed as a small floating point n...
def set_common_keys(dict_target, dict_source): """ Set a dictionary using another one, missing keys in source dictionary are reported""" keys_missing=[] for k in dict_target.keys(): if k in dict_source.keys(): dict_target[k]=dict_source[k] else: keys_missing.append(k)...
def check_shell_asterisk(cmd): """ Determine whether a command appears to involve shell stars. :param str cmd: Command to investigate. :return bool: Whether the command appears to involve shell stars. """ return r"*" in cmd
def in_box(point, c1, c2): """Is point in box with *opposite* corners c1 and c2""" c1x, c1y = c1 c2x, c2y = c2 x, y = point return min(c1x, c2x) <= x <= max(c1x, c2x) and min(c1y, c2y) <= y <= max(c1y, c2y)
def get_hms(t_sec): """Converts time in seconds to hours, minutes, and seconds. :param t_sec: time in seconds :return: time in hours, minutes, and seconds :rtype: list """ h = t_sec//3600 m = (t_sec - h*3600)//60 s = t_sec%60 return h,m,s
def int2word(num, separator="-"): """Demonstrates a field formatter function From: https://codereview.stackexchange.com/questions/156590/create-the-english-word-for-a-number """ ones_and_teens = {0: "Zero", 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven',...
def parse_like_term(term): """ Parse search term into (operation, term) tuple. Recognizes operators in the beginning of the search term. * = case insensitive (can precede other operators) ^ = starts with = = exact :param term: Search term """ cas...
def unit( x: str, c: str = 'csl', ) -> str: """ Return a notation of the unit x in context c. Input: x (str): unit c (str): context Output: s (str): notation of x """ if c == 'ttl': return fr"$ \mathrm{{ {x} }} $" else: return x.replace("{", ...
def get_earliest(*dates): """Calculates the earliest date """ smallest = dates[0] smallest_val = (365*int(smallest.split("/")[2]) + 30*int(smallest.split("/")[0]) + int(smallest.split("/")[1])) for i in range(1, len(dates)): final_val = 0 split_date = dates[i].split("/") ...
def first_char_to_lower(string): """Converts first letter to lower case. Args: string: A string. Returns: A string whose first letter is lower case. For example: "UserGroup" to "userGroup" """ if len(string) == 0: return string else: return string[0].lo...
def resolve_attr(attr_name, dct, mro): """ Resolve an attribute from a MRO If the attribute is not present anywhere, None is returned Parameters: attr_name: The name of the attribte to resolve dct: The dictionary of the most derived class body mro: The C3 lineari...
def invert(percentage=1.0): """ Color inversion filter. Author: Printed in XNA Unleashed - readpated for GLSL by SolarLune Date Updated: 6/6/11 """ return (""" // Name: Invert // Author: printed in XNA Unleashed, readapted by SolarLune // Date Updated: 6/6/11 uniform sampler2...
def to_str(data, separator=":"): """Stringify hexadecimal input; :param data: Raw data to print :type data: str or bytes or bytearray :param separator: The separator to be used **between** the two digits hexadecimal data. :type separator: str >>> to_str(bytes([1,16,5])) "01:0F:05" >>> ...
def get_dicom_path_by_index(idx, metadata_case): """ Key of metadata_case is the path of origin dicom file """ keys = list(metadata_case.keys()) k = keys[idx] return k
def tuplize_2d_array(arr): """Returns a list of tuples, each tuple being one row of arr.""" return [tuple(row) for row in arr]
def classy(value): """Converts random value to class CamelCase style for model generation. e.g. My random model name => MyRandomModelName """ return ''.join( [val[:1].upper() + val[1:] for val in value.split(' ')])
def clean_via_pos(tokens, pos): """ Clean a list of tokens according to their part-of-speech tags. In particular, retain only tokens which do not have the part-of-speech tag DT (determiner) or POS (possessive 's'). Args: tokens (list(str)): A list of tokens. pos (list(str)): A list of ...
def compose_name(hidden_units, learning_rate, epsilon, lmbda, lr_decay, search_plies=1): """Return name for parameter save file based on the hyperparameters.""" name = f'N{hidden_units:d}' name += f'-alpha{learning_rate:.3f}' name += f'-lambda{lmbda:.2f}' name += f'-epsilon{epsilon:.5f}' name +=...
def report_updated_registration(json_obj): """ Generate message for updated registration. Args: json_obj (obj): JSON obj. Returns: string: Message. """ name = json_obj['Dogodek'] registration_status = json_obj['Registration Status'] event_url = json_obj['Link'] msg ...
def get_track(degrees): """ Converts degree measurement to cardinal track """ track = '' if 0 <= degrees < 39: track = 'N' elif 39 <= degrees < 84: track = 'NE' elif 84 <= degrees < 129: track = 'E' elif 129 <= degrees < 174: track = 'SE' elif 174 <= ...
def filter_records(records, key, operator, test_value): """Removes all records from a list of records, which do not fulfill the specified criteria. The criteria are checked by applying the operator with the record's value for the specified key as the first and the test_value as the second operand. ...
def parse_camera_type(args): """parse args to get camera type @fn parse_camera_type @param args: all the arguments @return camera_type """ argc = len(args) if argc == 0: return None for i in range(0, argc): if args[i] == 'camera_type' and i+1 < argc: return a...
def flip_1_0(number): """Flip 1 to 0, and vice versa :parm number: 1 or 0 to flip :type number: int :returns flipped value :rtype: int """ assert number in [0, 1], 'number to flip is not a 0 or 1' assert isinstance(number, int), 'number to flip is not int' if number == 0: ret...
def process_primary_inputs(dict_): """ This functions processes the parameters specified by the user in the initialization dictionary. Parameters ---------- dict_: dict Estimation dictionary. Returned by grmpy.read(init_file). Returns ------- bins: int Number of his...
def _describe_snapshot_response(response): """ Generates a response for describe snapshot request. @param response: Response from Cloudstack. @return: Response. """ return { 'template_name_or_list': 'snapshots.xml', 'response_type': 'DescribeSnapshotsResponse', 'response...
def units_with_costs(units): """Filter units that have a cost or design method.""" return [i for i in units if i._cost or i._design]
def _reg2int(reg): """Converts 32-bit register value to signed integer in Python. Parameters ---------- reg: int A 32-bit register value read from the mailbox. Returns ------- int A signed integer translated from the register value. """ result = -(reg >> 31 & 0x1) ...
def get_extension(filename): """Get the file extension of the given filename.""" if '.' not in filename: return None return filename.split('.')[-1]
def author_affiliation_check(agr_data, value): """ check a database reference has an author with an affiliation :param agr_data: :param value: :return: """ result = 'Failure' if 'authors' not in agr_data: return 'Failure: No authors found in database' for author in agr_data...
def fib_recursion(n): """ using recursion :param n: :return: """ if n == 0: return 0 if n == 1: return 1 return fib_recursion(n - 1) + fib_recursion(n - 2)
def get_task_info(experiment_length, task_color): """Get Task Info. Generates fixed RSVPKeyboard task text and color information for display. Args: experiment_length(int): Number of sequences for the experiment task_color(str): Task information display color Return get_task...
def climb_stairs(n: int) -> int: """ LeetCdoe No.70: Climbing Stairs Distinct ways to climb a n step staircase where each time you can either climb 1 or 2 steps. Args: n: number of steps of staircase Returns: Distinct ways to climb a n step staircase Raises: Assert...
def convert_version_int_to_string(number, number_bits): """ Take in a verison string e.g. '3.0.1' Store it as a converted int: 3 * (2**number_bits[0]) + 0 * (2**number_bits[1]) + 1 * (2**number_bits[2]) >>> convert_version_int_to_string(50331649,[8,8,16]) '3.0.1' """ number_strings = []...
def hamming_distance(s1, s2): """ Return the Hamming distance between equal-length sequences """ if len(s1) != len(s2): #print(s1) #print(s2) #raise ValueError("Undefined for sequences of unequal length") return len(s1) if len(s1)>len(s2) else len(s2) return sum(ch1 !...
def poly_derivative(poly): """ find the derivative of a polynomial poly: list with the plynomial Return: list with the polynomial of the derivative """ result = [] if poly is None or type(poly) != list or poly == []: return None for i in range(len(poly)): if type(p...
def convert_input_vals_list(input_val_dict): """ Converts input val dictionary with string values to a dictionary of list integers """ output_dict = {} for k, v in input_val_dict.items(): ## if its a const input we don't want it to be a list if "(C)" in k: output_dict[k] = int(v) else: ...
def _dashCapitalize(name): """ Return a string which is capitalized using '-' as a word separator. @param name: The name of the header to capitalize. @type name: str @return: The given header capitalized using '-' as a word separator. @rtype: str """ return '-'.join([word.capitalize() ...
def resetCharStats(charStatsDict): """This method resets user's characters statistics. Args: charStatsDict (dict): Characters statistics. Returns: string: Return String representation of characters statistics dictionary. """ for char in charStatsDict.keys(): charStatsDic...
def bool_to_string(bool_instance): """ Function to convert boolean value to string value Args: bool_instance (bool) Return: true or false (str) """ return str(bool_instance).lower()
def form_url(site, loc): """Concatenate site URI with location specific parameters""" url = site + loc return url
def get_view_link(download_link): """Transform a download link into the equivalent view link.""" return download_link.replace("download", "view")
def chunk_text(string, chunk_size=50000): """ :param string: a string :type string: str :param chunk_size: the max characters of one chunk :type chunk_size: int :return: a list of chunks :type return: list """ chunks = [string[i:i + chunk_size] for i in range(0, len(string), chunk_s...
def number_from_class(number_class): """Helper method to return the last char as integer from a numbered class. example: stars1 stars2 stars3 Args: number_class (str): class name that has a number at the end Returns: int: the number representation of the class. """ try: ...
def update_restriction(lines, restriction, restype, val, func=False): """ <Purpose> Updates a resource in a restrictions file <Arguments> lines: The contents of the restrictions file, list each element is a line restriction: The name of the restriction e.g. resource, call restype: The type of r...
def parse_args(argv): """Parse Alfred Arguments Args: argv: A list of arguments, in which there are only two items, i.e., [mode, {query}]. The 1st item determines the search mode, there are two options: 1) search by `topic` 2) search ...
def Sqr_Chord_Len_C3V(vec1, vec2): """Computes the square length of the difference between the two arguments. The arguments are assumed to be 3d vectors (indexable items of length 3).""" diff0 = vec1[0] - vec2[0]; diff1 = vec1[1] - vec2[1]; diff2 = vec1[2] - vec2[2]; result = diff0 * diff0 + di...
def target_dir_name(build_config, target_device): """Returns a default output directory name string. Args: build_config: A string describing the build configuration. Ex: 'Debug' target_device: A string describing the target device. Ex: 'simulator' """ return '%s-%s' % (build_config, target_device)
def next(array, current_index): """ Returns the next element of the list using the current index """ return array[int(current_index) + 1]
def get_child_with_matching_tag(parent, tag_name): """ Find whether Child node with tag = tag_name exists, if exists then return the child node""" child_node = "" try: child_node = parent.getElementsByTagName(tag_name)[0] except Exception as exception: child_node = "" return child_no...
def filter_result(result): """Remove keys from shell/command output. """ stdout = result.pop('stdout', '') stdout_lines = result.pop('stdout_lines', []) if not stdout_lines and stdout: stdout_lines = stdout.split('\n') # for key in ('changed', 'cmd', 'invocation', # 's...
def convert_language_code(django_lang): """ Converts Django language codes "ll-cc" into ISO codes "ll_CC" or "ll" :param django_lang: Django language code as ll-cc :type django_lang: str :return: ISO language code as ll_CC :rtype: str """ lang_and_country = django_lang.split("-") tr...
def point_is_on_left(a, b, c): """Returns true iff c is on the left of the infinite line ab""" return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0])
def resource_with_name(resources, name): """Returns the resource with the given name.""" matches = [x for x in resources if x['name'] == name] if matches: return matches[0] else: raise Exception('No resource matching name {}'.format(name))
def get_instance_region(instance, region): """ Get the region attribute stored in instance if one is not provided. """ if region is None: if not hasattr(instance, "region_"): raise ValueError("No default region found. Argument must be supplied.") region = getattr(instance, "r...
def morton3D(k, x, y, z): """ Computes and returns the morton code of the x, y, z coordinates each represented with k bits Args: k: Bits to represent each coordinate with x: X coordinate y: Y coordinate z: Z coordinate Returns: The morton code in integer for...
def find_closest_smaller_value(find_value, list_of_values): """ Returns the closest value from a list of values that is smaller than find_value :param find_value: The value we are searching for :param list_of_values: The list of values :return: The index of the closes value in the list. Returns -1 i...
def process_error_helper(root, base_dir, process_func, errors_to_handle=(), **func_kwargs): """Wrapper which applies process_func and handles some common errors so one bad run does not spoil the whole batch. Useful errors to handle include: OSError: if you are not sure if all ...
def len_of_thing(thing, operation = None): """Wrapped to be consistent and because I may provide more information in case I try to do this recursively.""" try: return len(thing) except: return 0
def find_first_occurrence(root, target): """ Question 15.2: Find first occurrence of key in binary search tree, with possible duplicate elements """ if root is None: return None if root.val < target: return find_first_occurrence(root.right, target) left_res = find_first...
def _next_regular(target): """ Copied from scipy. Find the next regular number greater than or equal to target. Regular numbers are composites of the prime factors 2, 3, and 5. Also known as 5-smooth numbers or Hamming numbers, these are the optimal size for inputs to FFTPACK. Target must ...
def encode_csv_string(str): """ Encode a string to be used in CSV file. Args: str: String to encode Returns: Encoded string, including starting and ending double quote """ res = ['"'] for c in str: res.append(c) if c == '"': res.append('"') res.a...
def get_compatible_filename(filename: str, extension: str): """ Get the filename as a non-problematic string (replace ' ' by '_', ...). Removes the extension. """ no_ext = str(filename).lower().rstrip(extension.lower()) return (no_ext).replace(" ", "_").replace("-", "_").replace(".", "_")
def match_gt_with_preds(ground_truth, predictions, match_labels): """Match a ground truth with every predictions and return matched index.""" max_confidence = 0. matched_idx = -1 for i, pred in enumerate(predictions): if match_labels(ground_truth, pred[1]) and max_confidence < pred[0]: ...
def plugins(switches=0, *pattern): """plugins(switches=0, *pattern)-> list of str Returns a list of every loaded plugin or every plugin available. By default each plugin is returned as the full pathname of the plugin file. You can give a glob-style matching pattern and only the plugins whose filenames (not path) ...
def replace_sublist_at(list, index, length, sublist): """ Return a list that contains the given sublist in place of the existing sublist that starts at the given index and has the given length. If the index is one past the end, append the sublist. If the index is otherwise out of bounds, return th...
def isempty(line): """ Checks if a line is empty (contains only witespaces or tabs)""" if len(line.replace("\n","").replace(" ","").replace("\t","")) == 0: return True else: return False
def GenerateFilename(group, count, index): """Generate test filename.""" filename = group assert index >= 0 and index < count if count > 1: index_str = str(index) if index < 10: index_str = "0" + index_str filename += "_" + index_str filename += ".html" return filename
def converter(value): """Tries to convert input value to an integer. If input can be safely converted to number it returns an ``int`` type. If input is a valid string but not an empty one it returns that. In all other cases we return None, including the ones which an ``TypeError`` exception is rais...
def chunks(items, size): """ Split list into chunks of the given size. Original order is preserved. Example: > chunks([1,2,3,4,5,6,7,8], 3) [[1, 2, 3], [4, 5, 6], [7, 8]] """ return [items[i:i+size] for i in range(0, len(items), size)]
def BinToDec(b): """ Convert a binary coded string to a decimal integer """ l = list(b) l.reverse() p = 1 d = 0 for bit in l: d += p * int(bit) p = p << 1 return d
def ngrams(tokens, min_n, max_n): """ Generates ngrams(word sequences of fixed length) from an input token sequence. tokens is a list of words. min_n is the minimum length of an ngram to return. max_n is the maximum length of an ngram to return. returns a list of ngrams (words separated by a spa...
def __convert_RF_dict_to_LF(x): """Converts a right-side encoded frond dict into a left-side encoded frond dict. x -> u, y -> v""" new_x = {'u': x['x'], 'v': x['y']} return new_x
def lamPoint(numLams, lambdas, lam): """Return the array index of the wavelength array (lambdas) closest to a desired value of wavelength (lam)""" help = [0.0 for i in range(numLams)] for i in range(numLams): help[i] = lambdas[i] - lam; help[i] = abs(help[i]); ...
def has_an_update(page_data: dict, tracker_data: dict) -> bool: """Checks if there was an update comparing two story mappings of the same story. Arguments: page_data {dict} -- Requested story mapping, from `get_story_data`. tracker_data {dict} -- Story mapping from the tracked list. Re...
def map_to_range( old_min: float, old_max: float, new_min: float, new_max: float, value: float, ) -> float: """Maps a value from within one range of inputs to within a range of outputs.""" return ((value - old_min) / (old_max - old_min)) * (new_max - new_min) + new_min
def skip(line): """Returns true if line is all whitespace or shebang.""" stripped = line.lstrip() return stripped == '' or stripped.startswith('#!')
def _prod(sizes): """ Product of tiny list of sizes. It is faster than numpy.prod and torch.prod. Parameter --------- sizes : list or tuple Size of inputs, output, or weights, usually 2/3/4 dimensions. Performance ----------- prof...
def short_words_extractor(word_tokens): """short_words Counts the number of words shorter than four characters in the text. Known differences with Writeprints Static feature "number of short words": None. Args: word_tokens: List of lists of token.text in spaCy doc instances. Returns: ...
def char_month_converter(month): """ integer month to 3 character month """ months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] return months[(month-1)]
def _success(code=200, **body_data): """Return successfully""" return { "hark_ok": True, **body_data, }
def _ConcurrencyValue(value): """Returns True if value is an int > 0 or 'default'.""" try: return value == 'default' or int(value) > 0 except ValueError: return False
def convert_x1y1x2y2_to_XcYcWH(box): """ Convert box from dictionary of {"x1":,"y1":,"x2":,"y2"} to {"x_centre":,"y_centre":,"width":,"height":} Assumption 1: point 1 is the top left and point 2 is the bottom right hand corner """ assert box["x1"] <= box["x2"] assert box["y1"] <= box["y2...
def wrap_functional_unit(dct): """Transform functional units for effective logging. Turns ``Activity`` objects into their keys.""" data = [] for key, amount in dct.items(): if isinstance(key, int): data.append({"id": key, "amount": amount}) else: try: ...
def formatNumber(lNum, sThousandSep = ' '): """ Formats a decimal number with pretty separators. """ sNum = str(lNum); sRet = sNum[-3:]; off = len(sNum) - 3; while off > 0: off -= 3; sRet = sNum[(off if off >= 0 else 0):(off + 3)] + sThousandSep + sRet; return sRet;
def hide_link(url: str) -> str: """ Hide URL (HTML only) Can be used for adding an image to a text message :param url: :return: """ return f'<a href="{url}">&#8203;</a>'
def projection_dict(projection): """Get a projection dictionary from a list of attribute names to project. Args: projection: List of string names of attributes to project. Returns: Dictionary like {'attr1': 1, 'attr': 1, ... }. """ if projection: return dict(zip(projection, [1]...
def calculate_distance(pos1: tuple, pos2: tuple) -> int: """ Taxicab/Manhattan distance """ return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
def get_max_lock(value): """ Return if Max lock is on or off """ if (value & 32) == 32: return 'Max lock on' else : return 'Max lock off'
def scaleSize(scaleFactor, size): """Helper method to scale a size using the logical DPI @param size: The size (x,y) as a tuple or a single numerical type to scale @returns: The scaled size, returned as the same type""" if isinstance(size, tuple): return (scaleFactor * size[0], scaleFactor * size[1]) retur...
def postprocess_keylist(field, keylist, **options): """Split a comma-separated string of keys into a list.""" if not keylist: return [] stripped_keys = [key.strip() for key in keylist.split(',')] return [key for key in stripped_keys if key]
def _is_valid_email(email): """ Determines if the email is valid. Args: email: Email to test. Returns: bool: If the email is valid. """ if "@" not in email: return False if "." not in email: return False return True
def dot(v, w): """v_1 * w_1 + ... + v_n * w_n""" return sum(v_i * w_i for v_i, w_i in zip(v, w))
def _html(message): """This just generates an HTML document that includes `message` in the body. Override, or re-write this do do more interesting stuff. """ content = f"<html><body><h1>{message}</h1></body></html>" return content.encode("utf8")
def getAssemblies(nodes): """ Return any top-level nodes (assemblies) that contain a list of nodes Args: nodes: A list of node long-names. Does not support short names or PyNodes. """ if not isinstance(nodes, (list, tuple)): nodes = [nodes] return list(set([n[:(n...