content
stringlengths
42
6.51k
def get_secret(str_or_list): """ Find and returns mail secret. Mail secret uses following format: SECRET{ some-secret } note that there are no spaces between all capitalized keyword SECRET and immediately following it curly brackets. However, the text inside curly brackets can be surr...
def has_docstring(func): """Check to see if the function `func` has a docstring. Args: func (callable): A function. Returns: bool """ ok = func.__doc__ is not None if not ok: print("{} doesn't have a docstring!".format(func.__name__)) else: print(...
def is_hidden(var, X, e): """Is var a hidden variable when querying P(X|e)?""" return var != X and var not in e
def __highlight_function__(feature): """ Function to define the layer highlight style """ return {"fillColor": "#ffaf00", "color": "green", "weight": 3, "dashArray": "1, 1"}
def _call_with_frames_removed(func, *args, **kwds): """ remove_importlib_frames in import.c will always remove sequences of importlib frames that end with a call to this function Use it instead of a normal call in places where including the importlib frames introduces unwanted noise into the traceba...
def appendUrl(baseUrl, appendedPath): """ Concatinates 2 url paths, eliminating the trailing / from the first one, if required. This function is not compatible with query paramters or anything other than urlpaths. baseUrl (str): The base url to be appended to. appendedPath (str): The appended por...
def infixe(arbre): """Fonction qui retourne le parcours prefixe de l'arbre sous la forme d'une liste """ liste = [] if arbre != None: liste += infixe(arbre.get_ag()) liste.append(arbre.get_val()) liste += infixe(arbre.get_ad()) return liste
def LowercaseMutator(current, value): """Lower the value.""" return current.lower()
def OffsetPosition(in_ra,in_dec,delta_ra,delta_dec): """ Offset a position given in decimal degrees. Parameters ---------- in_ra: float Initial RA (decimal degrees). in_dec: float Initial DEC (demical degrees). delta_ra: float Offset in RA (decimal degrees). ...
def GetRateURL(base, symbols, date="latest"): """Create the URL needed to access the API. For a date and chosen currencies.""" url = "http://api.fixer.io/%s?base=%s&symbols=%s" % (date, base, symbols) return url
def is_code_line(line): """A code line is a non empty line that don't start with #""" return line.strip()[:1] not in {'#', '%', ''}
def clamp(n, range): """ Given a number and a range, return the number, or the extreme it is closest to. :param n: number :param range: tuple with min and max :return: number """ minn, maxn = range return max(min(maxn, n), minn)
def IsWithinTMRegion(pos, posTM):#{{{ """Check whether a residue position is within TM region """ isWithin = False for (b,e) in posTM: if pos >= b and pos < e: return True return False
def normalization(value, maxvalue, minvalue): """ normalization method """ value = (value - minvalue) / (maxvalue - minvalue) return value
def parenthesize(digitList): """ For each digit x in the digit list, this method adds x parenthesis before and after the digit. It returns the new list. """ parenthesizedList = [] for x in digitList: parenthesizedList += ['(']*int(x) + [x] + [')']*int(x) return parenthesizedList
def find_next_square(sq): """ Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. If the parameter is itself not a perfect square, than -1 should be returned. You may assume the parameter is positive. :param sq: a positive integer. ...
def split_rpm_filename(rpm_filename): """ Parse the components of an rpm filename and return them as a tuple: (name, version, release, epoch, arch) foo-1.0-1.x86_64.rpm -> foo, 1.0, 1, '', x86_64 1:bar-9-123a.ia64.rpm -> bar, 9, 123a, 1, ia64 :param rpm_filename: a string filename (not path) of an...
def _smallest_size_at_least(height, width, smallest_side): """Computes new shape with the smallest side equal to `smallest_side`. Computes new shape with the smallest side equal to `smallest_side` while preserving the original aspect ratio. Args: height: an int32 scalar indicating the current heig...
def apply_fn_to_list_items_in_dict(dictionary, fn, **kwargs): """ Given a dictionary with items that are lists, applies the given function to each item in each list and return an updated version of the dictionary. :param dictionary: the dictionary to update. :param fn: the function to apply. ...
def split_reversible_reactions(crn): """ Replace every reversible reaction with the two corresponding irreversible reactions. """ new = [] for [r, p, k] in crn: assert len(k) == 1 or len(k) == 2 new.append([r, p]) if len(k) == 2: new.append([p, r]) return ...
def celsius_to_fahrenheit(celsius: float) -> float: """Convert degrees Celsius to degrees Fahrenheit :param float celsius: a temperature in Celsius :return: a temperature in Fahrenheit :rtype: float """ return celsius * 9.0/5.0 + 32.0
def calculate_diagnol_periphery_73251a56(i, j, y, diagonol): """Looking at 6 directions to the current y[i,j] location which is not equal to the diagonal element and append it to the list""" near_diagnol_element = [] if (y[i + 1][j] != 0 and y[i + 1][j] != diagonol): near_diagnol_element.append(...
def params_to_mongo(query_params): """Convert HTTP query params to mongodb query syntax. Converts the parse query params into a mongodb spec. :param dict query_params: return of func:`rest.process_params` """ if not query_params: return {} for key, value in query_params.items(): ...
def function_with_types_in_docstring(param1, param2): """Compare if param1 is greater than param2. Example function with types documented in the docstring. Function tests if param1 is greater than param2 (True) otherwise returns False. `PEP 484`_ type annotations are supported. If attribute, para...
def search_box(display_mode, query_params, user, *args, **kwargs): """ Template tag to render the search box. """ return { "display_mode": display_mode, "GET_params": query_params, "user": user, }
def parse_video_time_format(s, fps=30.): """ Format MM:SS.f """ m, sf = s.split(":") m = float(m) s, f = [float(x) for x in sf.split(".")] time_interval = m * 60. + s + 1. /fps * f return time_interval
def _translate_int(exp, length): """ Given an integer index, return a 3-tuple (start, count, step) for hyperslab selection """ if exp < 0: exp = length+exp if not 0<=exp<length: raise ValueError("Index (%s) out of range (0-%s)" % (exp, length-1)) return exp, 1, 1
def _partition(env_list, is_before): """partition the list in the list items before and after the sel""" before, after = [], [] iterator = iter(env_list) while True: try: item = next(iterator) except: break if is_before(item): before.append(ite...
def rivers_with_station(stations): """ Given a list of station objects, this function returns a set, with the names of the rivers with a monitoring station. """ rivers = set() for station in stations: rivers.add(station.river) return rivers
def get_labels(filename, logger=None): """Returns a dictionary of alternative sequence labels, or None - filename - path to file containing tab-separated table of labels Input files should be formatted as <key>\t<label>, one pair per line. """ labeldict = {} if filename is not None: if...
def f(x): """ A function. """ y = x + 10 return y
def _stringToList(str: str) -> list: """Convert a string containing endLine char into a list. """ l = [] s = '' for c in str: if c == '\n': l.append(s) s = '' else: s += c l.append(s) return l
def get_root(region_parent_zip, region_id): """ Return the penultimate `parent_id` for any `region_id`. The penultimate parent is one layer below the root (0). The set of penultimate parents are the distinct regions contained in the segmentation. They correspond to putative functional regions. ...
def get_all_manifests(image_assembly_config_json): """Returns the list of all the package manifests mentioned in the specified product configuration. Args: image_assembly_config_json: Dictionary, holding manifest per categories. Returns: list of path to the manifest files as string. Raises: KeyEr...
def _legacy_client_key_set(clients): """ Transform a set of client states into a set of client keys. """ return {cs.client_key for cs in clients}
def new_test(tag, name): """Create default, empty sub-test result objects :param tag: tag for resource being tested :param name: name of sub-test :return: sub-test object """ # init all status message to 'could not be executed' failures test = {'tag': tag, 'test': na...
def tags_to_spans(tags): """Convert tags to spans.""" spans = set() span_start = 0 span_end = 0 active_conll_tag = None for index, string_tag in enumerate(tags): # Actual BIO tag. bio_tag = string_tag[0] assert bio_tag in ["B", "I", "O"], "Invalid Tag" conll_tag = string_tag[2:] if bio_t...
def real(s): """Proper function from kata designer.""" head = s.rstrip('0123456789') tail = s[len(head):] if tail == "": return s+"1" return head + str(int(tail) + 1).zfill(len(tail))
def lat_dict_to_list(dct: dict) -> list: """Make a dictionary of lattice information to a 6-vector [a, b, c, alpha, beta, gamma].""" return [ dct[k] for k in ("a", "b", "c", "alpha", "beta", "gamma") ]
def replace_strings(s, replacers): """Performs a sequence of find-replace operations on the given string. Args: s: the input string replacers: a list of (find, replace) strings Returns: a copy of the input strings with all of the find-and-replacements made """ sout = s ...
def extract_num(buf, start, length): """ extracts a number from a raw byte string. Assumes network byteorder """ # note: purposefully does /not/ use struct.unpack, because that is used by the code we validate val = 0 for i in range(start, start+length): val <<= 8 val += ord(buf[i]) return val
def str_to_seconds(string): """Pocesses a string including time units into a float in seconds. Args: string (str): Input string, including units. Returns: float: The processed time in seconds. Examples: >>> int(round(str_to_seconds('1'))) 1 >>> int(round(str_to...
def to_square(coefficients): """ Computes f^2 and returns its coefficients, where f is a polynomial function given as a list of coefficients :param coefficients: list of coefficients of a polynomial function f :return result: list of coefficients of polynomial function f^2 """ result = [0 for nu...
def forward_differences(f, h, x): """ Forward Finite Differences. Approximating the derivative using the Forward Finite Method. Parameters: f : function to be used h : Step size to be used x : Given point Returns: Approximation """ return (f(x + h) - f(x)) / h
def sigmoid_pw(x): """A piecewise linear version of sigmoid.""" # Make use of sigmoid(-x) = 1 - sigmoid(x) positive = True if x < 0.: positive = False x = -x if x < 1.: y = 0.23105 * x + 0.50346 elif x < 2.: y = 0.14973 * x + 0.58714 elif x < 3.: y =...
def route_file_paths(fpaths,dir_src,dir_dst): """Convert list of files to src:dst maps, replacing src with dst filepath :param fpaths: list of globbed filepaths :param dir_src: filepath (str) :param dir_dst: filepath (str) :return: list of dicts with src:dst filepaths (str) """ return [ {'src': f, 'dst': ...
def complement_angle(angle): """ 90 minus angle, in degrees""" return 90 - angle;
def users_in_same_organization(user_one, user_two): """Returns true if the two users passed in belong to the same organization.""" if not hasattr(user_one, 'organization') or not hasattr(user_two, 'organization'): return False return user_one.organization == user_two.organization
def set_bit(current, epaddr, v): """ >>> bin(set_bit(0, 0, 1)) '0b1' >>> bin(set_bit(0, 2, 1)) '0b100' >>> bin(set_bit(0b1000, 2, 1)) '0b1100' >>> bin(set_bit(0b1100, 2, 0)) '0b1000' >>> bin(set_bit(0b1101, 2, 0)) '0b1001' """ if v: return current | 1 << epadd...
def closed_range(start: int, stop: int, step=1) -> range: """ Creates a closed range that allows you to specify a case from [start, stop] inclusively. ``` with switch(value) as s: s.case(closed_range(1, 5), lambda: "1-to-5") s.case(closed_range(6, 7), lambda: "6") ...
def letterMatch(letter, alphalist, letterlist, hanglist): """Hangman letter test with logic for no retries of prior submitted letters. Return True if match, False if no match, or None if invalid letter.""" ch = letter[0] if (str == type(letter)) and (0 < len(letter)) else None fmatch = None if ...
def first_or_default(iterable, predicate=None, default=None): """First the first value matching a perdicate otherwise a default value. :param iterable: The items over which to iterate. :param predicate: A predicate to apply to each item. :param default: The value to return if no item matches. :retu...
def match_strings(str1, str2): """ Returns the largest index i such that str1[:i] == str2[:i] """ i = 0 min_len = len(str1) if len(str1) < len(str2) else len(str2) while i < min_len and str1[i] == str2[i]: i += 1 return i
def sizeof_fmt(num, suffix='B'): """Size to human readable format. From stack overflow. """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def invert(n): """Return 1 if n is 0, 0 if n is 1, otherwise n.""" if n == 0: return 1 elif n == 1: return 0 else: # NaN case return n
def create_ant(var_num): """ :param var_num: number of variables needed for the obj.function :return: a combined list of 2 elements. Element 0 is the path as a list. Element 1 is the obj. value. """ path = [] #for initial values we believe the ants chose the 0-th discrete value. (count...
def quantify(iterable, pred=bool): """Count the number of items in iterable for which pred is true.""" return sum(1 for item in iterable if pred(item))
def get_boolean(entry): """ This function ... :param entry: :return: """ return entry == "True"
def reverse_seq(seq): """(str) -> str Return reverse complement of sequence (used for writing rev comp sequences to fastq files). >>> reverse_seq('TCAGCATAATT') 'AATTATGCTGA' >>> reverse_seq('ACTGNN') 'NNCAGT' """ rev_comp = '' nuc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'...
def phred(q): """Convert 0...1 to 0...30 No ":". No "@". No "+". """ n = int(q * 30 + 33) if n == 43: n += 1 if n == 58: n += 1 return chr(n)
def unique(L): """ L is a list Return unique elements in L """ unique = [] for i in L: if i not in unique: unique.append(i) return unique
def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: O(n) Space Complexity: O(n) """ if num ==0: raise ValueError if num == 1: return '1' p = [0,1,1] for i in range(3, num+1): sum = p[p[...
def calculate_condensate_params(Rvi, Bgi): """ Calculate theoretically the undefined properties of gas-condensate (Bo, Rs) Input: Rvi: initial Rv, float Bgi: initial Bg, float Output: Rsi: initial Rs, float Boi: initial Bo, float """ Rsi = 1 / Rvi Boi = Rsi * Bgi retu...
def bytes_to_hexstr(value, start='', sep=' '): """Return string of hexadecimal numbers separated by spaces from a bytes object.""" return start + sep.join(["{:02X}".format(byte) for byte in bytes(value)])
def pow_mod(n, k, mod): """ Exponentiation by squaring :return: n ** k """ if k == 0: return 1 elif k & 1 == 1: return pow_mod(n, k - 1, mod) * n % mod else: tmp = pow_mod(n, k // 2, mod) return tmp * tmp % mod
def get_valid_macs(data): """Get a list of valid MAC's from the introspection data.""" return [m['mac'] for m in data.get('all_interfaces', {}).values() if m.get('mac')]
def integer_bit_length_shift_counting(num): """ Number of bits needed to represent a integer excluding any prefix 0 bits. :param num: Integer value. If num is 0, returns 0. Only the absolute value of the number is considered. Therefore, signed integers will be abs(num) before the number's bit...
def bytes_to_string(_bytes) -> str: """Decodes bytes to utf-8 string Args: _bytes (bytes): bytes value Returns: str .. todo:: We're not decoding the string here, because it fails for certain windows commands """ value = str(_bytes.replace(b"\x00", b""))[2:-1].replace("...
def quit(msg=''): """Return a valid QUIT message with an optional reason.""" return 'QUIT :%s' % msg
def rot2omega(rot,twotheta,ccwrot): """ sign dependent determination of omega from rot and twotheta """ if ccwrot: return(rot-twotheta/2.0) else: return(-rot-twotheta/2.0)
def _get_all_authors(commits_info): """ Returns all authors' information The information includes name and Email """ authors_unduplicated = [{'name': commit_info['author'], 'email': commit_info['authorEmail']} for commit_info in commits_info] all_names = [] authors...
def argToInt(value): """ Given a size or addresse of the type passed in args (ie 512KB or 1MB) then return the value in bytes. In case of neither KB or MB was specified, 0x prefix can be used. """ for letter, multiplier in [("k", 1024), ("m", 1024 * 1024), ("kb", 1024), ("mb", 1024 * 1024), ]: i...
def number_of_short_term_peaks(n, t, t_st): """ Estimate the number of peaks in a specified period. Parameters ---------- n : int Number of peaks in analyzed timeseries. t : float Length of time of analyzed timeseries. t_st: float Short-term period for which to estim...
def all_equal(elements): """return True if all the elements are equal, otherwise False. """ first_element = elements[0] for other_element in elements[1:]: if other_element != first_element: return False return True
def search_boolean(search_query, forward_index, inverted_index, documents_id): """Search the words of search_query in inverted index :param str search_query: normilized with stemming :param dict forward_index: :param dict inverted_index: :param list of str documents_id: :return list of...
def slices_overlap(slice_a, slice_b): """Test if the ranges covered by a pair of slices overlap.""" assert slice_a.step is None assert slice_b.step is None return max(slice_a.start, slice_b.start) \ < min(slice_a.stop, slice_b.stop)
def flatten(some_list): """ Flatten a list of lists. Usage: flatten([[list a], [list b], ...]) Output: [elements of list a, elements of list b] """ new_list = [] for sub_list in some_list: new_list += sub_list return new_list
def _assert_int(num): """ Tries to parse an integer num from a given string :param num: Number in int/string type :return: Numeric value """ if isinstance(num, int): return num num_str = str(num) radix = 16 if num_str.lower().startswith('0x') else 10 res = int(num_str, radix...
def __int_to_binary_char__(char_as_ord): """converts ordinal char represenation to binary string, e.g. b'x'. It is used for parametrized test because the chars are passed as integers. """ return chr(char_as_ord).encode()
def ruby_strip(chars): """Strip whitespace and any quotes.""" return chars.strip(' "\'')
def eh_tabuleiro(tab): """ eh_tabuleiro recebe um argumento de qualquer tipo e devolve True se o argumento corresponder a um tabuleiro (ou seja, um tuplo com 3 tuplos em que cada um deles contem um inteiro igual a -1, 1 ou 0), caso contrario devolve False. """ if not type(tab)==tuple:...
def get_prg_ids(prg_num: int, c_addrs: str, curr_text: str, ids_row: list) -> bool: """ Function that generates indices of points in PRG table matching current text """ # Definiujemy podstawowe parametry c_start = 0 found_flag = False empty_idx = ids_row.index('') for i in range(prg_num): ...
def construct_url(uri, bbox, srs, size, image_format, styles, layers): """Constructing URL for retrieving image from WMS Server.""" full_uri = uri full_uri += '&BBOX=%s' % ",".join(map(str, bbox)) full_uri += '&SRS=%s' % srs full_uri += '&HEIGHT=%d&WIDTH=%d' % size full_uri += '&TRANSPARENT=true...
def sums(a,b,c): """ :param a: (float) Varaible a sumar. :param b: (float) Varaible b a sumar. :param c: (float) Variable c a sumar. :return d: (float) a+c. :return e: (float) a+b+c """ d = a + c e = a + b +c return d, e
def convert_to_bool(string): """ Convert a string passed in the CLI to a valid bool. :return: the parsed bool value. :raise ValueError: If the value is not parsable as a bool """ upstring = str(string).upper() if upstring in ['Y', 'YES', 'T', 'TRUE']: return True if upstring in...
def Dic_Remove_By_Subkeylist(indic,keylist): """ Return a new dic, with key/value pairs present in keylist removed. """ outdic=indic.copy() for key in outdic.keys(): if key in keylist: del outdic[key] return outdic
def purge(data): """ Removes all data entries with a blank game name. :param data: the data read from titlekeys.json :type data: list :returns: the data devoid of entries having blank game names :rtype: list """ return [d for d in data if d.get("name")]
def mapAddress(name): """Given a register name, return the address of that register. Passes integers through unaffected. """ if type(name) == type(''): return globals()['RCPOD_REG_' + name.upper()] return name
def writeConfig(xyTuple): """Creates a config file (config.py) and writes 4 values into it Arguments: xyTuple: a tuple of structure (xMin, xMax, yMin, yMax) """ outfile = open("config.py","w") outfile.write("X_MIN="+str(xyTuple[0])+"\n") outfile.write("X_MAX="+str(xyTuple[1])+"\n") outfile.write("Y_MIN="+s...
def get_correlative(vector, index): """Get correlative item in vector, e.g. get_correlative([3, 45, 6], 11) => 6""" return vector[index % len(vector)]
def is_table_mask(line: str) -> bool: """Decide whether or not a string is a table mask. A table mask starts with an indentation, then a '!' character, and then a mixture of ' ' and '-' """ return ( line.startswith(" ") and line.lstrip().startswith("!") and "-" in line ...
def pick_wm_class_0(tissue_class_files): """ Returns the csf tissu class file from the list of segmented tissue class files Parameters ---------- tissue_class_files : list (string) List of tissue class files Returns ------- file : string Path to segment_seg_0.nii.gz ...
def del_none(d): """ Delete keys with the value ``None`` in a dictionary, recursively. So that the schema validation will not fail, for elements that are none """ for key, value in list(d.items()): if value is None: del d[key] elif isinstance(value, list): fo...
def _unpack_idx(idx, nbits, dim): """ Convert from raster coords to (i_1, i_2,..., i_dim) """ mask = (2**nbits)-1 res = [] for i in range(dim): res.append((idx>>(nbits*(dim - 1 - i))) & mask) return tuple(res)
def sectype(cid): """Get the SWC structure type (sid) from section name `cid`""" if '.dend[' in cid: stype = 3 elif '.dend_' in cid: stype = int(cid.split('_')[-1].split('[')[0]) elif 'soma' in cid: stype = 1 elif 'axon' in cid: stype = 2 else: stype = 0 ...
def loss_and_metric_and_predictions_fn(provider): """Helper function to create loss and metric fns.""" metric_fn = None loss_fn = None predictions_fn = None if getattr(provider, "get_metric_fn", None) is not None: metric_fn = provider.get_metric_fn() if getattr(provider, "get_loss_fn", None) is not None...
def is_list_like(spec): """ :param spec: swagger object specification in dict form :rtype: boolean """ return isinstance(spec, (list, tuple))
def loader_from_key(key): """Returns the name, loader pair given a key.""" if ":" in key: return key.split(":") return key, None
def find_ori(dna, ori): """ Identify start and end index of the origin of replication in the given circular DNA. """ circular_dna = [x for x in dna] start, end = -1, -1 for i in range(len(ori) - 1): circular_dna.append(dna[i]) for i in range(len(circular_dna) - len(ori) + 1): ...
def fold(header): """Fold a header line into multiple crlf-separated lines at column 72.""" i = header.rfind("\r\n ") if i == -1: pre = "" else: i += 3 pre = header[:i] header = header[i:] while len(header) > 72: i = header[:72].rfind(" ") if i == -1: ...