content
stringlengths
42
6.51k
def contains(input_list, e): """ determines whether e is contained in the list """ for elem in input_list: # elem is short for element (an item in the list) if elem == e: return True return False
def preprocess_joke(raw_joke: dict): """Perform preprocessing to clean raw jokes.""" dictObject = {} dictObject["type"] = raw_joke.get("type") dictObject["category"] = raw_joke.get("category") if raw_joke.get("type") == "single": dictObject["joke"] = raw_joke.get("joke") return dict...
def elapsed_str(elapsed): """return a string of the form hh:mm:sec""" hrs = int(elapsed/3600) elapsed -= (hrs * 3600) mins = int(elapsed/60) elapsed -= (mins * 60) return "%02d:%02d:%.2f" % (hrs, mins, elapsed)
def gpsWeekCheck(t): """Makes sure the time is in the interval [-302400 302400] seconds, which corresponds to number of seconds in the GPS week""" if t > 302400.: t = t - 604800. elif t < -302400.: t = t + 604800. return t
def calculate_prediction(x: float, threshold: float) -> int: """ Returns a class depending on the value of the threshold. """ if x <= threshold: return 0 else: return 1
def cmp(x, y): """Compare the two objects x and y and return an integer according to the outcome.""" return (x > y) - (x < y)
def css_to_sile(style): """Given a CSS-like style, create a SILE environment.""" font_keys = {'script', 'language', 'style', 'weight', 'family', 'size'} margin_keys = { 'margin-left', 'margin-right', 'margin-top', 'margin-bottom' } keys = set(style.keys()) has_font = bool(keys.intersec...
def isleap(year): """Return True or False if year is a leap year.""" return (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0
def parse_eatery_type(eatery): """Parses the classification of an eatery. Returns the type of an eatery (dining hall, cafe, etc). Args: eatery (dict): A valid json dictionary from Cornell Dining that contains eatery information """ try: return eatery["eateryTypes"][0]["descr"] ...
def check(input, solution, history): """ Compares input and the solution and outputs a mastermind-like result (black, white)""" white = black = 0 for i in range(5): if(input[i] == solution[i]): black = black + 1 if(input[i] in solution and input[i] != solution[i]): wh...
def test_1(in_string): """Counts number of letter 'E'""" return in_string.count('E')
def eyeMatrix(m): """ return a list of lists which represents the identity matrix of size m """ out = [[0.0 for x in range(m)] for y in range(m)] for i in range(m): out[i][i] = 1.0 return out
def _is_folder_type(item_json): """Determine if one drive file type can be represented as a CFolder""" return ('folder' in item_json or 'album' in item_json)
def item_or_tuple(x): """Returns :obj:`x` as a tuple or its single element.""" x = tuple(x) if len(x) == 1: return x[0] else: return x
def sort_species(species_dict): """Sorts a dictionary of species frequencies by genus name then frequency. Written by Phil Wilmarth, OHSU, 2009. """ # first sort by Genus name using the "sort" attribute sorted_list = list(species_dict.items()) sorted_list.sort() return sorted_list
def fori_loop(lower, upper, body_fun, init_val): """ For dubgging only """ val = init_val for i in range(lower, upper): val = body_fun(i, val) return val
def bind_var(var, db='oracle'): """Format of named bind variable""" if db == 'postgresql': return '%({})s'.format(var) elif db == 'oracle': return ':{}'.format(var) else: return ':{}'.format(var)
def apply_all(x, func): """ Apply a function to a list of tensors/images or a single tensor/image """ if isinstance(x, list) or isinstance(x, tuple): return [func(t) for t in x] else: return func(x)
def reliability_calc(RACC, ACC): """ Calculate Reliability. :param RACC: random accuracy :type RACC: float :param ACC: accuracy :type ACC: float :return: reliability as float """ try: result = (ACC - RACC) / (1 - RACC) return result except Exception: retu...
def input_class(input_type): """A tag to get the correct Bulma input class given an input type to be used in forms""" input_class ={ 'text':'text', 'email':'text', 'password':'text', 'checkbox':'checkbox', } return input_class[input_type]
def _quote_field(data, field): """ Quote a field in a list of DNS records. Return the new data records. """ if data is None: return None data[field] = '"%s"' % data[field] data[field] = data[field].replace(";", "\;") return data
def get_points(place): """ Transfers one given place to points by following rules: 1st place = 200p 2nd place = 190p 3rd place = 182p 4th place = 176p 5th place = 172p 6th place = 170p 7th place = 169p 8th place = 168p ... 175th place = 1p """ if place == "1.": ...
def type_files(filelist, ext): """Given a list of filenames and an extension, returns a list of all files with specific extension... """ # If last chars (case insensitive) match "."+ext return [filename for filename in filelist \ if filename.lower().endswith("." + ext.lower())]
def _air_check( game_data ): """ Below-min breath is called exhaustion. Knowing when to breathe is important. """ for p in range( 2 ): c = game_data[str(p)]['calm'] # Punish will if calm is below zero if c < 0: game_data[str(p)]['calm'] = 0 game_data[str(p)]['will'] += c # Treat Air as maximum Calm ...
def verbose_print(verbose: bool): """ Verbose printing Parameters ---------- verbose Returns ------- """ return print if verbose else lambda *a, **k: None
def get_relative_delta(new, last): """ :param new: float New value :param last: float Last value :return: float Increase (or decrease) since last value """ if new is None or last is None: # cannot produce result return 0.0 new = float(new) last = float(...
def dpa_pass(context, event): """Dummy property assigned function that returns "data" item of context.""" return context["data"]
def canvas(with_attribution=True): """!Math of the molssi @param with_attribution: bool, Optional, (default=True) Set whether or not to display who the quote is from @return: quote (str) Compiled string including quote and optional attribution """ quote = "The code is but a canvas ...
def _get_n_opt_and_check_type_nested_list_argument(candidate, argument_required, name): """Calculate number of inputs and check input types for argument that is expected as list/tuple or nested list/tuple. Args: candidate Argument argument_required (bool): Whether a...
def api_url(host): """ Make api url to obtain version info :param host: str :return: str # """ return '{}/api/version/'.format(host)
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None): """ Run "func" with "args"&"kwargs", return "default" if not finished after "timeout" """ import signal class TimeoutError(Exception): pass def handler(signum, frame): raise TimeoutError() signal.sign...
def ib_to_cell(ib, nx, ny, nz): """Convert from cell number in Eclipse internal ordering to (i,j,k) Args: ib: Cell number in Eclipse ordering (int) nx: Grid dimension (int) ny: Grid dimension (int) nz: Grid dimension (int) Returns: 3D tuple cell number (i,j,k)...
def dict_to_stdout(dict_item: dict) -> bool: """ Prints the dict objects contents to screen. :param dict_item: A dict object to print out. :return bool: True on finish. """ for _key, _value in dict_item.items(): print(f'{_key}: {_value}') return True
def get_depth(string): """Calculates amount of whitespaces leading the given string and returns int""" # expected input (example): # string = [' 09140 Cellular Processes'] # # expected output (example): # depth = 13 depth = len(string) - len(string.lstrip(' ')) return depth
def downsample(values, target_length): """Downsamples 1d values to target_length, including start and end. Algorithm just rounds index down. Values can be any sequence, including a generator. """ assert target_length > 1 values = list(values) if len(values) < target_length: return ...
def generate_group_data(count=1): """ generate a list of dictionaries containing data necessary to create a Group object :param count: :return: """ return [{'name': 'group_{:03}'.format(i)} for i in range(1, count + 1)]
def is_valid_joint_degree(joint_degrees): """ Checks whether the given joint degree dictionary is realizable as a simple graph. A *joint degree dictionary* is a dictionary of dictionaries, in which entry ``joint_degrees[k][l]`` is an integer representing the number of edges joining nodes of degree ...
def u2i(number): """ Converts a 32 bit unsigned number to signed. number:= an unsigned 32 bit number ... print(u2i(4294967272)) -24 print(u2i(37)) 37 ... """ mask = (2 ** 32) - 1 if number & (1 << 31): v = number | ~mask else: v = number & mask return v
def validate_ticket_name(name): """ Validates that a given ticket name is valid :param name: The ticket name :return: True if name is valid """ if not name.isalnum(): return "Name must have alphanumeric characters only." if len(name) > 60: return "Name must be less than 60 c...
def clean_whitespace(text): """ Replace sequence of whitespaces by a single space """ return ' '.join(text.split())
def _cue_cmd_outputs(output_name): """Get map of cue_cmd outputs. Note that the arguments to this function are named after attributes on the rule. Args: output_name: The rule's `output_name` attribute Returns: Outputs for the cue_cmd """ outputs = { "export": output_name, ...
def wires_pyramid(wires): """Wire sequence for the pyramid pattern.""" sequence = [] for layer in range(len(wires) // 2): temp = wires[layer : len(wires) - layer] sequence += [[temp[i], temp[i + 1]] for i in range(0, len(temp) - 1, 2)] return sequence
def is_tissue_compatible(recv_pra, recv_id, don_id): """ Modeling actual compatibility is complex, and depends on properties of different HLA markers and various other complications. Instead of dealing with the medical complexities, we use a simple model that produces a uniformly-distributed value...
def _helpArraysXml(idx, inputName=None, label=None): """Internal helper """ if inputName is None: inputName = 'Input' if label is None: label = 'Array%d' % idx return''' <StringVectorProperty name="SelectInputScalars%d" label="%s" command="SetInputArrayT...
def reduceby(key, binop, seq, init): """ Perform a simultaneous groupby and reduction The computation: >>> result = reduceby(key, binop, seq, init) # doctest: +SKIP is equivalent to the following: >>> def reduction(group): # doctest: +SKIP ... return reduce...
def ensureByteString(string): """ :param string: A string. :return: The string as a byte string. """ return string if isinstance(string, bytes) else string.encode('utf-8')
def is_winner(pC, cL): """Return a Bool if the given player is a winner.""" return ((cL[0] == pC and cL[1] == pC and cL[2] == pC) or #victory in first row (cL[3] == pC and cL[4] == pC and cL[5] == pC) or #victory in second row (cL[6] == pC and cL[7] == pC and cL[8] == pC) or #victory in ...
def get_section_similarity(tokens_in_sentence, tokens_in_section): """ Computes the similarity of a paper' section with a sentence. Parameters ---------- tokens_in_sentence: list All tokens in the sentence. tokens_in_section: list All tokens in the selected section. Returns ...
def ListToString(MyInput): """ To change list into string """ if isinstance(MyInput,str): return(MyInput) else: return(MyInput[0])
def _definitely_lb_config(probably_lb_config): """ Returns a load balancer configuration unscathed. If passed something that looks like a CLB id, synthesizes a fake load balancer configuration. :param probably_lb_config: An object that is probably a load balancer configuration, except maybe...
def real_or_comp(str_rep): """ convert the string representation of a real or complex number into float or complex e.g. real_or_comp('1.5') -> 1.5, real_or_comp('(1.0,-1.0)') -> 1.0-1j*1.0 Args: str_rep (str): string representation of a real or complex number Returns: complex/real: value of str_rep ""...
def get_common_elements(element_list): """ :param element_list: list of list where each internal list contains values :return: a sorted list of elements which are common in all the internal lists """ common_element_list = set(element_list[0]) index = 1 while index < len(element_list): ...
def power(x,n): """ Compute x^n, where x, n can both be negative integer. :param x: Int -- the base :param n: Int -- the exponent :return: Int -- x^n """ try: if n==0: return 1 elif n==1: return x elif n>1: return x*power(x,n-1) ...
def _get_authz_from_row(row): """ Given a row from the manifest, return the field representing file's expected authz resources. Args: row (dict): column_name:row_value Returns: List[str]: authz resources for the indexd record """ return [item for item in row.get("authz", ""...
def get_ohm_stakers(ohm_supply, reward_rate): """ ohm_supply: The total supply of existing OHM, not including bonds_outstanding. Bonded OHMs are gradually added to ohm_supply during the vesting period. reward_rate: The set percentage of OHM distributed to the stakers on each ...
def get_alias_data(alias_list, ext_refs): """This function generates the Alias Description section for the pages""" if not alias_list: return [] alias_data = [] # Look through the list of aliases to find a match to the external # references. Then, create a list of all the mapped aliases ...
def getStringParams(param_str): """Determines which keys are required if param_str.format() function is used. Returns the required keys as a list. """ params = [] index = 0 while True: index = param_str.find("{", index) if index >= 0: end_index = param_str.find("}"...
def clean_astrometry(ruwe, ipd_gof_harmonic_amplitude, visibility_periods_used, astrometric_excess_noise_sig, astrometric_params_solved, use_5p = False): """ Select stars with good astrometry in Gaia. """ labels_ruwe = ruwe <= 1.4 labels_harmonic_amplitude = ipd_gof_harmonic_amplitude <= 0.2 ...
def capitalize_name(your_name: str): """Decorator that checks NumPy results and CuPy ones are equal. Args: err_msg(str): The error message to be printed in case of failure. verbose(bool): If ``True``, the conflicting values are appended to the error message. name(str): A...
def decode_rate_depth(x: int): """return rate and depth from encoded representation""" rate = x >> 8 depth = x & 0xff return rate, depth
def gcd(a,b): """ Returns the greatest common divisor of a and b """ while b > 0: a, b = b, a % b return a
def or_combination(disjunction, term): """ Join together a disjunction and another term using an OR operator. If the term is a lexeme, we simply append it as a new conjunction to the end of the disjunction. If the term is another disjunction, then we concatenate both disjunctions together. """ i...
def nested_functions(x): """Docstring.""" def inner_fn(y): return y return inner_fn(x)
def convert_to_float(s): """Takes a string s and parses it as a floating-point number. If s can not be converted to a float, this returns None instead.""" to_return = None try: to_return = float(s) except: to_return = None return to_return
def _first_or_none(array): """ Pick first item from `array`, or return `None`, if there is none. """ if not array: return None return array[0]
def isstring(value): """ Filter that returns a type """ if value is str: return True else: return False
def get_meta_params(meta): """ Parse the metadata selections for querying """ duration = meta.get('duration', ['any']) views = meta.get('views', ['any']) upload = meta.get('upload', ['any']) meta_new = {} # Figure out the max duration requested if len(duration) == 3 or 'any' in duration: ...
def get_offset_limit(args): """ return offset limit """ if 'offset' in args and 'limit' in args: try: offset = int(args.get('offset', 0)) except ValueError: offset = 0 try: limit = int(args.get('limit', 20)) except ValueError: limit = 0...
def to_ustr(obj): """Convert to string.""" if isinstance(obj, str): return obj elif isinstance(obj, bytes): return str(obj, 'utf-8') else: return str(obj)
def _calculate_graduation_year(x): """Calculate the cohort year for an enrollment record""" if x["Grade"] == "K": return int(x["Year"]) + 5 elif x["Grade"] == "1": return int(x["Year"]) + 4 elif x["Grade"] == "2": return int(x["Year"]) + 3 elif x["Grade"] == "3": retu...
def linkDifference(linko): """The longest link from the nodes.""" differences=[] for (node, entry) in enumerate(linko): if len(entry[2]) != 0: differences.append(max({fl - node for fl in entry[2]})) else: differences.append(0) return differences
def agent_is_active(agent_path, time_step): """Checks whether or not an agent changes his position at any time in the future. :param agent_path: The agent's solution. :param time_step: The time step, from which one the path should be checked. :return: Whether or not the agent will move at any time in t...
def make_versioned_tag(tag, version): """ Generate a versioned version of a tag. """ return '%s-%d' % (tag, version)
def get_shape_e(ba): """ Return ellipticity ``e`` given minor-to-major axis ratio ``ba``. Parameters ---------- ba : float, ndarray Minor-to-major axis ratio (b/a). Returns ------- e : float, ndarray Ellipticity. References ---------- https://www.legacysurv...
def list_string_to_dict(string): """Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.""" dictionary = {} for idx, c in enumerate(string): dictionary.update({c: idx}) return dictionary
def read_run_id(run_id: str): """Read data from run id""" parts = run_id.split("-") git_commit = parts[-1] timestamp = parts[-2] model_name = "-".join(parts[:-2]) return model_name, timestamp, git_commit
def unify_walk(d1, d2, U): """ Tries to unify values of corresponding keys. """ for (k1, v1) in d1.items(): if d2.has_key(k1): U = unify_walk(v1, d2[k1], U) if U is False: return False return U
def lis_dp(array): """ Returns the length of the longest increasing sub-sequence in O(N^2) time. This is not fast enough to pass with the HackerRank time constraints. """ n = len(array) if n == 0: return 0 dp = [1] * n # Let F(i) be the LIS ending with array[i]. F[i] = max({1 +...
def create_job_key(executor_id, job_id): """ Create job key :param executor_id: prefix :param job_id: Job's ID :return: exec id """ return '-'.join([executor_id, job_id])
def _data_not_in_spec(spec): """check to see if the data element is defined for this spec """ if isinstance(spec, dict): return 'data' not in spec return True
def NoDups( s ): """Return true if s has no duplicates""" return len( set( s ) ) == len( s )
def eval_box_corners(box, tfm_func): """" (x1,x1,y1,y2) -> ( xa, ya, xb, yb, xc, yc, xd, yd ) ad bc """ x1,y1,x2,y2 = box return tfm_func(x1,y1) + tfm_func(x1,y2) + tfm_func(x2,y2) + tfm_func(x2,y1)
def skip_prologue(text, cursor): """skip any prologue found after cursor, return index of rest of text""" ### NOT AT ALL COMPLETE!!! definitely can be confused!!! prologue_elements = ("!DOCTYPE", "?xml", "!--") done = None while done is None: #print "trying to skip:", repr(text[cursor:cursor...
def cameraEfficiencySimtelFileName(site, telescopeModelName, zenithAngle, label): """ Camera efficiency simtel output file name. Parameters ---------- site: str South or North. telescopeModelName: str LST-1, MST-FlashCam-D, ... zenithAngle: float Zenith angle (deg). ...
def pointInShape(s, p): """ check wether a given point p lies within the shape s. this is the problem known as point in polygon. to do so it counts the intersections of a ray going out of the point towards the upper left corner. if the number of intersections is even, the point is on the outside...
def get_item_count_dictionary_from_list(generic_list): """ Given a list of items returns a dictionary containing its counts :param generic_list: List containing the items :return: Dictionary containing the item counts """ generic_dict = dict({}) for element in generic_list: if eleme...
def clean_str(val): """Cleanup a bad string (invalid UTF-8 encoding).""" if isinstance(val, bytes): val = val.decode('UTF-8', 'replace') return val
def merge_partials(header, used_partials, all_partials): """Merge all partial contents with their header.""" used_partials = list(used_partials) return '\n'.join([header] + [all_partials[u] for u in used_partials])
def gridIndicesToMatIndices(i,j, maxI, maxJ): """ converts grid coordinates to numpy array coordiantes grid has (0,0) at bottom left corner, numpy has (0,0) at top left corner. :param i: x - column index :param j: y - row index :param maxI: number of columns in grid :param maxJ: number o...
def add_resource_to_list(resourcedict_list, resource_dict, debug=False): """Add a single resource_dict to a resourcedict_list if URL is unique Arguments: resourcedict_list (List of dicts): package_show(id="xxx")["resources"] resource_dict (dict): One resource dict debug (Boolean): D...
def _ljust(input, width, fillchar=None): """Either ljust on a string or a list of string. Extend with fillchar.""" if fillchar is None: fillchar = ' ' if isinstance(input, str): return input.ljust(width, fillchar) else: delta_len = width - len(input) if delta_len <= 0: ...
def normalize_study_id(study_id): """We still have some un-prefixed IDs (at least on the devapi)""" try: int(study_id) return 'pg_' + str(study_id) except: return study_id
def mean(data): """Return the sample arithmetic mean of data.""" n = len(data) if n < 1: return 0 return sum(data)/float(n)
def int_triples_leq_n_when_summed(n): """ Construct a list of 3-tuples of integers (>=0) such that the sum of each tuple is less or equal `n`. Parameters ---------- n : int Upper bound for the sum of each 3-tuple. Returns ------- triples_list : list A list of 3-tupl...
def process_sentence(sentence): """Convert a string into a list of lowercased words.""" return sentence.lower().split()
def screaming_snake_to_snake_case(text: str) -> str: """Convert SCREAMING_SNAKE_CASE to snake_case.""" return text.lower()
def avg_coords_list(coords): """ :param coords: list of lists or tuples [(lon1, lat1), ...(lonN, latN)] :return: dict {lat: xxx, lon: yyy} """ count = float(len(coords)) lon, lat = 0, 0 for x in coords: lon += x[0] lat += x[1] return {"lat": lat/count, "lon": lon/count}
def get_row_col_bounds_here(level): """ [x,y] or [col, row], start from bottom left, go anti-clockwise level 0: 0,0 level 1: 0,0; 1,0 level 2: 0,0; 0,1; 1,0; 1,1; 2,0; 2,1; 3,0; 3,1 """ nrow = 2 ** (level - 1) if level else 1 ncol = 2 ** level return nrow, ncol
def median(numbers): """ Parameters ---------- numbers : list a list of numbers Returns ------- median : double the median of the list of numbers passed """ numbers.sort() if len(numbers) % 2 == 1: median = numbers[-round(-len(numbers) / 2)] media...
def _K1(n, s, t, lambda_decay=0.5): """ K'_n(s,t) in the original article; auxiliary intermediate function; recursive function :param n: length of subsequence :type n: int :param s: document #1 :type s: str :param t: document #2 :type t: str :return: intermediate float value """ ...