content
stringlengths
42
6.51k
def load_log(log_file): """Reads the processed posts log file and creates it if it doesn't exist. Returns ------- list A list of Reddit posts ids. """ try: with open(log_file, "r", encoding="utf-8") as temp_file: return temp_file.read().splitlines() except File...
def parse_instruction(instruction): """Deprecated""" sint = str(instruction).zfill(5) parm3 = bool(int(sint[0])) parm2 = bool(int(sint[1])) parm1 = bool(int(sint[2])) op = int(sint[-2:]) return op, parm1, parm2, parm3
def ParseList(List): """Parse lists (e.g. 0,1,3-8,9)""" Res = list() if ( str(List).isdigit() ): Res.append(int(List)) else: for Element in List.split(','): if '-' in Element: x1,x2 = Element.split('-') Res.extend(list(range(int(x1), int(x2)+1))) else: Res.append(int(Element)) return Res
def is_json_schema(data): """ :param dict data: JSON data :returns: whether the JSON data is a JSON Schema :rtype: bool """ return '$schema' in data or 'definitions' in data or 'properties' in data
def getWhiteSpaceLessStringMap(string): """ Map the characters in a string from which whitespace has been removed to their indices in the original string. """ map = {} whiteSpaceLessPos = 0 for originalPos in range(len(string)): if not string[originalPos].isspace(): map[w...
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ if not input_list: return -1 if len(input_list) == 1: ...
def genomic_dup2_free_text(dmd_gene_context): """Create test fixture containing params for genomic dup VD.""" params = { "id": "normalize.variation:TSC2%20g.2137939_2137949dup", "type": "VariationDescriptor", "variation_id": "", "variation": dict(), "molecule_context": "t...
def AddFlagPrefix(name): """Add the flag prefix to a name, if not present.""" if name.startswith('--'): return name # Does not guarantee a valid flag name. return '--' + name
def convert_to_float(str_list): """ Return a list of floats """ values = [] for value in str_list: values.append(float(value)) return values
def load_data(file_handle, element, element_size): """Read element_size bytes of binary data from file_handle into element""" if element_size == 0: return element, True if element is None: element = file_handle.read(element_size) else: read_size = element_size - len(element) ...
def multiply_matrices(m_1: list, m_2: list) -> list: """ Parameters ---------- m_1 : list of lists => [[1, 2, 3], [4, 5, 6], [7, 8, 9]] m_2 : list of lists => [[10, 11, 12], [13, 14, 15], [17, 18, 19]] Returns ------ transformation : list of ...
def safe_str(s: str) -> str: """A lowercase string with some special characters replaced.""" for char in "[]()'": s = s.replace(char, "") s = s.replace(" ", "-") s = s.replace(".", ",") return s.lower()
def sort_key(item): """Sort list by the first key.""" if len(item) != 1: item = item[0] return (list(item.keys())[0],)
def get_trunc_hour_time(obstime): """Truncate obstime to nearest hour""" return((int(obstime)/3600) * 3600)
def string_to_list(str_): """ Returns a list from the given string >>> string_to_list(['1', '2', '3']) >>> # ['1', '2', '3'] :param str_: :return: list """ str_ = '["' + str(str_) + '"]' str_ = str_.replace(' ', '') str_ = str_.replace(',', '","') return eval(str_)
def readout_tbexec(line, tbexeclist, tbinfo, goldenrun): """ Builds the dict for tb exec from line provided by qemu """ split = line.split('|') # generate list element execdic = {} execdic['tb'] = int(split[0], 0) execdic['pos'] = int(split[1], 0) return execdic
def is_subsub(q, ts): """ check is `q is a subset of any subset in set `ts """ iok = False for tsi in ts: if set(q) <= tsi: iok = True; break return iok
def compute_variance_by_mode(n_EOF, singular_val, cov=True): """Compute variance contained in any mode (EOF). Based on Beckers and Rixen 2001 """ tot_variance = 0 variance = [] # singular values of field matrix X are the square roots # of the eigenvalues of Xt*X if not cov : sing...
def chunks(chunkable, n): """ Yield successive n-sized chunks from l. """ chunk_list = [] for i in range(0, len(chunkable), n): chunk_list.append( chunkable[i:i+n]) return chunk_list
def makeListFromCommaSepString(s): """ Reads in comma-separated list and converts to list of successive keyword,value pairs. """ if s.count(",") % 2 == 0: raise Exception("Must provide even number of items in argument of commas-separated pairs of values: " + s) l = [] items = s.spli...
def part2(data): """ >>> part2([199, 200, 208, 210, 200, 207, 240, 269, 260, 263]) 5 >>> part2(read_input()) 1618 """ count = 0 for i in range(1, len(data) - 2): previous = sum(data[i - 1:i + 2]) value = sum(data[i:i + 3]) if value > previous: count ...
def get_evening_cars(morning_cars,requested,returned,max_cars): """ compute #cars avaiable in the evening, given #cars in the morning, #returned and #requests during the day """ return min(max(morning_cars - requested,0) + returned, max_cars)
def linear(n): """Trivial linear tweening function. Copied from pytweening module. """ if not 0.0 <= n <= 1.0: raise ValueError('Argument must be between 0.0 and 1.0.') return n
def fuzzyCompareDouble(p1, p2): """ compares 2 double as points """ return abs(p1 - p2) * 100000. <= min(abs(p1), abs(p2))
def tweetstyle(tweets_polarity, i,default=False): """ Determines the colour of a tweet based on its polarity. :param tweets_polarity: the array of polarities :param i: the position of the tweet polarity in the array :param default: default flag, True if section is in default :return styl...
def scan_alias(toks): """Scan the index of 'as' and build the map for all alias""" as_idxs = [idx for idx, tok in enumerate(toks) if tok == 'as'] alias = {} for idx in as_idxs: alias[toks[idx+1]] = toks[idx-1] return alias
def _convert(msg): """Convert a graphite key value string to pickle.""" path, timestamp, value = msg.split(' ') m = (path, (timestamp, value)) return m
def bit_not(n: int, numbits: int=32) -> int: """Return the bitwise NOT of 'n' with 'numbits' bits.""" return (1 << numbits) - 1 - n
def encode_string_text(text): """Replace special symbols with corresponding entities or magicwords.""" text = text.replace("<", "&lt;") text = text.replace(">", "&gt;") text = text.replace("[", "&#91;") text = text.replace("]", "&#93;") text = text.replace("{", "&#123;") text = text.replace(...
def get_id(element) -> str: """ Return the ID of an event or series. :param element: event or series :type element: dict :return: ID of element :rtype: str """ if "id" in element: return element["id"] elif "identifier" in element: return element["identifier"] el...
def convert_to_seconds(millis, return_with_seconds=True): """ Converts milliseconds to seconds. Arg: 'return_with_seconds' defaults to True and returns string ' sekunder' after the seconds """ if return_with_seconds: return (millis/1000) % 60 + " sekunder" else: return (millis/10...
def fn2Test(pStrings, s, outputFile): """ Function concatenates the strings in pStrings and s, in that order, and writes the result to the output file. Returns s. """ with open(outputFile, 'w') as fH: fH.write(" ".join(pStrings) + " " + s) return s
def boolean_string(s): """ https://stackoverflow.com/questions/44561722/why-in-argparse-a-true-is-always-true :param s: :return: """ if s.lower() not in {'false', 'true'}: raise ValueError('Not a valid boolean string') return s.lower() == 'true'
def min_max_prod(minimums, maximums): """ returns the smallest and largest products achievable by interweaving maximums and minimums >>> min_max_prod((3,6,0,1,6),(-4,3,-5,-4,0)) (-2880, 2160) """ assert len(maximums) == len(minimums) ret_min, ret_max = 1, 1 for op_min, op_max in zip(mi...
def _AppendOrReturn(append, element): """If |append| is None, simply return |element|. If |append| is not None, then add |element| to it, adding each item in |element| if it's a list or tuple.""" if append is not None and element is not None: if isinstance(element, list) or isinstance(element, tuple): ...
def clean_hostname(hostname): """ Remove the .local appendix of a hostname. """ if hostname: return hostname.replace('.local', '').replace('.lan', '')
def normalize(tensor, stats): """Normalize a tensor using a running mean and std. Parameters ---------- tensor : tf.Tensor the input tensor stats : RunningMeanStd the running mean and std of the input to normalize Returns ------- tf.Tensor the normalized tensor ...
def not_(column: str) -> str: """ >>> not_("col") 'NOT col' """ return f"NOT {column}"
def as_list(string_members): """Returns a string of comma-separated member addresses as a list""" ml = [] for m in string_members.split(","): ml.append(m.strip()) return ml
def linear_search_iterative(array, item): """Return the index of the targeted item""" # loop over all array values until item is found for index, value in enumerate(array): if item == value: return index # found return None
def f(x): """does some math""" return x + x * x
def match_parantheses(data): """ Makes sure the parantheses in data are correctly closed. Returns: True if the parantheses are correctly closed. """ parantheses = ['[', ']', '(', ')'] matches = { '[': ']', '(': ')' } stack = [] for char in data: if char ...
def in_sh(argv, allstderr=True): """ Provides better error messages in case of file not found or permission denied. Note that this has nothing at all to do with shell=True, since quoting prevents the shell from interpreting any arguments -- they are passed straight on to shell exec. """ # NB...
def monomial_pow(A, n): """Return the n-th pow of the monomial. """ return tuple([ a*n for a in A ])
def clean_phonological_groups(groups, liaison_positions, liaison_property): """Clean phonological groups so their liaison property is consistently set according to the the liaison positions :param groups: Phonological groups to be cleaned :param liaison_positions: Positions of the liaisons :param l...
def check_data(data_converter, data): """Store class method returns `None` in case the reaktor call returns `void`. For empty result (<> void), the data converter is still run because the backend omits empty and null attributes for bandwidth efficiency. In case of data being an array, a collection of it...
def U32(i): """Return i as an unsigned integer, assuming it fits in 32 bits. If it's >= 2GB when viewed as a 32-bit unsigned int, return a long. """ if i < 0: i += 1 << 32 return i
def is_blank(s: str) -> bool: """Checks if a string is blank or not""" return not bool(s and not s.isspace())
def rm_empty_by_copy(list_array): """copy the last non-empty element to replace the empty ones""" for idx in range(len(list_array)): if len(list_array[idx]) == 0: list_array[idx] = list_array[idx-1] return list_array
def div(a,b): """``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise an `ValueError` is raised. >>> div(10,2) 5 >>> div(10,3) Traceback (most recent call last): ... ValueError: 3 does not divide 10 """ res, fail = divmod(a,b) if fail: raise ValueError("...
def collect_reducer_set(values): """Return the set of values >>> collect_reducer_set(['Badger', 'Badger', 'Badger', 'Snake']) ['Badger', 'Snake'] """ return sorted(list(set(values)))
def argmax(l,f=None): """http://stackoverflow.com/questions/5098580/implementing-argmax-in-python""" if f: l = [f(i) for i in l] return max(enumerate(l), key=lambda x:x[1])[0]
def make_full_path(path, name): """ Combine path and name to make full path""" # path = make_bytes(path) #py3, this added for python3, path must be bytes, not unicode # import pdb; pdb.set_trace() name = name.decode('utf-8') #py3, added name will be byte string and combine_messages is always expecting...
def zip_values(x_vals: list, y_vals: list) -> list: """Returns a list of the specified X and Y values packaged together in tuples, with X at index 0 of the tuple.""" return [(x_vals[_], y_vals[_]) for _ in range(len(x_vals))]
def ordinal(num: int) -> str: """ Returns the ordinal representation of a number Examples: 11: 11th 13: 13th 14: 14th 3: 3rd 5: 5th :param num: :return: """ return f"{num}th" if 11 <= (num % 100) <= 13 else f"{num}{['th', 'st', 'nd', 'rd', 'th'][min...
def unique(seq, idfun=repr): """ Function to remove duplicates in an array. Returns array with duplicates removed. """ seen = {} return [seen.setdefault(idfun(e), e) for e in seq if idfun(e) not in seen]
def get_path_to_sfr_dir(name: str, data_directory: str) -> str: """Get the path to the directory where the star formation data should be stored Args: name (str): Name of the galaxy data_directory (str): dr2 data directory Returns: str: Path to SFR dir """ return f"{data_dir...
def noise_eliminate(lines, coordinates, flag): """ # delete the noise lines which are defined as the close lines. :param lines: list. lines saved as endpoints coordinates, eg:[[(x_0, y_0), (x_1, y_1), 'v'],[(x_2, y_2), (x_3,y_3), 'h'],...] :param coordinates: list. [x1, x2, x3,...] or [y1, y2, y3,.....
def sorted_unique(iterable): """Sort and uniquify elements to construct a new list. Parameters ---------- iterable : collections.Iterable[any] The collection to be sorted and uniquified. Returns ------- list[any] Unique elements as a sorted list. """ return sorted(s...
def legal_input(input_w): """ :param input_w: string, row. :return: True, if all are legal format. """ if len(input_w) != 7: return False for i in range(len(input_w)): if i % 2 == 0: if not input_w[i].isalpha(): return False elif i % 2 != 0: if input_w[i] != ' ': return False if i == len(inp...
def _indent(input_str: str, indentation: int = 2) -> str: """Indents a string by the specified number of spaces, defaulting to 2.""" spaces = " " * indentation lines = input_str.split("\n") # Prepend spaces to each non-empty line. lines = [f"{spaces}{line}" if len(line) else line for line in lines] return "...
def el(tag_type, *content): """ Returns a list of strings that represents an HTML element. If the first argument passed to *content is a dict, then the dict is unpacked into attribute pairs for the element. >>> el('div', {'class' : 'navbar'}, "This is my Navbar!") ['<div class="navbar">', 'Thi...
def nature_validation(nature): """ Decide if the nature input is valid. Parameters: (str): A user's input to the nature factor. Return: (str): A single valid string, such as "1", "0" or "-5" and so on. """ while nature != "5" and nature != "4" and nature != "3" and ...
def check_time(time, min, max): """ Check time submitted by user to make sure time is correct and follows a correct format :param time: time requested by user :param min: min possible value :param max: max possible value :return: """ if int(time) >= min and int(time) <= max: retu...
def circle_bbox(coordinates, radius=5): """the bounding box of a circle given as centriod coordinate and radius""" x = coordinates[0] y = coordinates[1] r = radius return (x - r, y - r, x + r, y + r)
def vec2spec_dict(n_bins, vec, spectra): """Take a vector of power spectra and return a power spectra dictionnary. vec should be of the form [spectra[0], spectra[1], ... ]. For example [cl_TT,cl_TE,cl_ET, ...., cl_BB] Parameters ---------- n_bins: int the number of bins per spectrum ...
def validate_input_json(data, expected): """Validates json recieved from request Args: data (): json recieved from request expected (dict): json format expected from request Returns: bool: state of validity, True if good request str: reason for validity int: request...
def get_cookie_value(cookies, cookie_name): """Gets a cookies value Arguments: cookies {request.cookies/dict} -- dictionary of cookies cookie_name {str} -- the cookies to retreive Returns: [str] -- returns the value of the item if the cookies exists else returns empty string "...
def addbreaks(text): """:addbreaks: Any text. Add an XHTML "<br />" tag before the end of every line except the last. """ return text.replace('\n', '<br/>\n')
def callable(object: object) -> bool: """callable.""" return hasattr(object, '__call__')
def generate_definition_list(op, prefix): """Generate a definition listing.""" ret = [] if isinstance(op, (list, tuple)): for ii in op: ret += [prefix + ii] elif isinstance(op, str): ret += [prefix + op] else: raise RuntimeError("weird argument given to definition list generation: %s" % (str...
def sec2hms(x, precision=0, mpersist=True): """ CONVERTS decimal seconds to hours : minutes : seconds """ out = '' if x > 60: if x > 3600: h = int(x / 3600) out = '%d:' % h x = x - 3600 * h m = int(x / 60) out += '%d:' % m x = x - 6...
def cdpro_input_header(firstvalue, lastvalue, factor): """ :returns: Multiline string mimicking cdpro output """ firstvalue = '{:0.4f}'.format(firstvalue) lastvalue = '{:0.4f}'.format(lastvalue) header = ("# \n" "# PRINT IBasis ...
def state_to_props(state): """Map state to props relevant to component""" return state.get("colorbar", None)
def afla_pasul(mesaj): """ Afla pasul encodarii """ first_letter = 'a' my_letter = mesaj[0] return ord(my_letter) - ord(first_letter)
def set_swfac(name: str) -> float: """ name is cfmt.vocalfont.name :param name: :return: """ swfac = 1.0 if name == "Times-Roman": swfac = 1.00 if name == "Times-Bold": swfac = 1.05 if name == "Helvetica": swfac = 1.10 if name == "Helvetica-Bold": ...
def record_pct(A): """ Input: list (list of tuples) - list of tuples of record percents Returns: record_pct (integer) - record percentage """ middle = list() for i in range(len(A)): possible = 1 for j in range(len(A[i])): possible *= A[i][...
def to_file_descriptor(fobj): """ Converts an object to a file descriptor. The given object can be either: - An integer file descriptor - An object with a ``fileno()`` method. :raises ValueError: If the given object cannot be converted. >>> class Descriptable: ... def fileno...
def adder_function(args): """Dummy function to execute returning a single float.""" loc, scale = args return loc + scale
def convert_mwh_bbtu(value: float) -> float: """converts energy in MWh to energy in billion btu. :param value: value in megawatt-hours of energy :type value: float :return: value in bbtu """ bbtu = value * 0.003412 return bbtu
def moment_from_muad(mu, A, d): """moment = mu * A * d :param mu: shear modulus, in Pa :type mu: float :param A: area, in m^2 :type A: float :param d: slip, in m :type d: float :returns: moment, in Newton-meters :rtype: float """ return mu*A*d;
def clean_alphanumeric(text): """ If text has any non-alphanumeric characters, replace them with a hyphen. """ text_clean = '' for charc in text: text_clean += charc if charc.isalnum() else '-' return text_clean
def represents_int(string: str): """Checks if a `string can be turned into an integer Args: string (str): String to test Returns: bool """ try: int(string) return True except ValueError: return False
def minimum_tls_version(supported_protocols): """Returns the minimum supported TLS version""" result = None tls_versions = ['ssl2', 'ssl3', 'tls10', 'tls11', 'tls12', 'tls13'] tls_versions_pretty = ['sslv2', 'sslv3', 'tls 1.0', 'tls 1.1', 'tls 1.2', 'tls 1.3'] for i, v in enumerate(tls_versions): ...
def format_number(number): """Format numbers for display. if < 1, return 2 decimal places if <10, return 1 decimal places otherwise, return comma formatted number with no decimal places Parameters ---------- number : float Returns ------- string """ if number == 0: ...
def say_hello(name: str = "World"): """ This is the docstring to the 'say_hello' function """ return "Hello {}".format(name)
def is_valid_seq(seq, max_len=2000): """ True if seq is valid for the babbler, False otherwise. """ l = len(seq) valid_aas = "MRHKDESTNQCUGPAVIFYWLO" if (l < max_len) and set(seq) <= set(valid_aas): return True else: return False
def detect_entry_fold(entry, folds): """Detect entry fold. Args: entry (str): Entry string folds (int): Number of folds Returns: int: Entry fold index """ entry_id = entry.split("[")[0] for i in range(len(folds)): if entry_id in folds[i]: return i ...
def parse_volume_bindings(volumes): """ Parse volumes into a dict. :param volumes: list of strings :return: dict """ def parse_volume(v): if ':' in v: parts = v.split(':') if len(parts) > 2: hp, cp, ro = parts[0], parts[1], parts[2] ...
def _pdbcls_callback(x): """Validate the debugger class string passed to pdbcls.""" message = "'pdbcls' must be like IPython.terminal.debugger:TerminalPdb" if x in [None, "None", "none"]: x = None elif isinstance(x, str): if len(x.split(":")) != 2: raise ValueError(message) ...
def reinsertList(lst,selection,insert_row,current_index=0): """ Generic implementation for reinserting a set of elements. lst : a list of items (data type not important) selection : list/set of indices of elements in lst insert_row : an integer index into lst current_index : index of the curre...
def get_machine_type(machine_type, accelerator_count): """Get machine type for the instance. - Use the user-specified machine_type if it is not None - Otherwise, use the standard type with cpu_count = 8 x accelerator_count if user-specified accelerator_count > 0 - Otherwise, use the standard type wit...
def adcStr_to_dict(args, curr_cfg=None): """Handler for `adcCfg`""" if curr_cfg: cfg = curr_cfg else: cfg = {} if int(args[1]) == 1: cfg['isComplex'] = True cfg['image_band'] = False #print('[NOTE] Complex 1x mode, Only Real IF Spectrum is filtered and sent to AD...
def _make_split_name(prefix, num, neededChars): """ Construct a split name from a prefix, a number, and the number of characters needed to represent the number. :param prefix: the prefix or None. :param num: the zero-based index. :param neededChars: the number of characters to append before the...
def define_a_plot_name(plot_idx): """Define unique plot name""" return f"PP" + str(plot_idx).zfill(8)
def _utf8_decode(b): """Decode (if needed) to str. Helper for type conversions among DataObjStr and DataObjBytes. """ if isinstance(b, bytes): return b.decode(encoding="utf-8") elif isinstance(b, str): return b else: raise TypeError("Argument must be 'bytes' or 'str'")
def phugoid_rating(phugoid_damping, ph_t2): """ Give a rating of the phugoid mode : Level1 Level2 or Level 3 according to MILF-8785C Args: phugoid_damping (float) : [-] ph_t2 (float): phugoid time to double amplitude [s] Returns: 1 one 2 or 3 corresponding to the flight level "...
def string_response(s, encoding='utf-8'): """Convert string to WSGI string response.""" return [bytes(s, encoding)]
def two_bounce(alphas, x0, xp0, x1, z1, x2, z2, z3): """ Calculates the x position of the beam after bouncing off two flat mirrors. Parameters ---------- alphas : tuple Tuple of the mirror pitches (a1, a2) in radians x0 : float x position of the source in meters xp0 : ...
def solve(ver1, op1, ver2, op2): """Solve conflicts.""" ver1_t = tuple(ver1.split(".")) ver2_t = tuple(ver2.split(".")) if op1 == "==": if op2 == "==": return ver1_t == ver2_t, f"{ver1} != {ver2}" if op2 == ">=": return ver1_t >= ver2_t, f"{ver1} < {ver2}" ret...