content
stringlengths
42
6.51k
def check_password_length(password): """ Password length must be between 6 and 32 """ if 6 <= len(password) <= 32: return True return False
def url_path_join(*pieces): """Join components of url into a relative url. Use to prevent double slash when joining subpath. This will leave the initial and final / in place. Copied from `notebook.utils.url_path_join`. """ initial = pieces[0].startswith("/") final = pieces[-1].endswith("/") ...
def path_is_url(path): """ returns True when input (assumed string) starts either http:// Or https:/ """ return path[0:4] == 'http' and path[6] == '/'
def stations_level_over_threshold(stations, tol): """returns a list of tuples, where each tuple holds (i) a station (object) at which the latest relative water level is over tol and (ii) the relative water level at the station. The returned list should be sorted by the relative level in descending order Parame...
def gcd(a, b): """Returns the greatest common divisor of a and b. Should be implemented using recursion. >>> gcd(34, 19) 1 >>> gcd(39, 91) 13 >>> gcd(20, 30) 10 >>> gcd(40, 40) 40 """ if a < b: return gcd(b, a) if a > b: return b if a % b == 0 else gc...
def remove_duplicates(source): """ Function to remove any duplicates elements in a list[].""" target = [] for element in source: if element not in target: target.append(element) return target
def list_of_str_from_list_of_int(list_int, fmt='%04d'): """Converts [1, 202, 203, 204,...] to ['0001', '0202', '0203', '0204',...] """ return [fmt % i for i in list_int]
def base_dir(path_of_file): """ Extract the previous or base directory name. """ base_path = path_of_file.split("/") del base_path[0] del base_path[-1] conc_base = [] for i in base_path: conc_base.append("/" + i) conc_base = "".join(conc_base) return conc_base
def pull_value(x, path): """ Safe extraction for pulling entity values """ crnt_obj = x for attr in path.split("."): try: crnt_obj = crnt_obj[attr] except KeyError: return None return crnt_obj
def merge(a, b, path=None, conflict_resolver=None): """merges b into a""" if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge(a[key], b[key], path + [str(key)], conflict_resolver) elif i...
def flattenDoc(docString): """ Take an indented doc string, and remove its newlines and their surrounding whitespace """ clean = '' lines = docString.split('\n') for line in lines: clean += line.strip() + ' ' return clean
def calc_shield_power(block_count, active=False): """ Calculate the power usage of Shield Rechargers Given the number of Shield Rechargers, this function will calculate how much power they draw in 'e/sec'. It will calculate both inactive (shields full) and active (shields charging) power consumption b...
def wtflist2str(wtflist): """Convert the crazy pandoc internal format into something that is much plain text.""" str_cache = "" for entity in wtflist: if entity['t'] == "Space": str_cache = str_cache + " " elif entity['t'] == "RawInline": #str_cache = str_cache + "\n"...
def convert_currency(s): """ Convert the string number value to a float - Remove $ - Remove commas - Convert to float type http://pbpython.com/pandas_dtypes.html """ new_s = s.replace(',','').replace('$', '') return float(new_s)
def _apply_signed_threshold(value, min_thr=None, max_thr=None): """ Apply threshold on signed value. usage examples : >>> _apply_signed_threshold(0.678, min_thr=0.5) 0.5 >>> _apply_signed_threshold(-0.678, min_thr=0.5) -0.5 >>> _apply_signed_threshold(0.678, max_thr=2.0) 0.678 >>> _apply_signed_thres...
def castDatalistToInteger(list = []): """ Converts a list to float number values """ datalist = list numberlist = [] for item in datalist: numberlist.append(int(item)) return numberlist
def time_as_float(time_string: str) -> float: """converts a given HH:MM time string to float""" try: hours, minutes = list(map(int, time_string.split(":"))) # parse given time string except ValueError as e: message = f"Invalid time string, ensure that the argument is in HH:MM format. Provid...
def is_3d(blockSize): """ Is the given block size a 3D block type? Args: blockSize (str): The block size. Returns: bool: ``True`` if the block string is a 3D block size, ``False`` if 2D. """ return blockSize.count("x") == 2
def groupby(keys, values): """Group values according to their key.""" d = {} for k, v in zip(keys, values): d.setdefault(k, []).append(v) return d
def gf_int(a, p): """ Coerce ``a mod p`` to an integer in ``[-p/2, p/2]`` range. **Examples** >>> from sympy.polys.galoistools import gf_int >>> gf_int(2, 7) 2 >>> gf_int(5, 7) -2 """ if a <= p // 2: return a else: return a - p
def processCEF(assemeblyModelSubstring): """This function parses the substrings of the assembly model string and provides back information on the modularity and planarity.""" assemeblyModelSubstring = assemeblyModelSubstring[1:] nummod = assemeblyModelSubstring.split('X') num = int(nummod[0]) mod = ...
def possible_contigious_sequence(interval, max_num): """All possible contigous subsequences of a list up to max length.""" subsequence = [] for num in range(2, max_num + 1): subsequence += [interval[i:i + num] for i in range(0, len(interval))][:(-(num-1))] return subsequence
def vLengthSquared(v): """ Return Vector length squared i.e., don't take the square root """ return v[0]*v[0] + v[1]*v[1] + v[2]*v[2]
def SDOF_dashpot(M,K,eta): """ Returns the dashpot rate of SDOF oscillator given mass, stiffness and damping ratio inputs $$ \lambda = 2\zeta\sqrt{KM} $$ *** Required: * `M`, mass (kg) * `K`, stiffness (N/m) * `eta`, damping ratio (1.0=critical) """...
def meters_to_km_miles(area): """ Meters are recorded as Cartesian Square Miles within shapely and this method will return both the square km and square Miles as a list :param area: Cartesian Square Miles area :return: list of [km_sq, Miles_sq] :rtype: list[float, float] """ kmsq = area...
def get_tag_params(tag_model): """Load param strs and n_header based on model of tag model""" tag_model = tag_model.replace("-", "") tags = dict() tags["W190PD3GT"] = [ "Acceleration-X", "Acceleration-Y", "Acceleration-Z", "Depth", "Propeller", "Temperatu...
def default_if_none(*values): """Return the first argument that is not 'None'.""" for value in values: if value is not None: return value return None
def index(i: int) -> str: """Return index if it is not -1 """ return "[{}]".format(i) if i != -1 else ""
def pyth_triplet_test(triplet): """ Checks if a given list of 3 integers is a pythagorean triplet :param triplet: List of 3 integers to be tested :returns: 'True' if 'triplet' is a pythagorean triplet, 'False' if not """ if triplet[0]**2 + triplet[1]**2 == triplet[2]**2: return True ...
def num_decodings2(enc_mes): """ :type s: str :rtype: int """ if not enc_mes or enc_mes.startswith('0'): return 0 stack = [1, 1] for i in range(1, len(enc_mes)): if enc_mes[i] == '0': if enc_mes[i-1] == '0' or enc_mes[i-1] > '2': # only '10', '20' ...
def _numeric_type(param): """ Checks parameter type True for float; int or null data; false otherwise :param param: input param to check """ return isinstance(param, (float, int)) or param is None
def create_subject(scheme, sid, term): """ """ subject = { 'id': sid, 'scheme': scheme, 'subject': term} return subject
def fixed(name, value, length=1): """Creates fixed hyperparameter setting.""" return [{name: value} for _ in range(length)]
def get_puzzle_data(puzzle, data={}): """Get length and list of numbers from puzzle.""" if not data: data['length'] = len(str(puzzle)) data['wanted'] = [int(num) for num in str(puzzle)] return data['length'], data['wanted']
def channel_to_freq(channel): """ freq -- frequqncy in Hz return -- channel number """ if 1 <= channel <= 13: return 2407000000 + channel * 5 * 1000000 if channel == 14: return 2484000000 if channel >= 15: return 5035000000 + (channel - 7) * 5 * 1000000 return None
def dict_merge(dict1: dict, dict2: dict): """Merges two dictionaries into one. Examples: >>> x = {'a': 1, 'b': 2}\n >>> y = {'b': 3, 'c': 4}\n >>> dict_merge(x, y)\n {'a': 1, 'b': 3, 'c': 4} References: https://www.youtube.com/watch?v=Duexw08KaC8 """ return ...
def read_file(infile): """Read an ASCII file and return the contents.""" f_in = open(infile) contents = f_in.readlines() f_in.close() return contents
def get_row(grid, n: int) -> list: """Returns a row""" return grid[n - 1]
def to_dict_with_sorted_values(d, key=None): """to dict with sorted values""" return {k: sorted(v, key=key) for k, v in d.items()}
def apply(fun, args, kwargs=None): """ applies a list of arguments (and an optional dict of keyword arguments) to a function. Complexity: O(k) where k is the complexity of the given function params: fun: the function that should be applied args: the list of values we should reduce ...
def smart_bool(s, fallback=False): """Convert a string that has a semantic boolean value to a real boolean. Note that this is not the same as ``s`` being "truthy". The string ``'False'`` will be returned as False, even though it is Truthy, and non- boolean values like ``'apple'`` would return the fallb...
def count_first_choices(L): """ Return dict giving count of all first choices in ballot list L. Args: L (list): list of ballots Returns: (dict): dictionary mapping all choices that occur at least once as a first choice to count of their number of choices. E...
def convert_bytes_to_size(some_bytes): """ Convert number of bytes to appropriate form for display. :param some_bytes: A string or integer :return: A string """ some_bytes = int(some_bytes) suffix_dict = { '0': 'B', '1': 'KiB', '2': 'MiB', '3': 'GiB', ...
def format_time(time): """Turn a time value in seconds into hh:mm:ss or mm:ss.""" if time < 0: time = abs(time) prefix = "-" else: prefix = "" if time >= 3600: # 1 hour # time, in hours:minutes:seconds return "%s%d:%02d:%02d" % (prefix, time // 3600, (time % 360...
def basis_function(degree, knot_vector, span, knot): """ Computes the non-vanishing basis functions for a single parameter. Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. Uses recurrence to compute the basis functions, also known as Cox - de Boor recursion formula. :param ...
def is_function(f): """ Is it a function? :param f: function :return: boolean """ return hasattr(f, '__call__')
def word_count(review_str)->int: """ count number of words in a string of reviews """ return len(review_str.split())
def get_value_from_dict(key_path, input_dict): """ Returns the value of a key in input_dict key_path must be given in string format with dots Example: result.dir """ if not isinstance(key_path, str) or not isinstance(input_dict, dict): return None for key in key_path.split('.'): ...
def collapse_ticket_lines(basket): """ Collapses ticket lines into a single quantity for each date Parameters: basket (Basket Dictionary): The basket to collapse Returns: (Dictionary): The collapsed dictionary """ ticket_dates = {} for date_id in basket: for type_id in bas...
def simple_atmo_opstring(haze, contrast, bias): """Make a simple atmospheric correction formula.""" gamma_b = 1 - haze gamma_g = 1 - (haze / 3.0) ops = ( "gamma g {gamma_g}, " "gamma b {gamma_b}, " "sigmoidal rgb {contrast} {bias}" ).format(gamma_g=gamma_g, gamma_b=gamma_b, contrast=contrast...
def clean_header(header: str): """Clean header for simulation outputs""" if '[' in header: return header[0:header.rindex('[')-1] return header
def annotate(items, fn, sort_fn=None, reverse=True): """Return a dict with elements of items as keys and their values under fn as their values, sorted by their values under sort_fn. If sort_fn isn't specified, use fn by default. >>> annotate([4, 3, 2, 1], fn=lambda x: x**2, sort_fn=lambda x: (-2)**x, reve...
def get_raw_title(title): """get raw title""" if title[-2:] == "_0": return title[:-2] return title
def calculate_pnl_per_equity(df_list): """Method that calculate the P&L of the strategy per equity and returns a list of P&L""" pnl_per_equity = [] # initialize the list of P&L per equity for df in df_list: # iterates over the dataframes of equities pnl = df['Strategy Equity'].iloc[-1] - df['Buy and...
def OR(p: bool, q: bool) -> bool: """ Disjunction operator used in propositional logic """ return bool(p or q)
def line2d(x, y, coeffs=[1]*3, return_coeff=False): """Returns the result of a 2D quadratic, or returns the coefficients""" a0 = (x*0+1)*coeffs[0] a1 = x*coeffs[1] a2 = y*coeffs[2] if return_coeff: return a0, a1, a2 else: return a0+a1+a2
def format_output(output,format): """ Return a string for 'output' with the specified format. If output is None, it returns 'NA'.""" if output!=None: return format%output else: return 'NA'
def get_expression(text, begin, separator): """Find the end of a expression or statement An expression or statement ends at a new-line or at the separator, unless the new-line or separator is encountered inside a string-literal or inside matching bracket pairs. @param text The total text being pars...
def fromSI(value: str) -> float: """converts from SI unit values to metric Args: value (str): a value in SI units, e.g. 1.3u Returns: float: the value in metric units. """ return float(value.replace("u", "e-6"))
def _parse_url(url): """ This function extracts certain components from a given URL. """ authority = url.split('/')[2] uri = '/'.join(url.split('/')[3:]) if ':' not in authority: port = 80 host = authority else: host, port = authority.split(':') return host...
def clamp(minVal, val, maxVal): """Clamp a `val` to be no lower than `minVal`, and no higher than `maxVal`.""" return max(minVal, min(maxVal, val))
def le16_bytes_to_list(bstr): """Convert 16bit little-endian bytes to list""" i = iter(bstr) return [lb + 256*next(i) for lb in i]
def _copy_with_exclude_idx(records, tgtidx): """ generate a new list of records without the target idx: tgtidx Arguments: records {[list of list]} -- [original records] tgtidx {[int]} -- [target idx will be excluded from records] Returns: [list of list] -- [...
def tf_node_name(name): """Get node name without io#.""" pos = name.find(":") if pos >= 0: return name[:pos] return name
def iterlines(text): """ Splits lines in string at '\n' while preserving line endings. """ lines = text.split('\n') if text[-1] == '\n': lines = [line + '\n' for line in lines[:-1]] return lines else: lines = [line + '\n' for line in lines[:-1]] + [lines[-1]] retu...
def rshift(x, n): """For an integer x, calculate x >> n with the fastest (floor) rounding. Unlike the plain Python expression (x >> n), n is allowed to be negative, in which case a left shift is performed.""" if n >= 0: return x >> n else: return x << (-n)
def secure_lookup(data, key1, key2 = None): """ Return data[key1][key2] while dealing with data being None or key1 or key2 not existing """ if not data: return None if key1 in data: if not key2: return data[key1] if key2 in data[key1]: return data[key1...
def non_none(*args, raise_if_all_none=None): """ Return the first arg that is not none; optionally raise specified exception if all none """ for a in args: if a is not None: return a if raise_if_all_none is not None: raise raise_if_all_none return None
def compositeWallSeries(resistanceList): """This function calculates the resistance value of resstances in series the input ("resistanceList" is a list of resistances each of which is adictionary for example:R1={"name":"R1","type":"cond","length":0.03,"area":0.25,"k":0.026} and a set of resistances resi...
def flatten(x): """Flatten a list of arbitrary depth. Returns a list with no sub-lists or sub-tuples. If the input is not a list or a tuple, it will be returned as a one-element list. """ if not isinstance(x, (list, tuple)): return [x] else: if len(x) == 0: return [] ...
def assign_vars(vars_, values): """Returns the update ops for assigning a list of vars. Args: vars_: A list of variables. values: A list of tensors representing new values. Returns: A list of update ops for the variables. """ return [var.assign(value) for var, value in zip(vars_, values)]
def rearange_base_link_dict(dictionary, base_link_index): """Rarange base link to beginning of table""" new_dict = {} for key, value in dictionary.items(): new_dict[key] = ( 0 if value == base_link_index else value + 1 if value < base_link_index else value ...
def ccw(x, y, z): """ Counterclockwise angle formed by [x, y] and [x, z] Taken from https://stackoverflow.com/a/9997374 """ return (z[1] - x[1]) * (y[0] - x[0]) > (y[1] - x[1]) * (z[0] - x[0])
def invert_dict(dic, sort=True, keymap={}, valmap={}): """Inverts a dictionary of the form key1 : [val1, val2] key2 : [val1] to a dictionary of the form val1 : [key1, key2] val2 : [key2] Parameters ----------- dic : dict Returns ----------- dict """ dic_...
def test_decoder(obj): """Decode objects generated by the TestEncoder. Returns datetime object as string instead of datetime instances. """ if '$dt' in obj: return obj['$dt'] return obj
def evaluateConditions(conditions, location): """ Return True if all the conditions matches the given location. If a condition has no minimum, check for < maximum. If a condition has no maximum, check for > minimum. """ for cd in conditions: value = location[cd['name']] if cd...
def valid_post_data(data, required_keys): """ Return any missing required post key names. """ return [key for key in required_keys if key not in data]
def point(value): """ Convert an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ return "{:20,.2f}".format(value)
def string_to_dict(separated_string, separator=',') -> dict: """ Takes a string e.g: a,b,,,,c, ,d and converts to: {'a':'', 'b':'', 'c':'', 'd':''} """ output = {} if isinstance(separated_string, str) and len(separated_string) > 0: values = separated_string.split(separato...
def intoDecimal(n): #converts the incoming character into decimal """ Input: String value as 'n' Returns: Corresponding decimal value of 'n' """ return int(n,2)
def argument(*name_or_flags, **kwargs): """Convenience function to properly format arguments to pass to the subcommand decorator. """ return [*name_or_flags], kwargs
def v11_add(matrix1, matrix2): """Add corresponding numbers in given 2-D matrices. Solving the second bonus - raise a ValueError exception when our lists-of-lists were different shapes. Calculating the length of the matrices to determine if they are the same size. """ if [len(r) for r in m...
def normalize(t): """ Get a sorted list of party letters for inserting into set/hash. :param t: set of letters :return: string with sorted letters """ return "".join(sorted(list(t)))
def dict_key_checker(current_dict, current_key): """ Function to check if a dictionary contains a key. Parameters: current_dict (dict): The dictionary. current_key (str): They key. Returns: True if the dictionary contains the key. False otherwise. """ if current_key in cu...
def _convert_type(type_): """ Given a ``type_``, convert to a UUID attribute name. The empty string converts to ``uuid``. :param type_: UUID type :type type_: str :return: UUID attribute name :rtype: str """ if type_ == 'uuid' or type_ == '': return 'uuid' else: ...
def merge_dicts(d_root: dict, d_append: dict) -> dict: """ Return new dictionary with d_append added to d_root at the root level :param d_root: input dictionary :param d_append: dictionary to append :return: combined dict """ return {**d_root, **d_append}
def pad_date(fld): """input a date field, strip off the time and format""" if fld is not None: lst = [int(i) for i in (str(fld).split(" ")[0]).split("-")] return "{}-{:02.0f}-{:02.0f}".format(*lst) else: return None
def calculate_height(distance, y_max, y_min, focal_y): """ Calculate real person height in centimeters. """ px_height = y_max - y_min person_height = distance * px_height / focal_y return person_height
def HexToRGB(hex_str): """Returns a list of red/green/blue values from a hex string. @param hex_str: hex string to convert to rgb """ if hex_str: hexval = hex_str if hexval[0] == u"#": hexval = hexval[1:] ldiff = 6 - len(hexval) hexval += ldiff * u"0" ...
def intersects(fields, values): """ Test if there are any fields in the values """ overlap = set(fields).intersection(values.keys()) return len(overlap) > 0
def hasConnection(passW,tags): """ Checks if the password has no connectio To the informations about the person Returns the strength of the Connection 0-10 """ connection=0 for i in tags: if(i.name.lower() in passW.lower()): print("[Found Connection]>",i.name.lower()) ...
def parseAvailable(available_text): """Parse an Available: line's data str -> [str] """ return [s.strip() for s in available_text.split(',')]
def get_service_type(f): """Retrieves service type from function.""" return getattr(f, 'service_type', None)
def both_positive(x, y): """Returns True if both x and y are positive. >>> both_positive(-1, 1) False >>> both_positive(1, 1) True """ return x > 0 and y > 0
def get_subset_lengths(length, split_percentages): """ :param length: length of dataset :param split_percentages: triple of floats that sum to 1 :return: triple of ints - lengths of subsets """ assert sum(split_percentages) == 1, "split_percentages have to sum up to 1" assert len(split_perce...
def at_least_ell_fct(i, ell): """At-least-ell score function. Gives a score of 1 if ell approved candidates are in the committee. The CC score function is equivalent to the At-least-1 score function.""" if i == ell: return 1 else: return 0
def separar_atributos(texto): """ Separates the attributes/Separa os atributos. """ atributos = [] if '&%loop' in texto: atributos.append('loop') if '&common_web' in texto: atributos.append('common_web') if '&google_dorks' in texto: atributos.append('google_dorks')...
def is_list_sorted(list): """ Check if sorted in ascending order. input is a list of values. output: sorted =1 or 0 """ sorted = 1; for index in range(0, len(list)-1): if list[index] > list[index+1]: sorted = 0; retu...
def list_to_id_dict(base, attribute): """ Return a dict from an attribute in a list of dicts. """ ret = {} for d in base: ret[d[attribute]] = d return ret
def go_var(s: str, export: bool = True) -> str: """Convert a variable name in the input file to a Go variable name.""" s = f"{(str.upper if export else str.lower)(s[0])}{s[1:]}" for sep in ["-", "_", ".*.", "[].", "."]: while sep in s: _len = len(sep) if s.endswith(sep): ...