content
stringlengths
42
6.51k
def break_string(string, length): """Attempts to line break a long string intelligently. Arguments: - string -- the string to be broken. - length -- the maximum length of the line. Returns: the line broken string. """ break_list = [] # Go through the string at points...
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 >>> falling(4, 0) 1 """ "*** YOUR CODE HERE ***" sum = 1 while n and k: sum *= n n -= 1 ...
def firmVolumeFrac(volume, shares, sharesUnit=1000): """ Fraction of shares turned over Returns FLOAT """ # SHROUT in thousands shares_out = shares * sharesUnit return volume / shares_out
def is_valid_version_code(version): """ Checks that the given version code is valid. """ return version is not None and len(version) == 5 and \ int(version[:4]) in range(1990, 2050) and \ version[4] in ['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
def symetry(m): """ Symetrisize the values of the matrix on the y axis. """ matrix = [] for row_index in range(len(m)): result_row = [] for value_index in range(len(m[0])): # symerization of matrix1 only by the row_index value (y axis) new_value = (float(m[ro...
def partition(arr, start, end): """ Helper function that partitions/orders array elements around a selected pivot values Time complexity: O(n) Space complexity: O(1) """ # Select pivot pivot = arr[end] # Initialize partition index as start partition_index = start ...
def boost_node(n, label, next_label): """Returns code snippet for a leaf/boost node.""" return "%s: return %s;" % (label, n['score'])
def get_headers(header_row): """ Takes array of headers and sets up a dictionary corresponding to columns. """ ans = {} for i in range(len(header_row)): ans[header_row[i]] = i return ans
def _char_hts_as_lists(data): """returns a [[(base, height), ..], ..]""" # data is assumed row-oriented result = [] for d in data: try: d = d.to_dict() except AttributeError: # assume it's just a dict pass if d: d = list(d.items())...
def to_html(r, g, b): """Convert rgb to html hex code.""" return "#{0:02x}{1:02x}{2:02x}".format(r, g, b)
def html_table_to_excel(table): """ html_table_to_excel(table): Takes an HTML table of data and formats it so that it can be inserted into an Excel Spreadsheet. """ data = {} table = table[table.index('<tr>'):table.index('</table>')] rows = table.strip('\n').split('</tr>')[:-1] for (x, row) ...
def parse_acl(acl_string): """ Parses a standard Swift ACL string into a referrers list and groups list. See :func:`clean_acl` for documentation of the standard Swift ACL format. :param acl_string: The standard Swift ACL string to parse. :returns: A tuple of (referrers, groups) where referrers is ...
def argsort(a): """return index list to get `a` in order, ie ``a[argsort(a)[i]] == sorted(a)[i]`` """ return sorted(range(len(a)), key=a.__getitem__)
def sgn(x): """Return the sign of x.""" return -1 if x < 0 else 1
def condition_3(arg): """ CONDITION 3: It contains a double letter(At least 2 similar letters following each other like b in "abba". :param arg: :return: """ alphabets = "abcdefghijklmnopqrstuvwxyz" for letters in alphabets: sub_string = letters * 2 if sub_string in arg: ...
def is_even(n: int) -> bool: """ Checks if a number is even(lol). :param n: The number. :return: True if it is even else false. """ return n % 2 == 0
def convert_cpu_limit(cpus: float) -> int: """Convert a provided number of CPUs to the equivalent number of nano CPUs accepted by Docker. Args: cpus: Represents the full number of CPUs. Returns: The equivalent number of nano CPUs. This is the number accepted by Docker. """...
def get_luminance(pixel): """Use the pixels RGB values to calculate its luminance. Parameters ----------- pixel : tuple Returns ------- float Value is between 1.0 and 0.0 """ luminance = 0.299 * pixel[0] + 0.587 * pixel[1] + 0.114 * pixel[2] luminance /= 255 retur...
def serialize_folder(metadata): """Serializes metadata to a dict with the display name and path of the folder. """ # if path is root if metadata['path'] == '' or metadata['path'] == '/': name = '/ (Full Dropbox)' else: name = 'Dropbox' + metadata['path'] return { 'nam...
def get_time_shift_pad_offset(time_shift_amount): """Gets time shift paddings and offsets. Arguments: time_shift_amount: time shift in samples, for example -100...100 Returns: Shifting parameters which will be used by shift_in_time() function above """ if time_shift_amount > 0: time_shift_paddin...
def str_to_bool(value): """ Convert a string representing a boolean to a real boolean """ if str(value).lower() in ["true", "yes", "o"]: return True elif str(value).lower() in ["false", "no", "n"]: return False else: raise ValueError("Not accepted boolean value: {}".format(value)...
def get_mesos_disk_status(metrics): """Takes in the mesos metrics and analyzes them, returning the status. :param metrics: mesos metrics dictionary :returns: Tuple of the output array and is_ok bool """ total = metrics['master/disk_total'] used = metrics['master/disk_used'] available = tot...
def only_some_keys(dic, keys): """Return a copy of the dict with only the specified keys present. ``dic`` may be any mapping. The return value is always a Python dict. :: >> only_some_keys({"A": 1, "B": 2, "C": 3}, ["A", "C"]) >>> sorted(only_some_keys({"A": 1, "B": 2, "C": 3}, ["A"...
def and_expr(terms): """Creates an SMTLIB and statement formatted string Parameters ---------- terms: A list of float values to include in the expression """ expr = "(and" for term in terms: expr += "\n " + term expr += ")" return expr
def is_seq_qual(seq,ambt,chars='ACGT'): """ Test if sequence is of good quality based on the proportion of ambiguous characters. Arguments: - seq - a string of letters - ambt - ambiguous characters threshold (%) - chars - string of allowed characters """ # no. of sites in the record ...
def adj_factor(original_size): """Calculates adjustment factor to resize images to 300x200 This function uses the input tuple of original image size to determine image orientation, calculate an adjustment factor, and return a list of new width and height. Args: original_size (tuple): tuple...
def two(words): """ :param words: :return: """ new = [] s = len(words) for index in range(s): w = words[index] for next_index in range(index + 1, s): next_w = words[next_index] new.append(frozenset([w, next_w])) return new
def check_conv_type(conv_type, sampling): """Check valid convolution type.""" if not isinstance(conv_type, str): raise TypeError("'conv_type' must be a string.") if not isinstance(sampling, str): raise TypeError("'sampling' must be a string.") conv_type = conv_type.lower() if conv_ty...
def lat2zone(lat): """ Convert longitude to single-letter UTM zone. """ zone = int(round(lat / 8. + 9.5)) return 'CDEFGHJKLMNPQRSTUVWX'[zone]
def success(message, data=None, code=200): """Return custom success message Args: message(string): message to return to the user data(dict): response data code(number): status code of the response Returns: tuple: custom success REST response """ response = {'status':...
def succ(n, P): """Return the successor of the permutation P in Sn. If there is no successor, we return None.""" Pn = P[:] + [-1] i = n-2 while Pn[i+1] < Pn[i]: i -= 1 if i == -1: return None j = n-1 while Pn[j] < Pn[i]: j -= 1 Pn[i], Pn[j] = Pn[j], Pn[i] ...
def make_simple_covariance(xvar, yvar): """ Make simple spherical covariance, as can be passed as upper_left_cov or lower_right_cov. The resulting covariance is elliptical in 2-d and axis-aligned, there is no correlation component :param xvar: Horizontal covariance :param yvar: Vertical covariance ...
def write_alpha_rarefaction( qza: str, qzv: str, metric: str, phylo: tuple, tree: tuple, meta: str, raref: str ) -> str: """ Parameters ---------- qza qzv metric phylo tree meta raref Returns ------- """ c...
def assemble_urls(year, name, subpages=['']): """ Combines team year, name and subpage strings to generate a list of URLs to scrape. """ urls = [] url_base = 'http://' + year + '.igem.org/Team:' + name for s in subpages: urls.append(url_base + s) return urls
def _reindent(string): """Reindent string""" return "\n".join(l.strip() for l in string.strip().split("\n"))
def _float_or_none(value): """ Helper function to convert the passed value to a float and return it, or return None. """ return float(value) if value is not None else None
def traverse(data, path): """Method to traverse dictionary data and return element at given path. """ result = data # need to check path, in case of standalone function use if isinstance(path, str): path = [i.strip() for i in path.split(".")] if isinstance(data, dict): for i ...
def contains(array, element): """[summary]Checks for element in list Arguments: array {[type]} -- [description] element {[type]} -- [description] Returns: [type] -- [description] """ print ("element: " + element) for i...
def append(l: list, obj: object) -> list: """Extend or append to list""" if isinstance(obj, list): l.extend(obj) else: l.append(obj) return l
def flow_text(tokens, *, align_right=70, sep_width=1): """ :param tokens: list or tuple of strings :param align_right: integer, right alignment margin :param sep_width: integer, size of inline separator :return: list of lists of strings flowing the text to the margin """ flowed = [] le...
def vol_pyramid(area_of_base: float, height: float) -> float: """ Calculate the Volume of a Pyramid. Wikipedia reference: https://en.wikipedia.org/wiki/Pyramid_(geometry) :return (1/3) * Bh >>> vol_pyramid(10, 3) 10.0 >>> vol_pyramid(1.5, 3) 1.5 """ return area_of_base * height...
def ordinal_number(number: int) -> str: """ Source: Gareth @ https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd#answer-4712 >>>ordinal_number(1) '1st' >>>ordinal_number(2) '2nd' >>>ordinal_number(4) '4th' """ return "%d%s" % (number, "tsnrhtdd"[(nu...
def filter_keys(model_keys): """ Remove untrainable variables left in pytorch .pth file. Args: model_keys: List of PyTorch model's state_dict keys Returns: A string list containing only the trainable variables from the PyTorch model's state_dict keys """ to_remove = [] ...
def check_sudoku(true_vars): """ Check sudoku. :param true_vars: List of variables that your system assigned as true. Each var should be in the form of integers. :return: """ import math as m s = [] row = [] for i in range(len(true_vars)): row.append(str(int(true_vars[i]) % 1...
def truncated_discrete_set(value, values): """ Provides a validator function that returns the value if it is in the discrete set. Otherwise, it returns the smallest value that is larger than the value. :param value: A value to test :param values: A set of values that are valid """ # Force t...
def deduplicate_targets(ander_json): """ deduplicate callsite targets, add pruned_num(for address_taken pruned targets of a callsite), ty_num(for type_based pruned targets of a calliste), and num(total targets of a callsite) """ for caller in ander_json.keys(): callsites = ander_json[caller] ...
def get_catalog_record_access_type(cr): """ Get the type of access_type of a catalog record. :param cr: :return: """ return cr.get('research_dataset', {}).get('access_rights', {}).get('access_type', {}).get('identifier', '')
def min_max(mi, ma, val): """Returns the value inside a min and max range >>> min_max(0, 100, 50) 50 >>> min_max(0, 100, -1) 0 >>> min_max(0, 100, 150) 100 >>> min_max(0, 0, 0) 0 >>> min_max(0, 1, 0) 0 >>> min_max(0, 0, 1) 0 """ return max(mi, min(ma, val))
def mac_normalize(mac): """Retuns the MAC address with only the address, and no special characters. Args: mac (str): A MAC address in string format that matches one of the defined regex patterns. Returns: str: The MAC address with no special characters. Example: >>> from netut...
def dapver(versions): """Return DAP version.""" __, dapver = versions return dapver
def parse_tensor_name_with_slicing(in_str): """Parse tensor name, potentially suffixed by slicing string. Args: in_str: (str) Input name of the tensor, potentially followed by a slicing string. E.g.: Without slicing string: "hidden/weights/Variable:0", with slicing string: "hidden/weights/Varaible:...
def extract_shelves(reviews): """Sort review data into shelves dictionary. :param reviews: A list of book reviews. """ shelves = {} for book in reviews: for shelf in book['bookshelves']: if shelf not in shelves: shelves[shelf] = [] shelves[shelf].app...
def get_file_name(path: str) -> str: """return the file name without extension given a path Args: path (str): absolute path to the file Returns: (str): file name """ return path.split("/")[-1].split(".")[0]
def flatten_unmatched(rules): """ Converts all nested objects from the provided backup rules into non-nested `field->field-value` dicts. :param rules: rules to flatten :return: the flattened rules """ return list( map( lambda entry: { 'line': entry[0]['line_...
def parse_origin(origin, individual=None): """ The center of the sphere can be given as an Atom, or directly as a list of three floats (x,y,z). If it's an Atom, find it and return the xyz coords. If not, just turn the list into a tuple. Parameters ---------- origin : 3-item list of coordina...
def alert_data_results(provides, all_app_runs, context): """Setup the view for alert results.""" context['results'] = results = [] for summary, action_results in all_app_runs: for result in action_results: # formatted = format_alert_result(result, True) formatted = { ...
def gcd(m, n): """Compute the GCD of m & n.""" while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n
def get_block_lines(b, mdata): """ Return the number of lines based on the block index in the RAW file. """ line_counts = [1, 1, 1, 1, 1, 4, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0] if b == 5: # for transformer if mdata[0][2] == 0: # two-winding transformer return 4 els...
def validate_yes(response=""): """Validates 'yes' user input. Returns `True` if a 'yes' input is detected.""" response = response.replace(" ", "") if response.lower() == "y" or response.lower() == "yes": return True return False
def _is_complex_type(data): """If data is a list or dict return True.""" return isinstance(data, list) or isinstance(data, dict)
def newtonraphson(f, f_, x0, TOL=0.001, NMAX=100): """ Takes a function f, its derivative f_, initial value x0, tolerance value(optional) TOL and max number of iterations(optional) NMAX and returns the root of the equation using the newton-raphson method. """ n=1 while n<=NMAX: x1 = x0 - (f(x0)/f_(x0)) if x1...
def anyfalse(bools): """Returns True iff any elements of iterable `bools` are False >>> anyfalse([True, True]) False >>> anyfalse([True, False, True]) True >>> anyfalse(None) False """ if bools is None: return False for b in bools: if not b: return True r...
def etcd_unpack(obj): """Take a JSON response object (as a dict) from etcd, and transform into a dict without the associated etcd cruft. >>> etcd_unpack({}) {} >>> etcd_unpack({'node': { 'key': 'a', 'value': 'AA'}}) {'a': 'AA'} >>> etcd_unpack({'node': {'nodes': [{'value': 'a', 'key': 'A'}, {'value': 'B', 'key': '...
def _format_compile_plugin_options(options): """Format options into id:value for cmd line.""" return ["%s:%s" % (o.id, o.value) for o in options]
def is_uuid(value): """Check if the passed value is formatted like a UUID.""" sizes = tuple([len(_) for _ in value.split('-')]) return sizes == (8, 4, 4, 4, 12)
def send_keytroke_to_process(process, command): """ Sends a simple command to the process's standard input. Parameters ---------- process : Process The process to control. Returns ------- True if the keystroke was sent successfully, false in case the process handler is invalid....
def add_css_tag(token, modification): """Returns a token wrapped with the corresponding css tag.""" if modification == 'replace': token = '<span class=\"delta-replace\">' + token + '</span>' elif modification == 'delete': token = '<span class=\"delta-delete\">' + token + '</span>' elif ...
def create_name_behavior_id(name: str, team_id: int) -> str: """ Reconstructs fully qualified behavior name from name and team_id :param name: brain name :param team_id: team ID :return: name_behavior_id """ return name + "?team=" + str(team_id)
def perigee(sma, ecc): """Calculate the perigee from SMA and eccentricity""" return sma * (1 - ecc)
def create_radar_template(actual_radar_file_name): """Create radar template file name from actual radar file name Parameters ---------- actual_radar_file_name : string Returns ------- radar_file_name_template : string or empty string """ # Search for the word "tile". If not found...
def fix_angle(ang): """ Normalizes an angle between -180 and 180 degree. """ while ang > 360: ang -= 360 while ang < 0: ang += 360 return ang
def extract(str_value, start_='{', stop_='}'): """Extract a string between two symbols, e.g., parentheses.""" extraction = str_value[str_value.index(start_)+1:str_value.index(stop_)] return extraction
def orientation(p, q, r): """Return positive if p-q-r are clockwise, neg if ccw, zero if colinear.""" return (q[1] - p[1]) * (r[0] - p[0]) - (q[0] - p[0]) * (r[1] - p[1])
def _build_constraint_str(constraint_l=None): """ builds the contraint string expression for different queries. Default is string 'true'. :param list constraint_l: list of constraints to be combined """ if constraint_l: constraint_str = " && ".join(constraint_l) else: co...
def custom_sort(dictionary, sort_top_labels, sort_bottom_labels): """ Given a dictionary in the form of {'<a_label>': { 'label': '<a_label>' 'value': '<a_value>' }, ... } and two...
def successors(instr): """Get the list of jump target labels for an instruction. Raises a ValueError if the instruction is not a terminator (jump, branch, or return). """ if instr['op'] == 'jmp': return instr['args'] # Just one destination. elif instr['op'] == 'br': return inst...
def get_schema_query(owner): """ Oracle query for getting schema information for all tables """ cols = ["TABLE_NAME", "COLUMN_NAME", "DATA_TYPE", "ORDINAL_POSITION"] cols = ",".join(cols) return f"""select {cols} from INFORMATION_SCHEMA.COLUMNS"""
def ndwi(swir, green): """ Compute Vegetation Index from SWIR and GREEN bands NDWI = \\frac { GREEN - SWIR } { GREEN + SWIR } :param swir: Swir band :param green: Green band :return: NDWI """ return (green-swir) / (green+swir)
def _split_inputs(orig_inputs): """Given an input specification containing one or more filesystem paths and URIs separated by '|', return a list of individual inputs. * Skips blank entries * Removes blank space around entries :param orig_inputs: One or more filesystem paths and/or ...
def to_string(val): """ Converts value to string, with possible additional formatting. """ return '' if val is None else str(val)
def sleep(time): """ Function that returns UR script for sleep() Args: time: float.in s Returns: script: UR script """ return "sleep({})\n".format(time)
def libc_version(AVR_LIBC_VERSION): """ Example: 10604 -> 1.6.4 """ s = str(AVR_LIBC_VERSION) ls = [s[0], s[1:3], s[3:5]] ls = map(int, ls) ls = map(str, ls) return '.'.join(ls)
def get_closest_elements(elems): """Return the two closest elements from a list sorted in ascending order""" e = elems.copy() if len(e) == 1: return e e.sort() diffs = [e[i+1] - e[i] for i in range(len(e)-1)] min_diff_index = diffs.index(min(diffs)) return e[min_diff_index:(min_diff_...
def model_type(discrete_vars=0, quad_nonzeros=0, quad_constrs=0): """Return the type of the optimization model. The model type is MIP, QCP, QP, or LP. """ mtype = "" if discrete_vars > 0: mtype += "MI" if quad_constrs > 0: mtype += "QC" elif quad_nonzeros > 0: mtype ...
def format_stat(x, is_neg_log10=False, na_val=0): """ Helper function to format & convert p-values as needed """ if x == 'NA': return float(na_val) else: if is_neg_log10: return 10 ** -float(x) else: return float(x)
def apply_bios_properties_filter(settings, filter_to_be_applied): """Applies the filter to return the dict of filtered BIOS properties. :param settings: dict of BIOS settings on which filter to be applied. :param filter_to_be_applied: list of keys to be applied as filter. :returns: A dictionary of filt...
def aviso_tll(tll): """Mensaje de tiempo de llegada.""" return 'El tiempo de llegada del siguiente cliente es: ' + str(tll)
def parse_snmp_return(ret): """Check the return value of snmp operations :param ret: a tuple of (errorIndication, errorStatus, errorIndex, data) returned by pysnmp :return: a tuple of (err, data) err: True if error found, or False if no error found data: a string o...
def kface_accessories_converter(accessories): """ ex) parameters : S1~3,5 return : [S001,S002,S003,S005] """ accessories = accessories.lower() assert 's' == accessories[0] alst = [] accessries = accessories[1:].split(',') for acs in accessries: ac...
def hex_to_ascii(hex_data): """Characteristics values (hex) as input and convert to ascii""" values = [int(x, 16) for x in hex_data.split()] #convert to decimal return "".join(chr(x) for x in values)
def chromosoneCheck(sperm): """ chromosome_check == PEP8 (forced mixedCase by Codewars) Spelling mistake courtesy of Codewars as well """ return "Congratulations! You're going to have a {}.".format( 'son' if 'Y' in sperm else 'daughter' )
def encode_varint(number: int) -> bytes: """Converts `number` into a varint bytes representation. Inverse of `decode_next_varint`. >>> encode_varint(58301).hex().upper() 'BDC703' """ if number < 0: raise ValueError('Argument cannot be negative') if number == 0: return b'\x00' ...
def getIdentifierScheme(identifier): """Uses string matching on the given identifier string to guess a scheme. """ if identifier is None or len(identifier) <= 0: return None if (identifier.startswith("doi:") | identifier.startswith("http://doi.org/") | identifier.startswith("https:...
def isValid(ip): """ Checks if ip address is valid or not :param ip: Takes ip as string :return: True if ip valid hence not """ # Check dots and null no_of_dots = ip.count(".") # Counts no of dots in string if ip == '' or no_of_dots != 3: # If ip is blank or dots!=3 returns...
def humanize_time(time): """Convert a time from the database's format to a human readable string. Args: time::Int - The time to convert. Returns: _::String - The converted time. """ time_str = '{:04d}'.format(time, ) if time_str[2:] == '25': return '{}:{}'...
def OpenFileForRead(filename): """ Exception-safe file open for read Args: filename: local file name Returns: file: if open succeeded None: if open failed """ try: f = open(filename, 'r') return f except: return None
def format_simple_string(kv): """This function format a simple key-varlue pair. It also highlight some of the fields in intent. """ sorted_list = sorted(list(kv.items()), key=lambda a: a[0]) arr = [] for el in sorted_list: key = str(el[0]) if key in ['return_time', 'departure_time']: key = """...
def swap_bytes(value, size): """ Swaps a set of bytes based on size :param value: value to swap :param size: width of value in bytes :return: swapped """ if size == 1: return value if size == 2: return ((value & 0xFF) << 8) | ((value & 0xFF00) >> 8) if size == 4:...
def count_disk(disks): """ Count disks with partition table; Return Nr of disks """ nr = 0 for disk in disks: if disks[disk]['partitions']: nr += 1 return nr
def binary(*args): """Converts a char or int to a string containing the equivalent binary notation.""" if isinstance(args[0], str): number = bin(ord(args[0]))[2:] else: number = bin(args[0])[2:] if len(args) == 1: return number st = len(number) - args[1] return number[st:...