content
stringlengths
42
6.51k
def __utf8_bisearch(ucs, table): """ auxiliary function for binary search in interval table. """ min = 0 max = len(table) - 1 if ucs < table[min][0] or ucs > table[max][1]: return False while max >= min: mid = (min + max) / 2 if ucs > table[mid][1]: min = mid + ...
def abbrev(name): """Get the abbreviation of label name: 'take (an object) from (a person)' -> 'take ... from ...' """ while name.find('(') != -1: st, ed = name.find('('), name.find(')') name = name[:st] + '...' + name[ed + 1:] return name
def form_success_return(result): """Assembles a GENI compliant return result for successful methods.""" return { 'code' : 0, 'value' : result, 'output' : None }
def to_lisp_rule(operation, field, value, term, missing, field_info): """Builds rule string in LISP from a predicate """ if term is not None: if field_info['optype'] == 'text': options = field_info['term_analysis'] case_insensitive = not options.get('case_se...
def _calculate_ticks(group_len: int, width: float): """Given some group size, and width calculate where ticks would occur. Meant for bar graphs """ if group_len % 2 == 0: start = ((int(group_len / 2) - 1) * width * -1) - (width / 2.0) else: start = (int((group_len / 2)) * width ...
def decimalHour(time_string): """ Converts time from the 24hrs hh:mm:ss format to HH.hhh format. """ hh, mm, ss = time_string.split(':') hh, mm, ss = map(float, (hh, mm, ss)) result = ((ss/60) + mm)/60 + hh return result
def get_len(p_1,p_2): """Get the length of a sarcomere from end points.""" return ((p_1[0]-p_2[0])**2.0 + (p_1[1]-p_2[1])**2.0 + (p_1[2]-p_2[2])**2.0)**(1.0/2.0)
def pluralize(name: str) -> str: """Turns a string into a pluralized form. For example sample -> samples and property -> properties Args: name (str): A non plural string to turn into it's plural Returns: str: The pluralized form of the string. """ if name.endswith("y"): ret...
def kmh_to_mps(speed_in_kmh): """Convert from kilometers per hour to meters per second Aguments: speed_in_kmh: a speed to convert Returns: speed_in_mps: a speed in m/s """ return speed_in_kmh * 1000.0 / 3600.0
def find_duplicates(my_list): """Return list of duplicated items in a list """ a_list = sorted(my_list) b_list = sorted(set(my_list)) c_list = [] if len(a_list) == len(b_list): return c_list while a_list: dee = a_list.pop() if dee in a_list: c_list.append(de...
def sumascii(a: str): """Convert a to code points, then sum""" return sum(bytes(a, encoding="utf-8"))
def MinPositiveValue(data): """ This function determines the minimum positive value of a provided data list Input: - *data* Output: - *minimum positive value* """ return min([elem for elem in data if elem > 0])
def jsEscapeString(s): """ Escape s for use as a Javascript String """ return s.replace('\\', '\\\\') \ .replace('\r', '\\r') \ .replace('\n', '\\n') \ .replace('"', '\\"') \ .replace("'", "\\'") \ .replace("&", '\\x26') \ .replace("<", '\\x3C') \ .replace...
def _parse_indent(line): """ This function is used for parsing indents, it returns the contents of an indent area and the count of indent symbols. """ offset = 0 contents = "" for c in line: if c.isspace(): offset += 1 contents = contents + c else: break return (contents, offset)
def to_ascii20(name: str) -> str: """ Converts the name to max 20 ascii-only characters. """ # ascii characters have codes from 0 to 127 # but 127 is "delete" and we don't want it return "".join([c for c in name if ord(c) < 127])[:20]
def horizontal_cylinder_natual_convection(Gr, Pr): """ Gr > 10000 """ if Gr < 5.76e8: C = 0.48 n = 0.25 elif Gr < 4.65e9: C = 0.0445 n = 0.37 else: C = 0.1 n = 0.3333 return C * (Gr * Pr)**n
def toast_message(text, color_name="bg-blue"): """Template tag for displaying notification messages.""" context = dict() context['text'] = text context['color_name'] = color_name return context
def _netid_subscription_url(netid, subscription_codes): """ Return UWNetId resource for provided netid and subscription code or code list """ return "/nws/v1/uwnetid/%s/subscription/%s" % ( netid, (','.join([str(n) for n in subscription_codes]) if isinstance(subscription_code...
def get_composition(stride_dict, pct_thr=0.6): """ Compute the main composition of the protein. The returned key comprises the top P% of secondary structures that make the protein. Parameters ---------- stride_dict : dict of str -> int The dictionary of secondary structures. pc...
def MAX(src_column): """ Builtin maximum aggregator for groupby Example: Get the maximum rating of each user. >>> sf.groupby("user", ... {'rating_max':tc.aggregate.MAX('rating')}) """ return ("__builtin__max__", [src_column])
def guess_str_length(string): """Guess length of a unicode string (treat non-ascii characters in unicode as 2)""" length = 0 for char in string: length = length + 2 if len(char.encode('utf8')) == 3 else length + 1 return length
def going_slow(data): """ >>> d = [{'speed':5,'angle':0},{'speed':1,'angle':20},{'speed':1,'angle':40},{'speed':1,'angle':60}] >>> going_slow(d) False >>> d = [{'speed':1,'angle':0},{'speed':1,'angle':20},{'speed':1,'angle':0},{'speed':1,'angle':60}] >>> going_slow(d) True """ if su...
def configure_pseudolabeler(pseudolabel: bool, pseudolabeler_builder, pseudolabeler_builder_args): """Pass in a class that can build a pseudolabeler (implementing __call__) or a builder function that returns a pseudolabeling function. """ if pseudolabel: return globals()[pseudolabeler_builder](*...
def parse_zk_conn(zookeepers): """ Parse Zookeeper connection string into a list of fully qualified connection strings. """ zk_hosts, root = zookeepers.split('/') if len(zookeepers.split('/')) > 1 else (zookeepers, None) zk_hosts = zk_hosts.split(',') root = '/'+root if root else '' ...
def to_c_string(text): """ Make 'text' agreeable as C/C++ string literal :return: str """ text = text.replace("\\", "\\\\") text = text.replace("\n", "\\n") text = text.replace("\r", "") text = text.replace('"', '\\"') return text
def chunk(lst, n): """ Yield successive n-sized chunks from l. >>> chunk([1,2,3,4], 2) [[1, 2], [3, 4]] >>> chunk([1,2,3,4,5], 2) [[1, 2], [3, 4], [5]] """ if len(lst) < n: return [lst] chunks = [] for i in range(0, len(lst), n): chunks.append(ls...
def get_hotfix_version(version): """Given a version it will return the next hotfix version""" parts = version.split('.') major = int(parts[0]) minor = int(parts[1]) hotfix = int(parts[2]) if len(parts) > 2 else 0 return "%d.%d.%d" % (major, minor, hotfix+1)
def bits_to_netmask(bits): """ Convert bits to netmask Args: bits ('int'): bits to converts ex.) bits = 32 Raise: None Returns: Net mask """ mask = (0xffffffff >> (32 - bits)) << (32 - bits) return (str((0xff000000 & mask) >> 24) + ...
def selection_sort(lst): """Implement selection sorting algorithm.""" if len(lst) < 2: return lst def smallest_index(lst): smallest = lst[0] sm_index = 0 for i in range(len(lst)): if lst[i] < smallest: smallest = lst[i] sm_index = ...
def rotate(deg, x, y): """ Generate an SVG transform statement representing rotation around a given point. """ return "rotate(%i %i %i)" % (deg, x, y)
def any_in(seq_a, seq_b): """ Parameters ---------- seq_a : list A list of items seq_b : list A list of items Returns ------- seq_a: bool Returns a boolean value if any item of seq_a belongs to seq_b or visa versa """ return any(elem in seq_b for elem ...
def schema_name_from_label(label): """Return the schema name from the label name.""" return label.split(".")[0]
def _need_braces(text): """Determine if braces will be needed.""" if len(text) > 1: return True return False
def gnss_antenna_status(is_shorted, is_open): """ Return a valid antenna-status-enumeration from vyatta-service-gnss-v1 """ state_table = { (0, 0): "short", (0, 1): "unknown", (1, 0): "OK", (1, 1): "open", } return state_table[is_shorted, is_open]
def f_to_istr(width, f): """ f is between 0 and 1. If f is 1 we want binary to be 010000000 (maxno). Used for generating the twiddle factor module. """ if f < 0 or f > 1: raise ValueError("f must be between 0 and 1") maxno = pow(2, width-2) return str(int(round(f * maxno)))
def _strip_prefix(path, prefix): """Strip prefix if matched exactly.""" if path.startswith(prefix): path = path[len(prefix):] return path
def float_to_ndigits(f): """ Returns the number of digits after the decimal point """ if f == int(f): return 0 return len(str(f).split('.')[-1])
def is_email_address_valid(email_addr): """ Validate that the input is an email address. This won't catch all error cases, but will catch the most outrageous ones. I believe in the fundamental goodwill of humanity, e.g. that users will not deliberately enter a stupid email address like aa\s\d\@derp..com...
def gradient_color(minval, maxval, val, color_palette): """ Computes intermediate RGB color of a value in the range of minval to maxval (inclusive) based on a color_palette representing the range. """ max_index = len(color_palette)-1 delta = maxval - minval if delta == 0: delt...
def EnsureFull(path): """Prepends 'end_snippet', making it the full field path. Args: path: the path to ensure is full. Returns: The path made full. """ if not path.startswith("end_snippet."): path = "end_snippet." + path return path
def is_negative_integer(b, c, d): """ >>> is_negative_integer(1, 0, 1) False """ return b < 0 and c == 0 and d == 1
def get_local_node_mapping(tree, last_tree, spr): """ Determine the mapping between nodes in local trees across ARG. A maps across local trees until it is broken (parent of recomb node). This method assumes tree and last_tree share the same node naming and do not contain intermediary nodes (i.e. si...
def get_unique_terms(terms, term_forms, tag_cloud): """Extracts the unique terms that occur in one of the alternative forms in term_forms or in the tag cloud. """ extend_forms = {} tag_cloud = tag_cloud.keys() for term, forms in term_forms.items(): for form in forms: exte...
def resolve_underlying_function(thing): """Gets the underlying (real) function for functions, wrapped functions, methods, etc. Returns the same object for things that are not functions """ while True: wrapped = getattr(thing, "__func__", None) or getattr(thing, "__wrapped__", None) or getattr(th...
def tally_organized_list(orglist): """ Given a list generated by h.organize_events_by_day, count the occurences of each header. eg [[Monday, 3], [Wednesday, 1], [Thursday, 3]] with the days spelled out as human days. """ retval = [] for day in orglist: # I wanted this t...
def calculateBoundingBoxCenter(bbox): """ Calculate the central point of the bounding box @param bbox A dict containing keys: minX, minY, maxX, maxY, srs, where srs='EPSG:4326' @return Tuple of floats of the form (longitude, latitude) """ x_diff = ( bbox['maxX'] - bbox['minX'] ...
def is_builder_newer(old_component, new_component): """ Return True if the given builder has been modified with respect to its state when the given component_meta was created. :param old_component: a dict of metadata describing a component ring :param new_component: a dict of metadata describing a ...
def non_null_unique(data): """Return True if data is a list containing all non-null values that are all equal. """ return (all(data) and len(set(data)) > 1)
def decompose_dateint(dateint): """Decomposes the given dateint into its year, month and day components. Arguments --------- dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. Returns ------- year : int The year component of the given datein...
def is_local_host(location): """ :param location: Location string in the format ip[/slot[/port]]. :returns: True if ip represents localhost or offilne else return False. """ return any(x in location.lower() for x in ('localhost', '127.0.0.1', 'offline', 'null'))
def _ValidateProjectClassifierConfig(project_classifier_config): """Checks that a project_classifier_config dict is properly formatted. Args: project_classifier_config (dict): A dictionary that provides mapping from project to its function patterns, path patterns and its host_directories, and some ...
def get_parameter_for_sharding(sharding_instances): """Return the parameter for sharding, based on the given number of sharding instances. Args: sharding_instances: int. How many sharding instances to be running. Returns: list(str). A list of parameters to represent the sharding config...
def strpar(cfg, section, key): """String representation of a section/key combination""" return "[{}] {} = {}".format(section, key, cfg[section][key])
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', \ '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) True >>> check_u...
def serialize_json_to_object(object, json): """ """ for key in json.keys(): s = dir(object) if key in dir(object): setattr(object, str(key), json[key]) else: raise Exception(f'attribute {key} not supported by this endpoint') return object
def ensure_kwarg_in(caller, key, allowed): """Checks a single **key** from keyword arguments against allowed keys. If **key** is not in **allowed** keys, throws :exc:`TypeError`. :param str caller: name of the caller, :param str key: the key to be examined, :param allowed: sequence of ...
def bytes2str(val): """ bytes 2 str conversion, only for python3 """ if isinstance(val, bytes): return str(val, "utf8") else: return val
def escape_perl_string(v): """Escape characters with special meaning in perl""" return str(v).replace("$", "\\$").replace("\"", "\\\"").replace("@", "\\@") if v else ''
def confirmColor(nclicks, r, g, b, dataset, backup): """ Callback to confirm a color. This will overwrite the previous one. Positional arguments: nclicks -- Button value. r -- Red value. g -- Green value. b -- Blue value. dataset -- Dataset to overwrite color of. backup -- Previous valu...
def pairwise(iterable): """ s -> (s0, s1), (s2, s3), (s4, s5), ... """ a = iter(iterable) return list(zip(a, a))
def guess(key, values): """ Returns guess values for the parameters of this function class based on the input. Used for fitting using this class. """ #a = (max(values)-min(values))/10 return [0.1, 0.4, 10, 0.4, 10, 0.2, 10, 105, 60]
def _compute_applied_hoop(pressure, R_od, t_wall): """Compute hoop stress WITHOUT accounting for stiffener rings INPUTS: ---------- pressure : float (scalar/vector), radial (hydrostatic) pressure R_od : float (scalar/vector), radius to outer wall of shell t_wall : float (scalar/vector),...
def hexString(value, numBytes): """Returns a fixed length hex string encoding a provided value. value -- an integer value numBytes -- the byte length to encode """ rawEncoding = str(hex(value)) #convert number to hex string encoding = rawEncoding[2:] #strip off "0x" #Fill out full length for i in range(numBy...
def strip_minijail_command(command, fuzzer_path): """Remove minijail arguments from a fuzzer command. Args: command: The command. fuzzer_path: Absolute path to the fuzzer. Returns: The stripped command. """ try: fuzzer_path_index = command.index(fuzzer_path) return command[fuzzer_path_in...
def origin_snapshot(origin_str): """Extracts original phisical snapshot name from origin record""" return origin_str.split("@")[1]
def power_factor(rp=0.0,ap=0.0,phase=1): """ Calculates the power factor for an AC circuit. formula's grabbed from: http://www.rapidtables.com/electric/Power_Factor.htm """ # If everything is 0.0, return 0.0 to avoid division by # zero errors if 0.0 not in (rp, ap): return 0.0 if phase is 3: # T...
def export_mealy_io(variables, values): """Return declarations of variable types. @rtype: list of dict """ vrs = list() for i, var in enumerate(variables): d = dict( name=var, values=list(values[i])) vrs.append(d) return vrs
def del_from_list(target, index_positions): """ Deletes the elements in a list given by a index_positions list :param target: a target list to have items removed :param index_positions: a list of index positions to be removed from the target list :type target: list ...
def tokenize(hexcode, bigrams=False): """ Tokenizes a bytecode file surprisingly fast """ # iterator over the split words i = iter(hexcode.split(' ')) if bigrams is True: # magic. zip(i, i) makes a list of sequential word pair tuples return [' '.join(x) for x in zip(i, i)] if...
def f(x, wave): """ used to plot the hyperplane in 2 dimensions, x is an array """ y = ((-wave[1] / wave[2]) * x) - (wave[0] / wave[2]) return y
def prepare_input(input_geojson: str, source_projection: str, expected_output_geojson: str): """ Collect url's """ return { 'input_geojson': input_geojson, 'source_projection': source_projection, 'expected_output_geojson': expected_output_geojson }
def apiname(field): """The full (qualified) programmatic name of a field""" if field["prefix"]: fieldname = u"{}.{}".format(field["prefix"], field["name"]) else: fieldname = field["name"] return fieldname
def n_5(x): """Max aft wing root location: x_offset + chord_0""" x_aft = x[0] + x[2] return x_aft
def parse_params_with_defaults(params_json, params_schema): """ Fill a parameters dict with the default values from param_schema. Dumbed down from ocr-d/core """ for param_name in params_schema: param_schema = params_schema[param_name] if param_name not in params_json and 'default' in pa...
def vpc_endpoint_type(endpoint_type): """ Property: VPCEndpoint.VpcEndpointType """ valid_types = ["Interface", "Gateway", "GatewayLoadBalancer"] if endpoint_type not in valid_types: raise ValueError( 'VpcEndpointType must be one of: "%s"' % (", ".join(valid_types)) ) ...
def bisect(start,end,line): """Returns the point of intersection of a line between start and end and an infinite line (defined by a point and delta vector). 0 = intersects at start 0.5 = intersects half way between start and end 1 = intersects at end <0 or >1 = intersects outside of those bounds...
def get_celsius(temperature_in_fahrenheit): """ Returns the temperature in Celsius of the given Fahrenheit temperature. For example, this function returns XXX when given YYY. Type hints: :type temperature_in_fahrenheit: float """ return (temperature_in_fahrenheit - 32) * (5 / 9)
def get_ff_par(atom_name, ff_parameters): """ Get sigma and epsilon values for given atom name and force field parameters dictionary. """ atom_index = ff_parameters['atom'].index(atom_name) sigma = ff_parameters['sigma'][atom_index] epsilon = ff_parameters['epsilon'][atom_index] return sigma, epsilo...
def get_email_footer(url): """ Construct a footer for email Args: url: To change the settings Returns: string: with the html styled footer """ text = ("You are receiving this e-mail because you signed up for MITx" " MicroMasters.<br/> If you don't want to receive thes...
def check_user_permitted(user_id, data_user_id, admin_ids): """ Check the data is permitted to be viewed or edited by the user. Admin users can view or edit any data :param user_id: ID of user requesting access to the data :param data_user_id: user ID to which the data belongs :param admin_ids...
def format_as_index(indices): """ format jsonschema error """ if not indices: return "" return "[%s]" % "][".join(repr(index) for index in indices)
def easter_date (y) : """Returns date of easter sunday computed by Spencer Jones algorithm as given by Jean Meeus: Astronomical Algorithms. >>> easter_date (1818) (1818, 3, 22) >>> easter_date (1943) (1943, 4, 25) >>> easter_date (1981) (1981, 4, 19) >>> east...
def concatenate(list): """ Shorthand to concatenate a list of lists Args: [[]] Returntype: [] """ return sum(filter(lambda elem: elem is not None, list), [])
def getUriFile(uri): """ Return file path string corresponding to supplied RO or RO component URI """ filebase = "file://" uri = str(uri) if uri.startswith(filebase): uri = uri[len(filebase):] return uri
def attrs_all_equal(iterable, attr_name): """ Return true if everything in the iterable has the same value for `attr_name` :rtype: bool """ return len({getattr(item, attr_name, float('nan')) for item in iterable}) <= 1
def generatetree(pred): """Rebuild the shortest path from root origin to destination. Parameters ---------- pred : list List of preceding vertices for traversal route. Returns -------- tree : dict key is root origin; value is root origin to destination. ...
def should_log_line(line): """ Filters out unhelpful lines in the stacktrace (such as type decorators) that can be left out without missing out. """ blacklist = ['google_appengine', 'typechecked_', 'add_1_monkey_patches', 'db_hooks', 'threading.py'] return all(word not in line for word in blacklist)
def read_key(line): """ Parse a key value line :param line: Line with key and value :return: Tuple with key and value. If no key and value are found their values are None """ k, v = None, None key_value = [p.strip() for p in line.split(':')] if len(key_value) == 2: k = key_value[...
def assign_global_token_index(sentences_conll): """ Assign global token indices to token-level dictionaries extracted from the CoNLL-format file """ token_index = 0 for s_i in range(len(sentences_conll)): for w_i in range(len(sentences_conll[s_i])): sentences_conll[s_i][w_i]["glo...
def pretty_diff_str(title, oA, oB): """ Generate a pretty diff of two dicts. :param title: the title/heading for the line :type title: string :param oA: first object :param oB: second object :returns: list of lines, each a list of 3 columns :rtype: list of lists """ if oA != oB:...
def rgb2int(rgb): """Convert a given rgb value to an integer :type rgb: list|tuple :rtype: int """ is_tuple = isinstance(rgb, tuple) rgb = list(rgb) if is_tuple else rgb colour = (int(rgb[0]*255) << 16) + (int(rgb[1]*255) << 8) + int(rgb[2]*255) return colour
def clockwise_turn(rows): """ performs a clock wise turn of items in a grid """ rows2 = [[v for v in r] for r in rows] rows2[0][1:] = [v for v in rows[0][:-1]] # first row, rows2[-1][:-1] = [v for v in rows[-1][1:]] # last row for ix, row in enumerate(rows[1:]): # left rows2[ix][0] = row[...
def make_maze(w=30, h=30): """returns an ascii maze as a string""" from random import shuffle, randrange vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)] ver = [["| "] * w + ['|'] for _ in range(h)] + [[]] hor = [["+--"] * w + ['+'] for _ in range(h + 1)] def walk(x, y): vis[y...
def readParameter(dictionary,key,fallback=None,quit_on_fail=False): """ Define a variable if it is contained in the dictionary, if not use a fallback or quit outright. Inputs: - dict dictionary: dictionary to read - str key: key to read - val fallbac: fallback to return instead, def...
def arg_return_greetings(name): """ This is greeting function with arguments and return greeting message :param name: :return: """ message = F"hello {name}" return message
def getFibonacciRecursive(n: int) -> int: """ Calculate the fibonacci number at position n recursively """ a = 0 b = 1 def step(n: int) -> int: nonlocal a, b if n <= 0: return a a, b = b, a + b return step(n - 1) return step(n)
def get_dimension(geometry): """Gets the dimension of a Fiona-like geometry element.""" coordinates = geometry["coordinates"] type_ = geometry["type"] if type_ in ('Point',): return len(coordinates) elif type_ in ('LineString', 'MultiPoint'): return len(coordinates[0]) elif type_...
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'): """Converts an integer to a base36 string.""" base36 = '' sign = '' if number < 0: sign = '-' number = -number if 0 <= number < len(alphabet): return sign + alphabet[number] while number !...
def split_authors_and_genres(string): """ A function for splitting strings by comma and space """ vector = string.split(", ") return vector
def is_coa(project_object): """ Return 1 if coa """ try: if project_object['coa']: return 1 else: return 0 except: pass return 0