content
stringlengths
42
6.51k
def increment_string(string, sep="_"): """Make a string unique by adding a number at the end of it, or increment that number if it does exist """ res = string.split(sep) try: inc = int(res[-1]) inc += 1 res.pop(-1) except ValueError: inc = 1 res.append(str...
def len_or_not(x) -> int: """Len of x or -1 if x has no len method""" if isinstance(x, str): # in this kata a string is NOT an ARRAY of chars. return -1 try: return len(x) except TypeError: return -1
def lookup_by_href_or_nickname(href, nickname, find_function): """ Helper to retrieve items by href or nickname :param href (optional): String of the item href :param nickname (optional): String of the item nickname :param find_function: The function to use to find by nickname :return: String o...
def steering3(course, power): """ Computes how fast each motor in a pair should turn to achieve the specified steering. Compared to steering2, this alows pivoting. Input: course [-100, 100]: * -100 means turn left as fast as possible (running left ...
def get_ssh_command(public_ip, user=None, proxyjump=None, flag=None): """ Return SSH command """ command = ['ssh'] if proxyjump: command.extend(['-J %s' % (proxyjump.strip())]) if flag: command.extend([flag.strip()]) if user: command.extend(['%s@%s' % (user, public_ip)])...
def normalizeValue(v, triple): """Normalizes value based on a min/default/max triple. >>> normalizeValue(400, (100, 400, 900)) 0.0 >>> normalizeValue(100, (100, 400, 900)) -1.0 >>> normalizeValue(650, (100, 400, 900)) 0.5 """ lower, default, upper = triple if not (lower <= defaul...
def _ParseClustering(clustering_fields=None): """Parses clustering from the arguments. Args: clustering_fields: Comma-separated field names. Returns: Clustering if any of the arguments is not None, otherwise None. Special case if clustering_fields is passed in as an empty string instead of None, ...
def pathappend(base, suffix, sep='/'): """Appends a path component to a base file path or URL. Like os.path.join, but always treats the suffix as a relative path. The separator can be any single character, by default `/`. >>> pathappend('http://example.com/api', 'test/') 'http://example.com/api/te...
def is_not_integer(input_messages): """Check if all elements are integers""" for message in input_messages: if not isinstance(message, int): return True return False
def guide_component_diff(guideA, guideB): """Components matching report. Compare guide "A" components, against guide "B" components. Considering A the guide that we want to check and B the guide used as a checker. Return a dictionary with marching components, missing components and extra component...
def render_build_args(options, ns): """Get docker build args dict, rendering any templated args.""" build_args = options.get('buildArgs', {}) for key, value in build_args.items(): build_args[key] = value.format(**ns) return build_args
def merge_and_dedup(*dicts): """ returns a deeply merged dict - any items that are not identical are turned into sets. """ out = {} for d in dicts: for k, v in d.items(): if k in out: if type(out[k]) == dict: out[k] = merge_and_dedup(out[k], v)...
def longest_increasing_subsequence(_list): """ The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for [10, 22, 9, 33, 21, 50, 41, 60...
def guess_linux(buff): """ linux heuristics 0x8: one of SCE 0x1C:0x1F (urb status): 0 => success, almost always windows: """ if len(buff) < 0x30: return False return sum(buff[0x1C:0x20]) == 0
def make_allowed_registries(registry_list): """ turns a list of wildcard registries to allowedRegistriesForImport json setting """ return { "allowedRegistriesForImport": [ {'domainName': reg} if isinstance(reg, str) else reg for reg in registry_list ] }
def throttling_mod_func(d, e): """Perform the modular function from the throttling array functions. In the javascript, the modular operation is as follows: e = (e % d.length + d.length) % d.length We simply translate this to python here. """ return (e % len(d) + len(d)) % len(d)
def linear_multiplicative_cooling( step: int, # Current step in annealing schedule t0: float, # Initial temperature t1: float, # Final temperature num_steps: int, # Number of steps in annealing schedule alpha=None, # Custom multiplicative sc...
def compare_digest(x, y): """Create a hmac comparison. Approximates hmac.compare_digest (Py 2.7.7+) until we upgrade. """ if not (isinstance(x, bytes) and isinstance(y, bytes)): raise TypeError("both inputs should be instances of bytes") if len(x) != len(y): return False result ...
def set_file_ext(ext: str): """Set the filename suffix(extension) """ global _EXT _EXT = ext return _EXT
def match_variable(var, replacement, bindings): """Bind the input to the variable and update the bindings.""" binding = bindings.get(var) if not binding: # The variable isn't yet bound. bindings.update({var: replacement}) return bindings if replacement == bindings[var]: #...
def lyap_lrcf_solver_options(lradi_tol=1e-10, lradi_maxiter=500, lradi_shifts='projection_shifts', projection_shifts_z_columns=1, projection_shifts_init_maxiter=20, projection...
def point_add(P1, P2): """ Add ``secp256k1`` points. Args: P1 (:class:`list`): first ``secp256k1`` point P2 (:class:`list`): second ``secp256k1`` point Returns: :class:`list`: ``secp256k1`` point """ if (P1 is None): return P2 if (P2 is None): return P...
def is_sequence(arg): """ Determine if the given arg is a sequence type """ return (not hasattr(arg, "strip") and hasattr(arg, "__getitem__") or hasattr(arg, "__iter__"))
def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None): """Generate common filters for any list request. :param marker: entity ID from which to start returning entities. :param limit: maximum number of entities to return. :param sort_key: field to use for sorting. :param sort_dir...
def method_test(**request): """ Method is expected to be mangled based on HB rules in this example. """ return {"original_request": request}
def get_provider_tag_name(tag_name): """ :param str tag_name: :return: """ return 'cloudshell-{}'.format(tag_name)
def MAGENTA(obj): """Format an object into string of magenta color in console. Args: obj: the object to be formatted. Returns: None """ return '\x1b[1;35m' + str(obj) + '\x1b[0m'
def relationship(model, type): """Returns the model's relationship to a given attached metadata type, or None if none exists. """ return getattr(model, type + '_entries', None)
def to_ascii(text): """Convert text to ascii.""" asciiText = ''.join([ch if ord(ch) < 128 else ' ' for ch in text]) return asciiText
def cool_number(value, num_decimals=6): """ Django template filter to convert regular numbers to a cool format (ie: 2K, 434.4K, 33M...) :param value: number :param num_decimals: Number of decimal digits """ int_value = int(value) formatted_number = '{{:.{}f}}'.format(num_decimals) i...
def serialize_attractor(info): """Turn an attractor (in describe_attractor format) into an object tree that can be serialized to JSON.""" if isinstance(info, dict): for species in info['species']: ftpeaks = list(species['ftpeaks'].items()) species['peaks'] = [int(fp[0]) for fp in...
def get_col_name(position): """ Return the column name like EXCEL is using in function of the position A, B, C, ..., Z, AA, AB, ..., AZ, BA, ..., BZ, CA, ... :param position: """ position = int(position) quotient = position / 26 remainder = position % 26 if position < 0: ret...
def is_GLIBC_ref(S): """ Return True is S looks like a reference to GLIBC as typically found in Elfs. """ return '@@GLIBC' in S
def get_default_suggestion(parameter, options): """ Provide default values for parameters without one defined in the config file. Note that options is assumed to be a list, tuple, or None. """ # For these parameters, steer users towards a default value rather than selecting the first # from the...
def arg_find_list(x, target, n=1, which='first'): """ Find the position of target elements in list :param x: a list :param target: target element :param n: how much elements needed to be find :param which: first or last :return: position Example: >>>x = [1, 2, 1, 3] ...
def __convert_to_lower_case__(text): """ Converts the specified text to lower case :param text: the text to convert :return: the lower cased text """ return " ".join(text.lower() for text in text.split())
def get_auto_name(name: str, rnn_layers: int, rnn_size: int, rnn_bidirectional=False, rnn_type='lstm') -> str: """Generate unique name from parameters""" model_name = f"{name}_{rnn_layers}l{rnn_size}" if rnn_bidirectional: model_name += 'bi' if rnn_type == 'gru': model_name += '_gru' ...
def prepare_model_fields(list_fields=None): """ Adds the extra keys needed for the response on the model :param list_fields: :return fields: Updated list of properties picked from a object to create the response """ # Default fields fields = ['slug', 'name', 'description', 'created_at'] ...
def _knapsack_1(limit, vs, ws): """ This is an O(pow(2, n)) inefficeint solution that uses recursion """ def _knapsack(limit, vs, ws, i): if limit == 0 or i == len(vs): return 0 accept, reject = 0, _knapsack(limit, vs, ws, i + 1) if ws[i] <= limit: acc...
def period(n): """ Divide entre x*=10 hasta encontrar un numero en el denominador que se repite. Basado en que el periodo no puede ser algo como 112233 o 1231234. Es decir, que cuando se repite un numero en el denominador es que ya inicio la siguiente secuencia """ me...
def neutron_public_url(catalog): """Get Neutron publicURL""" for i in catalog['access']['serviceCatalog']: if i['name'] == 'neutron': for endpoint in i['endpoints']: return endpoint['publicURL']
def decrease_parameter_closer_to_value(old_value, target_value, coverage): """ Simple but commonly used calculation for interventions. Acts to decrement from the original or baseline value closer to the target or intervention value according to the coverage of the intervention being implemented. Args: ...
def create_metadata(title, comment='', author=None): """Creates metadata for video. Args: title (string): title of the video comment (string): comment of the video author (strin): author of the video Returns: dict """ author = 'https://github.com/narimiran' if autho...
def make_zipf(length): """Returns a list of counts that follows a Zipf distribution. Args: length: the number of counts to be generated Returns: A list of the provided length of floating point numbers corresponding exactly the zipf distribution. For example, for length=5: ...
def comma(value: str) -> str: # Only one argument. """Converts a string into all lowercase""" value = f'{float(value):.2f}' return value.replace('.', ',')
def safe_pathname(filename: str) -> str: """Generate a safe pathname out of the string passed""" return "".join( [c for c in filename if c.isalpha() or c.isdigit() or c == " "] ).rstrip()
def extract_model_configs(full_entry): """ Given a full entry, extract model configurations and put into a dict. """ model = ["ico_encoder", "article_encoder", "attn", "cond_attn", "tokenwise_attention", "pretrain_attention", "tune_embeddings", "no_pretrained_word_embeddings"] pr...
def part2(captcha): """ >>> part2("1212") 6 >>> part2("12131415") 4 >>> part2(read_input()) 1220 """ half = len(captcha) // 2 rotated = captcha[half:] + captcha[:half] total = 0 for (a, b) in zip(captcha, rotated): if a == b: total += int(a) ret...
def guess_type_value_type(none=True): """ @param none if True and all values are empty, return None @return the list of types recognized by guess_type_value """ typstr = str return [None, typstr, int, float] if none else [typstr, int, float]
def bin2signedint(x,N=16): """ Converts an string with a binary number into a signed integer """ i = int(x,2) if i>=2**(N-1): i=i-2**N return i
def true_positives(T, X, margin=5): """Compute true positives without double counting >>> true_positives({1, 10, 20, 23}, {3, 8, 20}) {1, 10, 20} >>> true_positives({1, 10, 20, 23}, {1, 3, 8, 20}) {1, 10, 20} >>> true_positives({1, 10, 20, 23}, {1, 3, 5, 8, 20}) {1, 10, 20} >>> true_posi...
def alist_get(data, key): """Look up a value in an association list.""" for item in data: if item[0] == key: return item[1] raise KeyError(key)
def nix_header(pot_file): """Nix the POT file header since it changes and we don't care""" return pot_file[pot_file.find('\n\n')+2:]
def format_count(threads: int, messages: int) -> str: """Format the count of threads and messages.""" if threads == messages: return str(threads) if threads else "" return f"{threads} ({messages})"
def qtile(a, ir): """ This routine returns the ith entry of vector after sorting in descending order. Parameters ---------- a : list Input data distribution. ir : int Desired percentile. Returns ------- qtile : float Percentile value. """ as_sor...
def fact(x:int): """Recursive call stack example.""" # Begin call stack with current function if x == 1: # Resume completion of current function, exit recursion, and return 1 return 1 # Continue execution of current function else: # Pause completion of function and add recurs...
def flatten(lis): """ Given a list, possibly nested to any level, return it flattened. From: http://code.activestate.com/recipes/578948-flattening-an-arbitrarily-nested-list-in-python/ >>> flatten([['wer', 234, 'brdt5'], ['dfg'], [[21, 34,5], ['fhg', 4]]]) ['wer', 234, 'brdt5', 'dfg', 21, 34, 5, 'f...
def contains_whitespace(row): """Gets the total number of whitespaces from each column of a row""" return sum([" " in i for i in row if isinstance(i, str)])
def _prune_bifixes(set_of_words): """ Remove words from a set that are proper prefixes or suffixes of another word Example ------- >>> set_of_words = {'aba', 'a', 'aaba'} >>> _prune_bifixes(set_of_words) {'aaba'} """ cleaned = set() bad_words = set() for elem1 in set_of_word...
def reverse_str(s): """Reverses the words in a sting and returns the new string to the caller. A word in this context is defined as any space seperated sequence of non-whitespace characters. """ s_list = s.strip().split(' ') s_list.reverse() rs = '' for word in s_list: rs = rs + ...
def find_free_tag_column(tags): """ When user adds a new tag, identifies an empty db column & returns the column's name. """ that_tag_column = "" counter = 0 for tag in tags: counter += 1 if tag == None: that_tag_column = "tag" + str(counter) break ...
def find_message(text: str) -> str: """Find a secret message""" # return "" # return reduce(lambda x: x + x,(x for x in str if str.isupper(x)==true) y = '' for x in text: if x.isupper(): y = y + x return y
def strip_code_markup(content: str) -> str: """ Strips code markup from a string. """ # ```py # code # ``` if content.startswith('```') and content.endswith('```'): # grab the lines in the middle return '\n'.join(content.split('\n')[1:-1]) # `code` return content.strip('` \n...
def _listXform(line): """ Parse a line of the response to a LIST command. The line from the LIST response consists of a 1-based message number followed by a size. @type line: L{bytes} @param line: A non-initial line from the multi-line response to a LIST command. @rtype: 2-L{tuple...
def get_relation_id(relation): """Return id attribute of the object if it is relation, otherwise return given value.""" return relation.id if type(relation).__name__ == 'Relation' else relation
def get_mouse_from_id(mouse_id: int): """because mice_id are stored as int in datafile, they must be transformed back to the original names""" return 'M' + str(mouse_id)[:2]
def expand_args_to_list(args,type_=int): """ it generates a list of args from a sequence like 1,3,5 or 3-7 """ result = [] for arg in args.split(',' in args and ',' or ' '): if type_ is int and '-' in arg: vals = [type_(v) for v in arg.split('-',1)] result.extend(range(*(vals[0],vals[1]+1))) e...
def _is_int(string_inp: str) -> bool: """Method to check if the given string input can be parsed as integer""" try: int(string_inp) return True except ValueError: return False
def address_area_or_none(address_area): """ Get Formatted Address Area Result :param address_area: Address object returned on Company :return: Address as an id name object or None """ if address_area: return { 'id': str(address_area.id), 'name': address_area.name,...
def parameter_list_as_string(parameters): """ Input list of parameters Turn this into a string for display E.g. """ if parameters is None: return "" elif not isinstance(parameters, list): raise Exception("Unexpected parameter list %s" % (parameters,)) else: ...
def get_new_breakpoint(slope, x_intercept, max_available) -> float: """Compute new (lower/upper) breakpoint""" # Y-axis intercept try: y_intercept = -slope * x_intercept return (max_available - y_intercept) / slope # If line is vertical or horizontal, return original x-intercept ex...
def converg_kwargs(**kwargs): """Unpack keyword arguments related to monitor convergence.""" ndisplay = kwargs.get("nDisplay", 10) return ndisplay
def GetModelDir(options): """Returns the model directory for a given model.""" model_dir = "" if options["gan_type"] in ["MultiGAN", "MultiGANBackground"]: if options["n_blocks"] == 0 and options["n_heads"] == 0: model_dir = "Independent" model_dir += "%s-%d" % (options["gan_type"], options["k"]) ...
def get_exposed_resources(resource_dict, review_settings): """Compute a set of resources to be shown as part of the server's capabilities. This should include review settings for each resource but nothing related to the actual signing parameters for those resources.""" out = [] for resource in reso...
def get_postgres_insert_into(table_name, enable_mvcc=False): """ Get an INSERT INTO query compatible with `psycopg2.extras.execute_values` (to support bulk loading). """ if enable_mvcc: return "INSERT INTO {} (subject,predicate,object) VALUES %s".format(table_name) return "INSERT INTO {}...
def matrix_multiply_naive(A, B): """Square matrix multiplication by naive algorithm. Time complexity: O(n^3) Space complexity: O(n^3) """ n = len(A) C = [[0 for j in range(n)] for i in range(n)] for i in range(n): for j in range(n): for k in range(n): C[i...
def get_non_link_props(props): """Return subset of iterable props that are not links.""" return [val for val in props if '.' not in val]
def gen_key_i(i, kappa, K): """ Create key value where key = kappa, except for bit i: key_(i mod n) = kappa_(i mod n) XOR K_(i mod n) Parameters: i -- integer in [0,n-1] kappa -- string K -- string Return: key -- list of bool """ # Transform string into list of booleans kappa = list(kappa) kappa...
def intensity_perpendicular_from_anisotropy(Aniso, Fluo): """ Calculate perpendicular intensity from anisotropy and total fluorescence. """ return (1/3)*Fluo*(1-Aniso)
def beale(position): """ optimum at (3.0, 0.5) = 0 :param position: :return: """ x, y = position # x = 10**x # y = 10**y return (1.5 - x + x * y) ** 2 + (2.25 - x + x * y ** 2) ** 2 + (2.625 - x + x * y ** 3) ** 2
def buildHeap(q_chain, n): """ buildHeap(q_chain, n) - recursive method to generate all permutations of 0,1 of length n """ if len(q_chain) < n: q_chain_part0 = buildHeap(q_chain + [0],n) q_chain_part1 = buildHeap(q_chain + [1],n) if isinstance(q_chain_...
def crc16(string, value=0): """CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1 @param string: Data over which to calculate crc. @param value: Initial CRC value. """ crc16_table = [] for byte in range(256): crc = 0 for _ in range(8): if (byte ^ crc) & 1: ...
def GetMrk(idx=0, scheme=1): # marker """ Get marker ========== """ if scheme==1: M = ['o', '^', '*', 'd', 'v', 's', '<', '>', 'p', 'h', 'D'] else: M = ['+', '1', '2', '3', '4', 'x', '.', '|', '', '_', 'H', '*'] return M[idx % len(M)]
def search_for_project(project): """Generate a string search key for a project""" elements = [] elements.append(project['name_with_namespace']) elements.append(project['path_with_namespace']) return u' '.join(elements)
def get_ticket_url_from_id(ticket_id): """ Get the associate ticket id :param ticket_id: `str` ticket_id :return: `str` ticket url """ return "https://jira.com/id={0}".format(ticket_id)
def render_result(result): """Returns html where `result` is a listing dictionary.""" rendered = "" for key, value in result.items(): rendered += "<b style='font-size=14px'>%s</b>: %s<br>" % (key, value) return rendered
def code_block(text): """Create a markdown formatted code block containing the given text""" text = '\n' + text for char in ['\n', '\r']: text = text.replace(char, '\n ') return text
def texlogo(input, word): """Replace word with a logo version""" return input.replace(word, u'\\Logo{%s}' % (word))
def convert(value, type_): """Return the value converted to the type, or None if error. ``type_`` may be a Python type or any function taking one argument. """ try: return type_(value) except Exception: return None
def dict_delete(a: dict, b: dict): """Elements that are in a but not in b""" return [k for k in a if k not in b]
def make_combos(first_list, second_list): """provides a list which is a combination of one item from given lists""" combo_list = [] for first_item in first_list: for second_item in second_list: combo_list.append([first_item, second_item]) return combo_list
def rgba2hex(rgba): """Convert RGB to #hex""" return '#' + ''.join(['%02x' % int(x*255) for x in rgba])
def parse_time(string: str): """ Converts hh:mm:ss string to float """ hh, mm, ss = string.split(":") return float(int(hh) * 3600 + int(mm) * 60 + int(ss))
def attrs_union(attrs1, attrs2): """Find a union of two dictionaries with attrs.""" if attrs1 is None: if attrs2 is not None: return attrs2 else: return {} if attrs2 is None: return attrs1 res = dict() for key in attrs1: if key in attrs2: ...
def get_attribute(obj, key): """ Get an attribute from an object, regardless of whether it is a dict or an object """ if not isinstance(obj, dict): return getattr(obj, key) return obj[key]
def object_in_list(obj, l): """Returns True if object o is in list. Required compatibility function to handle WeakSet objects. """ for o in l: if o is obj: return True return False
def read_varint(readfn): """ Reads a variable-length encoded integer. :param readfn: a callable that reads a given number of bytes, like file.read(). """ b = ord(readfn(1)) i = b & 0x7F shift = 7 while b & 0x80 != 0: b = ord(readfn(1)) i |= (b & 0x7F) << sh...
def _clean_dna(dna_seq): """ This function removes any characters from the dna string if it is not A, G,C,T :param dna_seq: input dna sequences (string) :return: """ return ''.join(c for c in dna_seq.lower() if c in 'agct')
def srgb_to_linear(c): """Convert SRGB value of a color channel to linear value.""" assert 0 <= c <= 1 if c <= 0.03928: return c /12.92 else: return ((c + 0.055) / 1.055)**2.4
def datedDirPath(buildid, milestone): """ Returns a string that will look like: 2009/12/2009-12-31-09-mozilla-central """ year = buildid[0:4] month = buildid[4:6] day = buildid[6:8] hour = buildid[8:10] datedDir = "%s-%s-%s-%s-%s" % (year, month...