content
stringlengths
42
6.51k
def job_id_to_object_id(job_id): """ Extract the object ID from a RQ job ID """ try: object_id = int(job_id.split("_")[-1]) return object_id except ValueError: return None
def normalize_dict(data, flatten=False): """ converts the NestedDict `data` into a normal dict by calling its `to_dict` method. If data is already a dict it is returned unchanged. `flatten` determines whether the NestedDict is flattened into a dictionary with a single level and complex keys ...
def astore_url(package, uid, instance = "https://astore.corp.enfabrica.net"): """Returns a URL for a particular package version from astore.""" if not package.startswith("/"): package = "/" + package return "{}/d{}?u={}".format( instance, package, uid, )
def cmp_range(range1, range2): """ Compare 2 ranges""" # First sort with start position if range1[0] != range2[0]: return range1[0] - range2[0] # Then sort by (inverted) range (e.g. larger ranges comes first) return range2[1] - range1[1]
def get_label_based_on_thresold(x, thresold): """Generates label of probability x which will be 0 or 1. Args: x: Probability value of target category which was produced by the classifier. thresold: thresold which will be used for labeling. Returns: Label of probability x which will be 0...
def eat_comment(s): """Eat comment string after # char.""" n = s.find('#') if n >= 0: return s[:n] else: return s
def add_if_not_none(year, month, day): """Adds year, month a day to a list if each are not None.""" _list = [] _list.append(year) if year else None _list.append(month) if month else None _list.append(day) if day else None return _list
def multip_num(val1, val2): """restar_num :: Float x Float -> Float Multiplica los 2 valores solo si son Float""" if val1.__class__.__name__ == 'float' and val2.__class__.__name__ == 'float': res = val1 * val2 return res else: print(val1.__class__.__name__) print(val2.__...
def get_next_tile(thisTile, neighboringTile): """ Look 1 tile over in the direction specified by the value passed in neighboringTile (north, south, ..., etc.) """ row, column = thisTile # thisTile[i, j] row_neighboringTile, column_neighboringTile = neighboringTile # neighborTile[k, l], where [k, l] is the ...
def _bool(value): """casts a lower string to a booean""" return True if value == 'true' else False
def best_scale_factor(x, y): """Maximum distance from zero for one variable relative to another >>> best_scale_factor([.1, .2, .3], [.2, .4, .6]) # doctest: +ELLIPSIS 2.0 >>> best_scale_factor([-.1, -.2, -.3], [-1, -2, -3]) # doctest: +ELLIPSIS 10.0 For speed and simplicity, the scale factor...
def _join_host_port(host, port): """ Returns joined host:port, wrapping host in brackets if it looks like an IPv6 address :param str host: :param int port: :return str: """ if ':' in host: return '[%s]:%s' % (host, port) else: return '%s:%s' % (host, port)
def is_printable_as_block_string(value: str) -> bool: """Check whether the given string is printable as a block string.""" if not isinstance(value, str): value = str(value) # resolve lazy string proxy object if not value: return True # empty string is printable is_empty_line = True ...
def setup_data(obj): """ 1. Extracts text, quick replies, attachments from object 2. Adds available entities to a dict and returns it :param obj: <dict> :return: <dict> """ data = {} for prop in obj: if prop in ["text", "quick_replies", "attachments"]: data[prop] = ob...
def evaluate(definitions, values, defaults = {}): """evaluate(definitions, values, defaults = {}) Evaluates a dictionary of "values" according to the "definitions" of type. For each key in "values", "definitions" is searched for the corresponding type. If no type definition is found, 'string' is assumed. Then...
def find_set_difference(list0, list1): """ Parameters: -- list0 (list) : some list -- list1 (list) : some list Returns: -- stuff_in_list0_not_list1 : self-explanatory -- stuff_in_list1_not_list0 : self-explanatory """ stuff_in_list0_not_list1 = [] stuff_in_list1_...
def getlistfromfilter(inputlist,filterlist,filtval): """returns a list of only the entries that match acceptable filter values""" return [inputlist[i] for i in range(len(inputlist)) if filterlist[i]==filtval]
def token_to_char_position(tokens, start_token, end_token): """Converts a token positions to char positions within the tokens.""" start_char = 0 end_char = 0 for i in range(end_token): tok = tokens[i] end_char += len(tok) + 1 if i == start_token: start_char = end_char return start_char, end_...
def map_range( value: float, in_min: float, in_max: float, out_min: float, out_max: float ) -> float: """Map a value in one range to another.""" if in_max - in_min <= 0.0: raise ValueError("invalid input range") if out_max - out_min <= 0.0: raise ValueError("invalid output range") if...
def __check_obvious_pointer_type(var_name: str, rhs: str) -> bool: """Checks conditions for obvious pointer types. :param var_name: target variable name :param rhs: right hand side string to be analyzed :return: True, of None should be returned by __get_alias_statement. False, otherwise. """ # v...
def noblanklines(value): # pylint: disable=g-bad-name """Template filter to remove blank lines.""" return '\n'.join([line for line in value.split('\n') if line.strip()])
def encode_unit(value: None): """Encodes a unitary CL value, i.e. a null. """ return bytes([])
def filter_positive_even_numbers(numbers): """Receives a list of numbers, and returns a filtered list of only the numbers that are both positive and even (divisible by 2), try to use a list comprehension.""" number_list = [number for number in numbers if number > 0 if number % 2 == 0] return(n...
def reliable_test(test_fr, acceptable_fr, test_runs, min_run): """Check for a reliable test. A test should then removed from the set of tests believed not to run reliably when it has less than min_run executions or has a failure percentage less than acceptable_fr. """ return test_runs < min_run or ...
def get_grasp_code(filename, iters, alpha): """Creates code templates.""" command = "print grasp(problem," + str(alpha) + ","+str(iters)+")[-1]" code = """ import memproblem from grasp import grasp problem = memproblem.read_problem('"""+filename+"""') """ return command, code
def get_movie_tuple(entry): """ Parse a line in the movies dataset Args: entry (str): a line in the movies dataset in the form of MovieID::Title::Genres Returns: tuple: (MovieID, Title) """ items = entry.split('::') return int(items[0]), items[1]
def binary(lst: list, low: int, high: int, target: int or str) -> int: """ `binary` takes a SORTED list of length n, a low index, a high index, and a target value, and returns the index of the target value in the list, if present. If no match is identified, `binary_search` returns -1. >>>...
def to_serializable(o): """Used by default.""" if hasattr(o, "json_serialize"): return o.json_serialize() return str(o)
def get_parent_path(path): """ Get a new file path representing the parent of this one (one level up) """ # "/" is its own parent if path == "/": return path # For all other paths, cut off the last dir lastdir = path.rindex("/", 0, len(path)-1) # Special case if parent is "/", otherwise chop if...
def calculate_score(cards): """calculate the score from the list of cards""" #if score is 21 return as '0' to represent a blackjack if sum(cards) == 21 and len(cards) == 2: return 0 #if there's 2 aces (11,11), remove one value and assign it as 1 if 11 in cards and sum(cards) > 21: ...
def parseArguments(argvArray): """ Since sys.argv includes the name of the script itself, we omit the first element and combine the rest into a single string. Then we add a newline so appended tasks won't be bunched up.""" argsAsWord = " ".join(argvArray[1:-1]) argsAsPri = " ".join(argvArray[-1:]) ...
def idx_ppar( directions, idx, coo ): """ Return a pair [ index, data_name ]""" cood = ["x", "y", "z"] return [ directions.index(idx) * 6 + cood.index(coo) * 2, "[%s] in %s-axis" % ( ', '.join( map( str, idx ) ), coo ) ]
def make_dict(keys): """ >>> make_dict(['a','b']) {'b': True, 'a': True} """ return {key: True for key in keys}
def apply_constraint(data, constraint_func): """ Return a subset of data that satisfies constraint_function If constraint_func is None, return back entire data """ if constraint_func is None: return data else: outdata = {} for key, val in data.items(): if con...
def field_has_changed(new, old): """ Returns true if the field has changed. Considers a None value equivalent to an empty string. >>> field_has_changed(1, 1) False >>> field_has_changed("a", "a") False >>> field_has_changed("", None) False >>> field_has_changed([], []) False...
def rename_benchmark(benchmark_name): """We updated our benchmark name from "ours" to "ours-nc".""" if benchmark_name == 'ours': return 'ours-nc' return benchmark_name
def dms2decimal(decString, delimiter): """Converts a delimited string of Degrees:Minutes:Seconds format into decimal degrees. @type decString: string @param decString: coordinate string in D:M:S format @type delimiter: string @param delimiter: delimiter character in decString @rtype: float ...
def sum_of_N_natural_numbers(N:int): """ Sum of first N natural numbers Args: N (int): number Returns: int: sum """ return N*(N+1)//2
def iter_finder(line): """Split record on rows that start with iteration label.""" return line.startswith("# Iteration:")
def kilometers_to_miles(kilo): """Convert kilometers to miles PARAMETERS ---------- kilo : float A distance in kilometers RETURNS ------- distance : float """ # apply formula return kilo*0.621371
def __strip_list(attrs): """ This assumes that if you have a list of outputs you just want the second one (the second class). """ if isinstance(attrs, list): return attrs[1] else: return attrs
def removesuffix(text, suffix): """Removes a suffix from a string. If the string ends with the suffix string and the suffix is not empty, returns string[:-len(suffix)]. Otherwise, returns the original string. This function has been added in Python3.9 as the builtin `str.removesuffix`, but is define...
def get_used_materials(objects): """ Collect Materials used in the selected object. """ m_list = [] for obj in objects: if obj.type == 'MESH': for f in obj.data.polygons: if f.material_index < len(obj.data.materials): if not obj.data.materials[f.ma...
def binary_search(sequence, value, low, high): """Implements binary search, recursively. It operates on smaller and smaller sections of the given array.""" mid = low + (high - low) // 2 if low == mid and mid == high: if sequence[mid] != value: return -1 if value < sequence[mi...
def _shape_to_size(shape): """ Compute the size which corresponds to a shape """ out = 1 for item in shape: out *= item return out
def disabling_name_area(n_clicks): """ Disabling the button after its being clicked once """ if n_clicks >= 1: return {'display':"none"}
def dict_with_lengths(words): """ The function takes a list of words as its argument. Returns a dict with a length as key and a list of words with that length as value. For example, INPUT: ["apple", "ball", "cat", "dog", "egg", "fruit"] OUTPUT: {3: ["ball", "cat", "dog"], 4: ["ball"], 5: ["app...
def get_unique_repo_urls(vulnerability_entries): """ Retrieves a unique list of repository urls sorted by frequency. :param vulnerability_entries: :return: """ unique_repo_urls = {} for entry in vulnerability_entries: if entry.Vulnerability is None: continue commi...
def indent(t, indent=0): """Indent text.""" return "\n".join(" " * indent + p for p in t.split("\n"))
def eh_posicao(pos): # universal -> booleano """ Indica se certo argumento e uma posicao ou nao. :param pos: posicao :return: True se o argumento for uma posicao, False caso contrario """ # uma posicao e um tuplo com dois elementos em que ambos variam de 0 a 2 if type(pos) != tuple or len(p...
def get_valid_kernel_sizes(kernel): """ Provides the sizes along the dimensions of the kernel, outermost to innermost for a valid kernel Parameters ---------- kernel: nested list a valid N-dimensional kernel for computation Returns ------- sizes: list 1-D list of sizes,...
def num_to_bytes(n: int) -> bytes: """Converts a non-negative n into an unsigned big integer in big-endian.""" if n < 0: raise OverflowError("number can't be negative") if n == 0: return b'\x00' return n.to_bytes((n.bit_length() + 7) // 8, byteorder='big')
def take_list_first_item(any_list): """It returns the first item on a nested list """ list2 = [] for item in any_list: list2.append(item[0]) return list2
def _setdefault(obj, key, value): """ DO NOT USE __dict__.setdefault(obj, key, value), IT DOES NOT CHECK FOR obj[key] == None """ v = obj.get(key) if v == None: obj[key] = value return value return v
def get_placeholders(num, form): """ Example: >>> get_placeholders(num=3, form="%s") '%s, %s, %s' """ return ' '.join([form + "," for _ in range(num)])[:-1]
def lower_dict(dict_to_lower: dict) -> dict: """ Lower the keys of a dictionary :param dict_to_lower: :return: converted dictionary """ return dict((k.lower(), v) for k, v in dict_to_lower.items())
def compositeWallParallel(resistanceList): """This function calculates the resistance value of resstances in parallel the input ("resistanceList" is a list of resistances each of which is adictionary for example:R1={"name":"R1","type":"cond","length":0.03,"area":0.25,"k":0.026} and a set of resistances ...
def get_smallest_numeral_greater_or_equal(n): """ It would probably be slightly faster to do this using binary search, but realistically this list is so short that it's perfectly fine to just search through it from start to finish every time. """ sizes = [ (1, "I"), (4, "IV"), ...
def requivalent(res, config): """ Given a list of resistor values and their configuration, returns the equivalent resistance """ if config == 'series': return sum(res) elif config == 'parallel': return 1 / sum((1 / n for n in res)) else: raise ValueError('The given c...
def _completeEdits(filteredTokens, fullSentence): """Given a set of tokens (along with their edit path), generates a complete list of edit paths, adding the edit 'p' in case the token is not in the filtered tokens. """ allTokens = fullSentence.split(" ") edits = [] k = 0 for t in al...
def union(left, right): """Union of two streamlines dict (see hash_streamlines)""" # In python 3 : return {**left, **right} result = left.copy() result.update(right) return result
def rgb_to_hex(rgb): """ Convert an RGB color representation to a HEX color representation. (r, g, b) :: r -> [0, 255] g -> [0, 255] b -> [0, 255] :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value. :return: HEX representa...
def list_del_indices(mylist,indices): """ iteratively remove elements of a list by indices Parameters ---------- mylist : list the list of elements of interest indices : list the list of indices of elements that should be removed Returns ------- list the red...
def med_clamp(a,lo,hi): """Takes in 3 integers: a value to clamp, a lo, and a hi, returning the value if it is within the range of lo to hi, otherwise the nearest value of lo or hi.""" return min(hi, max(lo, a))
def remove_prefix(string, prefix): """ This funtion removes the given prefix from a string, if the string does indeed begin with the prefix; otherwise, it returns the string unmodified. """ if string.startswith(prefix): return string[len(prefix):] else: return string
def _init_min_ALL(req): """ Replaces every instance of min_needed="ALL" with the actual number. """ num_counted_from_below = 0 if "req_list" in req: for subreq in req["req_list"]: num_counted_from_below += _init_min_ALL(subreq) elif "course_list" in req: # written as loop in ...
def generate_phase_name(current_name, name_list): """ Provide a regular way to generate unique human-readable names from base names. Given a base name and a list of existing names, a number will be appended to the base name until a unique string is generated. Parameters ---------- current_...
def sqrt(num): """ Calculates the Square root of num :param num: Number :return: Square root of num """ # Checks if num is equal to zero if num == 0: return 0 elif num < 0: num = num * -1 is_negative = True else: is_negative = False # Newton/baby...
def dataqc_condcompress(p_orig, p_new, c_orig, cpcor=-9.57e-8): """ Description: Implementation of the Sea-Bird conductivity compressibility correction, scaling the input conductivity based on ratio of the original pressure and the updated pressure. Implemented by: 2013-04...
def has_token(token_sequence: str, tokens: str) -> bool: """Returns true, if `token` is contained in the blank-spearated token sequence. If `token` itself is a blank-separated sequence of tokens, True is returned if all tokens are contained in `token_sequence`:: >>> has_token('bold italic', 'it...
def insertionsort(list, descending=False): """ Takes in a list as an argument, and sorts it using an "Insertion Sort"-algorithm. --- Args: - list (list): The list to be sorted - descending (bool): Set true if the list be sorted high-to-low. Default=False Raises: - T...
def uf_key(element): """ Receives a dict Returns a tuple with UF and an element (UF, dict) """ key = element['uf'] return (key, element)
def flatten_routes(routes): """Flattens the grouped routes into a single list of routes. Arguments: routes {list} -- This can be a multi dementional list which can flatten all lists into a single list. Returns: list -- Returns the flatten list. """ route_collection = [] for ro...
def strip_noise_from_key_signature(key): """Removes any unneccessary characters (7,9,11,m,M etc...)""" #Change this to a map or something key = key.replace('9', '') key = key.replace('7', '') key = key.replace('5', '') key = key.replace('m', '') key = key.replace('M', '') return key
def nested_docfield_unwrapper(field: str, hitdict, value: dict) -> dict: """ Unwraps the JSON for nested fields in a document that was returned from a search """ if isinstance(value, dict): for (sf, sf_v) in value.items(): nested_docfield_unwrapper(field + '.' + sf, hitdict, sf_v) else: ...
def unquote(s): """Kindly rewritten by Damien from Micropython""" """No longer uses caching because of memory limitations""" res = s.split('%') for i in range(1, len(res)): item = res[i] try: res[i] = chr(int(item[:2], 16)) + item[2:] except ValueError: re...
def convert_coordinates(coordinates, board_size): """ Apply tore space to coordinates. Parameters ---------- coordinates: coordinates to convert (tuple(int, int)) board_size: Size of the tore tupe(int, int). Return ------ converted_coord: coord with the tore applied. Version ...
def get_y_depletion(accrate, x0, z): """Returns column density (y, g/cm^2) of hydrogen depletion Equation: Cumming & Bildsten (2000) """ return 6.8e8 * (accrate/0.1) * (0.01/z) * (x0/0.71)
def clamp(MIN: int, n: int, MAX: int) -> int: """Clam n in [MIN, MAX[""" if MIN < MAX: return max(MIN, min(n, MAX - 1)) else: raise ValueError("MAX value must be greater than MIN value")
def sub_template(template, template_tag, substitution): """make a substitution for a template_tag in a template""" template = template.replace(template_tag, substitution) return template
def get_diff_dict(d1, d2): """ return common dictionary of d1 and d2 """ diff_keys = set(d2.keys()).difference(set(d1.keys())) ret = {} for d in diff_keys: ret[d] = d2[d] return ret
def face_plane(point): """ Which of the six face-plane(s) is point P outside of? @type point: numpy.ndarray | (float, float, float) """ face_plane_code = 0 if point[0] >= .5: face_plane_code |= 0x01 if point[0] < -.5: face_plane_code |= 0x02 if point[1] >= .5: fa...
def parse_key_value_pairs(line): """ parse input a=b c=d into map""" next_value = True last_end = len(line) stack = list() for idx in reversed(range(len(line))): stop = '=' if next_value else ' ' if line[idx] == stop: sub = line[idx + 1: last_end] last_end = i...
def is_category_malicious(category, reputation_params): """ determine if category is malicious in reputation_params """ return category and category.lower() in reputation_params['malicious_categories']
def area(circle): """Get area of a circle""" return circle.get('radius') ** 2 * 3.14159
def build_individual_url(url, uniqueid): """ Takes a url with "$uniqueid" as a variable placeholder Returns url with the specified $uniqueid Attributes: url (str): a url string with '$uniqueid" within that string id (str): id of event """ # String replacement for variable (old ...
def get_sebastian_aho(player): """ This checks which Sebastian Aho it is based on the position. I have the player id's hardcoded here. This function is needed because "get_players_json" doesn't control for when there are two Sebastian Aho's (it just writes over the first one). :param player: playe...
def number_of_ones(n): """number of 1 bits in the number n""" c = 0 while n: c += n%2 n /= 2 return c
def filter(line): """Function to filter bytes from a given line. :param line: a given string :type line: bytes """ line = line.replace(b'\xff',bytes('','utf-8')).replace(b'\xfe',bytes('','utf-8')) return line
def merge_sort(lst): """Merge Sort.""" if len(lst) <= 1: return lst mid = len(lst) // 2 left = lst[mid:] right = lst[:mid] left = merge_sort(left) right = merge_sort(right) output = [] while left and right: if right[0] < left[0]: output.append(right.po...
def label_string(label): """Convert the given (optional) Label to a string.""" if not label: return "None" else: return '"%s"' % label
def restart_bug_check(full_traj): """ Observed that some of the trajectories had a strange identically cyclical behavior - suggesting that a checkpoint was restarted from an earlier checkpoint rather than the latest. Checks whether the trajectory provided falls within that bug. Args full_tr...
def fpoint5measure(precision, recall): """Returns the f0.5measure (or F0.5-score)""" beta = 0.5 betasqrd = beta ** 2 tmp = (precision * recall) / ((betasqrd * precision) + recall) return (1 + betasqrd) * tmp
def sort_cards(cards): """Sort shuffled list of cards, sorted by rank. sort_cards(['3', '9', 'A', '5', 'T', '8', '2', '4', 'Q', '7', 'J', '6', 'K']) ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] """ deck = [] alphas = [] for card in cards: if card.isalpha(): ...
def update_dict_with_flatten_keys(desc, flatten_keys): """Update dict with flatten keys like `conv.inchannel`. :param desc: desc dict :param flatten_keys: str :return: desc """ if not flatten_keys: return desc for hyper_param, value in flatten_keys.items(): dest_param = desc...
def sum_even_values(d: dict) -> int: """Returns the sum of all even values in d, using recursion if d contains nested dictionaries.""" total = 0 for value in d.values(): if type(value) == int: if not value % 2: total += value elif type(value) == dict: ...
def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message): """ Informs Amazon Lex that the user is expected to provide a slot value in the response. """ return { 'sessionAttributes': session_attributes, 'dialogAction': { 'type': 'ElicitSlot', ...
def _attr_lrem(attr, value): """Create a 'list remove' dictionary for update_workspace_attributes()""" return { "op" : "RemoveListMember", "attributeName" : attr, "addUpdateAttribute" : value }
def brix_to_sg(brix): """Convert the provided value from brix to specific gravity and return the result. Help pulled from https://straighttothepint.com/specific-gravity-brix-plato-conversion-calculators/""" return (brix / (258.6 - ((brix / 258.2) * 227.1))) + 1
def set_lim(values, scale): """Provides a range that contains all the value and adds a margin.""" v_min, v_max = min(values), max(values) margin = (v_max - v_min) * scale v_min, v_max = v_min - margin, v_max + margin return v_min, v_max