content
stringlengths
42
6.51k
def output_requirements(requirements): """Prepare print requirements to stdout. :param dict requirements: mapping from a project to its version specifier """ return '\n'.join('{0}{1}'.format(key, value) for key, value in sorted(requirements.items()))
def _get_referenced_services(specs): """ Returns all services that are referenced in specs.apps.depends.services, or in specs.bundles.services """ active_services = set() for app_spec in specs['apps'].values(): for service in app_spec['depends']['services']: active_services.a...
def read_unsigned_int(from_bytes: bytes) -> int: """ from_bytes is the binary file contents to read from :param from_bytes: string representation of binary bytes read from a file :return: integer """ return int.from_bytes(from_bytes, byteorder='little', signed=False)
def complementary_strand(strand): """Get complementary strand Parameters ---------- strand: string +/- Returns ------- rs: string -/+ """ if strand == "+": return "-" elif strand == "-": return "+" else: raise ValueError("Not a v...
def json_utf8_decode(obj: object) -> object: """Decode all strings in an object to UTF-8. :arg obj: Object. :returns: Object with UTF-8 encoded strings. """ if isinstance(obj, bytes): return obj.decode('utf-8') if isinstance(obj, list) or isinstance(obj, tuple): return [json_ut...
def get_scenario_start_index(base_times, start_time): """ Returns the index of the closest time step that is at, or before the scenario start time. """ assert ( base_times[0] <= start_time ), f"Scenario start time {start_time} is before baseline has started" indices_after_start_index = [...
def parse_out(line): """Parses an outoing IRC message into prefix and body. e.g: "PRIVMSG #test :testing" -> prefix="PRIVMSG #test ", body="testing" Outgoing messages are simpler in format than incoming messages. """ parts = line.strip().split(":") prefix = parts[0] body = ":".j...
def vaporEnthalpyFormation(T, vEFP): """ vaporEnthalpyFormation(T, vEFP) vaporEnthalpyFormation (kJ/mol) = A + B*T + C*T^2 Parameters T, temperature in Kelvin vEFP, A=vEFP[0], B=vEFP[1], C=vEFP[2] A, B, and C are regression coefficients Returns vapor Enthalpy of Form...
def adjust_color(variance): """Calc the adjustment value of the background color""" # Because there is 6 degrees mapping to 255 values, 42.5 is the factor for 12 degree spread factor = 42.5 adj = abs(int(factor * variance)) if adj > 255: adj = 255 return adj
def visible(filename): """Exclude hidden files""" return not filename.startswith('.')
def padding_alphabet(block_size): """ This is faster for the padding. """ return list(range(0, block_size))[::-1] + list(range(block_size, 256)) + [0]
def isstr(s): """True if 's' is an instance of basestring in py2, or of str in py3""" bs = getattr(__builtins__, 'basestring', str) return isinstance(s, bs)
def runge_kutta(diff_egn, r, t, h): """ 4th order Runge-Kutta method :param diff_egn: :param r: :param t: :param h: :return: """ k1 = h * diff_egn(r, t) k2 = h * diff_egn(r + k1 / 2, t + h / 2) k3 = h * diff_egn(r + k2 / 2, t + h / 2) k4 = h * diff_egn(r + k3, t + h) ...
def RADIUS_MAP(DIAMETER): """ Convert DIAMETER TO RADIUS""" return (DIAMETER/2)
def convert_byte_to_char(text, annotation): """Convert the byte offset in the annotation to char offsets.""" if annotation is not None: byte_to_char = {} byte_offset = 0 for i, c in enumerate(text): byte_to_char[byte_offset] = i byte_offset += len(c.encode("utf-8")) for entity in annota...
def reasonable_timestamp_ms(timestamp): """ checks that the timestamp is within 100 years and not zero this means a random value from memory will probably not be interpreted as a valid timestamp and a better error message could be printed """ return timestamp != 0 and timestamp < 1000 * 3600 * 2...
def reverse_px_py(original: str): """ This function replace PersonX PersonY in a string. :param original: The original string to be processed. :return: The string with PersonX and PersonY reversed. """ return original.replace("PersonX", "[PX]").replace("PersonY", "[PY]").replace("[PX]", "P...
def check_for_gold(bag, bag_rules): """Check if a shiny gold bag can be inside a bag""" rule = bag_rules[bag] if len(rule.keys()) == 1 and 'other bags' in rule.keys(): return False elif 'shiny gold bags' in rule.keys(): return True else: for n in rule.keys(): retu...
def clean_endpoint_for_naming(endpoint: str) -> str: """Convert endpoints like '/' and '/page/one' to 'root' and 'page_one' """ if endpoint == '/': endpoint = 'root' else: endpoint = endpoint.replace('/', '_') if endpoint.startswith('_'): endpoint = endpoint[1:] r...
def SplitNameValuePairAtSeparator(arg, sep): """Split a string at the first unquoted occurrence of a character. Split the string arg at the first unquoted occurrence of the character c. Here, in the first part of arg, the backslash is considered the quoting character indicating that the next character is to be...
def get_intermediates_to_exclude(industrial_route): """ Input: industrially practiced synthesis route as a list of SMILES reaction strings Output: SMILES string of intermediates to exclude delimited by "." """ intermediates_string = "" for step in industrial_route[:-1]: step_product = st...
def fizzbuzz(n): """Return a sequence up to "n" using the fizzbuzz rule.""" result = [] for i in range(1, n + 1): if i % 3 == 0 and i % 5 == 0: value = "fizzbuzz" elif i % 3 == 0: value = "fizz" elif i % 5 == 0: value = "buzz" else: ...
def _graph_string(graph): """Helper to serialize a graph to string.""" if graph: return graph.as_graph_def(add_shapes=True).SerializeToString() else: return b''
def vertices2line(points): """ Perform a simple linear interpolation on two points. Parameters: points (list of np.ndarray): list of two 2D numpy arrays. of form [[x1, E1], [x2, E2]]. Returns: (float, float): a tuple containing the gradient and intercept of the ...
def _add_header(headers, name, value): """ >>> headers = [] >>> assert _add_header(headers, 'n', 'v') == [('n', 'v')] >>> headers = {} >>> assert _add_header(headers, 'n', 'v') == {'n': 'v'} """ if isinstance(headers, dict): headers[name] = str(value) else: # pragma: no cover ...
def to_list(obj): """Convert a list-like object to a list. >>> to_list([1, 2, 3]) [1, 2, 3] >>> to_list("a,b,c") ['a', 'b', 'c'] >>> to_list("item") ['item'] >>> to_list(None) [] """ if isinstance(obj, (list, tuple)): return obj elif isinstance(obj, str): ...
def get_index_for_triples(x, y, z, size): """ Parameters ---------- x : int An integer in :math:`\\{0, 1, \\ldots, size\\}` such that :math:`x + y \\leq size` y : int Same as parameter x. z : int Same as parameter x. size : int Upper bound for the sum ...
def leapyr_check(year): """Check if year is leapyear""" if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True else: return False else: return True else: return False
def params_log_ces(factors): """Index tuples for the log_ces production function.""" return factors + ["phi"]
def number_of_antennas(positions): """ The number of unique places visited. """ return len(set(positions))
def ua_pivot(my_json, bad_hosts, final_bad_ua): """ Now that we have our known real bad UAs, we cycle back through the json Args: my_json(json): the json containing all the data bad_hosts(dict): known bad hosts final_bad_ua(list): our final list of bad IPs based on user_agent R...
def row_to_dictionary(row_obj, exclude_None=True): """Convert a row to a Python dictionary that is easier to work with""" if "cursor_description" in dir(row_obj): column_names = [desc[0] for desc in row_obj.cursor_description] row_dict = {} for i in range(len(column_names)): ...
def get_validated_seqids(sequences_list): """ A inputted list is checked for Seq-ID format, each of the Elements that are validated are returned to the user sequences_list: list of Seq-IDs to be validated """ validated_sequence_list = list() regex = r'^(2\d{3}-\w{2,10}-\d{3,4})$' import re ...
def _parse_single_header(b3_header): """ Parse out and return the data necessary for generating ZipkinAttrs. Returns a dict with the following keys: 'trace_id': str or None 'span_id': str or None 'parent_span_id': str or None 'sampled_str': ...
def fileSizeStrToInt(size_str: str) -> int: """Converts file size given in *iB format to bytes integer""" unit_dict = {"KiB": (2 ** 10), "MiB": (2 ** 20), "GiB": (2 ** 30), "TiB": (2 ** 40)} try: num = float(size_str[:-3]) unit = size_str[-3:] return int(num * unit_dict[unit]) e...
def search_fields_to_dict(fields): """ In ``SearchableQuerySet`` and ``SearchableManager``, search fields can either be a sequence, or a dict of fields mapped to weights. This function converts sequences to a dict mapped to even weights, so that we're consistently dealing with a dict of fields mappe...
def filter_coords(coords): """ Remove duplicate coordinates in LineString data; preserve coordinate ordering. """ unique = [] [unique.append(item) for item in coords if item not in unique] return unique
def build_os_environment_string(env): """ Creates a string of the form export key0=value0;export key1=value1;... for use in running commands with the specified environment :Parameter variables: a dictionay of environmental variables :Returns string: a string that can be prepended to a command to run the c...
def _later_date(date1, date2): """_later_date(date1, date2) Compares two (month, day, year) tuples to see which is later. Positional arguments: date1 (tuple) - first date tuple date2 (tuple) - second date tuple Returns: bool - True if the first date is later than the second, F...
def filter_list(list_to_check, list_to_include): """ Return a list with only items that matched an item in list_to_include. """ filtered_list = [] for checked in list_to_check: for included in list_to_include: if checked == included: filtered_list.append(checked) ...
def problem_19_1(x, y): """ Write a function to swap a number in place without temporary variables. """ # Bit-wise operations. #x = x ^ y #y = x ^ y #x = x ^ y #return (x, y) # Arithmetic operations. x = x - y y = y + x x = y - x return (x, y)
def _num_clips( duration_sec: float, fps: float, stride_frames: int, window_size_frames: int, backpad_last: bool = True, ) -> int: """ Utility to calculate the number of clips for a given duration, fps, stride & window_size """ num_frames = round(duration_sec * fps) N = num_frame...
def decode_resumable_upload_bitmap(bitmap_node, number_of_units): """Decodes bitmap_node to hash of unit_id: is_uploaded bitmap_node -- bitmap node of resumable_upload with 'count' number and 'words' containing array number_of_units -- number of units we are uploading to ...
def construct_processor_name(type_robot, type_processor): """ Construct the name of a single Post Processor. :param type_robot: Type of robot. :param type_processor: Type of processor. :return: """ return '{} {}'.format(type_robot, type_processor)
def searchInsert(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ lo = 0 hi = len(nums) - 1 mid = 0 while lo <= hi: mid = (hi + lo)//2 if nums[mid] < target: lo = mid + 1 ...
def ascii_join(data): """Convert sequence of numbers to ASCII characters""" return ''.join([chr(n) for n in data])
def expand_params(names: list) -> list: """ Return an expanded list of parameters from a list of comma-separated parameters. E.g. given a list of ['a', 'b,c,d'], returns ['a', 'b', 'c', 'd'] """ expanded_names = [] for name in names: expanded_names.extend( [i.strip() for i...
def normalize(normalize_s, default_value=""): """Normalization function. Args: normalize_s (str): string to normalize. default_value (str, optional): [description]. Defaults to "". Returns: [type]: [description] """ return str(normalize_s).lower() if normalize_s else defaul...
def deepgetattr(obj, attr, default = None): """ Get a named attribute from an object; multi_getattr(x, 'a.b.c.d') is equivalent to x.a.b.c.d. When a default argument is given, it is returned when any attribute in the chain doesn't exist; without it, an exception is raised when a missing attribute is...
def isPerfectSquare(p: int) -> bool: """Checks if given number is a perfect square. A perfect square is an integer that is a square of another integer. Parameters: p: int number to check Returns: result: bool True if number is a perfect square F...
def getAssetUrl(feature): """ Return the assets URL params: feature -> a feature """ return feature["_links"]["assets"]
def hex_to_bytes(hex_str): """ Convert a string hex byte values into a byte string. The hex byte values may or may not be space separated. """ bytes_ = [] hex_str = ''.join(hex_str.split(" ")) for i in range(0, len(hex_str), 2): bytes_.append(chr(int(hex_str[i:i + 2], 16))) r...
def _longest_matching_rule(rules, word_class, full_form): """Find the rule with the longest full form suffix matching specified full form and class.""" best = ("", [""]) if word_class not in rules: return best start_index = 0 word_class_rules = rules[word_class] while start_index <= len...
def get_conv_shape_1axis(image_shape, kernel_shape, border_mode, subsample, dilation=1): """ This function compute the output shape of convolution operation. Parameters ---------- image_shape: int or None. Corresponds to the input image shape on a given axis. None if undefined. kernel_s...
def animal_crackers(text): """ a function takes a two-word string and returns True if both words begin with same letter :param text: str :return: bool animal_crackers('Levelheaded Llama') --> True animal_crackers('Crazy Kangaroo') --> False """ wordlist = text.split() return wordlist...
def uniform_bin(parent1, parent2, bits): """Return a new chromosome using uniform crossover on a binary string. This is suitable for binary encoding. Args: parent1 (int): A parent chromosome. parent2 (int): A parent chromosome. bits (int): The number of bits used in the encoding. ...
def _bmaction(old, new): """small utility for bookmark pushing""" if not old: return 'export' elif not new: return 'delete' return 'update'
def lambda_(xTk): # pragma: no cover """ latent heat of vaporization: J / g :param xTk - temperature (K): :return: """ return 3149 - 2.370 * xTk
def dec_to_list(dec_val, num_bits): """ Converts decimal value to list of 1's and 0's. """ bin_str = '{0:b}'.format(dec_val) bin_str = str.zfill(bin_str, num_bits) ret_list = [] for bin_val in bin_str: ret_list.append(int(bin_val)) return ret_list
def _parse_layer_params(layer_desc_, num_expected): """Extracts parameters from network description layer and raises if there are issues.""" layer_type_, layer_params = layer_desc_[0], layer_desc_[1:] if len(layer_params) != num_expected: raise ValueError("Expected {} parameters for layer {} but rec...
def locations_of_substring(string, substring) : """Return a list of locations of a substring. ( https://stackoverflow.com/a/19720214 )""" substring_length = len(substring) def recurse(locations_found, start) : location = string.find(substring, start) if location != -1: retu...
def highlightregion(value, regions): """Highlights the specified regions of text. This is used to insert ``<span class="hl">...</span>`` tags in the text as specified by the ``regions`` variable. """ if not regions: return value s = '' # We need to insert span tags into a string a...
def get_export_type(export_type): """Convert template type to the right filename.""" return { "css": "colors.css", "json": "colors.json", "konsole": "colors-konsole.colorscheme", "putty": "colors-putty.reg", "scss": "colors.scss", "shell": "colors.sh", "xr...
def unique(sequence): """ Returns a new sequence containing the unique elements from the provided sequence, while preserving the same type and order of the original sequence. """ result = [] for item in sequence: if item in result: continue # we already have seen this it...
def binary_tp(gold, pred): """ for each member in pred, if it overlaps with any member of gold, return 1 else return 0 """ tps = 0 for p in pred: tp = False for word in p: for span in gold: if word in span: tp = True ...
def minhash(str_a, str_b): """ :param str_a: str :param str_b: str :Sentences: should be tokenized in string str_a = u"There is" str_b = u"There was" Thanks to Pulkit Kathuria(@kevincobain2000) for the definition of the function. The function makes use of...
def _mean(a,b): """Man value""" return 0.5 * (a+b)
def extract_data(stdout): """Extract data from youtube-dl stdout. Args: stdout (string): String that contains the youtube-dl stdout. Returns: Python dictionary. For available keys check self._data under YoutubeDLDownloader.__init__(). """ data_dictionary = dict() if n...
def maximum(numbers): """Find the max using an iterable of numbers Return None if the iterable is empty """ if not numbers: return None max_number = numbers[0] for number in numbers: max_number = number if number > max_number else max_number return max_number
def _to_encode(str_to_encode, encode_type = 'utf-8'): """ Encoding the string into `encode_type` for char pointer of ctypes. """ return str_to_encode.encode(encode_type)
def extract_volume_number(value): """Extract the volume number from a string, returns None if not matched.""" return value.replace("v.", "").replace("v .", "").strip()
def _aslist(arg1): """return a list, split from the string supplied""" return str(arg1).split(",")
def _judge_tuple_of_mixed_tensors_continuous(index_tensor_info_key: list): """Determine whether the tensor in the index appears continuously.""" for i in range(len(index_tensor_info_key) - 1): if index_tensor_info_key[i + 1] != index_tensor_info_key[i] + 1: return False return True
def oxygen_abundance(Z): """ Set the oxygen abundance. We assume Asplund et al 2009 abundance at Zsun and that Ao scales linearly with Z. Z in solar units """ Ao = 4.90e-4 return Ao*Z
def process_lower(cont): """ Make the value in lowercase """ return cont.lower()
def _get_log_time_scale(units): """Retrieves the ``log10()`` of the scale factor for a given time unit. Args: units (str): String specifying the units (one of ``'fs'``, ``'ps'``, ``'ns'``, ``'us'``, ``'ms'``, ``'sec'``). Returns: The ``log10()`` of the scale factor for the time...
def clamp(number, min_value=0.0, max_value=1.0): """ Clamps a number between two values :param number: number, value to clamp :param min_value: number, maximum value of the number :param max_value: number, minimum value of the number :return: variant, int || float """ return max(min(num...
def reduceAngle(deg): """ Reduces an angle (in degrees) to a value in [-180..180) """ return (((deg + 180.) % 360.) - 180.)
def integer_to_vector_multiple_numbers(x, n_options_per_element, n_elements, index_to_element): """Return a vector representing an action/state from a given integer. Args: x (int): the integer to convert. n_options_per_element(list): number of options for each element in the vector. ...
def square_reflect_y(x, y): """Reflects the given square through the x-axis and returns the co-ordinates of the new square""" return (x, -y)
def id(url): """return video id""" return url.split("/")[-1] if "=" not in url else url.split("=")[1]
def order_dict(data): """ Order dict by default order """ return {k: order_dict(v) if isinstance(v, dict) else v for k, v in sorted(data.items())}
def temperature_ensemble(val): """ :param val: string, Name of the ensemble :return: boolean, returns True if temperature should be specified """ if val=='MSST' or val=='MSST_DAMPED' or val=='NPT_F' or val=='NPT_I' or val=='NVT' or val=='NVT_ADIABATIC' or val=='NVT_GEMC' or val=='NPT_GEMC': ...
def verify_params(event): """ Verify dictionary keys are in place, grouped all keys needed here. :param event: data representing the captured activity :type event: dict :return: success all keys present :rtype: bool """ all_good = True message = '' if 'params' not in event: ...
def decode_text(int_array, id2char): """ decode array of integers to text with ID2CHAR """ return "".join((id2char[ch] for ch in int_array))
def set_blast_min_length(config): """Set minimum sequence length for running blast searches.""" return config["settings"].get("blast_min_length", 1000)
def remove_special_characters(value, remove_spaces=True): """ Removes all special characters from a string, so only [a-Z] and [0-9] stay. :param value: The value where the characters need to be removed from. :type value: str :param remove_spaces: If true the spaces are also going to be removed. ...
def inclusive_range(f: int, t: int) -> range: """Returns range including both ends""" return range(f, t + 1)
def encode_attribute(att, desc, targ): """ Encode the 'role' of an attribute in a model. `Role` means: - Descriptive attribute (input) - Target attribute (output) - Missing attribute (not relevant to the model) """ check_desc = att in desc check_targ = att in targ ...
def db2lin(x): """From decibel to linear""" return 10.0**(x/10.0)
def what_number(number): """Returns string positive/zero/negative specifying value of the number.""" # if <expr>: # elif <expr>: # else: if number > 0: return "positive" elif number == 0: return "zero" else: return "negative"
def rebound(x, low=1, high=2, octave=2): """ Rescale x within given octave bounds. x: int represents a peak value low: int Lower bound. Defaults to 1. high: int Higher bound. Defaults to 2. octave: int Value of an octave """ while x >= high: x = ...
def add_id(items): """ add ids to tokents Args: items: dict or list Returns: token2id, id2token: dict, dict >>> add_id({'a':10,'b':2,'<UNK>':1e20}) ({'<UNK>': 0, 'a': 1, 'b': 2}, {0: '<UNK>', 1: 'a', 2: 'b'}) >>> add_id(["S","D","E","S"]) ({'S': 3, 'D': 1, 'E': 2}, {0: ...
def permutationFilter(perm): """ This function can be used to selectively filter out specific permutation combinations. It is called by RunPermutations for every possible permutation of the variables in the permutations dict. It should return True for valid a combination of permutation values and False for an i...
def get_new_attributes(existing_attributes, changed_attributes): """ >>> existing_attributes = {'a': 1, 'b': 2, 'c': 3} >>> changed_attributes = {'a': 6, 'c': 'x,y'} >>> get_new_attributes(existing_attributes,changed_attributes) \ == {'b': 2, 'c': 'x,y', 'a': 6} True """ new_attribut...
def fitness_func(loci, **kwargs): """ Return if the tip can go to the point (3, 1). Notes ----- It is a minimization problem. Best possible score is 0. Worst score is float('inf'). """ # Locus of the Joint 'pin" tip_locus = tuple(x[0] for x in loci)[0] return (tip_locus[0] -...
def apriori_next_candidate(pre_frequent, k): """Generate k+1 size of frequent item set candidate from previous level :parameter pre_frequent: previous level of frequent item set :type pre_frequent: list of tuple :parameter k: size of candidate :type k: int :return candidate_list: candidate list ...
def getenditem(obj=None,keypath=""): """return the item on the end of `keypath` of `obj`; >>> getenditem() == None True >>> getenditem(attrsview) == attrsview True >>> getenditem(attrsview,'name/') == 'attrsview' True >>> getenditem(attrsview,'name/format/') == attrsview.name.format ...
def parseGoal(goal, d, domain): """Parses user goal into dictionary format.""" goal[domain] = {} goal[domain] = {'informable': [], 'requestable': [], 'booking': []} if 'info' in d['goal'][domain]: if domain == 'train': # we consider dialogues only where train had to be booked! ...
def avg(vals, count=None): """ Returns the average value Args: vals: List of numbers to calculate average from. count: Int of total count that vals was part of. Returns: Float average value throughout a count. """ sum = 0 for v in vals: sum += v if count is...