content
stringlengths
42
6.51k
def translate(command): """ Translate the serialization of a move into an action that the game can consume :param command: Representation of a move to be taken that can be translated into an action :return: the translated action """ command_player = command[0:1] if command_player != "1" and ...
def setup_config(quiz_name): """Updates the config.toml index and dataset field with the formatted quiz_name. This directs metapy to use the correct files Keyword arguments: quiz_name -- the name of the quiz Returns: True on success, false if fials to open file """ try: ...
def pkt_int_to_float(pkt_val_1, pkt_val_2, pkt_val_3=None): """Convert packet data to float. """ if pkt_val_3 is None: float_val = pkt_val_1 << 8 | pkt_val_2 else: float_val = pkt_val_1 << 16 | pkt_val_2 << 8 | pkt_val_3 return float_val/100
def build_clnsig(clnsig_info): """docstring for build_clnsig""" clnsig_obj = dict( value = clnsig_info['value'], accession = clnsig_info.get('accession'), revstat = clnsig_info.get('revstat') ) return clnsig_obj
def detect_duplicates(sequence, hashable=True, key=None, keep_last=False): """ Identify whether each element in a sequence is a duplicate of a previously existing element. Derived from solution by goes to Markus Jarderot from http://stackoverflow.com/a/480227/851699 :param sequence: The sequence you w...
def default(arg): """ A function to prepare an argument string for a default argument. (str) -> str """ return arg + ' [Default: %default]'
def f(i): """ Addiziona due numeri. <h2>Example</h2> <pre>{"x": 3, "y": 7} ==> {"r": 10}</pre> <h2>Try</h2> <script src="/api/v1/api.js"></script> <script> function btnClick() { api.add({'x': 3, 'y': 7}) .success(function (data) { alert(JSON....
def convertToSets(problem): """ Given a two-dimensional list of integers return a new two-dimensional list of sets. :param list problem: Two-dimensional list of integers :return: Two-dimensional list of sets :rtype: list """ # A set containing the numbers 1 through 9 will replace any l...
def treatAccNumber(accNumber): """ Used to return null if the acc does not exists :param accNumber: gi number :type accNumber: string :return: None if the acc number is non-existent :rtype None or string """ if accNumber == 'NA': return None else: return accNumber
def _get_docker_build_fuzzers_args_not_container(host_repo_path): """Returns arguments to the docker build arguments that are needed to use |host_repo_path| when the host of the OSS-Fuzz builder container is not another container.""" return ['-v', f'{host_repo_path}:{host_repo_path}']
def max_min(lst): """ Calculate the maximum and minimum of a list lst Parameters ---------- lst : list Returns ------- tuple (max, min) """ if not lst: raise ValueError('Empty list') return lst[-1], lst[0]
def flatten(l, ltypes=(list, tuple)): """Takes a list of lists and flattens it""" ltype = type(l) l = list(l) i = 0 while i < len(l): while isinstance(l[i], ltypes): if not l[i]: l.pop(i) i -= 1 break else: ...
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Using binary search Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ start, end = 0, len(input_list) - 1 if sta...
def clean_caesar(text): """Convert text to a form compatible with the preconditions imposed by Caesar cipher""" return text.upper()
def convert(nested_dict): """ Convert nested dict with bytes to str. This is needed because bytes are not JSON serializable. :param nested_dict: nested dict with bytes """ if isinstance(nested_dict, dict): return {convert(k): convert(v) for k, v in nested_dict.items()} elif isinstan...
def get_overlaps(first_intervals, second_intervals): """ >>> get_overlaps([(1, 2), (3, 4), (8, 9)], [(1, 4), (7, 8.5)]) [(1, 2), (3, 4), (8, 8.5)] >>> get_overlaps([(1, 4), (7, 8.5)], [(1, 2), (3, 4), (8, 9)]) [(1, 2), (3, 4), (8, 8.5)] >>> get_overlaps([(1, 8), (9, 10)], [(2, 3), (5, 6), (7, 9....
def factorial(n): """Return the factorial of n, an exact integer >= 0. >>> [factorial(n) for n in range(6)] [1, 1, 2, 6, 24, 120] >>> factorial(30) 265252859812191058636308480000000 >>> factorial(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 Factorials of floats are OK, but the flo...
def is_list_like(arg): """Returns True if object is list-like, False otherwise""" return (hasattr(arg, '__iter__') and not isinstance(arg, str))
def split_esc(s, delim): """Split with support for delimiter escaping Via: https://stackoverflow.com/a/29107566 """ i, res, buf = 0, [], "" while True: j, e = s.find(delim, i), 0 if j < 0: # end reached return res + [buf + s[i:]] # add remainder while j - e and...
def group_images_by_content_advisory(images): """ Returns dict with content advisory name as a key and list of images containing some RPM from that content_advisory as value. """ ret = {} for image in images: for advisory in image["repositories"][0]["content_advisory_ids"]: i...
def preprocessing_zip(x): """ Preprocesses the raw ZIP field""" x = str(x) # Remove Zips with \x00 x = x.replace("\X00", '') x = x.replace(" ", '') x = x.replace("-", '') # remove zero at the begining of the string (e.g., '062390000'). while x.startswith('0'): x = x[1:] # l...
def getRatios(vect1, vect2): """Assumes: vect1 and vect2 are lists of equal length of numbers Returns: a list containing the meaningful values of vect1[i]/vect2[i]""" ratios = [] for index in range(len(vect1)): try: ratios.append(vect1[index]/float(vect2[index])) ...
def is_sequence(item): """Returns True if an object is iterable.""" return hasattr(type(item), '__iter__')
def from_preorder(arr: list) -> dict: """ Convert a depth-first pre-order array to binary tree, returning the root node. """ node = {} size = len(arr) if size > 0 and arr[0] is not None: node['value'] = arr[0] half = (size // 2) + 1 if half > 1: half_1st = fro...
def htmlencode(text): """Use HTML entities to encode special characters in the given text.""" text = text.replace('&', '&amp;') text = text.replace('"', '&quot;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') return text
def unquote_string(quoted): """Unquote an RFC 7320 "quoted-string". Args: quoted (str): Original quoted string Returns: str: unquoted string Raises: TypeError: `quoted` was not a ``str``. """ if len(quoted) < 2: return quoted elif quoted[0] != '"' or quote...
def in_list(value, val=None): """returns "true" if the value is in the list""" if val in value: return "true" return ""
def token_to_char_offset(e, candidate_idx, token_idx): """Converts a token index to the char offset within the candidate.""" c = e["long_answer_candidates"][candidate_idx] char_offset = 0 for i in range(c["start_token"], token_idx): t = e["document_tokens"][i] if not t["html_token"]: ...
def dmp_zero(u): """Returns a multivariate zero. """ if not u: return [] else: return [dmp_zero(u-1)]
def sequential_search(list1, val): """ Carry out a sequential search of the given list for a given value Parameters ---------- list1: input list, no prior sorting assumed val: the value to be searched Returns ------- True/False """ for i in range(len(list1)): i...
def jaccard(a, b): """Creates a ... Args: a (float): b (float): Returns: ``float``: ``jac`` """ jac = 1 - (a * b) / (2 * abs(a) + 2 * abs(b) - a * b) return jac
def letter2num(letters, zbase=False): """A = 1, C = 3 and so on. Convert spreadsheet style column enumeration to a number. Answers: A = 1, Z = 26, AA = 27, AZ = 52, ZZ = 702, AMJ = 1024 >>> letter2num('A') == 1 True >>> letter2num('Z') == 26 True >>> letter2num('AZ') == 52 True...
def parse_checksums(checksums): """Parse standard checksums file.""" result = {} for line in checksums.split('\n'): if not line.strip(): continue checksum, fname = line.strip().split(None, 1) result[fname.strip().lstrip('*')] = checksum.strip() return result
def sum_first_n(n: int) -> int: """Finds the sum of the integers from 1 to n.""" return n * (n + 1) // 2
def choose_susan(fwhm, motion_files, smoothed_files): """The following node selects smooth or unsmoothed data depending on the fwhm. This is because SUSAN defaults to smoothing the data with about the voxel size of the input data if the fwhm parameter is less than 1/3 of the voxel size. ...
def isdir(string): """ Is string an existing dir? :param string: path :return: abspath or raise NotADirectoryError if is not a dir """ import os if os.path.isdir(string): return os.path.abspath(string) else: raise NotADirectoryError(string)
def parse_result(task_result, key=""): """ Used to parse the celery result for a specific value. :param task_result: A str, dict, or list. :param key: A key to search dicts for :return: The value at the desired key or the original task result if not in a list or dict. """ if not task_result:...
def _get_user_and_repository(repository_url: str) -> tuple: """ Get User name and repository name from the given Github repository link >>> _get_user_and_repository('https://github.com/user/repository') ('user', 'repository') :param repository_url: string :return: (user: string, repository: st...
def compare_names(str1, str2): """Compare two strings alphabetically.""" if str1 == str2: return "identical" elif not str1 or not str2: return False else: for index in range(min(len(str1), len(str2))): if str1[index] == str2[index]: continue ...
def add_commas(n): """ Receives integer n, returns string representation of n with commas in thousands place. I'm sure there's easier ways of doing this... but meh. """ strn = str(n) lenn = len(strn) i = 0 result = '' while i < lenn: if (lenn - i) % 3 == 0 and i != 0:...
def parse_speed(as_str: str) -> float: """Parses a speed in N.NNx format""" return float(as_str.rstrip("x"))
def no_comment_row(x_str): """ Tests if the row doesn't start as a comment line. """ return x_str[0] != "#"
def _mean(values:list)->float: """ Return mean """ return sum(values)*1.0/len(values)
def get_category(extension, extension_map): """ Gets the category of the extension like (ebook for a pdf file). Note: The extension must not start with a '.' Args: extension (str): String for which the category has to be found. extension_map (dict): A dictionary containing the category ...
def rational_function(X): """ Benchmark rational function f(x) = x/(x + 1)*2 """ return X/((X+1)**2)
def fibonacci(n=100): """Returns a list containing the Fibonacci series up to n (default 100).""" result = [] # list a, b = 0, 1 while a < n: result.append(a) a, b = b, a + b return result
def counter_overflow(counts, prev_counts, buffer, threshold=None): """handle overflow of counters with given scale and threshold""" turns = 0 if not threshold: threshold = buffer / 2 if prev_counts - counts >= threshold: turns += 1 elif prev_counts - counts <= -1 * threshold: ...
def GetParentUriPath(parent_name, parent_id): """Returns the URI path of a GCP parent resource.""" return '/'.join([parent_name, parent_id])
def join(*args, **kwargs): """ Faked join method, for mocking purposes """ return '/' + '/'.join([arg.strip('/') for arg in args])
def calculate_cn_values(m, sigma_veff): """ CN parameter from CPT, Eq 2.15a """ CN = (100 / sigma_veff) ** m if CN > 1.7: CN = 1.7 return CN
def listToString(x): """ """ rVal = '' for a in x: rVal += a + ' ' return rVal
def package_get_arch_name(package_name): """ Args: package_name (str): The msys2 package name suffix Returns: str: The Arch package name """ if package_name.startswith("mingw-w64-i686-"): package_name = package_name.split("-", 3)[-1] mapping = { "freetype": "fre...
def is_above(p, q, point): """ check wether 'point' is above the line q-p """ return (p[0] - point[0]) * (q[1] - point[1]) \ - (p[1] - point[1]) * (q[0] - point[0])
def _compute_fans(shape): """Computes the number of input and output units for a weight shape. Args: shape: Integer shape tuple or TF tensor shape. Returns: A tuple of integer scalars (fan_in, fan_out). """ if len(shape) < 1: # Just to avoid errors for constants. fan_in = fan_...
def is_hashable(obj): #8 (line num in coconut source) """Determine if obj is hashable.""" #9 (line num in coconut source) try: #10 (line num in coconut source) hash(obj) #11 (line num in coconut source) except Exception: #12 (line num in coconut source) return False #13 (line num in co...
def fix_dataparallel_statedict(model, state_dict): """The state_dict of PyTorch DataParallel model cannot be loaded by a non-DataParallel model and vice-versa.""" has_module = hasattr(model, 'module') if any(k.startswith('module.') for k in state_dict.keys()): if not has_module: # sa...
def even(value): """Test if value is even""" return value % 2 == 0
def dict_filter(d, keys, into=dict): """ keys can be an iterable or function """ if hasattr(keys, "__call__"): f = keys keys = filter(f, d.keys()) return into(map(lambda k:(k,d[k]), keys))
def matrixvector_multiply(a, x): """takes a matrix and a vector represented as a list of list and multiplies them""" if len(a[0]) == len(x): product = [] for i in range(len(a)): product.append(0) for j in range(len(x)): product[i] += a[i][j]*x[j] return product else: return """ Matrix Vector Mul...
def modular_exponential(base, power, mod): """Calculate Modular Exponential.""" if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> 1 base = (base * base) % mod return result
def is_function(term): """ Checks if the term is a LaTeX mathematical function. Source: http://web.ift.uib.no/Teori/KURS/WRK/TeX/symALL.html Args: term: string to be checked. Returns: True if the term is a mathematical function, False otherwise. """ function_terms = ('arcc...
def apihost(request): """Return an api_host for OpenWeatherMap API.""" # samples api host return 'samples.openweathermap.org'
def format_diff_float(new, old, precision=3): """ returns difference as a string with given precision """ diff = abs(new - old) sign = "+" if new >= old else "-" fmt = " {} {:.%df}" % precision return fmt.format(sign, diff)
def int_to_binary_string(num: int, num_bits: int) -> str: """Convert integer to binary string of size number of bits Args: num: Integer to be converted to binary string Returns: str: Binary string representation of an integer Raises: OverflowError: If num_bits is too small to ...
def name_to_class(key): """ Converts a note name to its pitch-class value. :type key: str """ name2class = {'B#': 0, 'C': 0, 'C#': 1, 'Db': 1, 'D': 2, 'D#': 3, 'Eb': 3, 'E': 4, 'Fb': 4, 'E#': 5, 'F': 5, ...
def check_cols(board: list) -> bool: """ Checks if there are no duplicates in the board's columns. >>> check_cols(['**12', '1234', '2481']) True >>> check_cols(['**12', '1234', '1481']) False """ for col in range(len(board)): col_nums = set() for row in range(len(board))...
def parse_line(line): """ Parse $VNYMR message: Yaw float deg Calculated attitude heading angle in degrees. Pitch float deg Calculated attitude pitch angle in degrees. Roll float deg Calculated attitude roll angle in degrees. MagX float Gauss Compensated magnetometer ...
def get_product_by_id(product_id): """ Gets all products :return: """ product = {"name": "test_product"} return product
def add_ingredients(ingredients): """Here the caller expects us to return a list.""" if "egg" in ingredients: spam = ["lovely spam", "wonderous spam"] else: spam = ["splendiferous spam", "magnificent spam"] return spam
def public_properties(obj, key=None): """ List the public properties of an object, optionally filtered by a `key` function """ props = [p for p in dir(obj) if p[0] is not '_'] if key is not None: props = [p for p in props if key(p)] return props
def check_json_object(obj): """ Simple check to fill in the map for automatic parameter casting JSON objects must be represented as dict at this level """ assert isinstance(obj, dict), 'Invalid JSON object: {}'.format(obj) return obj
def cmd_exists(cmd): """ Test whether a command is available by checking the return code from subprocess.call """ import subprocess return subprocess.call("type " + cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == ...
def validate_dotenv_var(variable_name: str, possible_variables: list): """ Validate to see if the variable is in the list of the valid variable provided. :param variable_name: :param possible_variables: :return: """ if variable_name in possible_variables: return True else: ...
def set_timing(animationId: str, duration: float, delay: float) -> dict: """Sets the timing of an animation node. Parameters ---------- animationId: str Animation id. duration: float Duration of the animation. delay: float Delay of the animation. """ ...
def problem_1_3(data): """ Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not. FOLLOW UP: Write the test cases for this method. Complexity: O(n) ...
def ERR_UMODEUNKNOWNFLAG(sender, receipient, message): """ Error Code 501 """ return "ERROR from <" + sender + ">: " + message
def add_eof(article): """ """ o_num, o_gen, o_ver = article['o_num'], article['o_gen'], article['o_ver'] ret = '' ret += f'<div id="obj{o_num}.{o_gen}.{o_ver}">\n<pre class="eof">\n' ret += f'%%EOF\n' ret += f'</pre>\n</div>\n' return ret
def adjust_height(v1, height): """ Increases or decreases the z axis of the vector :param v1: The vector to have its height changed :param height: The height to change the vector by :return: The vector with its z parameter summed by height """ return (v1[0], v1[1], ...
def skip_mul(n): """Return the product of n * (n - 2) * (n - 4) * ... >>> skip_mul(5) # 5 * 3 * 1 15 >>> skip_mul(8) # 8 * 6 * 4 * 2 384 """ if n <= 2: return n else: return n * skip_mul(n - 2)
def algname(alg): """return the mnemonic for a DNSSEC algorithm""" names = (None, 'RSAMD5', 'DH', 'DSA', 'ECC', 'RSASHA1', 'NSEC3DSA', 'NSEC3RSASHA1', 'RSASHA256', None, 'RSASHA512', None, 'ECCGOST', 'ECDSAP256SHA256', 'ECDSAP384SHA384') name = None if alg in range(l...
def _encode_pair(prevc, c): """ Encodes two 16 bit integers into 32 bits """ return prevc << 32 | c
def splitUrl(urllst): """when there are multiple urls, split them into individual ones to parse""" urls = [ "http" + i.replace("\n", "").replace('"', "").strip() for i in urllst.split("http") ] if "http" in urls: urls.remove("http") return urls
def unique_digits(str_num): """ Test that the digits of the input number are unique and are not 0. Args: str_num: <str> integer to test Returns: False if the digits of the input number are not unique else True """ str_num_set = set(str_num) if '0' in str_num_set: return Fals...
def alpha_operation_sorter(endpoint): """ sort endpoints first alphanumerically by path, then by method order """ path, path_regex, method, callback = endpoint method_priority = { 'GET': 0, 'POST': 1, 'PUT': 2, 'PATCH': 3, 'DELETE': 4 }.get(method, 5) # Sort ...
def num_beta(n, N): """ Counts the number of beta electrons in a Fock representation. Assumes that the orbitals are sorted by spin first. :param n: any positive integer :param N: number of bits/qubits used in representing the integer `n` :returns: an integer giving the number of alpha electrons...
def targets_equal(keys, a, b): """ Method compare two mount targets by specified attributes """ for key in keys: if key in b and a[key] != b[key]: return False return True
def is_parser_function(string): """Return True iff string is a MediaWiki parser function.""" # see https://www.mediawiki.org/wiki/Help:Extension:ParserFunctions return string.startswith('#') # close enough for our needs
def check_files(file_list): """ Verify if a list of files exist and have content. :param file_list: The list of files to check. :return: The list of files that exist. """ checked = [] for file in file_list: try: if open(file).read() != '': checked.append(...
def dict_to_attr_str(d: dict): """Get an graphviz attribute string from a dict >>> assert dict_to_attr_str(d) == '[label="tik tok" score="42"]' """ if d is not None and len(d) > 0: return '[' + ' '.join(f'{k}="{v}"' for k, v in d.items()) + ']' else: return ''
def filter_by_comid(record, filterset=[]): """ Filter by comids in the project """ return record['properties']['comid'] in filterset
def parse_attributes(attributes, type="gtf"): """ Parse the attributes string of gtf record Return the values corresponding to gene_name and transcript_id """ attribute_delimiter = {'gtf': '; ', 'gff': ';'} kv_delimiter = {'gtf': ' ', 'gff': '='} info = {i.split(kv_delimiter[type])[0]: i.spl...
def get_unique_ptr(obj): """Read the value of a libstdc++ std::unique_ptr""" return obj["_M_t"]['_M_head_impl']
def unrestricted_security_groups_ingress(sgs): """If Protocol, Ports and Range conjunction is *""" for sg in sgs["SecurityGroups"]: for ip in sg["IpPermissions"]: any_protocol = False any_port = False any_range = False # Protocol if 'FromPort' ...
def _not_null(value, field): """Check whether 'value' should be coerced to 'field' type.""" return value is not None or field.mode != 'NULLABLE'
def unique(list): """Select unique elements (order preserving)""" seen = set() return [x for x in list if not (x in seen or seen.add(x))]
def _to_plotly_color(scl, transparence=None): """ converts a rgb color in format (0-1,0-1,0-1) to a plotly color 'rgb(0-255,0-255,0-255)' """ if transparence: return 'rgb' + str((scl[0] * 255, scl[1] * 255, scl[2] * 255, transparence)) elif len(scl) > 3: return 'rgb' + str((scl[0] * ...
def build_array_object(row): """ Build "items" dictionary object according to Class type """ dict = {} # handle controlled-list attributes as enum if row['class'] == 'enum': dict['type'] = row['type'] dict[row['class']] = row['controlled_list_entries'] # create exception for ...
def ex3_pickle_name(n, jump_rate): """build name for pickle file Parameters ------ n, prop : float `n` population and `proportion` observed Returns ------ f_name : str return `f_name` file name to save pickle as """ f_name = f"rjukf_a...
def _join_logical_operator(op, expressions): """Create an expressions string Example input: op='AND' expressions=['a == b', 'c < d'] Example output: (a == b AND c < d) """ separator = ' ' + op + ' ' return '(' + separator.join(expressions) + ')'
def args(index: int): """Get index-th arguments of the program""" import sys assert index >= 0 and index < len(sys.argv) return sys.argv[index]