content
stringlengths
42
6.51k
def get_instructor_term_list_name(instructor_netid, year, quarter): """ Return the list address of UW instructor email list for the given year and quarter """ return "{uwnetid}_{quarter}{year}".format( uwnetid=instructor_netid, quarter=quarter.lower()[:2], year=str(year)[-2:]...
def not_at_goal_set(trees): """convenience / readability function which returns the not terminated trees from a list :param trees: list of input trees :type trees: list :return: trees from the input list which are not terminated :rtype: list """ not_at_goal = [] for tree in trees: ...
def __castToInt(*args): """ Cast the input args to int. """ return list(map(int, args))
def _munge_time(t): """Take a time from nvprof and convert it into a chrome://tracing time.""" # For strict correctness, divide by 1000, but this reduces accuracy. return t
def round_pruning_amount(total_parameters, n_to_prune, round_to): """round the parameter amount after pruning to an integer multiple of `round_to`. """ round_to = int(round_to) if round_to<=1: return n_to_prune after_pruning = total_parameters - n_to_prune compensation = after_pruning % round_to...
def isSubset(L1, L2): """Assumes L1 and L2 are lists. Returns True if each element in L1 is also in L2 and False otherwise.""" for e1 in L1: matched = False for e2 in L2: if e1 == e2: matched = True break if not matched: return False retur...
def split_chunk_for_display(raw_bytes): """ Given some raw bytes, return a display string Only show the beginning and end of largish (2xMAGIC_SIZE) arrays. :param raw_bytes: :return: display string """ MAGIC_SIZE = 50 # Content repeats after chunks this big - used by echo client, too if...
def to_unicode(text): """Convert the specified text to a unicode string.""" if not isinstance(text, type(u'')): try: return text.decode('utf-8') except UnicodeDecodeError: return text.decode('iso-8859-15') return text
def _sorted_items(x): """Returns items of a dict ordered by keys.""" return sorted(x.items(), key=lambda x: x[0])
def list_declaration_1(a="Mozart", b=1.2): """ Lists are mutable :param a: optional parameter :param b: optional parameter :return: a declared list """ artists = [a, b, "Caparezza", "Lety", "Pit", "Virgi"] print(artists) return artists
def bubbleSort(li): """Compare adjecent pairs and turn them around if they're not sorted properly, therefore "bubbling" higher elements to the end and lower elements to the beginning. We need to do it a maximum of len(li) times. >>> bubbleSort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> bubbleSort([5,...
def DidCrunchFail(returncode, stderr): """Determines whether aapt crunch failed from its return code and output. Because aapt's return code cannot be trusted, any output to stderr is an indication that aapt has failed (http://crbug.com/314885). """ return returncode != 0 or stderr
def char_to_number(value: str, required_type: str) -> str: """Converts the string representation of a number (int or float) to a number Args: value (str): String representation of a number required_type (str): Output type desired (bigint or double) Raises: Exception: The conversion...
def build_key(text, n): """ Builds a key out of the text and line number :param text: the text of translation :param n: line number :return: the key built """ return text + "." + str(n)
def recursive_array_count(l:list): """Count an array of elements using recursion.""" if l == []: return 0 else: l.pop() return 1 + recursive_array_count(l)
def temp2_swap(i, j): """temp_swap with one less assignment""" temp = i i = j return i, temp
def replace_right(source, target, replacement, replacements=None): """ String replace rightmost instance of a string. Args: source (string): the source to perform the replacement on target (string): the string to search for replacement (string): the replacement string replac...
def clean_postcode(postcode): """This function takes an string and returns a string of 5 digit postcode in the boston_massachusetts.osm""" # delete -XXXX after the five digit postcode if "-" in postcode: return postcode.split("-")[0] # delete MA in the postcodes elif "MA" in postcode: ...
def _check_nfft(n, n_fft, n_overlap): """Helper to make sure n_fft and n_overlap make sense""" n_fft = n if n_fft > n else n_fft n_overlap = n_fft - 1 if n_overlap >= n_fft else n_overlap return n_fft, n_overlap
def getstateloc(X_U, Y_U, size): """ This function find the state based on the current location and the grid size. :param X_U: Location of all UAVs. (X) :param Y_U: Location of all UAVs. (Y) :param size: The grid size. :return: This function returns the current state. """ stat...
def get_1d_distance(x1, x2): """returns the distance on a 1-dimensional plane from x1 to x2""" return abs(x1 - x2)
def _FormatData(text, data): """Returns formatted text, using key/value from data dictionary""" for (key, value) in data.items(): key_str = '%%(%s)s' % key if key_str in text: text = text.replace(key_str, value) return text
def make_badge(alt_text, badge_svg, url_base, local_path): """Generate a markdown element for a badge image that links to a file.""" return f"[![{alt_text}]({badge_svg})]({url_base}/{local_path})"
def pop_data(serving_dictionary, dict_key): """Return a value from a Python dictionary for a given key, if it exists, and also remove the key-value pair afterwards. :param serving_dictionary: :param dict_key: :return: """ result = None if dict_key in serving_dictionary: re...
def knight_amount(board_state, player): """ Returns amount of knights the player has """ board = board_state knight_amt = 0 for row in board: for column in row: if player == 1 and column == "k": knight_amt += 1 elif player == 0 and column == "K": ...
def cast(tensor, dtype): """Cast Args: tensor (Tensor): tensor to cast. dtype (str): type to cast. Usually floatx or intx """ if isinstance(tensor, float) or isinstance(tensor, int): if dtype in ['float', 'float32']: return float(tensor) elif dtype == ['int'...
def create_ordered_dict(items): """Creates an ordered dictionary from a list of items. Each item is added to a dictionary. The position of the item is set as the key value. These are set in the order that the items are supplied in the items list. The dictionary can then be returned in order by iter...
def matrix_multiplication(A, B): """ >>> A = [[1, 0], [0, 1]] >>> B = [[4, 1], [2, 2]] >>> matrix_multiplication(A, B) [[4, 1], [2, 2]] >>> A = [[1,0,1,0], [0,1,1,0], [3,2,1,0], [4,1,2,0]] >>> B = [[4,1], [2,2], [5,1], [2,3]] >>> matrix_multiplication(A, B) [[9, 2], [7, 3], [21, 8],...
def convert_to_negative_value(data): """ if the user entered a value and it's higher > 0, we wil convert to a, negative value. """ if data and data > 0: data = data * -1 return data
def shorter_name(key): """Finds a shorter name for an id by only taking the last part of the URI, after the last / and the last #. Also replaces - and . with _. Parameters ---------- key: str Some URI Returns ------- key_short: str A shortened, but more ambiguous, ident...
def positions_threshold_tag_from_positions_threshold(positions_threshold): """Generate a positions threshold tag, to customize phase names based on the threshold that positions are required \ to trace within one another. This changes the phase name 'phase_name' as follows: positions_threshold = 1 -> p...
def locate_folder(folders, target): """ Search for a target folder in the folders list and return the name and id. """ if type(folders) == list: folder = [f for f in folders if f['name'] == target] elif type(folders) == dict and folders.get('folders', False): folder = [f for f in fol...
def is_valid_xml_char(char): """Check if a character is valid based on the XML specification.""" codepoint = ord(char) return (0x20 <= codepoint <= 0xD7FF or codepoint in (0x9, 0xA, 0xD) or 0xE000 <= codepoint <= 0xFFFD or 0x10000 <= codepoint <= 0x10FFFF)
def make_minimal_cs_comment(overrides=None): """ Create a dictionary containing all needed comment fields as returned by the comments service with dummy data and optional overrides """ ret = { "type": "comment", "id": "dummy", "commentable_id": "dummy", "thread_id": "...
def _alpha_to_beta_(alpha, b0=0.25, b1=0.63): """ Ratio given by SNIFS """ return b0+alpha*b1
def parse_slice(val): """ Convert a string with a Python-like slice notation to a slice object. """ if ':' not in val: value = int(val) stop_value = value + 1 if value != -1 else None return slice(value, stop_value) else: value = val.split(':') start = None if value[0] == '' else int(value[0]) stop = N...
def fmt_ms(ms): """Take a time in milliseconds and convert it to mm:ss.ms""" time = int(ms) minutes = int(time / (60 * 1000)) time -= minutes * (60 * 1000) seconds = time / 1000 return str(minutes) + ':' + "{seconds:.3f}".format(seconds=seconds)
def name_paths(name_article): """ provide article type make the needed files """ name_src = str(name_article + '_src_query') name_dst = str(name_article + '_dst_query') name_summary = str(name_article + '_sum') name_unique = str(name_article + '_unique_df') plot_unique = s...
def resized_dims_and_ratio(img_size, max_dsize): """ returns resized dimensions to get ``img_size`` to fit into ``max_dsize`` FIXME: Should specifying a None force the use of the original dim? Args: img_size (tuple): max_dsize (tuple): Returns: tuple: (dsize, ratio...
def check_outputs(outputs): """Check output to determine if we need to send an alert email.""" alerts = [] if outputs[0] != 'BSSID: 5c:5b:35:31:5a:f1': # Check our connected BSSID alerts.append('Incorrect %s' % outputs[0]) # Add further checks here based on line[1] - n. return alerts
def hashmodarchdep(*args): """ .. function:: hashmodarchdep(args, divisor) -> int Returns a hash of the args. .. note:: This hash function is architecture dependent (32bit vs 64bit). Examples: >>> sql("select hashmodarchdep(65,5)") #doctest:+ELLIPSIS hashmodarchdep(65,5) ---...
def check_list(data): """check if data is a list, if it is not a list, it will return a list as [data]""" if type(data) is not list: return [data] else: return data
def dfs(start, target): """ Implementation of DFS (depth-first search) algorithm to find the shortest path from a start to a target node.. Given a start node, this returns the node in the tree below the start node with the target value (or null if it doesn't exist) Runs in O(n), where n is the number of...
def fib(n): """Returns the nth fibonacci number.""" if n == 1: return 1 elif n == 2: return 1 else: return fib(n - 1) + fib(n - 2)
def format_guesses(past_guesses): """Returns a string of the past_guesses. For example, format_guesses(['x', 'y', 'z']) should return the str 'x y z' Args: past_guesses: a list of strings Returns: A string: of past_guesses """ return " ".join(past_guesses)
def w1_cal_func(x): """Calibration fit for W1 from Patel+2014.""" if x < 8.0: return -0.1359+0.0396*x-0.0023*x**2 else: return 0.0
def response_example_keys(endpoint, method, success_code): """ Returns tuple of lists with keys for accessing response examples in oas dictionary """ return ( ["paths", endpoint, method, "responses", success_code, "$ref"], ["content", "application/fhir+json", "examples"], )
def outside_range(start: int, end: int, idx: int) -> bool: """double True if idx is not between start and end inclusive. """ if start <= end: return idx < start or idx > end return idx < end or idx > start
def _get_classes(): """Return a list of classes found in transforms directory. Returns: list of classes found in transforms directory. """ import inspect return [c for c in globals().values() if inspect.isclass(c)]
def toHex(n): """ Converts a numeric value to hex (pointer to hex) Arguments: n - the value to convert Return: A string, representing the value in hex (8 characters long) """ return "%08x" % n
def at_least(length:int) -> str: """ Match the previous pattern at least `length` times, greedily. >>> import superexpressive as se >>> se.at_least(4) '{4,}' >>> import superexpressive as se >>> se.DIGIT + se.at_least(6) '\\\\d{6,}' """ return f"{{{length},}}"
def add_endsemicolon_ocaml(text, semicolon=';;'): """ Build an OCaml indenpendent cell by adding a closing ';;' at the end. Parameters ---------- text : str Text to comment out. semicolon : str By default ';;'. """ if not text.endswith(semicolon): return text + s...
def resolve_module(includes, file_module_map): """Scan backwards through the list of includes to find the module. The files that SWIG operates on can recursively include other files. We are only interested in the most recent module declaration, so we scan the list backwards until we find a node that has declar...
def Report(build_statuses): """Generate the stdout description of a given build. Args: build_statuses: List of build_status dict's from FetchBuildStatus. Returns: str to display as the final report. """ result = '' for build_status in build_statuses: result += '\n'.join([ 'cidb_id: %s...
def split_int(i, p): """ Split i into p buckets, such that the bucket size is as equal as possible Args: i: integer to be split p: number of buckets Returns: list of length p, such that sum(list) = i, and the list entries differ by at most 1 """ split = [] n = i / p # min ...
def is_context_manager(obj): """An object is a context manager if it has __enter__ and __exit__ methods.""" return all(hasattr(obj, m) for m in ("__enter__", "__exit__"))
def max_val_rec(alist): """ For 1D array What if there is unsorted array? I doubt Binary Search would work. Doing a max peak value search by recursive divide. Not Binary Search. """ ln = len(alist) mid = ln//2 if ln > 2: left = max_val_rec(alist[:mid]) right = max...
def upper(text: str, *args, **kwargs) -> str: """Return text in UPPERCASE style. This is a convenience function wrapping inbuilt upper(). It features the same signature as other conversion functions. Note: Acronyms are not being honored. Args: text (str): Input string to be converted ...
def build_recurrent_dpcl(num_features, hidden_size, num_layers, bidirectional, dropout, embedding_size, embedding_activation, num_audio_channels=1, rnn_type='lstm', normalization_class='BatchNorm', normalization_args=None, mix_key='mix_magnitud...
def fleet_bad_action(rec): """ author: gavinelder description: Alert when a user carries out a bad action. reference: N/A playbook: (a) Reach out to the user who made the modification and confirm intent. (b) Link appropriate Jira ticket. """ return ( r...
def references_to_json(resources, references): """ Make a JSON/catalog representation of the references db, including the count for each """ dump_references = {} for reftype, refvalue in references.items(): dump_references[reftype] = {} for label, reference_resource in refvalue.items()...
def fix_target_idx(summ, assumed_idx, word, neighborhood=5): """ Tokenization can mess stuff up, so look around """ for i in range(1, neighborhood + 1): if assumed_idx + i < len(summ) and summ[assumed_idx + i] == word: return assumed_idx + i elif 0 <= assumed_idx - i < len(su...
def isOdd(number): """ input: integer 'number' returns true if 'number' is odd, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 != 0, bool), "compare bust been from type bool" return number % 2...
def DecodeFATTime(FATdate, FATtime): """Convert the 2x16 bits of time in the FAT system to a tuple""" day = FATdate & 0x1f month = (FATdate >> 5) & 0xf year = 1980 + (FATdate >> 9) sec = 2 * (FATtime & 0x1f) min = (FATtime >> 5) & 0x3f hour = FATtime >> 11 return (year, day, month, hour,...
def bias_term(power1, power2, power1_noise, power2_noise, n_ave, intrinsic_coherence=1.0): """Bias term needed to calculate the coherence. Introduced by Vaughan & Nowak 1997, ApJ 474, L43 but implemented here according to the formulation in Ingram 2019, MNRAS 489, 392 As recommended in the la...
def lower(stringarr): """ Convert values to lowercase. """ return """map( {stringarr}, |e: vec[i8]| result( for(e, appender[i8], |c: appender[i8], j: i64, f: i8| if(f > 64c && f < 91c, merge(c, f + 3...
def create_response(rec): """ Helper function to create a formated JSON response. """ resp = {} fields = ( 'id', 'system', 'itype', 'tag', 'status', 'userACL', 'groupACL', 'ENV', 'ENTRY', 'WORKDIR', 'last_pull', 'status_message', ) for field in fields: try: resp[f...
def site_author(request, registry, settings): """Expose website URL from ``tm.site_author`` config variable to templates. This is used in footer to display the site owner. """ return settings["tm.site_author"]
def add_score(user, score): """Add a score of the game Parameters: user: the dictionary of the user (dict) score: the score of the game (int) Returns: user: the update user (dict) """ user['game']['score'] = score return user
def avg(grades): """Assertions; an example of good defensive programming >>> avg([68, 89, 96, 88, 75]) 83.2 >>> avg([68, 50, 91, 80, 65]) 70.8 >>> avg([49, 60, 81, 97, 55]) 68.4 """ assert not len(grades) == 0, 'no grades data' return sum(grades) / len(grades)
def get_unstresses(stresses: list, count: int) -> list: """Given a list of stressed positions, and count of possible positions, return a list of the unstressed positions. >>> get_unstresses([0, 3, 6, 9, 12, 15], 17) [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16] """ return list(set(range(count)) - set(s...
def convex_area(vertices): """Returns the area of a convex polygon Args: vertices (list): list of (x,y) vertices of convex polygon Returns: The area of the polygon """ off = vertices[0] twicearea = 0 nverts = len(vertices) for i in range(nverts): j = (i - 1) % n...
def _to_int(val, multi=100.0): """Safe conversion.""" if val.strip() == "": return None try: return int(val) * multi except ValueError: return None
def inside_area(location, corners): """ Check if the location is inside an area. :param location: location :param corners: corner points of the rectangle area. :return: """ x1 = corners[0][0] x2 = corners[1][0] y1 = corners[0][1] y2 = corners[1][1] return (location[0] > x1 an...
def convert_r_groups_to_tuples(r_groups): """ Converts a list of R-Group model objects to R-Group tuples""" return [r_group.convert_to_tuple() for r_group in r_groups]
def timestamp_format_to_redex(time_format): """ convert time stamp format to redex Parameters ---------- time_format : str datetime timestamp format Returns ------- redex : str redex format for timestamp """ time_keys = {'%Y': r'\d{4}', '%m': r...
def parse_ircounter(hex_str, port=None): """ Parse payload like "d77e3700030002" or "d77e070dae3700040001" struct of mixed values :param hex_str: IR counter hex payload :param port: LoRaWAN port :return: dict containing values """ data = None if (hex_str[4:6] == "07"): data = { ...
def str2bytes(data): """ Converts string to bytes. >>> str2bytes("Pwning") b'Pwning' """ return bytes(data, encoding="utf-8")
def format_float_val_as_currency(v) -> str: """ Given a float value, format it as currency. Note that the sign is backwards due to the fact that the charge_fields in the data that comes back are positive numbers but are written as negative on the invoice. There's also the fact that in our format string,...
def ses(count, plural='s', singular=''): """ ses is pronounced "esses". Return a string suffix that indicates a singular sense if the count is 1, and a plural sense otherwise. So, for example: log.info("%d item%s found", items, utils.ses(items)) would log: ...
def gaussian2d(x, y, sigma): """The symmetric 2d unit gaussian function. .. math:: \\frac{1}{2\\pi\\sigma^2}e^{\\frac{x^2 + y^2}{2\\sigma^2}} """ from math import exp, pi s2 = sigma * sigma ret = exp(-0.5 * (x*x + y*y)/s2) / (2 * pi * s2) return ret
def _normalize_sql(sql, maxlen=180): """Collapse whitespace and middle-truncate if needed.""" out = ' '.join(sql.split()) if len(out) > maxlen: i = int(maxlen / 2 - 4) out = (out[0:i] + ' ... ' + out[-i:None]) return out
def find_first_kmer(in_string, k): """function to find the first k mer of given length from string""" r_string = str(in_string[0:k]) return(r_string)
def create_base_config(log_dir, seed=123456789): """ Create the base configuration for the experiments. @param log_dir: The directory where this run should be created. @param seed: The random seed to use. @return: A dictionary containing the base configuration for the SP. """ return { 'ninp...
def inner_load_env_mapping(key, env_keys): """ Instantiates an environment configuration by key :param key: :param env_keys: :return: """ if key in env_keys: return env_keys[key]() raise KeyError("No %s configuration found" % key)
def decode_binary(binary): """This function decodes a binary into a UTF-8 encoded string. .. versionadded:: 2.6.0 :param binary: The binary to be decoded :returns: The properly decoded string :raises: :py:exc:`TypeError`, :py:exc:`ValueError` """ return binary.decode('utf-8')
def context_field(field_desc): """ Return a bound_field like object corresponding to suppliedfield details. The supplied parameter is a dictonary of field descriptiopn values, with a small number of additional keys recognized as setting values of the bound_field. """ copy_field_desc = field_des...
def find_defining_class(obj, method_name): """Finds and returns the class object that will provide the definition of method_name (as a string) if it is invoked on obj. obj: any python object method_name: string method name """ for ty in type(obj).mro(): if method_name in ty.__dict_...
def convertTimes(times, unit_tick): """Takes a list of timestamps, and normalizes them to the given unit. For convenience, None is normalized to None. This is important to allow undefined points in the list.""" return [None if x is None else x / unit_tick for x in times]
def int_to_bytearray(number): """ Return a bytearray representation of 64-bit number. """ try: if number.bit_length() > 64: raise ValueError("Number must be less than {}".format(2**64)) except AttributeError: raise TypeError("Number must be an integer.") if number < 0...
def addmargins(blocks): """Adds empty blocks for vertical spacing. This groups bullets, options, and definitions together with no vertical space between them, and adds an empty block between all other blocks. """ i = 1 while i < len(blocks): if (blocks[i]['type'] == blocks[i - 1]['type'...
def reduce_code(line): """ a last patch to solve some issues replace every trivial power and remove last Python sqaure (`expr**2`) """ import re # first remove all trivial power line = (line .replace("std::pow(t, 2)","t*t") .replace("std::pow(t, 3)","t*t*t") .replace("std::pow(t, 4)",...
def create_loaded_bin_struct(binid: int, entrypoint: int, start: int, end: int): """ Creates the binary data to populate the KERNEL_BINARY_TABLE structs """ return b''.join(num.to_bytes(4, 'little') for num in (binid, entrypoint, start, end))
def human_to_bytes(size): """Given a human-readable byte string (e.g. 2G, 30M), return the number of bytes. Will return 0 if the argument has unexpected form. """ bytes = size[:-1] unit = size[-1] if bytes.isdigit(): bytes = int(bytes) if unit == 'P': bytes...
def remove_first(base, string): """Remove the first substring from a string""" return base.replace(string, '', 1)
def filter_seg_appear_prop(x, filter_column, prop): """ Only keep those segments that appear >= prop*len(segment). Note: appeared days are original days before filling. Do it for the filled record. """ all_record = x['all_record'] to_filter_record = x[filter_column] result_dict = {} ...
def strip(text, chars=None): """ Creates a copy of ``text`` with the leading and trailing characters removed. The ``chars`` argument is a string specifying the set of characters to be removed. If omitted or None, the ``chars`` argument defaults to removing whitespace. The ``chars`` argument ...
def is_sequence(arg): """ Determine if an object is iterable but is not a string. """ return (not hasattr(arg, "strip")) and hasattr(arg, "__iter__")
def aggregator_revenue(r,N): """ Calculates the aggregator's revenue, which indicates the profit achieved for sharing COVID-19 data""" R_ag=[] # revenue of aggregator for c in range(N): R_ag.append(r * c) return R_ag
def noam_step(iter_count: int, warmup_steps: int, dimensionality: int, scaling_factor: float): """ Computes the learning rate at a given step of the noam learning rate scheduler. :param iter_count: The number of iterations (optimizer steps) taken so far. :param...