content
stringlengths
42
6.51k
def dummy_get_counts(a): """This is a convenient/dummy function for mimicking cosine profile around min/max values.""" from math import cos, radians return cos(radians(a))
def uniform(a, b, u): """Given u in [0,1], return a uniform number in [a,b].""" return a + (b-a)*u
def calculate_change(current_value, previous_value): """ Calculate change in value given current value and previous value. Can be either +ve or -ve :param current_value: str :param previous_value: str :return: str or na (convert number to string to make data type consistent) """ if not previ...
def _get_graph_consistency(num_R_vertices: int, num_E_vertices: int): """ Calculates the consistency of the given graph as in Definition 3.2. :param num_R_vertices: number of R vertices contained in a graph. :param num_E_vertices: number of E vertices contained in a graph. :return: consistency score...
def waber(lumin, lambdaValue): """ Weber's law nspired by Physhilogy experiment. """ # lambdaValue normally select 0.6 w = lumin**lambdaValue #w = (255*np.clip(w,0,1)).astype('uint8') return(w)
def center_coordinate(a: int, b: int) -> int: """Return the starting coordinate of an object of size b centered in an object of size a.""" return (a // 2) - (b // 2) - b % 2
def generate_voucher_number(number): """ NEED AN INTEGER generate_voucher_number(number objects) """ sno = '' number = int(number)+1 number = str(number) if len(number)<2: sno = '00000000'+number elif len(number)<3: sno = '0000000'+number elif len(number)<4: ...
def normalized(name, feed_entries): """Returns a list of normalized kvstore entries.""" data = [] for feed_entry in feed_entries: if 'indicator' not in feed_entry or 'value' not in feed_entry: continue # Make the entry dict. entry = feed_entry.copy() entry['splun...
def get_f_option(opts): """Return value of the -f option""" for opt, arg in opts: if opt == "-f": return arg else: return None
def remove_empty_elements_for_context(src): """ Recursively remove empty lists, empty dicts, empty string or None elements from a dictionary. :type src: ``dict`` :param src: Input dictionary. :return: Dictionary with all empty lists,empty string and empty dictionaries removed. :rtype: ``dict`...
def remove_trailing_exclamation(text): """A lot of abstracts end with '!' and then a bunch of spaces.""" while text.endswith('!'): text = text[:-1] return text
def build_name(host): """Gets the build name for a given host. The build name is either "linux" or "darwin", with any Windows builds coming from "linux". """ return { 'darwin': 'darwin', 'linux': 'linux', 'windows': 'linux', }[host]
def format_solution(code_str: str) -> str: """Format the solution to match the format of codex. Args: code_str (str): The code string to format. Returns: str: The formatted code string. """ if ('def' in code_str) or code_str.startswith('class'): return code_str code_arr...
def mandel(x, y, max_iters): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. """ c = complex(x, y) z = 0.0j for i in range(max_iters): z = z * z + c i...
def validate_homedirectory_type(homedirectory_type): """ Validate HomeDirectoryType for User Property: User.HomeDirectoryType """ VALID_HOMEDIRECTORY_TYPE = ("LOGICAL", "PATH") if homedirectory_type not in VALID_HOMEDIRECTORY_TYPE: # NOQA raise ValueError( "User HomeDirect...
def getSirionSiCpsPerNa(e0): """getSirionSiCpsPerNa(e0) Output the cps per nA for the Sirion Oxford EDS detector for a given e0. These values were determined for PT 6, 5 eV/ch, 2K channels in 2014-09-12-Cu-Si. Example: import dtsa2.jmGen as jmg a = jmg.getSirionSiCpsPerNa(7.0)""" val = 0.0 if(e0 == 5.0): val...
def sort_json_policy_dict(policy_dict): """ Sort any lists in an IAM JSON policy so that comparison of two policies with identical values but different orders will return true Args: policy_dict (dict): Dict representing IAM JSON policy. Basic Usage: >>> my_iam_policy = {'Principle': {'A...
def to_rtl(path): """Modifies a path to look like the RTL net/register names""" return '_'.join(path.split('.'))
def fixup_enums(obj, name_class_map, suffix="AsString"): """ Relying on Todd's THRIFT-546 patch, this function adds a string representation of an enum to an object that contains only the integer version. Callers must supply two arrays of the same length: the list of classes that the enums belongs to, and the ...
def IsTryJobResultAtRevisionValidForStep(result_at_revision, step_name): """Checks if a flake try job result is valid. Args: result_at_revision (dict): The result of running at a revision. For example, { 'browser_tests': { 'status': 'failed', 'failures': ['TabCaptureA...
def trim_path_prefixes(path, prefixes): """ Removes the longest matching leading path from the file path. """ # If no prefixes are specified. if not prefixes: return path # Find the longest matching prefix in the path. longest_matching_prefix = None for prefix in prefixes: ...
def plans_from_nspace(nspace): """ Extract plans from the namespace. Currently the function returns the dict of callable objects. Parameters ---------- nspace: dict Namespace that may contain plans. Returns ------- dict(str: callable) Dictionary of Bluesky plans """...
def parse_x12_major_version(x12_implementation_version) -> str: """ Parses the x12 major version from an implementation version string. If the version is invalid, an empty string is returned. Example: x = parse_x12_major_version("005010X279A1") print(x) # prints 5010 x ...
def unescape(text): """ Do reverse escaping. """ return text.replace('&amp;', '&').replace('&lt;', '<').replace('&gt;', '>').replace('&quot;', '"').replace('&#39;', '\'')
def resolve_field_type(field): """Keep digging into field type until finding a non-null `name`.""" type_ = field["type"] while type_["name"] is None: try: type_ = type_["ofType"] except: return None return type_["name"]
def sep_join(values): """Prepare parameters that take multiple values See https://www.wikidata.org/w/api.php?action=help&modules=main#main/datatypes """ if any((('|' in set(v)) for v in values)): # we need to use an INFORMATION SEPARATOR ONE (U+001F) character as delimiter SEPARATOR = '\...
def GetSingleListItem(list, default=None): """Return the first item in the list, or "default" if the list is None or empty. Assert that the list contains at most one item. """ if list: assert len(list) == 1, list return list[0] return default
def median(nums): """ Find median of a list of numbers. >>> median([0]) 0 >>> median([4,1,3,2]) 2.5 Args: nums: List of nums Returns: Median. """ sorted_list = sorted(nums) med = None if len(sorted_list) % 2 == 0: mid_index_1 = len(sorted_list) ...
def get_xls_dslx_ir_generated_files(args): """Returns a list of filenames generated by the 'xls_dslx_ir' rule found in 'args'. Args: args: A dictionary of arguments. Returns: Returns a list of files generated by the 'xls_dslx_ir' rule found in 'args'. """ return [args.get("ir_file")]
def format_import(source_module_name, source_name, dest_name): """Formats import statement. Args: source_module_name: (string) Source module to import from. source_name: (string) Source symbol name to import. dest_name: (string) Destination alias name. Returns: An import statement string. """ ...
def detect_header_value(headers: dict, key: str, source: str = "Response"): """ Detect a title case, lower case, or capitalised version of the given string. """ variants = key.title(), key.lower(), key.capitalize() try: return next(headers.get(k) for k in variants if k in headers) except...
def flip_sequence(seq: list) -> list: """ Flip the control sequence i.e., high-level effective <---> low level effective """ if seq[0] == 0: if seq[-1] == 0: return seq[1:-1] else: return seq[1:] + [0] else: if seq[-1] == 0: return [0] ...
def physiology_features_wrapper(voltage_base, input_resistance, dct): """Wraps the extracted features into the dictionary format with names and units. Args: voltage_base (float): resting membrane potential (mV) input_resistance (float): input resistance (MOhm) dct (float): membrane time...
def get_artifact_paths_from_build(build_dict): """ Given a dict containing the build details return a list of artifact paths associated with that build """ artifact_paths = [] for artifact in build_dict.get('artifacts'): if artifact.get('relativePath').endswith('_benchmark.json'): a...
def pressure_out_of_plane_R_disp(r, p, ri, ro, E, nu, dT, alpha): """ Assumption of cylinder closed at both ends (constant axial force) """ A = ri**2 * ro**2 * -p / (ro**2 - ri**2) C = p * ri**2 / (ro**2 - ri**2) u = (-A*nu - A + C*r**2*(1 - 2*nu))/(E*r) return u
def _valid_zone_type(zone_type: str) -> bool: """Implemented zone types.""" if zone_type in ['dbt-rh', 'xy-points']: return True return False
def flat_path(path): """ Flattens a path by substituting dashes for slashes """ import re return re.sub('/', '-', path)
def layer_function2(x): """ lambda function """ return x[0] + x[1]
def _compare_fq_names(this_fq_name, that_fq_name): """ :param this_fq_name: list<string> :param that_fq_name: list<string> :return: True if the two fq_names are the same """ if not this_fq_name or not that_fq_name: return False elif len(this_fq_name) != len(that_fq_name): ret...
def get_lomb_frequency(lomb_model, i): """Get the ith frequency from a fitted Lomb-Scargle model.""" return lomb_model['freq_fits'][i-1]['freq']
def break_words(word): """Split the word..""" words =word.split(' ') return words
def next_multiple(query, multiple): """Get the next multiple Args: query (int): To test multiple (int): Divider Returns: int: Next multiple of divider """ result = query while result % multiple: result += 1 return result
def bool_or_string(s): """Discern if a string is a bool or a normal string.""" true_strings = ["true", "1"] false_strings = ["false", "0"] if(s.lower() in true_strings): return True elif(s.lower() in false_strings): return False return s
def nice_price(price): """ Returns the price in nice numbers with k/m/b on the end as a string """ if price < 1000: return f'{price:,.0f} gp' elif price < 1000000: return f'{price / 1000:,.1f} K gp' elif price < 1000000000: return f'{price / 1000000:,.1f} M gp' else: ...
def maxSequence(arr): """ max_sequence == PEP8 (forced mixedCase by CodeWars) """ maximum = total = 0 for a in arr: total = max(0, total + a) if total > maximum: maximum = total return maximum
def cell(text): """Format text as a table cell for wikitext markup""" text = str(text) if text[0] == '|' or text[0] == '!': return text else: return f"| {text}\n"
def bubble_sort(arr): """ insertion sort using swap Time: O(n^2) Space: O(1) """ for i in range(len(arr)): for j in range(len(arr) - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr
def alt_a_split_profile(dictionary, profile): """Create the split profile.""" dictionary['Keyboard Map']["0x61-0x80000"] = { "Action": 28, "Text": profile, } return dictionary
def as_list(items): """ Convert to list Parameters ---------- items : list or int or str Returns ------- list """ return [items] if type(items) is not list else items
def MAE(X, Y): """ Mean Absolute Error (MAE) """ r = 0.0 for x,y in zip(X,Y): r += abs(x-y) return r/len(X)
def encode_message(chat_name, port, message_type, sender_id, message, length): """Encode message for sending. In the format of ChatName_ListenPort_type_id_content_length. Actually length is only useful when sending images or files. """ message = '{}_{}_{}_{}_{}_{}'.format( chat_name, port, ...
def show_procs(procs, mem_limit): """Pretty print host procs in ps-like fashion""" mem_limit_kb = mem_limit / 1024 result = "" fmt_line = "%(user)5d %(pid)5d %(cpu)5.1f %(mem)5.1f %(vsz)8d \ %(rss)8d %(state)6s %(command)s\n" if procs: result = "\n%5s %5s %5s %5s %8s %8s %6s ...
def is_sorted(dictionary: dict): """ Function that checks if a dict is sorted (true if sorted false if not) Parameters ---------- dictionary: dict The dict to check Returns ------- bool If the dict is sorted or not """ prev = None for value in dictionary.val...
def cosine(seen_doc, unseen_doc): """ cosine(weighted_a, weighted_b) -> float value of cosine similarity of two input vectors seen_doc = dictionary that is a BM25-weighted document term vector unseen_doc = dictionary that is a BM25-weighted document term vector """ similarity = 0 for w,score in ...
def sunrise_float(solar_noon_float, hour_angle_sunrise): """Returns Sunrise as float with Solar Noon Float, solar_noon_float and Hour Angle Deg, hour_angle_deg""" sunrise_float = (solar_noon_float * 1440 - hour_angle_sunrise * 4) / 1440 return sunrise_float
def from_hex(hs): """ Returns an RGB tuple from a hex string, e.g. #ff0102 -> (255, 1, 2) """ return int(hs[1:3], 16), int(hs[3:5], 16), int(hs[5:7], 16)
def yesno(b): """ returns yes if b it true, no if b is false """ if b: return "yes" else: return "no"
def fix_and_quote_fortran_multiline(txt): """Fortran can't handle multiple, so adding continuation character '&' if necessary""" if isinstance(txt, str): txt = txt.replace('\n', '"// & \n & "') return '"%s"'%txt return txt
def format_datetime(dt, fmt='%a %b %d %Y %H:%M:%S %Z'): """ Format datetime human readable """ if dt is None: return "-" try: return dt.strftime(fmt) except TypeError: pass return str(dt)
def argument_checker(Sin, Sout): """Reads the 2 arguments in from the command line and checks if they're of the correct format""" if not (Sin < 64000 and Sin > 1024): print('ERROR: Ports of wrong size') return False if not (Sout < 64000 and Sout > 1024): print('ERROR: Ports of wrong...
def fill_in_whitespace(text): """Returns 'text' with escaped whitespace replaced through whitespaces.""" text = text.replace(r"\n", '\n') text = text.replace(r"\t", '\t') text = text.replace(r"\r", '\r') text = text.replace(r"\a", '\a') text = text.replace(r"\b", '\b') return text
def validate_page_size(page_size): """ Validate that page size parameter is in numeric format or not :type page_size: str :param page_size: this value will be check as numeric or not :return: True if page size is valid else raise ValueError :rtype: bool """ if not page_size or not str...
def mk_xor_expr(expr1, expr2): """ returns an or expression of the form (EXPR1 XOR EXPR2) where EXPR1 and EXPR2 are expressions """ return {"type" : "xor" , "expr1" : expr1 , "expr2" : expr2 }
def amount(gen, limit=float("inf")): """ Iterates through ``gen`` returning the amount of elements in it. The iteration stops after at least ``limit`` elements had been iterated. Examples -------- >>> amount(x for x in "abc") 3 >>> amount((x for x in "abc"), 2) 2 >>> from itertools import count ...
def calc_hba1c(value): """ Calculate the HbA1c from the given average blood glucose value. This formula is the same one used by Accu-Chek: https://www.accu-chek.com/us/glucose-monitoring/a1c-calculator.html# """ if value: return ((46.7 + value) / 28.7) else: return 0
def extract_sent_interaction(sent_1, sent_2, type="word"): """ sentence interaction lenght feature, with word/character n-gram :param sent: :return: """ sent_1 = sent_1.split(" ") sent_2 = sent_2.split(" ") sent_len_dict = {} sent_len_dict["union_len_%s" % type] = len(se...
def field(date, type=None, lead_time=None): """Forecast field locator Maps verification date and lead time off set to file name and index along file *time_counter* .. note:: User-specified stub :param date: The verification date in string format ``'%Y%m%d'`` :param type: Forecast type :pa...
def right_d_threshold_sequence(n, m): """ Create a skewed threshold graph with a given number of vertices (n) and a given number of edges (m). The routine returns an unlabeled creation sequence for the threshold graph. FIXME: describe algorithm """ cs = ['d'] + ['i'] * (n - 1) # crea...
def _positive_int(integer_string, strict=False, cutoff=None): """ Cast a string to a strictly positive integer. """ ret = int(integer_string) if ret == -1: return -1 if ret < 0 or (ret == 0 and strict): raise ValueError() if cutoff: return min(ret, cutoff) return ...
def GetStringBetweenQuotation(string): """ Pick up strings between quotations in 'string' :param str string: string data :return: strlst(lst) - list of strings """ strlst=[]; quo="'"; dquo='"' while len(string) > 0: qs=string.find(quo); ds=string.find(dquo) if qs < ...
def unravel_artifacts(rpt_artifact_msg): """ Converts a repeated Artifact field of a protobuf message into a list of names. Parameters ---------- rpt_artifact_msg : google.protobuf.pyext._message.RepeatedCompositeContainer Repeated Artifact field of a protobuf message. Returns ----...
def find_uniques(p, uniques): """ :param p: :param uniques: :return: """ unique = True for u in uniques: if p['id'] == u['id'] and p['latestDate'] == u['latestDate'] and p['location'] == u['location']: return False elif p['id'] == u['id'] and p['location'] == u['...
def audience(*types): """Select audience that match all of the given selectors. >>> audience(tag('sports'), tag_and('business')) {'audience': {'tag':['sports'], 'tag_and':['business']}} """ if 1 == len(types) and 'all' == types[0]: return "all" audience = {} for t in types: ...
def generate_docs(params, response, summary, path): """This will generate the documentation for a function given some information about the params, the response (not currently used), the summary, and the path.""" docstring = "{0}\n".format(summary) docstring += "{0}\n".format(path) pathParam...
def monthly_loan(loan: float, interest_rate: float, years: int) -> float: """ Calculate monthly loan payment :param loan: initial loan amount :param interest_rate: interest rate :param years: loan term in years :return: monthly payment """ n = years * 12 r = interest_rate / (100 * 1...
def newline_space_fix(text): """Replace "newline-space" with "newline". This function was particularly useful when converting between Google Sheets and .xlsx format. Args: text (str): The string to work with Returns: The text with the appropriate fix. """ newline_space = '...
def contains_all(d_, *keys): """ Does the dictionary have values for all of the given keys? >>> contains_all({'a': 4}, 'a') True >>> contains_all({'a': 4, 'b': 5}, 'a', 'b') True >>> contains_all({'b': 5}, 'a') False """ return all([d_.get(key) for key in keys])
def cap(name): """Function Cap @args: name -> string @returns: string """ return name.upper()
def dot_product(features,weights): """ Calculate dot product from features and weights input: features: A list of tuples [(feature_index,feature_value)] weights: the hashing trick weights filter, note: length is max(feature_index) output: dotp: the dot product """ dotp = 0 for f in features: dotp += w...
def _sanitize_title(string): """a form of slugification. foo = Foo foo-bar => FooBar foo-bar-baz => FooBarBaz FOO-BAR-BAZ => FooBarBaz""" return "".join(map(str.capitalize, string.split("-")))
def package_to_path(package): """ Convert a package (as found by setuptools.find_packages) e.g. "foo.bar" to usable path e.g. "foo/bar" No idea if this works on windows """ return package.replace('.', '/')
def color_variant(hex_color, brightness_offset=1): """ takes a color like #87c95f and produces a lighter or darker variant """ if len(hex_color) != 7: raise Exception("Passed %s into color_variant(), needs to be in #87c95f format." % hex_color) rgb_hex = [hex_color[x:x+2] for x in [1, 3, 5]] new...
def unique_counts(rows): """ :param rows: :return: """ results = {} for row in rows: # The result is the last column r = row[len(row) - 1] if r not in results: results[r] = 0 results[r] += 1 return results
def get_urn(url): """ convert https://blog.scrapinghub.com/page/6/ into blog.scrapinghub.com/page/6/ :param url: :return: """ if "://" in url: return url.split("://")[1] return url
def even_or_odd(x=0): ## if not specified, x should take value 0 """Find whether a number x is even or odd >>> even_or_odd(10) '10 is Even!' >>> even_or_odd(5) '5 is Odd!' whenever a float is provided, then the closest integer >>> even_or_odd(3.2) '3 is Odd!' in case of negative numbers, the positive is ta...
def normalize(s): """Convert to integer.""" try: x = int(s) except ValueError: x = s return x
def legendre_symbol(a, p): """ Compute the Legendre symbol a|p using Euler's criterion. p is a prime, a is relatively prime to p (if p divides a, then a|p = 0) Returns 1 if a has a square root modulo p, -1 otherwise. """ ls = pow(a, (p - 1) // 2, p) return -1 if ls == p - 1 else ls
def get_extension_from_data(data): """ given data as base64, returns extension from data headers """ headers = data.split(',')[0] if 'png' in headers: return 'png' elif 'jpg' in headers: return 'jpg' else: return 'jpeg'
def production_variant( model_name, instance_type, initial_instance_count=1, variant_name="AllTraffic", initial_weight=1, accelerator_type=None, ): """Create a production variant description suitable for use in a ``ProductionVariant`` list. This is also part of a ``CreateEndpointConfig`...
def get_e_rtd_H(e_rtd_H_raw): """ Args: e_rtd_H_raw: Returns: """ return round(e_rtd_H_raw * 1000) / 1000
def unhash_index(_hash): """ Decode hased value to tuple :param _hash: str, hash_index result :return: tuple of tuples hash = 'q1::1__q2::2' return ((q1, 1), (q2, 2)) """ try: return tuple(map(lambda x: tuple(x.split('::')), _hash.split('__'))) except: print(_hash)
def _as_int(string, default: int = 0): """Return first sequence as int.""" return int(string.strip().partition(" ")[0] or default)
def to_vartype(input, default=None, vartype=str): """ Returns input converted to vartype or default if the conversion fails. Parameters ---------- input : * Input value (of any type). default : * Default value to return if conversion fails. vartype : data type Desire...
def is_cjk(character): """ Python port of Moses' code to check for CJK character. >>> CJKChars().ranges [(4352, 4607), (11904, 42191), (43072, 43135), (44032, 55215), (63744, 64255), (65072, 65103), (65381, 65500), (131072, 196607)] >>> is_cjk(u'\u33fe') True >>> is_cjk(u'\uFE5F') False...
def convert_numbers(item): """ Try to convert str to number. >>> try_int('2') 2 >>> try_int('foo') 'foo' """ try: return int(item) except ValueError: try: return float(item) except ValueError: return item
def construct_APDU(cla, ins, p1, p2, data, le): """ Constructs an APDU according to ISO 7816. note that CLA is defined for 0x0X, reserved for 0x10 to 0x7F """ lc = len(data) if lc == 0: lc_bytes = [] elif lc < 2**8: lc_bytes = [lc] else: raise Exc...
def get_address(device_number): """ Maps device numbers. """ if device_number == 0: return 0x1C elif device_number == 1: return 0x1D else: raise ValueError("Bad device number:", device_number)
def Step(v, threshold=0, act_value=1, inact_value=0): """ Step function where the threshold, activated and inactivated value can be defined. """ return act_value if v > threshold else inact_value
def run_prime_factorization(max_number: int) -> dict: """Run prime factorization. Args: max_number: Int of number (greater than 1). Returns: A dictionary's items ((base, exponent) pairs). Landau notation: O(log n) """ from math import sqrt ans = dict() remain = max_numb...
def escape_for_markdown_v2(message: str) -> str: """ Escape a message so it can be sent with markdown_v2 Args: message (str): Message without escaped characters Returns: str: Message with escaped characters """ return ( message.replace('-', '\-') .replace('!', ...