content
stringlengths
42
6.51k
def get_child_schema(self): """An optional function which returns the list of child keys that are associated with the parent key `docs` defined in `self.schema`. This API returns an array of JSON objects, with the possible fields shown in the example. Hence the return type is list of lists, because this plugin returns a list of objects, each with this possible set of keys. Returns: [['year', 'title', 'description', 'mediatype', 'publicdate', 'downloads', 'week', 'month', 'identifier', 'format', 'collection', 'creator', 'score']] Example of one of the child objects in the array associated with `docs`: { year: 1998, title: "AAPL CONTROL ROOM AERO ACOUSTIC PROPULSION LABORATORY AND CONTROL ROOM PERSONNEL", description: "AAPL CONTROL ROOM AERO ACOUSTIC PROPULSION LABORATORY AND CONTROL ROOM PERSONNEL", mediatype: "image", publicdate: "2009-09-17T17:14:53Z", downloads: 5, week: 0, month: 0, identifier: "GRC-C-1998-853", format: [ "JPEG", "JPEG Thumb", "Metadata" ], collection: [ "nasa", "glennresearchcentercollection" ], creator: [ "NASA/Glenn Research Center" ], score: 2.617863 } """ return [['year', 'title', 'description', 'mediatype', 'publicdate', 'downloads', 'week', 'month', 'identifier', 'format', 'collection', 'creator', 'score']]
def getItemPos(item, inList): """ get item position from the list """ for i, j in enumerate(inList): if j == item: return i return -1
def list_to_string(l): """ Converts a string list in to a string @param l is the string list @returns a concatentation of each element in the list """ res = "" for elem in l: res += elem return res
def validate_slots(slots : dict) -> dict: """ Validate slots Arguments: slots {dict} -- slots dictionary to be validate Returns: dict -- validated version """ #slots["ESMLFileTypes"] = to_validate_text(slots.get("ESMLFileTypes"), ["text", "image"]) return slots
def score_grid(dim): """ Creates empty score grid for use in mc_move """ return [ [0 for dummy_col in range(dim)] for dummy_row in range(dim)]
def pig_latin(word): """Translate the string 'word' into Pig Latin Examples: >>> pig_latin("apple") 'applehay' >>> pig_latin("banana") 'ananabay' """ if word[0] in "aeiou": return word + "hay" else: return word[1:] + word[0] + "ay"
def single_object_row_factory(column_names, rows): """ returns the JSON string value of graph results """ return [row[0] for row in rows]
def GenerateFilename(group): """Generate test filename.""" filename = group filename += ".html" return filename
def getCoOrdinates(xValue, yValue): """ retuns an object with x any y values """ return {"x": xValue, "y": yValue}
def append_all(src_str, append, delimiter): """ Add the append string into each split sub-strings of the first string(=src=). The split is performed into src string using the delimiter . E.g. appendAll("/a/b/,/c/b/,/c/d/", "ADD", ",") will return /a/b/ADD,/c/b/ADD,/c/d/ADD. A append string with null value is consider as an empty string. A delimiter string with value null is considered as no append in the string. """ if not delimiter: return src_str if not append: append = "" split_str = src_str.split(delimiter) appended_list = [] for split in split_str: appended_list.append(split + append) return delimiter.join(appended_list)
def _extract_source_ips(finding, key_in_additional_info=None): """ Extracts source IP addresses from a GuardDuty finding. https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_findings.html :param finding: a GuardDuty finding :param key_in_additional_info: key name in 'additionalInfo' field for extraction :return: collection of source IP addresses """ source_ips = set() service = finding['service'] if service['action']['actionType'] == 'AWS_API_CALL': source_ips.add(service['action']['awsApiCallAction']['remoteIpDetails']['ipAddressV4']) elif service['action']['actionType'] == 'NETWORK_CONNECTION': source_ips.add(service['action']['networkConnectionAction']['remoteIpDetails']['ipAddressV4']) elif service['action']['actionType'] == 'PORT_PROBE': source_ips.add(service['action']['portProbeAction']['portProbeDetails'][0]['remoteIpDetails']['ipAddressV4']) for item in service.get('additionalInfo', {}).get(key_in_additional_info, []): if item.get('ipAddressV4'): source_ips.add(item['ipAddressV4']) return source_ips
def row_selection(row_element,idx_pos): """ small helper function for the next function """ if row_element in idx_pos: return True else: return False
def validate_spin(value, _): """ Validate spin_option input port. """ if value: allowedspins = ["q", "s", "x", "y", "z"] if value.value not in allowedspins: return f"The allowed options for the port 'spin_option' are {allowedspins}."
def getRowClsName(name): """ Utility method for naming the test module class that a row belows to """ return("mod-" + name)
def rem_comment(line): """Remove a comment from a line.""" return line.split("#", 1)[0].rstrip()
def splitParents(parents): """Splits the input string into at most 3 parts: - father's first name - mother's first name - mother's last name. The input is in the format: "{father_first_name},{mother_first_name} {mother_last_name}" """ split = parents.split(',', 1) if len(split) == 1: father = '' mother = parents else: father = split[0].strip() mother = split[1].strip() motherSplit = mother.rsplit(' ', 1) if not father: return motherSplit return [father] + motherSplit
def getDirectoryFromPath(path: str) -> str: """Retrieves the directory string from a path string.""" path_temp = path.rpartition("/") new_path = path_temp[0] + path_temp[1] return new_path
def serialize(mongo_dict): """Serialize just converts the MongoDB "_id" ObjectId into a string "id" in a dictionary :param mongo_dict: The dict from MongoDB :type: mongo_dict: dict :rtype: dict """ if mongo_dict and "_id" in mongo_dict: mongo_dict["id"] = str(mongo_dict.pop("_id")) return mongo_dict
def _transpose_list(list_of_lists): """Transpose a list of lists.""" return list(map(list, zip(*list_of_lists)))
def populate_list(dictionary, key, list_to_populate): """Functions to populate a list with valuesof the given key""" value = dictionary[key] if value != "null": list_to_populate.append(value) return list_to_populate
def _is_prefix(prefix, name): """Determines whether one fullname is a prefix of another. Args: prefix: The fullname that might be a prefix. name: The entire fullname. Returns: A boolean indicating whether or not the first fullname is a prefix of the second. """ prefix_parts = prefix.split('.') if prefix else [] name_parts = name.split('.') if name else [] return name_parts[:len(prefix_parts)] == prefix_parts
def format_response_google(data): """ formatter data from google api books """ if len(data) > 0: return list(map(lambda item: { 'title': item['volumeInfo']['title'], 'sub_title': item['volumeInfo']['subtitle'] if 'subtitle' in item['volumeInfo'].keys() else None, 'authors': item['volumeInfo']['authors'] if 'authors' in item['volumeInfo'].keys() else [], 'categories': item['volumeInfo']['categories'] if 'categories' in item['volumeInfo'].keys() else [], 'description': item['searchInfo']['textSnippet'] if 'searchInfo' in item.keys() and 'textSnippet' in item['searchInfo'].keys() else None, 'publish_date': item['volumeInfo']['publishedDate'] if 'publishedDate' in item['volumeInfo'].keys() else None, 'editor': item['volumeInfo']['publisher'] if 'publisher' in item['volumeInfo'].keys() else None, 'image': item['volumeInfo']['imageLinks']['thumbnail'] if 'imageLinks' in item['volumeInfo'].keys() and 'thumbnail' in item['volumeInfo']['imageLinks'].keys() else None, 'source_book': 'google-api' }, data['items'])) return []
def arbitrary_item(S): """ Select an arbitrary item from set or sequence S. Avoids bugs caused by directly calling iter(S).next() and mysteriously terminating loops in callers' code when S is empty. """ try: return next(iter(S)) except StopIteration: raise IndexError("No items to select.")
def find_cycle(source_graph): """Return True if the directed graph has a cycle. The graph must be represented as a dictionary mapping vertices to iterables of neighbouring vertices. https://codereview.stackexchange.com/a/86067 """ visited = set() path = [object()] path_set = set(path) stack = [iter(source_graph)] while stack: for v in stack[-1]: if v in path_set: return True elif v not in visited: visited.add(v) path.append(v) path_set.add(v) stack.append(iter(source_graph.get(v, ()))) break else: path_set.remove(path.pop()) stack.pop() return False
def three_shouts(word1, word2, word3): """Returns a tuple of strings concatenated with '!!!'.""" # Define inner def inner(word): """Returns a string concatenated with '!!!'.""" return word + '!!!' # Return a tuple of strings return (inner(word1),inner(word2),inner(word3))
def hsv2rgb(hsvColor): """ Conversione del formato colore HSV in RGB :param hsvColor: Stringa del colore HSV :return: Tripla RGB """ # hsvColor = '#1C8A88' #LOW # hsvColor = '#BDEFEF' #HIGH h = hsvColor.lstrip('#') rgb = tuple(int(h[i:i + 2], 16) for i in (0, 2, 4)) return rgb[0], rgb[1], rgb[2]
def isFailed(posBox, posWalls, posGoals): """This function used to observe if the state is potentially failed, then prune the search""" rotatePattern = [[0,1,2,3,4,5,6,7,8], [2,5,8,1,4,7,0,3,6], [0,1,2,3,4,5,6,7,8][::-1], [2,5,8,1,4,7,0,3,6][::-1]] flipPattern = [[2,1,0,5,4,3,8,7,6], [0,3,6,1,4,7,2,5,8], [2,1,0,5,4,3,8,7,6][::-1], [0,3,6,1,4,7,2,5,8][::-1]] allPattern = rotatePattern + flipPattern for box in posBox: if box not in posGoals: board = [(box[0] - 1, box[1] - 1), (box[0] - 1, box[1]), (box[0] - 1, box[1] + 1), (box[0], box[1] - 1), (box[0], box[1]), (box[0], box[1] + 1), (box[0] + 1, box[1] - 1), (box[0] + 1, box[1]), (box[0] + 1, box[1] + 1)] for pattern in allPattern: newBoard = [board[i] for i in pattern] if newBoard[1] in posWalls and newBoard[5] in posWalls: return True elif newBoard[1] in posBox and newBoard[2] in posWalls and newBoard[5] in posWalls: return True elif newBoard[1] in posBox and newBoard[2] in posWalls and newBoard[5] in posBox: return True elif newBoard[1] in posBox and newBoard[2] in posBox and newBoard[5] in posBox: return True elif newBoard[1] in posBox and newBoard[6] in posBox and newBoard[2] in posWalls and newBoard[3] in posWalls and newBoard[8] in posWalls: return True return False
def combine_signatures(*args, function=set.intersection): """Combine signatures (e.g. by taking the intersection) Args: *args: list of signature dictonaries function: set operation to combine the signatures Returns: dict of set: combined signature dictionary. >>> s1 = {"A": {1, 2, 3}, "B": {2, 3, 4}} >>> s2 = {"A": {1, 3, 4, 5}, "B": {42}} >>> pprint(combine_signatures(s1, s2)) {'A': {1, 3}, 'B': set()} """ assert len(args) > 0, "No signatures provided" keys = args[0].keys() for sig in args: assert sig.keys() == keys, "All signature dictonaries must have identical keys." return {k: function(*[set(sig[k]) for sig in args]) for k in keys}
def concatenate_comments(tidy_advice: list, format_advice: list) -> list: """Concatenate comments made to the same line of the same file.""" # traverse comments from clang-format for index, comment_body in enumerate(format_advice): # check for comments from clang-tidy on the same line comment_index = None for i, payload in enumerate(tidy_advice): if ( payload["line"] == comment_body["line"] and payload["path"] == comment_body["path"] ): comment_index = i # mark this comment for concatenation break if comment_index is not None: # append clang-format advice to clang-tidy output/suggestion tidy_advice[comment_index]["body"] += "\n" + comment_body["body"] del format_advice[index] # remove duplicate comment return tidy_advice + format_advice
def _skip_if_p2os(overlay, pkg, distro, preserve_existing, collector): """Skip if it's a p2os package""" collector.append(pkg) if 'p2os' in pkg: return False, False return True, pkg
def get_class_name(instance_class): """Get the instance class name.""" if not hasattr(instance_class, '__bases__'): instance_class = instance_class.__class__ bases = [x.__name__ for x in instance_class.__bases__] if 'Field' in bases: return 'Field' if 'MediaFile' in bases: return 'MediaFile' return instance_class.__name__
def repeated(pattern, sep, least=1, most=None): """ Returns a pattern that matches a sequence of strings that match ``pattern`` separated by strings that match ``sep``. For example, for matching a sequence of ``'{key}={value}'`` pairs separated by ``'&'``, where key and value contains only lowercase letters:: repeated('[a-z]+=[a-z]+', '&') == '[a-z]+=[a-z]+(?:&[a-z]+=[a-z]+)*' Args: pattern (str): a pattern sep (str): a pattern for the separator (usually just a character/string) least (int, positive): minimum number of strings matching ``pattern``; must be positive most (Optional[int]): maximum number of strings matching ``pattern``; must be greater or equal to ``least`` Returns: a pattern """ if least <= 0: raise ValueError('least should be positive; it is: %d' % least) if most is not None: if most < 2: raise ValueError('it does not make any sense to call this function with most<2:\n' 'for most=1, you could just write the <pattern> argument') if most < least: raise ValueError('most must be greater or equal to least') least_s = str(least - 1) if least > 1 else '' most_s = str(most - 1) if most else '' if most and least == most: if least == 2: return pattern + sep + pattern reps = '{%s}' % least_s else: reps = '{%s,%s}' % (least_s, most_s) if reps == '{,}': reps = '*' elif reps == '{1,}': reps = '+' elif reps == '{,1}': reps = '?' return ('{pattern}(?:{sep}{pattern}){reps}' .format(pattern=pattern, sep=sep, reps=reps))
def count(text, min_length=2): """ Indexes a count of all words found in text """ index = {} for word in text.split(" "): if index.get(word.lower()): index[word.lower()] += 1 elif len(word) >= min_length: index[word.lower()] = 1 return index
def is_iterable(obj): """ Checks whether the given object is an iterable by calling iter. :param obj: the object to check :return: true if the object is iterable """ try: _ = iter(obj) except TypeError: return False else: return True
def galois_multiplication(a, b): """Galois multiplication of 8 bit characters a and b.""" p = 0 for counter in range(8): if b & 1: p ^= a hi_bit_set = a & 0x80 a <<= 1 # keep a 8 bit a &= 0xFF if hi_bit_set: a ^= 0x1b b >>= 1 return p
def raises(exception, f, *args, **kwargs): """ Determine whether the given call raises the given exception. """ try: f(*args, **kwargs) except exception: return 1 return 0
def subplot_shape(size): """ Get the most square shape for the plot axes values. If only one factor, increase size and allow for empty slots. """ facts = [[i, size//i] for i in range(1, int(size**0.5) + 1) if size % i == 0] # re-calc for prime numbers larger than 3 to get better shape while len(facts) == 1: size += 1 facts = [[i, size//i] for i in range(1, int(size**0.5) + 1) if size % i == 0] sum_facts = [abs(pair[0]-pair[1]) for pair in facts] smallest = min(sum_facts) shape = facts[sum_facts.index(smallest)] return shape
def unindent(s, skipfirst=True): """Return an unindented version of a docstring. Removes indentation on lines following the first one, using the leading whitespace of the first indented line that is not blank to determine the indentation. """ lines = s.split("\n") if skipfirst: first = lines.pop(0) L = [first] else: L = [] indent = None for l in lines: ls = l.strip() if ls: indent = len(l) - len(ls) break L += [l[indent:] for l in lines] return "\n".join(L)
def get_svg_string(svg_name, verbose=False): """ Helper function returning an SVG string from the given file :param svg_name: The filename to search in :param verbose: Whether to print ancillar information :return: The contents of the SVG file, or an empty string if none are found. """ try: with open(svg_name, 'r') as input_file: raw_string_data = input_file.read() if verbose: print(f'Loading "{svg_name}"') return raw_string_data except: print(f'Error: No file "{svg_name}" found') return '' None ''
def say_hello(name: str, salutation: str = "Hello") -> str: """Say hello to the user.""" return f"{salutation.capitalize()}, {name.capitalize()}. Welcome to the wonderful world of Python."
def is_point_in_rect2(point, rect_center, rect_w, rect_h): """Checks whether is coordinate point inside the rectangle or not. Rectangle is defined by center and linear sizes. :type point: list :param point: testing coordinate point :type rect_center: list :param rect_center: point, center of rectangle :type rect_w: float :param rect_w: rectangle width :type rect_h: float :param rect_h: rectangle height :rtype: boolean :return: boolean check result """ cx, cy = rect_center x, y = point if abs(x - cx) <= rect_w / 2.0 and abs(y - cy) <= rect_h / 2.0: return True return False
def dot(u, v): """Dot product between vectors ``u`` and ``v``.""" return sum(uu * vv for uu, vv in zip(u, v))
def mmss_to_frames(fps, m, s=0): """ Converts minutes and seconds of video to frames based on fps :param fps: frames per second of video :param m: minutes :param s: seconds :return: frame number """ return int((m * 60 + s) / fps)
def read_hosts_from_temp(filename, mode): """ Retrieves list of hosts that were active in previous iteration of ranking algorithm. Args: filename: (str) Name of file to retrieve host names from. mode: (str) Opening file mode. Returns: prev_hosts: List of host names read from file. """ try: f = open(filename, 'r') except (FileNotFoundError, IOError): f = open(filename, 'w+') f = open(filename,mode) prev_hosts = [] if f.mode == mode: prev_hosts_str = f.read() prev_hosts = prev_hosts_str.split('\n') if len(prev_hosts[-1]) == 0: del prev_hosts[-1] return prev_hosts
def editDistance(s1, s2): """ Calculate edit distance between 2 strings Args: s1: string 1 s2: string 2 Returns: Edit distance between s1 and s2 """ # ignore the case s1 = s1.upper() s2 = s2.upper() if len(s1) > len(s2): s1, s2 = s2, s1 distances = list(range(len(s1) + 1)) for i2, c2 in enumerate(s2): distances_ = [i2+1] for i1, c1 in enumerate(s1): if c1 == c2: distances_.append(distances[i1]) else: distances_.append(1 + min((distances[i1], distances[i1 + 1], distances_[-1]))) distances = distances_ return distances[-1]
def average(lst): """ Calculates average of a list """ avg = sum(lst) / len(lst) avg_float_decimal = float("{0:.3f}".format(avg)) return avg_float_decimal
def weightDifference(vG1, vL1, vO1, vG2, vL2, vO2): """ Get the difference as weight2 - weight2 :param vG1: :param vL1: :param vO1: :param vG2: :param vL2: :param vO2: :return: """ vG = vG2 - vG1 vL = vL2 - vL1 vO = vO2 - vO1 return (vG, vL, vO)
def convert_blender_file_format(extension): """ Converts a blender format like JPEG to an extension like .jpeg """ extensions = { "BMP": ".bmp", "PNG": ".png", "JPEG": ".jpg", "TARGA": ".tga", "TIFF": ".tiff" } if extension in extensions: return extensions[extension] # In case we can't find the extension, return png print("Warning: Unkown blender file format:", extension) return ".png"
def _border_properties_to_styles(properties): """ Convert the properties to border styles. :param properties: Ordered list of OOXML properties :return: dictionary of border styles """ styles = {} # - 'border-top', 'border-right', 'border-bottom', 'border-left' for style, prop in properties: # formats -- order is important formats = ('val', "{val}"), ('sz', "{sz}pt"), ('color', "{color}") values = [fmt.format(**prop) for key, fmt in formats if key in prop] if values: styles[style] = " ".join(values) if any('space' in prop for style, prop in properties): # - 'border-collapse' property selects a table's border model(separated or collapsing). # Value is "collapse" if all spaces == 0 spaces = [prop.get('space', 0) for style, prop in properties] all_spaces_are_nul = all(space == 0 for space in spaces) styles['border-collapse'] = "collapse" if all_spaces_are_nul else "separate" # - 'border-spacing' property specifies the distance between the borders of adjacent cells. if not all_spaces_are_nul: spacing = ["{0}pt".format(prop.get('space', 0)) for style, prop in properties] styles['border-spacing'] = " ".join(spacing) # - The box-shadow property attaches one or more shadows to an element. # Use the border size, the default color, without effect (blur...) has_shadow = any(prop.get('shadow') for style, prop in properties) if has_shadow: shadow = ["{0}pt".format(prop['sz'] if prop.get('shadow') else "0pt") for style, prop in properties] styles['box-shadow'] = " ".join(shadow) return styles
def help_get_docstring(func): """ Extract Docstring from func name""" import inspect try: lines = func.__doc__ except AttributeError: lines = "" return lines
def hex_str(s): """ Returns a hex-formatted string based on s. :param s: Some string. :type s: str :return: Hex-formatted string representing s. :rtype: str """ return ' '.join("{:02x}".format(ord(b)) for b in s)
def listToIndex2item(L): """converts list to dict of list index->list item""" d = {} for i, item in enumerate(L): d[i] = item return d
def LongestFromList(ls: list): """ Determines the object with the longest length inside a list. Args: ls: A list containing an array of objects. Returns: The object with the longest length from the list. None if not applicable. """ try: current = ls[0] for obj in ls: if len(obj) > len(current): current = obj return current except: # There could be many reasons for which above code fails: # ls of length 0, obj of a type without support for len(), or ls is not an iterable. return None
def fahrenheit(celsius): """Convert celsius to fahrenheit.""" return ((celsius/5)*9)+32
def bytes_as_char_array(b): # type: (bytes) -> str """ Given a sequence of bytes, format as a char array """ return '{ ' + ', '.join('0x%02x' % x for x in b) + ' }'
def ones_like(x): """Return an array of the same shape as `x` containing only ones.""" return x * 0. + 1.
def count_bags_inside(bag_name, rules): """Count total number of bags in bag_name.""" if not rules[bag_name]: return 0 count = 0 for inside_bag, number_of_bags in rules[bag_name].items(): count += (number_of_bags + number_of_bags * count_bags_inside(inside_bag, rules)) return count
def _cmplx_add_ ( s , o ) : """add complex values >>> r = v + other """ return o + complex ( s )
def topic_name_from_path(path, project): """Validate a topic URI path and get the topic name. :type path: string :param path: URI path for a topic API request. :type project: string :param project: The project associated with the request. It is included for validation purposes. :rtype: string :returns: Topic name parsed from ``path``. :raises: :class:`ValueError` if the ``path`` is ill-formed or if the project from the ``path`` does not agree with the ``project`` passed in. """ # PATH = 'projects/%s/topics/%s' % (PROJECT, TOPIC_NAME) path_parts = path.split('/') if (len(path_parts) != 4 or path_parts[0] != 'projects' or path_parts[2] != 'topics'): raise ValueError('Expected path to be of the form ' 'projects/{project}/topics/{topic_name}') if (len(path_parts) != 4 or path_parts[0] != 'projects' or path_parts[2] != 'topics' or path_parts[1] != project): raise ValueError('Project from client should agree with ' 'project from resource.') return path_parts[3]
def removeDups(aSeq): """Remove duplicate entries from a sequence, returning the results as a list. Preserves the ordering of retained elements. """ tempDict = {} def isUnique(val): if val in tempDict: return False tempDict[val] = None return True return [val for val in aSeq if isUnique(val)]
def dense_output(t_current, t_old, h_current, rcont): """ Dense output function, basically extrapolatin """ # initialization s = (t_current - t_old) / h_current s1 = 1.0 - s return rcont[0] + s * (rcont[1] + s1 * ( rcont[2] + s * (rcont[3] + s1 * (rcont[4] + s * (rcont[5] + s1 * (rcont[6] + s * rcont[7]))))))
def powerset(s): """Computes all of the sublists of s""" rv = [[]] for num in s: rv += [x+[num] for x in rv] return rv
def getKey(data, key, default=None): """ Returns the key from the data if available or the given default :param data: Data structure to inspect :type data: dict :param key: Key to lookup in dictionary :type key: str :param default: Default value to return when key is not set :type default: any """ if key in data: return data[key] else: return default
def switch_player(current_player): """Switches the player from x to o""" if current_player == "x": return "o" else: return "x"
def getAxisVector(axis, sign=1): """ Return a vector for a signed axis """ i = int(axis) v = [0, 0, 0] v[i] = 1 * (1 if sign >= 0 else -1) return tuple(v)
def difference(array, k=1): """Calculate l[n] - l[n-k] """ if (len(array) - k) < 1: raise ValueError() if k < 0: raise ValueError("k has to be greater or equal than zero!") elif k == 0: return [i - i for i in array] else: return [j - i for i, j in zip(array[:-k], array[k:])]
def get_rh(pial_list): """ Is there a better way of doing this? """ for p in pial_list: if p.endswith('rh.pial'): return p
def velocity_to_bin(velocity, step=4): """ Velocity in a midi file can take on any integer value in the range (0, 127) But, so that each vector in the midiparser is fewer dimensions than it has to be, without really losing any resolution in dynamics, the velocity is shifted down to the previous multiple of step """ assert (128 % step == 0), "128 possible midi velocities must be divisible into the number of bins" assert 0 <= velocity <= 127, f"velocity must be between 0 and 127, not {velocity}" #bins = np.arange(0, 127, step) #bins[i] is the ith multiple of step, i.e., step * i idx = velocity // step return idx
def get_mesos_cpu_status(metrics): """Takes in the mesos metrics and analyzes them, returning the status :param metrics: mesos metrics dictionary :returns: Tuple of the output array and is_ok bool """ total = metrics['master/cpus_total'] used = metrics['master/cpus_used'] available = total - used return total, used, available
def apply_bids_label_restrictions(value): """Sanitize file names for BIDS. """ # only alphanumeric allowed # => remove everything else if value is None: # Rules didn't find anything to apply, so don't put anything into the # spec. return None from six import string_types if not isinstance(value, string_types): value = str(value) import re pattern = re.compile('[\W_]+') # check return pattern.sub('', value)
def MakeOldStyle(newstyle_fieldpath): """New style: a.b.000003.c -> old style: a.b[3].c . Args: newstyle_fieldpath: new-style path to convert. Returns: Old-style version of path. """ tokens = newstyle_fieldpath.split(".") oldstyle = "" is_first = True for token in tokens: if token.isdigit(): assert not is_first, "indexes are never first" oldstyle += "[%d]" % int(token) else: oldstyle += token if is_first else "." + token is_first = False return oldstyle
def gradient_add(grad_1, grad_2, param, verbose=0): """ Sum two gradients :param grad_1: (TensorFlow Tensor) The first gradient :param grad_2: (TensorFlow Tensor) The second gradient :param param: (TensorFlow parameters) The trainable parameters :param verbose: (int) verbosity level :return: (TensorFlow Tensor) the sum of the gradients """ if verbose > 1: print([grad_1, grad_2, param.name]) if grad_1 is None and grad_2 is None: return None elif grad_1 is None: return grad_2 elif grad_2 is None: return grad_1 else: return grad_1 + grad_2
def bytes_to_long(data): """ Convert byte string to integer :param data: byte string :return: integer """ try: return int.from_bytes(data, 'big') except TypeError: return bytes_to_long(data.encode('utf-8')) except AttributeError: return int(data.encode('hex'), 16)
def check_bounds(value): """Check if the given value is out-of-bounds (0 to 4095) :args: the value to be checked :returns: the checked value """ try: if int(value) > 4095: return 4095 elif int(value) < 0: return 0 else: return value except ValueError: print("Value was not a number, returned default value of 0") return 0
def get_recursively(search_dict, field): """ Takes a dict with nested lists and dicts, and searches all dicts for a key of the field provided. """ fields_found = [] for key, value in search_dict.items(): if key == field: fields_found.append(value) elif isinstance(value, dict): results = get_recursively(value, field) for result in results: fields_found.append(result) elif isinstance(value, list): for item in value: if isinstance(item, dict): more_results = get_recursively(item, field) for another_result in more_results: fields_found.append(another_result) return fields_found
def reversedbinary(i,numbits): """Takes integer i and returns its binary representation as a list, but in reverse order, with total number of bits numbits. Useful for trying every possibility of numbits choices of two.""" num = i count = 0 revbin = [] while count < numbits: revbin.append(num%2) num = num//2 count += 1 return revbin
def add_md(text, s, level=0): """Adds text to the readme at the given level""" if level > 0: if text != "": text += "\n" text += "#" * level text += " " text += s + "\n" if level > 0: text += "\n" return text
def GetFragTuple(fragid): """ Fragment ids should have the form: "NAME:NUMBER" or "NAME-NUMBER". This splits the fragment into the name and number value. Args: fragid (str): the fragment id string. Return: (tuple): fragment name, fragment number """ markers = [":", "-", "+"] if all(x not in fragid for x in markers): raise ValueError("Invalid format for fragment ID") if '+' in fragid: return tuple(fragid.split("+")) # elif '-' in fragid: # return tuple(fragid.split("-")) elif isinstance(fragid, str): return tuple(fragid.split(":")) else: return tuple(fragid)
def list_check(lista): """ If a list has only one element, return that element. Otherwise return the whole list. """ try: e2 = lista[1] return lista except IndexError: return lista[0]
def Slide_body(cont_Object_f): """ :param cont_Object_f: The sequence of "f" values of Object objects contained in this Slide :type cont_Object_f: Array """ return '\n'.join(cont_Object_f)
def easing(current_time, begin, change, total_time): """ current_time = how much time has passed since start begin = starting value change = final value - starting value total_time = how long ease should take """ return change * current_time / float(total_time) + begin
def to_ascii(s): """Convert the bytes string to a ASCII string Usefull to remove accent (diacritics)""" if s is None: return s if isinstance(s, str): return s try: return str(s, 'utf-8') except UnicodeDecodeError: return s
def escaped(txt, specs): """ Escape txt so it is latex safe. Parameters ---------- txt : string value to escape specs : dictionary Dictionary of user-specified and default parameters to formatting Returns ------- string """ ret = txt.replace("_", "\_") return ret
def sleeptime(retries): """ purpose: compute suggested sleep time as a function of retries paramtr: $retries (IN): number of retries so far returns: recommended sleep time in seconds """ if retries < 5: my_y = 1 elif retries < 50: my_y = 5 elif retries < 500: my_y = 30 else: my_y = 60 return my_y
def _setDefaults(configObj={}): """ set up the default parameters to run drizzle build,single,units,wt_scl,pixfrac,kernel,fillval, rot,scale,xsh,ysh,blotnx,blotny,outnx,outny,data """ paramDict={"build":True, "single":True, "in_units":"cps", "wt_scl":1., "pixfrac":1., "kernel":"square", "fillval":999., "rot":0., "scale":1., "xsh":0., "ysh":0., "blotnx":2048, "blotny":2048, "outnx":4096, "outny":4096, "data":None, "driz_separate":True, "driz_combine":False} if(len(configObj) !=0): for key in configObj.keys(): paramDict[key]=configObj[key] return paramDict
def delta(a, b): """ Function that returns the Kronecker delta delta(a, b). Returns 1 if a = b and 0 otherwise. """ if a==b: return 1 else: return 0
def get_lowcase_bool(value): """ Transform Python False, True into false, true >>> get_javascript_value(True) true >>> get_javascript_value(10) 10 """ if isinstance(value, bool): if value: return 'true' else: return 'false' else: return value
def site_time_zone(request, registry, settings): """Expose website URL from ``tm.site_time_zone`` config variable to templates. By best practices, all dates and times should be stored in the database using :term:`UTC` time. This setting allows quickly convert dates and times to your local time. Example: .. code-block:: html+jinja <p> <strong>Bar opens</strong>: {{ opening_at|friendly_time(timezone=site_time_zone) }} </p> Default value is ``UTC``. See `timezone abbreviation list <https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations>`_. """ return settings.get("tm.site_timezone", "UTC")
def lookup_module_function( module_reference, function_name ): """ Acquires a function reference from a module given an function name. Takes 2 arguments: module_reference - Module whose interface is searched for function_name. function_name - String specifying the function whose handle is sought. Returns 1 value: function_reference - Reference to the requested function. None if function_name is not part of module_reference's interface or if there was an error acquiring the reference. """ # get a reference to the function requested. return None if it isn't part # of the module's interface. function_reference = getattr( module_reference, function_name, None ) return function_reference
def getfields(jsondict: dict, types: bool = False): """Return list of field names or a name:type dict if types=True""" if types: return { f["name"]: f["type"].replace("esriFieldType", "") for f in jsondict["fields"] } else: return [f["name"] for f in jsondict["fields"]]
def video_player(obj): """ Receives object with 'video' FileField and returns HTML5 player. """ return {'object': obj}
def pad_sequence(seqlist, pad_token): """Left pad list of token id sequences. Args: seqlist (list): list of token id sequences pad_token (int): padding token id Returns: final (list): list of padded token id sequences """ maxlen = max(len(x) for x in seqlist) final = [([pad_token] * (maxlen - len(x))) + x for x in seqlist] return final
def read_signature(obs_by_pos): """ Returns a string made from the positions where bases were able to be observed from the read. """ return ','.join(["%d:%s" % (pos, obs_by_pos[pos]) for pos in sorted(obs_by_pos)])
def _mixrange(short_hand): """Working with splitting on on command and dashes.""" ranges = [] # Taken from https://stackoverflow.com/a/18759797 for item in short_hand.split(','): if '-' not in item: ranges.append(int(item)) else: l, h = map(int, item.split('-')) ranges += range(l, h + 1) return ranges
def expr_prod(factor: float, expression: str) -> str: """helper function for building an expression with an (optional) pre-factor Args: factor (float): The value of the prefactor expression (str): The remaining expression Returns: str: The expression with the factor appended if necessary """ if factor == 0: return "0" elif factor == 1: return expression elif factor == -1: return "-" + expression else: return f"{factor:g} * {expression}"
def _xr_to_keyset(line): """ Parse xfsrestore output keyset elements. """ tkns = [elm for elm in line.strip().split(":", 1) if elm] if len(tkns) == 1: return "'{}': ".format(tkns[0]) else: key, val = tkns return "'{}': '{}',".format(key.strip(), val.strip())
def get_side(given_name): """ Assuming the given name adheres to the naming convention of crab this will extract the side/location element of the name. :param given_name: Name to extract from :type given_name: str or pm.nt.DependNode :return: str """ parts = given_name.split('_') if not parts: return '' return parts[-1]
def create_dna( num, alphabet='actg'): """ num : integer alphabet : string, optional, The default is 'actg'. Returns : string To create a random string of dna of desired length. """ import random return ''.join([random.choice(alphabet) for i in range(num)])
def sequential_search(alist, item): """Sequential search Complexity: item is present: best case=1, worst case=n, avg=n/2 item not present: best case=n, worst case=n, avg=n Args: alist (list): A list. item (int): The item to search. Returns: bool: Boolean with the answer of the search. Examples: >>> alist = [1, 2, 32, 8, 17, 19, 42, 13, 0] >>> sequential_search(alist, 3) False >>> sequential_search(alist, 13) True """ pos = 0 found = False while pos < len(alist) and not found: if alist[pos] == item: found = True else: pos += 1 return found
def get_unique_name(existing, initial): """Get a name either equal to initial or of the form initial_N, for some integer N, that is not in the set existing. :param existing: Set of names that must not be chosen. :param initial: Name, or name prefix, to use""" if initial not in existing: return initial for i in range(len(existing) + 1): test = f"{initial}_{i + 1}" if test not in existing: return test assert False