content
stringlengths
42
6.51k
def accelerator_ipaddresstype(type): """ Property: Accelerator.IpAddressType """ valid_types = ["IPV4"] if type not in valid_types: raise ValueError( 'IpAddressType must be one of: "%s"' % (", ".join(valid_types)) ) return type
def ideal_efficiency(induced_velocity, velocity): """Given the effective area, momentum theory ideal efficiency.""" return velocity / (velocity + induced_velocity)
def toBytes(text): """Convert string (unicode) to bytes.""" try: if type(text) != bytes: text = bytes(text, 'UTF-8') except TypeError: text = "\n[WARNING] : Failed to encode unicode!\n" return text
def round_exp(x,n): """Round floating point number to *n* decimal digits in the mantissa""" return float(("%."+str(n)+"g") % x)
def round_filters(filters, width_coefficient, depth_divisor): """ Round number of filters based on width multiplier. """ filters *= width_coefficient new_filters = int(filters + depth_divisor / 2) // depth_divisor * depth_divisor new_filters = max(depth_divisor, new_filters) # Make sure ...
def default_density(depth, vp): """Default rule for density as a function of Vp. Args: depth (float) Depth of location in m. vp (float) P wave speed in m/s. Returns: Density in kg/m**3. """ return 1.74e+3 * (vp*1.0e-3)**0.25
def is_header(bounds_list, position, font_size, i): """Determines whether a piece of text is considered header or not. Args: bounds_list ([(int, int)]): text position bounds for each page in the document. position (int): pixel position of a piece of text. font_size (int): font size of a piece of text. i (...
def list_string(alist, key=lambda a: a): """Given items a, b, ..., x, y, z in an array, this will print "a, b, ..., x, y and z" """ if len(alist) == 0: return "[empty]" elif len(alist) < 2: return str(key(alist[0])) elif len(alist) == 2: return "{} and {}".format(str(key(...
def get_value(obj): """ Extract value from obj. "Description": { "value": "application/epub+zip", "memberOf": null } """ if obj is None or isinstance(obj, str): return obj return obj['Description']['value']
def is_convertible_to_float(value): """Returns True if value is convertible to float""" try: float(value) except ValueError: return False else: return True
def signed_number(number, precision=2): """ Return the given number as a string with a sign in front of it, ie. `+` if the number is positive, `-` otherwise. """ prefix = '' if number <= 0 else '+' number_str = '{}{:.{precision}f}'.format(prefix, number, precision=precision) return number_str
def parse_string_list_from_string(a_string): """ This just parses a comma separated string and returns either a float or an int. Will return a float if there is a decimal in any of the data entries Args: a_string (str): The string to be parsed Returns: A list of integers Auth...
def known_mismatch(hashes1, hashes2): """Returns a string if this is a known mismatch.""" def frame_0_dup_(h1, h2): # asymmetric version return ((h1[0] == h2[0]) and (h1[2:] == h2[2:]) and (h1[1] != h2[1] and h2[1] == h1[0])) def frame_0_dup(h1, h2): retu...
def shape_attr_name(name, length=6, keep_layer=False): """ Function for to format an array name to a maximum of 10 characters to conform with ESRI shapefile maximum attribute name length Parameters ---------- name : string data array name length : int maximum lengt...
def find_brackets(s): """Get indices of matching square brackets in a string.""" # Source: https://stackoverflow.com/questions/29991917/indices-of-matching-parentheses-in-python toret = {} pstack = [] for i, c in enumerate(s): if c == '[': pstack.append(i) elif c ==...
def _SkipOmitted(line): """ Skip lines that are to be intentionally omitted from the expectations file. This is required when the file to be compared against expectations contains a line that changes from build to build because - for instance - it contains version information. """ if line.endswith('# OMI...
def tuple_sort_key(values): """ Key for sorting tuples of integer values. First sort according to the first value, then second ... :param values: tuple of positive integers :return: positive integer that can be used as sort key """ key = 0 max_value, multi = 100000000, 1 for value in val...
def get_metadata_path_value(map_value): """ Get raw metadata path without converter """ return map_value[1] if isinstance(map_value, list) else map_value
def quicksort(lyst): """This is a quicksort """ def partition_helper(lyst, first, last): pivot = lyst[first] left = (first + 1) right = last done = False while not done: while left <= right and lyst[left] <= pivot: left += 1 whi...
def statusInvoiceObject(account_data: dict, order_reference: str) -> dict: """ example: https://wiki.wayforpay.com/view/852526 param: account_data: dict merchant_account: str merchant_password: str param: order_reference : str """ return { "req...
def save(file_name, content): """Save content to a file""" with open(file_name, "w", encoding="utf-8") as output_file: output_file.write(content) return output_file.name
def normalize(vector): """ Returns a 3-element vector as a unit vector. """ magnitude = vector[0] + vector[1] + vector[2] + 0.0 return vector[0] / magnitude, vector[1] / magnitude, vector[2] / magnitude
def listize(item): """Create a listlike object from an item Args: item (dict): The object to convert Returns: Seq: Item as a listlike object Examples: >>> listize(x for x in range(3)) # doctest: +ELLIPSIS <generator object <genexpr> at 0x...> >>> listize([x for x in range...
def JavaFileForUnitTest(test): """Returns the Java file name for a unit test.""" return 'UT_{}.java'.format(test)
def zero_plentiful4(arr): """.""" four_zero = 0 count = 0 if arr == [0]: return 0 elif len(arr) == arr.count(0): return 1 else: for el in arr: if el == 0: count += 1 if count >= 4: four_zero += 1 ...
def width(s): """ Calculates the width of a string. .. note:: The string passed to this function is expected to have been :attr:`normalized <normalize>`. Parameters ---------- s: :class:`str` The string to calculate the width of. Returns ------- :class:`in...
def lr_schedule(epoch): """Learning Rate Schedule Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs. Called automatically every epoch as part of callbacks during training. # Arguments epoch (int): The number of epochs # Returns lr (float32): learning rate ...
def R_minus(x): """ Negative restriction of variable (x if x<0 else 0) """ return 0.5 * (x - abs(x))
def padding_zero(int_to_pad, lim): """ Adds a leading, or padding, zero to an integer if needed. Returns the int as a str Parameters ------------ int_to_pad : int The integer to add padding/leading zero to, if needed lim : int Used to check to see if the param int needs a p...
def _onegroup(it, n): """Return the next size-n group from the given iterable.""" toret = [] for _ in range(n): try: toret.append(next(it)) except StopIteration: break if toret: return toret else: raise StopIteration
def displayRangeToBricon(dataRange, displayRange): """Converts the given brightness/contrast values to a display range, given the data range. :arg dataRange: The full range of the data being displayed, a (min, max) tuple. :arg displayRange: A (min, max) tuple containing the d...
def checkmark(value, show_false=True, true='Yes', false='No'): """ Display either a green checkmark or red X to indicate a boolean value. Args: value: True or False show_false: Show false values true: Text label for true values false: Text label for false values """ ...
def tree_height(t): """ Returns the height of a tree. """ if t is None or not t.left and not t.right: return 0 else: return 1 + max(tree_height(t.left), tree_height(t.right))
def normalize_slice(s): """ Replace Nones in slices with integers >>> normalize_slice(slice(None, None, None)) slice(0, None, 1) """ start, stop, step = s.start, s.stop, s.step if start is None: start = 0 if step is None: step = 1 if start < 0 or step < 0 or stop is not ...
def get_min_bbox(box_1, box_2): """Get the minimal bounding box around two boxes. Args: box_1: First box of coordinates (x1, y1, x2, y2). May be None. box_2: Second box of coordinates (x1, y1, x2, y2). May be None. """ if box_1 is None: return box_2 if box_2 is None: ...
def message(s) -> str: """Function to convert OPTIONS description to present tense""" if s == 'Exit program': return 'Shutting down' return s.replace('Parse', 'Parsing').replace('eXport', 'Exporting').replace('Find', 'Finding').replace('build', 'Building').replace('Index', 'index')
def listify(dct, key): """Make sure a key in this dct is a list""" if key not in dct: dct[key] = [] elif not isinstance(dct[key], list): dct[key] = [dct[key]] return dct[key]
def op_abs(x): """Returns the absolute value of a mathematical object.""" if isinstance(x, list): return [op_abs(a) for a in x] else: return abs(x)
def strip_brackets(string): """ Strips brackets from a string. """ return string.replace('[', '').replace(']', '')
def create_histogram_dict(words_list): """Return a dictionary representing a histogram of words in a list. Parameters: words_list(list): list of strings representing words Returns: histogram(dict): each key a unique word, values are number of word appearances """ histog...
def _add_aligned_message(s1: str, s2: str, error_message: str) -> str: """Align s1 and s2 so that the their first difference is highlighted. For example, if s1 is 'foobar' and s2 is 'fobar', display the following lines: E: foobar A: fobar ^ If s1 and s2 are long, only display a...
def has_cycle(head): """" boolean function to identify a cycle in a linked list """ print('\nIn has_cycle') count = {} if head != None: while head: if head.next in count: return True else: count[head] = 1 head = head.next return False # space complexity is O(n)
def chunks(l, n): """Yield successive n-sized chunks from l.""" return [l[i : i + n] for i in range(0, len(l), n)]
def cat_cmd(last_output, expected_output): """Command to convert or concat files. >>> cat_cmd('file1.osm', 'file2.osm.pbf') ('osmium cat file1.osm -o file2.osm.pbf', None) >>> cat_cmd('file1.osm file2.osm.pbf', 'file3.osm.gz') ('osmium cat file1.osm file2.osm.pbf -o file3.osm.gz', None) >>> cat_cmd('file1.osm fi...
def flatten_(items, seqtypes=(list, tuple)): """Flattten an arbitrarily nested list IN PLACE""" for i, x in enumerate(items): while i < len(items) and isinstance(items[i], seqtypes): items[i:i+1] = items[i] return items
def response_ssml_text(output, endsession): """ create a simple json plain text response """ return { 'outputSpeech': { 'type': 'SSML', 'ssml': "<speak>" +output +"</speak>" }, 'shouldEndSession': endsession }
def is_valid_dataset_dict(data): """Validate passed data (must be dictionary of sets)""" if not (hasattr(data, "keys") and hasattr(data, "values")): return False for dataset in data.values(): if not isinstance(dataset, set): return False else: return True
def _find_error_code(e): """Gets the approriate error code for an exception e, see http://tldp.org/LDP/abs/html/exitcodes.html for exit codes. """ if isinstance(e, PermissionError): code = 126 elif isinstance(e, FileNotFoundError): code = 127 else: code = 1 return cod...
def fortran_int(s, blank_value = 0): """Returns float of a string written by Fortran. Its behaviour is different from the float() function in the following ways: - a blank string will return the specified blank value (default zero) - embedded spaces are ignored If any other errors are encountered, N...
def _ensure_iterable(item): """Ensure item is a non-string iterable (wrap in a list if not)""" try: len(item) has_len = True except TypeError: has_len = False if isinstance(item, str) or not has_len: return [item] return item
def _split_path(path): """split a path return by the api return - the sentinel: - the rest of the path as a list. - the original path stripped of / for normalisation. """ path = path.strip('/') list_path = path.split('/') sentinel = list_path.pop(0) return sentinel, ...
def dict_set(_dict, keys, values): """Set dict values by keys.""" for key, value in zip(keys, values): _dict[key] = value return _dict
def set_element(base, index, value): """Implementation of perl = on an array element""" base[index] = value return value
def isclose(actual, desired, rtol=1e-7, atol=0): """ rigourously evaluates closeness of values. https://www.python.org/dev/peps/pep-0485/#proposed-implementation """ return abs(actual-desired) <= max(rtol * max(abs(actual), abs(desired)), atol)
def splitFilename(fn) : """Split filename into base and extension (base+ext = filename).""" if '.' in fn : base,ext = fn.rsplit('.', 1) #ext = '.' + _ext else : ext = '' base = fn return base,ext
def get_tag(blocks): """ Template tag to get the html tag. Search for every block and return the first block with block_type 'tag' """ for block in blocks: if block.block_type == 'tag': return block return ''
def _create_shifted_copy(arrays, arrays_index, index, delta): """Creates a copy of the arrays with one element shifted.""" A = arrays[arrays_index] A_shifted = A.copy() A_shifted[index] += delta arrays_shifted = list(arrays) arrays_shifted[arrays_index] = A_shifted return arrays_shifted
def is_valid_url(url): """ Check if the href URL is valid """ return ( url != "#" and url != "" and url[0] != "?" and url[0] != "#" and not url.startswith("tel:") and not url.startswith("javascript:") and not url.startswith("mailto:") )
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 """ initial = pieces[0].startswith("/") final = pieces[-1].endswith("/") stripped = [s.strip("/") for s in pieces] ...
def ms_to_mph(ms): """Input: wind speed in meters/second, Returns a human friendly string in mph. """ try: mph = float(ms) * 2.236936 if mph<1: ws = "wind speed: calm" else: ws = "wind speed: %d mph" % round(mph,0) except Exception as e: ws = '' # ...
def get_bbox(x_start, y_start, x_end, y_end): """ This method returns the bounding box of a face. Parameters: ------------- x_start: the x value of top-left corner of bounding box y_start: the y value of top-left corner of bounding box width : the x value of bottom-right corner ...
def _constructSingleSummonerURL(name): """Takes a summonername and returns its op.gg profile.""" return "https://euw.op.gg/summoner/userName=" + name.lower()
def _SedPairsToString(pairs): """Convert a list of sed pairs to a string for the sed command. Args: pairs: a list of pairs, indicating the replacement requests Returns: a string to supply to the sed command """ sed_str = '; '.join(['s/%s/%s/g' % pair for pair in pairs]) if pairs: sed_str += ';...
def clean_dict(d): """ remove the keys with None values. """ ktd = list() for k, v in d.items(): if not v: ktd.append(k) elif type(v) is dict: d[k] = clean_dict(v) for k in ktd: d.pop(k) return d
def tar_entry_size(filesize): """Get the space a file of the given size will actually require in a TAR. The entry has a 512-byte header followd by the actual file data, padded to a multiple of 512 bytes if necessary. Args: filesize (int): File size in bytes Returns: int: Bytes consume...
def checkIfDuplicates_2(listOfElems): """ Check if given list contains any duplicates """ setOfElems = set() for elem in listOfElems: if elem in setOfElems: return True else: setOfElems.add(elem) return False
def contacts_to_list_items(contacts) -> str: """ A module helper function to convert a list of contacts to a string of HTML unordered list items ... Parameters ---------- contacts : [Contact] a list of contact objects to transform ... Returns ------- str a str...
def get_item_hash(terms, i): """ Computes the hash of the `terms`, based on its index `i`. :param terms: the terms :type terms: List[Term] :param i: the index of the term :type i: int :return: the hash :rtype: int """ if terms[i] is None: return 0 if terms[i].is_cons...
def strip_term(term, collation): """Strip out undefined letters from a term.""" return ''.join(c for c in term if c in collation)
def apply_backward_euler(Delta_t, u): """ Apply the backward Euler (fully implicit, first order) time discretization method. """ u_t = (u[0] - u[1])/Delta_t return u_t
def minWithNone(a, b): """ Returns minimal value from two values, if any of them is None, returns other one. :param a: int, float or None value :param b: int, float or None value :return: class instance with given properties >>> minWithNone(None, 1) 1 """ if a == None: return b ...
def make_hash(obj, hash_func=hash): """ Return the hash value for the given object. :param obj: The object which to calculate the hash. :param hash_func: Hash function to use. :return: The hash value. """ if isinstance(obj, (tuple, list)): return hash_func((type(obj), tuple(make_has...
def clean_file_record(raw_record_string): # type: (str) -> str """ Performs some basic cleansing of the provided string, and returns it """ return raw_record_string.replace('\x00', '')
def table_name(obj): """ Return table name of given target, declarative class or the table name where the declarative attribute is bound to. """ class_ = getattr(obj, 'class_', obj) try: return class_.__tablename__ except AttributeError: pass try: return class_....
def get_idx_scores_mapping(scores): """Get mat index to scores mapping.""" return {i: score for i, score in enumerate(scores)}
def strip_string_to_integer(string): """ :param string: :return: """ return int("".join(filter(lambda x: x.isdigit(), string)))
def yper(p): """Calculates the y position for a given amount of peroxide.""" return 100 + (p - 12) * -10
def isnamedtuple(x): """Returns whether x is a namedtuple.""" # from https://bit.ly/2SkthFu t = type(x) b = t.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(t, '_fields', None) if not isinstance(f, tuple): return False return all(type(n)==str for n in f)
def get_utxos(tx, address): """ Given a transaction, find all the outputs that were sent to an address returns => List<Dictionary> list of UTXOs in bitcoin core format tx - <Dictionary> in bitcoind core format address - <string> """ utxos = [] for output in tx["vout"]: if "add...
def build_kwargs_for_template_rendering(module): """This method receives a process chain for an actinia module, isolates the received values and returns them so they can be filled into the process chain template. """ kwargs = {} inOrOutputs = [] if module.get('inputs') is not None: ...
def count_circle_lattice_points(cx: int, cy: int, r: int, k: int) -> int: """ count up integer point (x, y) in the circle or on it. centered at (cx, cy) with radius r. and both x and y are multiple of k. """ assert r >= 0 and k >= 0 cx %= k cy %= k def is_ok(dx: int, dy: int) -> bo...
def add_lists(a, b): """ >>> add_lists([1, 1], [1, 1]) [2, 2] >>> add_lists([1, 2], [1, 4]) [2, 6] >>> add_lists([1, 2, 1], [1, 4, 3]) [2, 6, 4] >>> list1 = [1, 2, 1] >>> list2 = [1, 4, 3] >>> sum = add_lists(list1, list2) >>> list1 == [1, 2, 1] True >>> list2 == [1, 4, 3] True """ len_a = len(a) -1 le...
def get_directive_type(directive): """Given a dict containing a directive, return the directive type Directives have the form {'<directive type>' : <dict of stuff>} Example: {'#requirement': {...}} --> '#requirement' """ keys = list(directive.keys()) if len(keys) != 1: raise ValueError(...
def build_success_response(result, status="success"): """Make Success Response based on the result""" return dict(status=status, success=True, result=result)
def merge_sort(aList): """Sort a list of integers from least to greatest""" n = len(aList) # Check for base case if n <= 1: return aList # Split the list into two halves and call recursively first = merge_sort(aList[0:int(n/2)]) second = merge_sort(aList[int(n/2):n]) #pdb.se...
def alpha1(Te): """[cm^3 / s]""" return 1.95e-7 * (Te / 300.)**(-0.7)
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 is_greek_or_latin(name): """ This function determins if one name is of latin or greek origin. Note that this function only applies to concepts in CUB dataset, and should not be regarded as a universal judgement """ if name.endswith('dae') or name.endswith('formes'): _is = True el...
def check_two_box_is_overlap(a_box, b_box): """ :param a_box: :param b_box: :return: """ in_h = min(a_box[2], b_box[2]) - max(a_box[0], b_box[0]) in_w = min(a_box[3], b_box[3]) - max(a_box[1], b_box[1]) inter = 0 if in_h < 0 or in_w < 0 else in_h * in_w return inter > 0
def extendListNoDuplicates(listToBeExtended, newItems): """Extend list with items without duplicities. :param list listToBeExtended: list to be extended :param list newItems: new items :return: extended list :rtype: list >>> extendListNoDuplicates([1, 2, 3, 4], [4, 5, 6]) [1, 2, 3, 4, 5, 6...
def extrakey(key): """Return True if key is not a boring standard FITS keyword. To make the data model more human readable, we don't overwhelm the output with required keywords which are required by the FITS standard anyway, or cases where the number of headers might change over time. This list is...
def get_time_groupby_name(time_groups): """Return a name reflecting the temporal groupby operation.""" # Define time groupby name time_groups_list = [] for k, v in time_groups.items(): if v == 1: time_groups_list.append(k) else: time_groups_list.append(...
def multi_label_f_score(y_true, y_pred): """ Reference: https://www.kaggle.com/onodera/multilabel-fscore https://github.com/KazukiOnodera/Instacart :return: Examples -------- >>> y_true, y_pred = [1, 2, 3], [2, 3] >>> multi_label_f_score(y_true, y_pred) 0.8 >>> y_true, y_pre...
def _indent(text, prefix, predicate=None): """Adds 'prefix' to the beginning of selected lines in 'text'. If 'predicate' is provided, 'prefix' will only be added to the lines where 'predicate(line)' is True. If 'predicate' is not provided, it will default to adding 'prefix' to all non-empty lines that ...
def _call_args_kwargs(func_arg1, call_arg1, func_mult, call_mult): """Test utility for args and kwargs case where values passed from call site""" return (func_arg1 + call_arg1) * func_mult * call_mult
def joinString(str1, list): """This method joins a list of strings to a input string.\n returns a string object. """ for i in list: str1 += i str1 + " " str1 + " " return str1
def jaccard_similarity(b1, b2): """Jaccard similarity between two set b1 and b2 :param b1: set of index if there is a rate for business b1 :param b2: set of index if there is a rate for business b2 :return: jaccard similarity of two sets """ return len(b1.intersection(b2))/len(b1.union(b2))
def tamiz3(m): """Algoritmo alternativo""" found, numbers, i = [], [], 2 while (i <= m): if i not in numbers: found.append(i) for j in range(i, m+1, i): numbers.append(j) i += 1 return found
def yp_raw_competitors(data_path): """ The file contains the list of business objects. File Type: JSON """ return f'{data_path}/yp_competitors.json'
def doc_or_uid_to_uid(doc_or_uid): """Given Document or uid return the uid Parameters ---------- doc_or_uid : dict or str If str, then assume uid and pass through, if not, return the 'uid' field Returns ------- uid : str A string version of the uid of the given docu...