content
stringlengths
42
6.51k
def listify(obj): """wrap a list around something, if it is not currently a list""" if type(obj) is list: return obj return [obj]
def condTo25(cond, temp): """ Converts given value of specific conductance to the value at 25 C. Uses the relation from Sorensen and Glass (1987), as found in Equation 4 of Hayashi (2004). Parameters ---------- cond : float or array measured value of specific conductance temp : ...
def get_supercategories(image_categories, cat_to_super): """ Group supercategories by image """ image_supercategories = {} for image in image_categories: image_supercategories[image] = list(set([cat_to_super[x] for x in image_categories[image]])) return image_supercategories
def is_binary_data(url) -> bool: """ Determine whether the URL is for a page of plain HTML or binary data. """ url = url.lower() return ( url.endswith(".pdf") or url.endswith(".png") or url.endswith(".jpeg") or url.endswith(".jpg") )
def problem_9_6(matrix, key): """ Given a matrix in which each row and each column is sorted, write a method to find an element in it. Matrix is size M*N such that each row is sorted left to right and each column is sorted top to bottom. Solution: divide and conquer. Start in the top-right and go down ...
def get_param(name, dictionary): """Retrieves the parameter dictionary[name] or dictionary["templates_dict"][name] Raises: KeyError """ if ("templates_dict" in dictionary): dictionary = dictionary["templates_dict"] if (name in dictionary): return dictionary[name] rai...
def unnormalize_y(y, y_mean, y_std, scale_std=False): """Similar to the undoing of the pre-processing step above, but on the output predictions""" if not scale_std: y = y * y_std + y_mean else: y *= y_std return y
def regions_overlap(region1,region2): """Determine if two regions have any overlap Returns True if any part of the first region overlaps any part of the second region (including one region being completely inside the other). Arguments: region1: tuple of numbers representing the limits of the...
def get_particles_with_lowest_acceleration(particles): """Get particles with lowest acceleration from particles.""" particle_accelerations = [ (sum(abs(num) for num in particle['acceleration']), particle_number) for particle_number, particle in particles.items()] minimum = sorted(particle_ac...
def create_order(v): """Identify all unique, positive indices and return them sorted.""" flat_v = sum(v, []) x = [i for i in flat_v if i > 0] # Converting to a set and back removes duplicates x = list(set(x)) return sorted(x)
def mulv3s(vec, scalar): """multiply elements of 3-vector by scalar""" return (vec[0]*scalar, vec[1]*scalar, vec[2]*scalar)
def validateFilename(value): """Validate filename. """ if 0 == len(value): msg = "Filename for ASCII input mesh not specified. " + \ "To test PyLith, run an example as discussed in the manual." raise ValueError(msg) try: open(value, "r") except IOError: r...
def format_error(exc): """Creates a human-readable error message for the given raised error.""" msg = 'Error occurred in the Google Cloud Storage Integration' if hasattr(exc, '__class__'): class_name = exc.__class__.__name__ details = str(exc) if isinstance(exc, BaseException) and d...
def github_disable_two_factor_requirement_user(rec): """ author: @mimeframe description: Two-factor authentication requirement was disabled for a user. repro_steps: (a) Visit /settings/two_factor_authentication/configure reference: https://help.github.com/enterprise/2.11/admin/articles/au...
def get_and_check_size(iterator, n): """Check if the iterator is length n and return consumed elements. Consumes the next n+1 elements if possible (up to the end of the iterator). Returns (is_length_n, elems) """ elements = [] try: for _ in range(n): elements.append(next(ite...
def group(lst, n): """group([0,3,4,10,2,3], 2) => [(0,3), (4,10), (2,3)] Group a list into consecutive n-tuples. Incomplete tuples are discarded e.g. >>> group(range(10), 3) [(0, 1, 2), (3, 4, 5), (6, 7, 8)] """ return [list(a) for a in zip(*[lst[i::n] for i in range(n)])]
def bubble_sort(l): """ :param l - a list :return a sorted list """ for i in range(len(l)-1, -1, -1): for j in range(0, i): if l[j] > l[j+1]: l[j], l[j+1] = l[j+1], l[j] return l
def encode_ber(value, ber_length=0): """ Encodes an integer to ber length You can set the ber_length manually. return: bitearray object """ if not ber_length: if value < 127: # 1 byte case return bytearray([value]) ber_length = 1 while value >= pow(2, 8*ber_le...
def max_commits(input): """finds the highest number of commits in one day""" output = set() for line in input: for day in line.split(): if "data-count=" in day: commit = day.split('=')[1] commit = commit.strip('"') output.add(int(commit)) ...
def parsejson(j): """ returns a tuple: (asn, list of v4 prefixes, list of v6 prefixes) or None if not OK.""" if j['status'] != 'ok': return None asn = j['data']['resource'] prefixes_v4 = j['data']['prefixes']['v4']['originating'] prefixes_v6 = j['data']['prefixes']['v6']['originating'] ...
def splitLast(myString, chunk): """ returns a tuple of two strings, splitting the string at the last occurence of a given chunk. >>> splitLast('hello my dear friend', 'e') ('hello my dear fri', 'nd') """ p = myString.rfind(chunk) if p > -1: return myString[0:p], myString[p + len(chun...
def sum_of_middle_three(score1, score2, score3, score4, score5): """ Return sum of 3 middle scores """ min_score = min(score1, score2, score3, score4, score5) max_score = max(score1, score2, score3, score4, score5) sum_score = score1 + score2 + score3 + score4 + score5 return sum_score - min...
def format_response(code, message='', data=None, errors=None, **kwargs): """An util function unify the api response format """ status_map = { 200: 'Success', 400: 'Invalid Parameters', 404: 'Not Found', 500: 'Internal Error' } wrapper = { 'code': code, ...
def is_even(num): """ Function intended to take an integer as input. Returns True if even and False if odd :param num: the integer to be tested :return: Boolean value representing if the number is even or not """ if int(num) % 2 == 0: return True else: return False
def mscale(matrix, d): """Return *matrix* scaled by scalar *d*""" for i in range(len(matrix)): for j in range(len(matrix[0])): matrix[i][j] *= d return matrix
def gen_buckets_probs_with_ppf(ppf, nbuckets): """Generate the buckets and probabilities for chi_square test when the ppf (Quantile function) is specified. Parameters ---------- ppf : function The Quantile function that takes a probability and maps it back to a value. It's the inve...
def catch(func, *args, verbose=False): """Error handling for list comprehensions. In practice, it's recommended to use the higher-level robust_comp() function which uses catch() under the hood. Parameters ----------- func: function *args: any type Arguments to be passed to func. ...
def bit_flip(array): """Given a binary array, find the maximum number zeros in an array with one flip of a subarray allowed. A flip operation switches all 0s to 1s and 1s to 0s.""" original_zeroes = 0 current_sum, max_sum = 0, 0 for value in array: if not value: value = -1 ...
def merge_on_empty_fields(base, tomerge): """Utility to quickly fill empty or falsy field of $base with fields of $tomerge """ has_merged_anything = False for key in tomerge: if not base.get(key): base[key] = tomerge.get(key) has_merged_anything = True return has...
def generate_autosa_cmd_str(cmds): """ Generate the cmd to print. Specifically, 'tuning' flag is filtered out if exists. """ cmd_str = '' is_first = True for cmd in cmds: if cmd.find(' --tuning') != -1: cmd = cmd.replace(' --tuning', '') if not is_first: ...
def recast_to_supercell(z, z_min, z_max): """Gets the position of the particle at ``z`` within the simulation supercell with boundaries ``z_min`` y ``z_max``. If the particle is outside the supercell, it returns the position of its closest image. :param z: :param z_min: :param z_max: :retur...
def extract_entities(openapi_str): """ Extract entities from an OpenAPI string, where entities are defines as anything within "```" :param openapi_str: The OpenAPI str :type openapi_str: ```str``` :return: Entities :rtype: ```List[str]``` """ entities, ticks, space, stack = [], 0, 0, [...
def bytes_to_human(bytes): """Convert bytes to a human readable format. Args: bytes (int): Bytes. Returns: str: Return bytes into human readable format. """ suffix = 'B' for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(bytes) < 1024.0: return '%3...
def get_statistic_name(statistic: str) -> str: """ Returns the full name of the statistical abbreviation. Keyword arguments: statistic -- the abbrevation of the statistical function. """ if statistic not in ['simpson', 'shannon']: raise ValueError('Expects one of the values: "simpson",...
def is_even(number: int) -> bool: """ Test if a number is a even number. :param number: the number to be checked. :return: True if the number is even, otherwise False. >>> is_even(-1) False >>> is_even(-2) True >>> is_even(0) True >>> is_even(3) False >>> is_even(4) ...
def ccs_full(optlevel, chunksize, slicesize): """Correct the slicesize and the chunksize based on optlevel.""" if optlevel in (0, 1, 2): slicesize //= 2 elif optlevel in (3, 4, 5): pass elif optlevel in (6, 7, 8): chunksize //= 2 elif optlevel == 9: # Reducing the ch...
def GuessLanguage(filename): """ Attempts to Guess Langauge of `filename`. Essentially, we do a filename.rsplit('.', 1), and a lookup into a dictionary of extensions.""" try: (_, extension) = filename.rsplit('.', 1) except ValueError: raise ValueError("Could not guess language as '%s' does not have an \...
def associate(first_list, second_list, offset=0.0, max_difference=0.02): """ Associate two dictionaries of (stamp,data). As the time stamps never match exactly, we aim to find the closest match for every input tuple. Input: first_list -- first dictionary of (stamp,data) tuples second_list -- se...
def is_list_with_len(value, length) -> bool: """ Is the given value a list of the given length? :param value: The value to check :type value: Any :param length: The length being checked for :type length: Nat :return: True if the value is a list of the length :rtype: bool """ return i...
def encode_payload(payload: str) -> str: """ Encode payload with URL-safe base64url. """ from base64 import urlsafe_b64encode result: bytes = urlsafe_b64encode(payload.encode()) return result.decode()
def is_prime(n): """ Highly inefficient!!! Method to determine whether an input number is Prime :param n: input integer :return: prints "Prime" in case a num is prime, and "Not prime" otherwise """ if n <= 1: return False elif (n % 2 == 0) or (type(n**0.5) is not float): ...
def get_fastq_id(fastq_name): """Splits and returns the first part of the read name""" return fastq_name.split(' ')[0]
def split_dropout(do_value): """ Handles both string and number dropout values, with or without the "s" suffix (see create_dropout). """ do_str = str(do_value) if do_str.endswith('s'): s = True do_str = do_str[:-1] else: s = False return float(do_str), s
def total_ordering(cls): """Class decorator that fills in missing ordering methods""" convert = { '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)), ('__le__', lambda self, other: self < other or self == other), ('__ge__', lambda self, o...
def act_diagnosis(driver, submit, acc): """ Pushes submit button """ if acc: return False else: submit.click() return True
def validate_post_request(post_field, allowed_fields): """ Validators returning None if everything is OK - otherwise suitable HTTP status and message is set. """ error_msg = None dict_diff = list(set(post_field) - set(allowed_fields)) if dict_diff: error_msg = 'There are fields not a...
def check_dict_word(word, target_lst): """ Check dict word. If one character not in searching word, then not add the word to python_dict. :param word: str, word in dictionary.txt. :param target: str, the searching word :return: True, all character within are in searching word. """ # Level one: check len if 4 <=...
def sizeof_fmt(num, suffix='B'): """Format bytes to human readable value""" for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Pi', suffix)
def create_questions_images_ids(questions_captions): """ Returns: questions: set of question ids. image_ids: Set of image ids. """ questions = set() image_ids = set() for q in questions_captions: question_id = q['question_id'] questions.add(question_id) ...
def open_or_senior(data): """ The Western Suburbs Croquet Club has two categories of membership, Senior and Open. They would like your help with an application form that will tell prospective members which category they will be placed. To be a senior, a member must be at least 55 years old and have a ha...
def formatMeta(featureMeta): """Reorder meta data. Parameters ---------- meta: dict Dictionary of meta data: keyed by feature, valued by a dict of metadata in the form of key values Returns ------- dict A copy of the dict but with the values for metadata keys ...
def get_layers(layers): """ Does it's best to extract a set of layers from any data thrown at it. """ if type(layers) == int: return [x == layers for x in range(0, 32)] elif type(layers) == str: s = layers.split(",") l = [] for i in s: try: l +...
def select_input(context): """ Dependencies for select2_input gizmo. """ return ('tethys_gizmos/vendor/select2_3.5.1/select2.css', 'tethys_gizmos/vendor/select2_3.5.1/select2.js')
def differ_by_one_char(str1, str2): """Function to determine if the hamming distance between two strings is 1 Args: str1(string): First string. str2(string): Second string. Returns: Boolean indicating if hamming distance is equal to 1. Raises: """ difference_c...
def computeTemplatesByParent(templates: dict, Civs: list, CivTemplates: dict): """Get them in the array""" # Civs:list -> CivTemplates:dict -> templates:dict -> TemplatesByParent TemplatesByParent = {} for Civ in Civs: for CivUnitTemplate in CivTemplates[Civ]: parent = CivTemplates[C...
def open_output(name, mode='a+'): """ Open output for writing, supporting either stdout or a filename """ if name == '-': return False else: return open(name, mode)
def isCallable(obj): """ Returns boolean whether object can be called (like a function)""" return hasattr(obj, '__call__')
def decode_permissions(permissions_dict): """Given a permissions dict, returns the highest permission""" if permissions_dict.get("admin"): return "admin" elif permissions_dict.get("push"): return "push" elif permissions_dict.get("pull"): return "pull" else: raise Valu...
def cmdstr(cmd): """Return a string for the |cmd| list w/reasonable quoting.""" quoted = [] for arg in cmd: if ' ' in arg: arg = '"%s"' % (arg,) quoted.append(arg) return ' '.join(quoted)
def _poly_func(x, a, b, c, d, e): """ Model polynomial function for polynomial baseline correction. """ return a * x**6 + b * x**5 + c * x**4 + d * x**3 + e * x**2
def merge_sort(list): """ Takes in a list and sorts it using merge sort logic. Returns the list. """ if len(list) <= 1: print(list) return list mid = len(list) // 2 left_slice = list[:mid] right_slice = list[mid:] left = merge_sort(left_slice) right = merge_sort(rig...
def bit_not(n, bit_length): """ defines the logical not operation :param n: the number to which the not operation is applied :param bit_length: the length of the bit to apply the not operation :return: """ return (1 << bit_length) - 1 - n
def get_time_seconds(string): """Returns Slurm-compatible time string as seconds """ while (len(string.split(":")) < 3): string = "00:" + string return sum(secs * int(digit) for secs,digit in zip([3600, 60, 1], string.split(":")))
def get_role(row): """ Extracts the role from a given row :param row: Row to look at :return: The role """ role = row[6] # Normalize roles Lead Link and Rep Link, as they contain the circle name as well if "Lead Link" in role: role = "Lead Link" if "Rep Link" in role: ...
def hmsm_to_days(hour=0, min=0, sec=0, micro=0): """ Convert hours, minutes, seconds, and microseconds to fractional days. """ days = sec + (micro / 1.e6) days = min + (days / 60.) days = hour + (days / 60.) return days / 24.
def h3_get_resolution(h3_address): """Returns the resolution of an `h3_address` :return: nibble (0-15) """ return int(h3_address[1], 16)
def php_type(java_type): """ Returns the PHP corresponding to the specified Java type. This is used only in the PHP docs. """ if java_type == "java.lang.Long": return "int" if java_type == "java.lang.String": return "string" if java_type == "java.util.List": return "string" if java_type....
def bbox2location(bbox): """ From bbox [x,y,width,height] to location [top,right,bot,left] Args: bbox (list): bounding box [x,y,width,height] Returns: **location** (list) - coordinate [top,right,bot,left] """ location = [bbox[1],bbox[0]+bbox[2],bbox[1]+bbox[3],bbox[0]] return location
def is_repo_url(url): """ Concreate assumes any absolute path is not url """ return not url.startswith('/')
def quoteStringArgument(argument): """ Quote an argument to L{serverFromString} and L{clientFromString}. Since arguments are separated with colons and colons are escaped with backslashes, some care is necessary if, for example, you have a pathname, you may be tempted to interpolate into a string li...
def sort_terms(node, parent_children, hierarchy): """Recursively create a list of nodes grouped by category.""" for c in parent_children.get(node, []): hierarchy.append(c) sort_terms(c, parent_children, hierarchy) return hierarchy
def cooperating_rating(cooperation, nplayers, turns, repetitions): """ A list of cooperation ratings for each player Parameters ---------- cooperation : list The cooperation matrix nplayers : integer The number of players in the tournament. turns : integer The number...
def reshape_nd(data_or_shape, ndim): """Return image array or shape with at least ndim dimensions. Prepend 1s to image shape as necessary. >>> reshape_nd(numpy.empty(0), 1).shape (0,) >>> reshape_nd(numpy.empty(1), 2).shape (1, 1) >>> reshape_nd(numpy.empty((2, 3)), 3).shape (1, 2, 3) ...
def find_variables(param_dict): """Finds items in dictionary that are lists and treat them as variables.""" variables = [] for key, val in param_dict.items(): if isinstance(val, list): variables.append(key) return variables
def get_html5_ids(html5_sources): """ Helper method to parse out an HTML5 source into the ideas NOTE: This assumes that '/' are not in the filename """ html5_ids = [x.split('/')[-1].rsplit('.', 1)[0] for x in html5_sources] return html5_ids
def to_bytes(s): """convert str to bytes for py 2/3 compat """ if isinstance(s, bytes): return s return s.encode('utf-8', 'ignore')
def rotate(elements, rotation): """Rotate list of elements by rotation places.""" length = len(elements) rotated = [None] * length for i in range(length): j = (i + rotation) % length rotated[j] = elements[i] return rotated
def get_workflow_wall_time(workflow_states_list): """ Utility method for returning the workflow wall time given all the workflow states @worklow_states_list list of all workflow states. """ workflow_wall_time = None workflow_start_event_count = 0 workflow_end_event_count = 0 workflow_sta...
def get_ap_os_version(ap): """Parses os_version from AP data Removes model from start of os version if found. Args: ap (dict): ap data returned from FortiOS managed-ap REST endpoint Returns: str: OS version on 'unknown' id not detected """ if 'os_version' not in ap: ...
def transform_snake_list(linked_snake): """Transforms a linked snake list to a canonical snake list, i.e. from something of the form: (x1,y1,x2,y2,itype,previous_snake) to something of the form: [ ..., (x1,y1,x2,y2,ityp), ... ] This is needed to go from the linked list snake search to...
def verify_structure(memlen, itemsize, ndim, shape, strides, offset): """Verify that the parameters represent a valid array within the bounds of the allocated memory: char *mem: start of the physical memory block memlen: length of the physical memory block offset: (char *)buf...
def normalize_fields(dict_or_list, extra_list): """ helper merge settings defined fileds and other fields on mutations """ if isinstance(dict_or_list, dict): for i in extra_list: dict_or_list[i] = "String" return dict_or_list else: return dict_or_list + extra_...
def process_label(text_label): """Processes an input integer label and returns a 1 or 2, where 1 is for silence and 2 is for speech. Arguments: text_label -- input label (must be integer) """ prev_label = int(text_label) if prev_label not in [1, 2]: raise ValueError("Expecting l...
def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string int) returns: integer """ handLength = 0 # Iterate through letters in current hand for letter in hand: # Increment handLength handLength += hand[lett...
def capfirst_filter(value): """ Capitalize the first letter in the string. We can't use the capitalize filter because that one capitalizes the first letter and decapitalizes all the other ones (wut). """ first = value[0].upper() return '%s%s' % (first, value[1:])
def byte_to_str(data): """ convert data to str :param data: data :return: str(data) """ return str(data if isinstance(data, str) else data.decode() if isinstance(data, bytes) else data)
def join(a, p): """Join two or more pathname components, inserting '/' as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator.""" path = a for b in p: if b.startswith('/'): ...
def score_overlap(sig,test): """ Scores the overlap between the gene signature and the test signature Parameters: ----------- sig: set Gene signature test: set Test signature """ num = len(sig & test) den = float(len(sig)) return num / den
def update_Qi(Qval, RPE, alpha=.3): """ update q-value of selected action, given RPE and alpha """ QUpdate = Qval + alpha*RPE return QUpdate
def without_empty_values(input_dict): """ Return a new dict not including empty value entries from `input_dict`. `None`, empty string, empty list, and empty dict/set are cleaned. `0` and `False` values are kept. """ empty_values = ([], (), {}, '', None) return { key: value ...
def respond_echo(input_string, number_of_echoes, spacer): """ Repeat input several times. Parameters ---------- input_string : string String that to be repeated by certain nymber of times. number_of_echoes : integer Integer that determines how many times the input will be re...
def separated_string_list(s, char): """ Return a list of non-empty strings separated with a given character """ fields = s.split(char) l = [] for s in fields: s = s.strip() if len(s) > 0: l.append(s) return l
def parser_callback(ctx, param, value: str): """click callback to parse a value to either None, int or float Args: ctx (_type_): ignored param (_type_): ignored value (str): value to parse """ if isinstance(value, (int, float)): return value # None value if valu...
def fwhm_dict(fwhm): """Convert a list of FWHM into a dictionary""" fwhm = [float(f) for f in fwhm] return {'x': fwhm[0], 'y': fwhm[1], 'z': fwhm[2], 'avg': fwhm[3]}
def ip_from_bytes(binary_ip: bytes) -> str: """converts IP bytes into a dotted format string""" return '.'.join(str(int(byte)) for byte in binary_ip)
def add_event_to_args(fun_arg_tuple, event): """ Adds the event to the positional arguments of the function. Event is always inserted as the first positional argument. """ fun, arg, kwargs = fun_arg_tuple arg = (event, ) + arg return fun, arg, kwargs
def get_ratio_standard(width, height): """find out if resolution are more closer to 16x9 or 4x3 Args: width (str): height (str): Returns: (str): '16x9' or '4x3' """ width = int(width) height = int(height) division_16_9 = 16 / 9 division_4_3 = 4 / 3 divisio...
def first_missing_positive(a): """ O(n) time but reuses the array for state. """ n = len(a) i = 0 while i < n: j = a[i] while 0 < j <= n and a[j-1] != j: a[j-1], j = j, a[j-1] i += 1 for i, x in enumerate(a): if x != i+1: return i+1
def _half_window(window): """Computes half window sizes """ return tuple((w[0] / 2, w[1] / 2) for w in window)
def merge(b, a): """ Merges two dicts. Precedence is given to the second dict. The first dict will be overwritten. """ for key in a: if key in b and isinstance(a[key], dict) and isinstance(b[key], dict): b[key] = merge(b[key], a[key]) elif a[key] is not None: b[ke...