content
stringlengths
42
6.51k
def improve_temperature_measurement(temp_raw, dig_t): """Refine the temperature measurement. Adapts the raw temperature measurement according to a formula specified in the Bosch data sheet. Args: temp_raw (int): raw temperature reading dig_t (list): blocks of data pertaining to tempera...
def _format_pval(p_value): """Helper function for formatting p-value.""" if p_value < 0.0001: return 'p < 0.0001' else: return 'p = {:5.4f}'.format(p_value)
def rk4_backward(f, x, h, **kwargs): """Implements a backwards classic Runge-Kutta integration RK4. Parameters ---------- f : callable function to reverse integrate, must take x as the first argument and arbitrary kwargs after x : numpy array, or float state needed by functi...
def combine(intervals): """combine overlapping and adjacent intervals. >>> combine([(10,20), (30,40)]) [(10, 20), (30, 40)] >>> combine([(10,20), (20,40)]) [(10, 40)] >>> combine([(10,20), (15,40)]) [(10, 40)] """ if not intervals: return [] new_intervals = [] inte...
def handle_to_osrelpath(handle, is_windows=False): """Return OS specific relpath from handle.""" directories = handle.split("/") if is_windows: return "\\".join(directories) return "/".join(directories)
def _filetype(filepath): """returns the file extension of a file""" if '.' in filepath: return filepath.lower()[filepath.rindex('.')+1:]
def sort_string(string: str) -> str: """ >>> sort_string("kjldsk") 'djkkls' """ return "".join(sorted(string))
def create_entail_axioms(relations_to_pairs, relation='synonym'): """ For every linguistic relationship, check if 'relation' is present. If it is present, then create an entry named: Axiom ax_relation_token1_token2 : forall x, _token1 x -> _token2 x. """ rel_pairs = relations_to_pairs[relation] ...
def for_approach_rate(approach_rate): """ for a approach rate get how much before the circle appers and when it has full opacity :param approach_rate: float ar :return: preempt in ms, fade time in ms """ if approach_rate < 5: preempt = 1200 + 600 * (5 - approach_rate) / 5 fade_in...
def extract_vertices(vertices): """ Extract two opposite vertices from a list of 4 (assumption: rectangle) """ min_x,max_x,min_y,max_y = float("inf"),float("-inf"),float("inf"),float("-inf") for v in vertices: if v.get('x',min_y) < min_x: min_x = v.get('x') if v.get('x',max_y) > max_x: max_x = v.get('x')...
def gzipped(content): """ test if content is gzipped by magic num. """ if content is not None and len(content) > 10 \ and ord(content[0:1]) == 31 and ord(content[1:2]) == 139 \ and ord(content[2:3]) == 8: return True return False
def validate_hs_code(code): """ validate HS Code is the right length """ if code and (len(code) not in (6, 8, 10) or not str(code).isdigit()): return False return True
def gen_q_list(q_bands): """ convert q_bands into a list of q_indices """ lis =[] for i in range(-q_bands,q_bands+1): lis.append(i) return lis
def extract_values_from_json(obj, key) -> list: """ Extracts recursively values from specific keys. :param obj: json object :param key: key to extract values from :return: list of values for given key types """ """Pull all values of specified key from nested JSON.""" arr = [] def ex...
def check_input_format(input_data): """ check if the input data is numbers > 0. :param input_data: str, the input number of row runs to achieved. :return: str, the data in legal format. """ while not input_data.isdigit() or int(input_data) <= 0: input_data = input("Illegal format, please enter numbers > 0: ") ...
def _arg_scope_func_key(op): """Returns a key that can be used to index arg_scope dictionary.""" return getattr(op, '_key_op', str(op))
def options(amount=None): """Provides values for options which can be ORed together. If no amount is provided, returns a generator of ever growing numerical values starting from 1. If amount is provided, returns a amount-sized list of numerical values. """ def generator(): exp = 0 c...
def mapToDict(dictShape, x): """ Make a dict over two lists. Parameters ---------- dictShape : list of any The labels of the returned dict. x : list of any The values of the returned dict. Returns ------- dict Each key in dictShape corresponds to the value i...
def bytes_to_readable_str(num_bytes, include_b=False): """Generate a human-readable string representing number of bytes. The units B, kB, MB and GB are used. Args: num_bytes: (`int` or None) Number of bytes. include_b: (`bool`) Include the letter B at the end of the unit. Returns: (`str`) A strin...
def mock_get_benchmark_config(benchmark): """Mocked version of common.benchmark_config.get_config.""" if benchmark == 'benchmark1': return { 'unsupported_fuzzers': ['fuzzer2'], } if benchmark == 'benchmark2': return { 'unsupported_fuzzers': ['fuzzer2', 'fuzzer...
def get_index_of_max(iterable): """Return the first index of one of the maximum items in the iterable.""" max_i = -1 max_v = float('-inf') for i, iter in enumerate(iterable): temp = max_v max_v = max(iter,max_v) if max_v != temp: max_i = i return max_i
def number_to_event_name(number): """ Convert an integer to an NCANDA event name (Arm 1 + full-year visits only) """ if number == 0: return "baseline" elif number >= 1: return "followup_%dy" % number else: raise KeyError("Number %d is not eligible for conversion" % number...
def change_pose_f1(bodys, is_gt=False): """ format: ---> a total list [[jtype1, X1, Y1, Z1], [jtype2, X2, Y2, Z2], ...] """ include_together = [] if len(bodys) > 0: for body in bodys: for i in range(15): joint = [] if not is_gt: ...
def uk_to_mjy(t_uK, nu_GHz, th_arcmin): """Convert brightness temperature [uK] to flux density [mJy]. See equation at https://science.nrao.edu/facilities/vla/proposing/TBconv: T = 1.36 * ( lambda[cm]^2 / theta[arcsec]^2 ) * S[mJy/beam] Parameters ---------- t_uK: brightness temperature...
def encode_pair(left: str, right: str, rep: int, s: str) -> str: """Encodes a left/right pair using temporary characters.""" return ( s.replace("", "") .replace(left, "\ufffe" * rep) .replace(right, "\uffff" * rep) )
def not_blank(key, obj, blanks): """Test value is not blank.""" return key in obj and obj[key] and obj[key] not in blanks
def inorder_traverse_re(root): """Inorder traversal (recursive).""" values = [] def traverse(node): if not node: return traverse(node.left) values.append(node.val) traverse(node.right) traverse(root) return values
def __create_code_block(message): """Create a code block""" return f"```\n{message}```"
def unparse_host_port(host, port=None): """ Undo parse_host_port(). """ if ':' in host and not host.startswith('['): host = '[%s]' % host if port: return '%s:%s' % (host, port) else: return host
def count_unequal_bits(a, b): """Counts number of bits that are different between them a and b. Args: a, b: Non-negative integers. Returns: Number of bits different between a and b. Raises: ValueError: If either of the arguments is negative. """ if a < 0 or b < 0: ...
def merge_lists(old_list, new_list): """Merge two dictionaries.""" for mac in new_list: old_list[mac] = new_list[mac] return old_list
def _XSWAP(value): """Swap 2 least significant bytes of @value""" return ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8)
def merge_column_sets(columns: set, exclusions: set) -> set: """ Take the column set and subtract the exclusions. :param columns: set of columns on the instance :param exclusions: set of columns we want to ignore :return: set of finalised columns for publication :rtype: set """ return c...
def remove_special_characters(returned_string): """ Function to clean up the list provided by the 'search_string' function. The function removes special characters from elements in the list. E.g. '*' and ','. Example to remove line breaks from the middle of words and delete excess elements from the end ...
def is_permutation(str1, str2): """Check if given strings are permutation of each other :param str1: String one :param str2: String two :returns: True/False accordingly """ # Very first check is to see if they both are equal so we can return True quickly if str1 == str2: return True...
def make_pretty_name(method): """Makes a pretty name for a function/method.""" meth_pieces = [method.__name__] # If its a server method attempt to tack on the class name if hasattr(method, '__self__') and method.__self__ is not None: try: meth_pieces.insert(0, method.__self__.__class...
def assert_single_element(iterable): """Get the single element of `iterable`, or raise an error. :raise: :class:`StopIteration` if there is no element. :raise: :class:`ValueError` if there is more than one element. """ it = iter(iterable) first_item = next(it) try: next(it) except StopIteration: ...
def build_descriptor(comp, splitby, mask, normalization, split, algo="smrt", level="short"): """ Generate a shorthand descriptor for the group a result belongs to. """ # From actual file, or from path to result, boil down comparator to its abbreviation comp_map = { 'hcp_niftismooth_conn_parby-glass...
def get_changed_properties(current, new, unchangeable=None): """Get the changed properties. :param current: Current properties :type current: dict :param new: New properties to be set :type new: dict :param unchangeable: Set of unchangeable properties, defaults to None :type unchangeable: s...
def get_default_readout(n_atom_basis): """Default setting for readout layers. Predicts only the energy of the system. Args: n_atom_basis (int): number of atomic basis. Necessary to match the dimensions of the linear layer. Returns: DEFAULT_READOUT (dict) """ default_re...
def get_backbone(ca_list,c_list, n_list): """ oputput: mainchain atom ca_list: Ca atom of all amino acids c_list: c atom of all amino acids n_list: n atom of all amino acids """ mainchain = [] for i in range(len(ca_list)): mainchain.append(n_list[i]) mainc...
def _serialize_query_value(value): """ Serialize a query value. :param value: :return: """ if isinstance(value, bool): return "true" if value else "false" return "'%s'" % str(value).replace("\\", "\\\\").replace("'", "\\'")
def calc_adda_mm_per_px(px_per_unit, x_px=1024, unit_fact=1.0e-9): """calc_adda_mm_per_px(px_per_unit, x_px=1024, unit_fact=1.0e-9) Compute the mm per pixel for the maximum pixel size (4096) of a Soft Imaging Systems ADDA-II slow scan interface. This is entered into the channel calibration in the Analy...
def loc_tech_is_in(backend_model, loc_tech, model_set): """ Check if set exists and if loc_tech is in the set Parameters ---------- loc_tech : string model_set : string """ if hasattr(backend_model, model_set) and loc_tech in getattr( backend_model, model_set ): ret...
def get_processable_layers(layers): """ Returns computable layers from a list of layers, along with their types. We check that by searching specific keywords in layer's name, since we can't be sure about layer's type. If you wish to extend the project and add compatibility for more layers, you...
def _get_test_item_id(x): """ custom test ids """ if isinstance(x, bool) or x is None: return "swagger_format={}".format(x) else: return "call_mode={}".format(x)
def get_font_face(font_name: str, part: str, unicode: str, subset_filename: str): """Format @font-face string. Parameters: font_name: Font name part: subset part unicode: unicode range of the part subset_filename: woff2 filename of the subset Returns: css string of ...
def sci_notation(x: float): """ Format scientifically as 10^ Parameters ---------- x : float Returns ------- y : str """ a, b = '{:.2e}'.format(x).split('e') return r'${}\times10^{{{}}}$'.format(a, int(b))
def default_to_list(value): """ Ensures non-list objects are add to a list for easy parsing. Args: value(object): value to be returned as is if it is a list or encapsulated in a list if not. """ if not isinstance(value, list) and value is not None: value = [value] el...
def check_equal(dictionary_of_key_values): """Just a useful function to make nose stdout readable.""" print("-"*30) print("Testing") result = False print(result) print("-"*30) return result
def get_value_or_404(json: dict, key: str): """ If a key is present in a dict, it returns the value of key else None.""" try: return json[key] except BaseException: # print(f'{key} not found') return None
def processtext(tokens): """ Preprocessing token list for filtering '(' and ')' in text :type tokens: list :param tokens: list of tokens """ identifier = '_!' within_text = False for (idx, tok) in enumerate(tokens): if identifier in tok: for _ in range(tok.count(identifi...
def split_class_str(name): """construct output info""" return str(name).split('\'')[1].split('.')[-1] + '-> '
def cleanPath(path): """Clean the path, remove `//`, './', '../'. """ stack, i, n = [], 0, len(path) while i < n: string = [] while i < n and path[i] != '/': string.append(path[i]) i += 1 i += 1 string = ''.join(string) if string == '..':...
def nws_api_gave_error(response): """Checks to see if the API gave an error by checking to see if ``correlationId`` is in the keys. There should be a more robust way to check to see if it's a bad API response. :param response: The response object from the ``requests`` module. :type response: reque...
def heun_step(u, delta_t, t, du): """ Implementation of the Heun's Method (Trapezoid) approximation for systems of coupled ODEs Parameters: ----------- u: array-like vector of initial conditions delta_t: float time step size t: float current t...
def check_bounds( x0, mn, mx): """ Checks that bounds are valid, and asserts False with a usable warning message if not. """ for i in range(len(x0)): if not (mn[i] <= x0[i] and mx[i] >= x0[i]): return False return True
def _get_date_columns_selector(available_date_offsets, required_date_offsets): """ Return a numpy "fancy index" which maps one set of matrix columns to another. Specifically, it will take a matrix with the "available" date columns and transform it to one with the "required" columns. If any of the r...
def bcost(action): """Returns the cost (a number) of an action in the bridge problem.""" # An action is an (a, b, arrow) tuple; a and b are # times; arrow is a string. a, b, arrow = action return max(a,b)
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 get_printable_object_name(obj): """ Get a human-readable object name for our reports. This function tries to balance useful information (such as the `__repr__` of an object) with the shortest display (to make reports visually understandable). Since this text is only read by humans, it can be any for...
def load_urls_from_text(text): """Load urls from text, one per line, ignore lines with #, ignores duplicity""" urls = set() lines = text.split('\n') for line in lines: # Ignore all white characters url = line.strip() # Take url only if is not commented if not line.s...
def extract_path(x): """ extract_path(x) Return the path from the circuit `x`. Assumption: The start city is city 0. """ n = len(x) start = 0 # we start at city 0 path = [] for _i in range(n): start = x[start] path.append(start) return path
def format_sale(sale): """Formats the results to a dictionary""" sale = { "id": sale[0], "books": sale[1], "total": sale[2], "created_by": sale[3], "attendant_name": sale[5], "created_at": str(sale[4]) } return sale
def list_intersect(a, b): """ return the intersection of two lists """ return list(set(a) & set(b))
def dummy_hash(x): """ Supplies a constant dummy hash """ return 'dummy_hash'.encode('utf-8')
def column(matrix, i): """ Returning all the values in a specific columns Parameters: X: the input matrix i: the column Return value: an array with desired column """ return [row[i] for row in matrix]
def isiterable(x): """check if an object is iterable""" #try: # from collections import Iterable # return isinstance(x, Iterable) #except ImportError: try: iter(x) return True except TypeError: return False
def line2dict(inline): """ Take a line of a todo.txt file and convert to a helpful dict. """ result = {} if inline[0:2] == 'x ': result['done'] = True # see if there's a completed date possible_date = inline.split()[1] else: result['done'] = False return re...
def extract_between(source: str, start: str, end: str) -> str: """Extract all of the characters between start and end. :param source: The input string from which to extract a substring. :param start: The substring that marks the extraction starting place. :param end: The substring that marks the place ...
def pair_greedy(pairs, label_budgets, budget, mapper): """ pairs: (obj_val, id) label_budgets: label -> budget budget: int mapper: id -> label """ label_budgets = {k: v for k, v in label_budgets.items() if v is not None} result = set() for val, v in pairs: if len(...
def is_happy(num): """Process of finding happy numbers""" eval_set = set() while num not in eval_set and num > 0: num_string = str(num) squares = [pow(int(i), 2) for i in num_string] num_sum = sum(squares) if num_sum != 1: eval_set.add(num) num = num_s...
def compute_f1(actual, predicted): """ Computes the F1 score of your predictions. Note that we use 0.5 as the cutoff here. """ num = len(actual) true_positives = 0 false_positives = 0 false_negatives = 0 true_negatives = 0 for i in range(num): if actual[i] >= 0.5 and predic...
def write_clusters(filehandle, clusters, max_clusters=None, min_size=1, header=None): """Writes clusters to an open filehandle. Inputs: filehandle: An open filehandle that can be written to clusters: An iterator generated by function `clusters` or a dict max_clusters: S...
def pack_op_args(inputs, outputs, attrs): """ flatten inputs outputs attrs """ op_args = (inputs, outputs, attrs) return [item for arg in op_args for item in arg]
def align_data(data): """Given dict with lists, creates aligned strings Adapted from Assignment 3 of CS224N Args: data: (dict) data["x"] = ["I", "love", "you"] (dict) data["y"] = ["O", "O", "O"] Returns: data_aligned: (dict) data_align["x"] = "I love you" ...
def chain_dict_update(*ds): """Updates multiple dictionaries into one dictionary. If the same key appears multiple times, then the last appearance wins. >>> m, n, o = {'a':10}, {'b':7}, {'a':4} >>> chain_dict_updates(m, n, o) ... {'b': 7, 'a': 4} """ dct = {} for d in ds: dct.up...
def to_unicode(value): """Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8. """ if isinstance(value, (str, type(None))): return value if not isinstanc...
def extractBits(number, numBits, position): """ Extract bits from a large number and return the number. Parameters: number the number to extract from numBits the amount of bits to extract position the position to start from Returns: int ...
def _dict_to_other_case(d, switch_case_func): """Apply switch_case_func to first layer key of a dict.""" r = dict() for key, value in d.items(): key = switch_case_func(key) r[key] = value return r
def isASubset(setToTest,pileList): """ Check if setToTest is ordered subset of pileList in O(n) @ In, setToTest, list, set that needs to be tested @ In, pileList, list, pile of sets @ Out, isASubset, bool, True if setToTest is a subset """ if len(pileList) < len(setToTest): return False in...
def lorentz_transform( p_in, px_in, py_in, pz_in, gamma, beta, nx, ny, nz ): """ Perform a Lorentz transform of the 4-momentum (p_in, px_in, py_in, pz_in) and return the results Parameters ---------- p_in, px_in, py_in, pz_in: floats The coordinates of the 4-momentum gamma, beta: fl...
def replaceSuffix(path, old_suffix, new_suffix=None, params=None): """Replace the last part of a URL path with something else. Also appends an optional list of query parameters. Used for replacing, for example, one link ID at the end of a relative URL path with another. Args: path: HTTP request relativ...
def prob2(limit=4000000): """ Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four m...
def process_problem_name(problem_name): """ Remove commas and replace space with underscore in problem name @param problem_name :: name of the problem that is being considered @returns :: the processed problem name """ problem_name = problem_name.replace(',', '') problem_name = problem_na...
def short_type(obj: object) -> str: """Return the last component of the type name of an object. If obj is None, return 'nil'. For example, if obj is 1, return 'int'. """ if obj is None: return 'nil' t = str(type(obj)) return t.split('.')[-1].rstrip("'>")
def TiltToTime(Tilt): """ 'Tilt' is in degrees and this function outputs the hours and minutes """ TiltTime = (((Tilt)%360)/360)*12 Hrs = int(TiltTime) if Hrs == 0: Hrs = 12 mins = int(round(TiltTime*60)%60) return(Hrs,mins)
def is_license_plate(string): """ Retruns true when the string is in Ontario license plate with example format such as ABCD-012, with 4 letters, followed by a hyphen, and 3 numbers. """ if string[0].isalpha(): if string[1].isalpha(): if string[2].isalpha(): if...
def find_argmax(topics_list): """ returns the maximum probability topic id in a [(topic_id, topic_prob)...] topics distribution """ m = -1. r_tid = -1 for tid, tprob in topics_list: if tprob > m: m = tprob r_tid = tid return r_tid
def drange(start, stop, step): """ Generate a sequences of numbers. """ values=[] r = start while r <= stop: values.append(r) r += step return values
def space(string, length): """ :param string: '556e697432332d41' :param length: 4 :return: 556e 6974 3233 2d41 """ return ' '.join( string[i:i + length] for i in range(0, len(string), length))
def sizeof_fmt(num, suffix='b'): """ Format a number of bytes in to a humage readable size """ for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def trim_irrelevant_characters(text: list, delimiter: str) -> list: """ :param text: a list of words :param delimiter: the delimiter character value ("," / " " / "\n") :return: a list of words stripped from irrelevant characters """ new_text = [] for word in text: if delimiter == '...
def validate_params_dict(params): """validates params data type Args: params: dict. Data that needs to be validated. Returns: dict. Returns the params argument in dict form. """ if not isinstance(params, dict): raise Exception('Excepted dict, received %s' % params) # Th...
def generate_media_name(file_name: str) -> str: """Camel cased media name Addition of "media" is due to the "upload_to" argument in the media model used - `file = models.FileField(upload_to="media", verbose_name=_("file"))` """ name = file_name.replace(" ", "_") return f"media/{name}"
def get_fake_pcidevice_required_args(slot='00:00.0', class_id='beef', vendor_id='dead', device_id='ffff'): """Get a dict of args for lspci.PCIDevice""" return { 'slot': slot, 'class_id': class_id, 'vendor_id': vendor_id, 'device_id': device_id...
def prayer_beads(data=None, nprays=0): """ Implement a prayer-bead method to estimate parameter uncertainties. Parameters ---------- data: 1D float ndarray A time-series dataset. nprays: Integer Number of prayer-bead shifts. If nprays=0, set to the number of data points...
def _remove_startswith(chunk: str, connector: str) -> str: """ Returns first string with the second string removed from its start. @param chunk: String to be updated @param connector: String to be removed from the beginning of the chunk @return: Updated 'chunk' string """ if chunk.startswit...
def _comment(s): """Returns a new string with "#" inserted before each line in 's'.""" if not s: return "#" res = "".join(["#" + line for line in s.splitlines(True)]) if s.endswith("\n"): return res + "#" return res
def compareTripletsSFW(a, b): """Same as compareTriplets, implemented strightforwardlly""" result = [0, 0] for i in range(min(len(a), len(b))): if a[i] > b[i]: result[0] = result[0] + 1 elif b[i] > a[i]: result[1] = result[1] + 1 return result