content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from collections import deque, defaultdict def _cif_parse_loop(keys, data_block): """ A hacky way to parse CIF data loops that can be split by quotes or spaces. There must be a better way... Parameters: keys (list of str): list of keys for the loop. data_block (str): raw string of the ent...
6f6a389bc50472eed505ab1d6b7a25a6dea20335
633,907
def molarweights(): """returns a partial table of molecular weights for elements and oxides that can be used in other functions Returns ======= w : dictionary containing the molar weights of elements and oxides: - si, ti, al, fe, li, na, k, mg, ca, ba, o (no upper case, symbol calling) ...
098a2947cfd27e481849f821dcc1b2a5e209be46
633,908
def to_digital(d, num): """ 进制转换,从10进制转到指定机制 :param d: :param num: :return: """ if not isinstance(num, int) or not 1 < num < 10: raise ValueError('digital num must between 1 and 10') d = int(d) result = [] x = d % num d = d - x result.append(str(x)) while d >...
c0da087a78ce7ae4e2a554b187664135c18bc796
633,909
import os def get_environment(): """Return app environment""" return os.environ.get('APPLICATION_ENV') or 'development'
22a1d2bcf7a307eb6232a9dcece474b065359110
633,911
from datetime import datetime def parse_timestamp_query(query, schema): """Interpret date column queries as JSON.""" if query: for date_column in schema.datetimes(query.keys()): query[date_column] = { key: datetime.fromtimestamp(int(value)) for (key, value) in ...
ea91297703359415cc4e87f8ba9d37e1112b457b
633,912
def mergeTwoListsIntoOne(list1, list2): """ Function that takes two lists and assembles them into one list such that each entry of the final list is a list containing the two corresponding entries of the two input lists """ if len(list1) != len(list2): raise ValueError("Input lists not o...
d6eec1b20b1cecf64e7ae457b1a62e34db79d68e
633,913
def int_to_str(num, max_num=0): """ Converts a number to a string. Will add left padding based on the max value to ensure numbers align well. """ if num is None: num_str = 'n/a' else: num_str = '{:,}'.format(num) max_str = '{:,}'.format(int(max_num)) return num_str.rjust(...
d6bcdef45a545f354b0c3889c7ef35fdae20e668
633,914
from typing import Counter def reduce_counter(counts, reducer): """ Returns a new counter from an existing one where keys have been mapped to in many-to-one fashion and counts added """ new_counts = Counter() for key, count in counts.items(): new_key = reducer(key) new_counts[...
38887a762525c2646f2ae7ced48767eeaf566997
633,915
def invertir(palabra): """Esta funcion invierte un texto""" tamano = len(palabra) nueva_palabra = "" for i in range( 1, ( tamano + 1 ) ): nueva_palabra = nueva_palabra + palabra[-i] return nueva_palabra
65b9066ac47b998f07cec5d1512a1960a2914d07
633,916
def nested_haskey(x, keys): """ For a nested dictionary 'x' and list of keys, checks if all keys exist in the nested key path. """ if len(keys) == 1: return (keys[0] in x) if keys[0] in x: return nested_haskey( x[keys[0]], keys[1:]) else: return False
6c99bb9d1d8b6a63f2670394ea266564b3435122
633,917
import pathlib import pkg_resources def get_path(resource_name): """ Returns a path to a resource WARNING: existence of file is not guaranteed. Use resources.exists WARNING: resource files are supposed to be used as read-only! """ resource_path = pathlib.Path( pkg_resources.resource_filen...
33a4d12b19aa0276ff0fc9464b757713dc9a6a01
633,918
def parse_flag(value): """ Convert string to boolean (True or false) :param value: string value :return: True if the value is equal to "true" (case insensitive), otherwise False """ return value.lower() == "true"
4555e655ecd39f362d11065718e10b144ecf2b85
633,919
def is_int(array): """ Checks if NumPy array is int or float type. Arguments: ndarray:n -- Array to check """ floats = ['float16', 'float32', 'float64'] dtype = str(array.dtype) return False if dtype in floats else True
bcd4d9ef8cfbc084503824231af882095e57aabb
633,920
def args(*subcommands): """Decorator that makes another Command's flags active on this command also :Example: class Foo(Command): @arg("--che", "-c", dest="che", default=1, help="the che value") def handle(self, che): pass class Bar(Command): @args(Foo) ...
6e40bf23b9bb04c51ce6ba03ad24c3c4b0d6272f
633,921
def capacity_cost_rule(mod, g, p): """ The capacity cost for new-build generators in a given period is the capacity-build of a particular vintage times the annualized cost for that vintage summed over all vintages operational in the period. """ return sum( mod.GenNewBin_Build[g, v] ...
5cf427ad93f8a34cdb2d75b4e503622dbe2be9aa
633,922
def d_file_query(query_utils, page_start, page_end): """Retrieve D1 or D2 data. Args: query_utils - object containing: file_utils - fileD1 or fileD2 utils sess - DB session agency_code - FREC or CGAC code for generation start - Beg...
5a08c7daa84aab023f206db9accdbcff8b489a7f
633,923
import os def is_airflow(): """Returns: True for Airflow env""" return "AIRFLOW_CONFIG" in os.environ or "AIRFLOW_HOME" in os.environ
0d5b7a7f66888cdb425389f97a59b24cd195f962
633,924
def getTimeRegime(*args): """Access protected class data to evaluate and monitor the current regime in which the system is operating. The returned value representation is an integer ranging from '0' to '4'. This approach is a secure method to access saved system state values. Argument...
8e580b1732ebc0e4528f0112d22c8e5f05a2a64a
633,925
def printm(matrix,less=True): """Print a list of list, only showing changes in each column (if less is True).""" def ditto(m,mark="."): def worker(lst): out = [] for i,now in enumerate(lst): before = old.get(i,None) # get old it if exists out += [mark if before == now else ...
f4c6abe28fdc319eedf24614c3d43aad038742a4
633,927
def nillable_dict(func): """Decorator that retuns empty dictionary if input is None""" def wrapper(cls, element): if element is None: return {} else: return func(cls, element) return wrapper
80e424bf84ab64db5ec99d8c9a91298d67e790b1
633,928
def get_sampled_df(df, columns): """ Return a subset of the general df by selecting the columns and adding the columns of year and Country """ if isinstance(columns, str): columns = [columns] initial_col = ["Country", "Year"] initial_col.extend(columns) return df[initial_col]
5e63e8d60cc0f824994696040fddea9da4d6ae99
633,930
def generate_test(filename): """ From the text filename extract the id and the tweet. Arguments: filename (the name of the text file) """ test_data = open(filename, "r", encoding='utf-8') id_ = [line[:line.find(",")] for line in test_data.readlines()] test_data = open(filename, "r", enco...
624fa9c2b087b2dbb24fbc36d720099cb5cc530b
633,933
def get_reqs(path): """Parse a pip requirements file. :param str path: The path to the requirements file :returns list: A list of package strings """ reqs = [] with open(path) as req_file: for line in req_file: # Remove any comments line = line.split("#", 1)[0]....
8f625a24973aed42617107e3be2e0e18e471c9ef
633,934
def order_by_length(*items): """Orders items by length, breaking ties alphabetically.""" sorted_items = sorted(items, key=lambda item: (len(str(item)), str(item))) return ' '.join(sorted_items)
dc0b8406c531d96e8192de5702c702fd4e533f5a
633,935
def backtrack2(f0, g0, x1, f1, b1=0.1, b2=0.5): """ Safeguarded parabolic backtrack Note for equation look to Nocedal & Wright, 2006 ?? :type f0: float :param f0: initial misfit function value :type g0: float :param g0: slope :type x1: float :param x1: step length value ...
d5cad1ffe138da496d807f873460051726d51d75
633,937
def voltage_lim(SV, self, val): """ Check to see if the voltage limits have been exceeded. """ # Save local copies of the solution vector and pointers for this electrode: SVptr = self.SVptr SV_loc = SV[SVptr['residual']] # Calculate the current voltage, relative to the limit. The simul...
62073900939807a0e7675e443f53dc679902d108
633,938
import torch def prepare_batch(batch): """This is the collate function. The mass spectra must be padded so that they fit nicely as a tensor. However, the padded elements are ignored during the subsequent steps. Parameters ---------- batch : tuple of tuple of torch.tensor A batch of d...
56ba032b5e2a8d27d1d589d4eb0c96153d47cc88
633,939
def index_to_packed(px): """Convert 0x88 index to 0-63 index""" return ((px & ~7) // 2) + (px & 7)
820fff187362beb4422313abcd9841c95e3fe40d
633,940
def task_type_args_are_valid(instance): """Determines whether a task type's argument fields are valid. The argument fields are valid if the argument keys in the required_arguments_default_values field are a subset of its required arguments. Arg: instance: A task type instance. Returns:...
bb45d1bcd174001e96a7f07fce86b6de294cf232
633,941
import argparse def _parse_args(): """ Argument parsing """ cmd_parser = argparse.ArgumentParser(description='Execute a Streams application using a Streaming Analytics service.') ctx_group = cmd_parser.add_mutually_exclusive_group(required=True) ctx_group.add_argument('--service-name', help='Subm...
a8c83748afed62242a87fa49354f40679ac730b9
633,942
def get_inx(x, image_width, target_width, coordinate_transformation_mode): """Infer input x from output x with various coordinate transformation methods""" scale = image_width / target_width if coordinate_transformation_mode == "half_pixel": in_x = (x + 0.5) * scale - 0.5 elif coordinate_transfo...
8ab435a75df0e2a9bb4215d7a1af1fcc27b6b024
633,943
def insert_boat_in_matrix( direction, boat_size, initial_position, board_matrix, ): """ :param direction: :param boat_size: :param initial_position: :param board_matrix: :return: """ if direction == 'UP': first_square = initial_position['y'] for cu...
7e2509984facbf484ddd11e61b9350042404a924
633,944
def sign_split(M): """Given a matrix M, return two matrices. The first contains the positive entries of M; the second contains the negative entries of M, multiplied by -1. """ M_plus = M*(M>0).astype(int) M_minus = -M*(M<0).astype(int) return M_plus, M_minus
af573a2c68a6156cd92b5f3076c0fa6fb3c3c95e
633,946
def untokenize(token_list): """Untokenize a token list to its origin expression. :type token_list: list[TokenBase] :param token_list: The token list. :rtype : str :return: The origin expression. """ # Initialize the expression. expr = "" # Append the symbol of each item of the t...
e88cd9d4b6ad3ea2ec19fe47e30f43ab9bb47157
633,947
def ksi_of_t_rhythmic(T, r): """ Local regressor. Rhythmic system """ return 0 * T + r
59dba4b5a19dda8bcbe2c6652f4b15c5e50348ef
633,948
import re def get_usfm3_word_links(usfm3_line): """ Retrieves the tW links from a usfm3 word :param usfm3_line: :return: """ links = [] if usfm3_line and re.match(r'.*x-tw=', usfm3_line): links = re.findall(r'x-tw="([^"]*)"', usfm3_line, flags=re.IGNORECASE | re.UNICODE) return...
e568dc7da2852c6ac309f1e8ccfca8b7abf4229f
633,949
from datetime import datetime def to_datetime_from_date(value): """ converts the input date to it's equivalent python datetime. the time info will be set to `00:00:00`. :param date value: date value to be converted. :rtype: datetime """ return datetime(year=value.year, month=value.mont...
7bd31f1df9b6c418c72b955dfca1d7af865fe235
633,950
def update_numbers(molecule_structure): """This function will update the number of atoms, bonds, angle, dihedrals, impropers, bond types, angle types, dihedral types, improper types, etc. of a Molecule_File data structure.""" mol = molecule_structure mol.natoms = len(mol.atoms) mol.nbonds = len(...
a82fce52db2184c523ee76eeab353e92e42dbabe
633,951
def jaccard_similarity(list1, list2): """ Calculate Jaccard Similarity between two sets """ intersection = len(list(set(list1).intersection((set(list2))))) union = len(list1) + len(list2) - intersection return float(intersection) / union
31da84ce335c8c404197e6ac7b8500178005e935
633,952
import os def get_file_upload_path(instance, filename): """ This function is called to obtain the upload path (relative to MEDIA_ROOT) including the filename for the file to be saved to disk. """ name, ext = os.path.splitext(filename) new_filename = "{}{}".format(instance.file_id, ext) ...
eb2f5b469d6ec222f24cf170fb181de839305302
633,953
def _scope_to_bind_var_to(function_call, enclosing): """Find a scope to bind variables set by function_call.""" if function_call.name == "set": try: if function_call.arguments[2].contents == "PARENT_SCOPE": assert enclosing.parent is not None enclosing = enclo...
7223aca5581bf23beb3d00de36579be91ebd5cb7
633,954
def render_menu_children(request, parent, items, menu_tag): """ Recursively render menu children. """ childs = [] output = [] for menu in items: if menu['parent_id'] == parent['id']: childs.append(menu) if childs: output.append('<%s class="ul_sublevel">' % menu_...
c047ec7508b5f51f57dd9a5a3ef38eeb9e020dc4
633,955
import subprocess def extract_reads(fasta_input, temp_read_list_file): """ Extract reads. """ cdx_input = fasta_input+ ".cidx" cdbyank = "cdbyank {0} < {1}" yank_command = cdbyank.format(cdx_input, temp_read_list_file) fasta = subprocess.check_output(yank_command, shell=True) re...
c23551cba7fc6b8e7cd9d4a93172964d6b73b981
633,956
def toAdjacencyList(molecule, label='', pattern=False, removeH=False): """ Convert the `molecule` object to an adjacency list. `pattern` specifies whether the graph object is a complete molecule (if ``False``) or a substructure pattern (if ``True``). The `label` parameter is an optional string to pu...
e6f194be8bcbaf94c31c42dfacc9b4ee2831076b
633,958
def defaultBBoxDeltaFun(w): """ When we reduce the width or height of a bounding box, we use this function to compute the deltaX or deltaY , which is applied on x1 and x2 or y1 and y2 For instance, for horizontal axis x1 = x1 + deltaFun(abs(x1-x2)) x2 = x2 + deltaFun(abs(x1-x2)) ...
c5aefadfd32def3f80815836be11c123e714da38
633,959
from typing import Tuple from pathlib import Path import os def split_s3_path(full_path: str) -> Tuple[str, str]: """Split a S3 path to bucket name and folder (file) path. Parameters ---------- full_path: str A full S3 path in format <bucket-name>/<folder1>/.../<folderN>/<file-name> Retu...
ac98c9d2765fe50bb9b25e82121e6700b7b78b38
633,960
def _GetLineNumberOfSubstring(content, substring): """ Return the line number of |substring| in |content|.""" index = content.index(substring) return content[:index].count('\n') + 1
444bad1aeef0f264ebe26b9b0ee15d066ff6c472
633,961
def build_component_descriptions(components): """Returns a colored description string for every log component based on its help attribute""" output = [] for k, v in components.iteritems(): output.append(" %s: %s" % (v['color'](k), v['help'])) return '\n'.join(output)
63eb8d52b0647f02ed18cb3e5258ae0f5d7e5be9
633,962
def is_success_type(qtype): """ Interprets a qtype (BINARY, UNKNOWN, etc.) as a "success" or "failure" """ return qtype[0] == 's'
e6224154e17620f98ce947fdf9769b9a935eef7a
633,963
import re def string_to_list(option): """Convert string to list. List may be enclosed in [], {}, (), or not enclosed. List entries must be comma delimited. Args: option (str) String to convert. Returns: (list) List of strings. """ PATTERN = r"[\{\[\(](.*)[\}\]\)]"...
78c3e82b845a73b354f4840393a3a2d3a511c30a
633,965
def add_percent_sign(n): """Add a % sign to the end of x, unless x is empty""" if not isinstance(n, str): n = str(n) if len(n) > 0: return n + "%" return n
83f5d89cb80ab8ebc6de75a3f30728f4c30d1747
633,966
import torch def backproject_th(depth, K): """Backproject a depth map to a cloud map. :param depth: Input depth map [H, W] :param K: Intrinsics of the camera :return: An organized cloud map """ assert depth.ndim == 2, depth.ndim H, W = depth.shape[:2] Y, X = torch.meshgrid( ...
75e69d36f737551fbdeae28a0fa5304b10bb2d89
633,968
def check(file): """ 检查文件是否已按小到大排序 :param file: 待检查文件 :return: 是否已排序 """ with open(file, 'r') as fd: # 第一个整数 line = fd.readline() if not line: return True prev = int(line.strip()) # 后续整数 while True: line = fd.readline() ...
6205a1181164b6792f7afa6a5f6c47546c55157d
633,969
def isCoveredBy(poly, poly1): """isCoveredBy(poly, poly1) - returns 1 if poly is completely covered by poly1, 0 if not""" return not (poly-poly1)
eb71c884a28d803f5c6d6569c119ed3d6faba834
633,970
def _int_or_str(c): """Return parameter as type integer, if possible otherwise as type string """ try: return int(c) except ValueError: return c
f569257b5114ad7c8317bd60469993b604b1cfc4
633,971
import functools def none_on_exception(func): """A decorator that returns the return value of a function or None if an exception is raised.""" @functools.wraps(func) def _decorator(*args, **kwargs): try: return func(*args, **kwargs) except Exception: return None ...
581b551912e8a81d9c657182e96d9ecbf4078ddc
633,972
import math def right_ascension_radians(oblqec, eclong): """Returns assention from right in radians from obliquity and ecliptic longitude radians.""" num = math.cos(oblqec) * math.sin(eclong) den = math.cos(eclong) ra = math.atan(num / den) if den < 0: ra += math.pi if den >= 0.0 and d...
9f43502c9f8da6dd57452994b1b21fc5644631bb
633,973
import subprocess import os def example_path(tmpdir_factory): """ Pytest fixture funtion to download the examples, decompress and return the path to the example/ folder """ # tmpdir_factory is a pytest built-in fixture that has "session" scope tmpdir = tmpdir_factory.mktemp('torsiondrive_test_tmp') tm...
5583587af7b5bfaac5192e5e41233af7c1edee4f
633,974
import random def seeds(count): """Return a list of random values of the specificed length.""" return [random.randint(0, 1 << 32 - 1) for i in range(count)]
2768e9cba10694b6f76bd4080ebab5cc2fec6ea0
633,975
import math def ent(x): """ Entropy [bits] given a vector of log probabilities """ x = [ math.exp(-val) for val in x ] logs = [ math.log(val, 2) for val in x ] prods = [ a * b for a,b in zip(x, logs) ] return - sum(prods)
eaada453d12171b461c5e9f476ed5b1dab2fe52b
633,976
def get_child_name_list(parent_object, object_list): """Get child's name list""" child_list = set() for child in object_list: if child in parent_object.child_list: child_list.add((child.name, "Child")) return child_list
a750400cf88ce158d64f0489fefb3d2ccec9cdef
633,977
def get_url(url): """ 1、构造请求代理 ip 网站链接 :param url 国内高匿代理的链接 :return 生成要爬取目标网址的链接 """ url_list = [] for i in range(1,100): url_new = url + str(i) url_list.append(url_new) return url_list
69ac4c64c29bb732b03ab96cef559df60ce3e2db
633,978
from pathlib import Path def is_package_file(f: Path, sap_code: str, name_pattern: str) -> bool: """Determine if the file is the right application JSON file :param f (Path): json file path :param sap_code (str): Adobe SAP code for product being processed :param name_pattern (str): json filename patter...
d9e9be639d7388f21a345938bd666f0bb5dfaa8b
633,979
def _str2float(s): """Cast string to float if it is not None. Otherwise return None. Args: s (str): String to convert or None. Returns: str or NoneType: The converted string or None. """ return float(s) if s is not None else None
78fcf41c91c41795b2b8c9e4465c6da5c8f2701a
633,980
import glob def extract_valid_auc(path_to_logs): """ Parse the AUC evolution from the log files. """ all_auc = [] for log_file in glob.glob(path_to_logs + '/*.txt'): with open(log_file) as f: valid_auc = [] for line in f: pos = line.find('Valid AUC')...
b54d390e7f4f9dc82514f04b2d228f53b8446e07
633,981
def round_scores(df): """ Some labels were interpolated by the data provider, so they must be rounded to the nearest integer to be used as a label. """ return df.score.round()
7c37ae909b0a3ad521c884ddd4b50f52fc567cbd
633,982
def lint_codeblock(styleguide, tmp_path): """Fixture which runs the styleguide's `lint` subcommand when executed.""" def run_linter( codeblock, *styleguide_args, # We ignore unused import warnings as most of the codeblocks which produce this warning # are just demonstrations of ...
67ad6ed2184c9d30de9d60491463c7ac18fe5690
633,983
import torch def cat_batch(*args): """ Concatenates batches of tensors :return: concatenated tensor :rtype: torch.Tensor """ return torch.cat(args, dim=0)
9678fdccf4e55adc761b9ac5c343233448bf3943
633,984
def _build_delete_sql_section(table_info): """ Build the "delete-sql" section of the pkey file. @param IN table_info Table information @return The section as a string """ result_lines = [] text = """ "delete-sql", " DELETE FROM %s WHERE """ % table_info.table_name...
8817f7e5c14258a86616709626f7c94554b99685
633,985
import hashlib def _rehash(value, salt2=""): """Rehash a value.""" for idx in range(1, 20): value = hashlib.sha256(f"{value}{idx}{salt2}".encode()).hexdigest() return value
678d96dbbaeadb0bf57b166511eab1eba8963a30
633,987
def inserter(cls): """ Mark a class as an inserter. """ cls.__inserter__ = True return cls
036fba2c6aeb187d6f0f04a33e3197f0eb199657
633,988
def loadinput(filepath): """Read a file and save each line as a list element Parameters ---------- filepath : str The path to the input file of the puzzle""" with open (filepath, "r") as inputfile: inputlines = inputfile.readlines() inputs = [line.rstrip() for li...
f00b264cea59372abbee300c6a563a1135941ba8
633,989
def FbetaScore(summary_stats, beta=0.5): """A metric between 0 and 1 that balances Precision and Recall. Returns the metric you get if you consider Recall to be ``beta`` times as important as Precision. """ tp = summary_stats.true_positives fp = summary_stats.false_positives fn = summary_stats.false_nega...
1ab06c65cd5d52e3727ce67d90d308a98e3abb56
633,990
def makeDivisorList(num): """ 入力された数の約数に1を加えたリストを返す [in] num: 約数を計算したい数 [out] divisor_list: numの約数に1を加えたリスト """ if num < 1: return [0] elif num == 1: return [1] else: divisor_list = [i for i in range(2, num // 2 + 1) if num % i == 0] divisor_lis...
74d3f99c6697dbeec1f1de5470d2efd2d881aab5
633,991
import logging def merge_correct_incorrect_total(correct, incorrect, total): """Merges the three lists of tuples and verifies the total""" log = logging.getLogger('read_density') merged = {} # Merge for x, y in total[1]: merged[x] = [0, 0, y] for x, y in correct[1]: if x != "...
91e32e4b36905ba6a208960ce2d975110d687ad8
633,992
def format_variable_assignment(step): """Format an assignment statement.""" asn = step['detail'] lhs, rhs, binary = asn['lhs'], asn['rhs-value'], asn['rhs-binary'] binary = '({})'.format(binary) if binary else '' return '{} = {} {}'.format(lhs, rhs, binary)
91a9c873ab7095eb99661bb74b5d1db0ef122755
633,993
def _run_py_cmd_with_output(runner, imports_line, command): """ To overcome the situation where additional info is printed to stdout when a command execution occurs, a string is appended to the output. This will then search for the string and the following closing brackets to retrieve the original o...
bbf5093cd73e3b773735d4c906ce4e8210652c8b
633,994
def create_internal_cookie(name, value, expires): """Create individual cookie to be stored inside Target cookie""" return { "name": name, "value": value, "expires": expires }
099315018a4235457f2acbbd344bd4530f09822d
633,995
def inflate_lvol_bdev(client, name): """Inflate a logical volume. Args: name: name of logical volume to inflate """ params = { 'name': name, } return client.call('inflate_lvol_bdev', params)
0826f77c6b9da7e8cce00b48b1e6236440c7a8bf
633,997
import requests import json def get_token_data(oauth_service, token): """ Gets the OAuth2 user attributes using the supplied token :param OAuthSSHCertSigningService oauth_service: an OAuthSSHCertSigningService object :param basestring token: an OAuth2 token :return: a json object of user a...
f4ddcb5985f67a7fbbb488b167127b7652edbb8a
633,998
import os def readme(new_dir): """ make a readme in the output folder """ nm = os.path.join(new_dir, 'params', 'readme.txt') f = open(nm, 'w') f.close() return f
3c009c72c0d8772332b9c0f7d8c6d0613657118d
634,000
import torch def training_data_covar_complex(covars_initialization_data): """ defines simple training data that corresponds to covar_complex (covars_initialization_data[1]), where covar_complex is the right format for initialization of the full user-facing class TuneSession (greattunes.TuneSession) ...
36d412ff92f03698a997c02eec387711716c7f5a
634,001
def add_sort_list( l1: list, l2: list, ) -> list: """Add two lists and sort them Parameters ---------- l1 : list The first list to be added l2 : list The second list to be added Returns ------- list The added and sorted list """ # Add ...
fc213db09e029d2f7e8052801593dc318fb87e3f
634,002
from typing import Any def get_data_representation(data: Any): """Common data representations. Other specific types should be handled by the user in his Parameter class.""" if isinstance(data, dict): return {key: get_data_representation(val) for key, val in data.items()} elif isinstance(data, ...
10412eba2b9e95e19f5f19029ac9079c31fd8e3e
634,003
def get_int_param(request, param, default=None): """ @return Numerical value of named parameter. """ try: return int(request.params[param]) except: return default
945594688dcc66cf1f85aedcbf9efa138bc36f83
634,004
def trapezoidal(f, a, b, n=10000): """trapez method for numerical integration""" s = 0.0 h = (b - a) / n for i in range(0, n): s += f(a + i * h) return h * (s + 0.5 * (f(a) + f(b)))
113a6a047e3fe320f5e0d511dc3119d6564fffa5
634,005
def password_length(): """Retrieves password length and returns a number """ length = input("Please input preferred password length: ") return int(length)
9d6c5443a50456c37df41ab055de13ec759eadb8
634,006
import optparse def parse_args(argvish): """ Build OptionParser and evaluate command line arguments. """ parser = optparse.OptionParser() parser.add_option('-r', '--region', type="int", help="Region") parser.add_option('-z', '--zone', type="int", hel...
a8fa21d013b4455947d808bfd2dadf628d608318
634,008
def omega_HI(z, cosmo, formula='powerlaw'): """ Omega_HI(z), obtained using a simple polynomial fit to Mario's data. Default: 'powerlaw' """ if formula == 'old': # Old formula, a polynomial fit to Mario's old data return cosmo['omega_HI_0'] * (1. + 4.77e-2*z - 3.72e-2*z**2.) else...
bed13c0b70da813cc71e49b1b6267db6ebed0991
634,009
import json def jsonify(*args, **kwargs): """ Helper based on flask jsonify and helsp convert lists and dicts into valid reponses. """ indent = None separators = (',', ':') headers = {'Content-Type': 'application/json'} headers.update(kwargs.get('headers', {})) if args and kwargs: ...
606c04663bc594c939489340dafc9bc7313ce432
634,010
def read_script_settings(extraction): """Reads CONSTANTS and generate settings for script. Returns: dict: Settings in one object """ settings = {} labels_and_attributes = {key:value for (key,value) in extraction.target_attributes.items()} settings['extend_with_reversed'] = extraction.ex...
ac40b382b0560fcc4ca26abeb4191ed7a39b4e40
634,011
def validate_resume(s2nd_out): """ Verify that s2nd properly resumes sessions. """ resume_count = 0 for line in s2nd_out.splitlines(): if line.startswith("Resumed session"): resume_count += 1 if resume_count == 5: break if resume_count != 5: pri...
a1735a71e62f80d1f43ce2320491b441c10ae415
634,012
def circular_indices(vector, start, length, num): """docstring for circular_indices""" if start > length: start = start-length if start+num < length: return vector[start: start+num] # get all till end, then from beginning return vector[start:] + vector[:start+num-length]
7e0fb784cc107b60d568defd76c38dc6998d84f3
634,013
import os def get_output_path(prefs, app_name, developer, recipe_type=None): """Build a path to the output dir or output recipe for app_name.""" path = os.path.join(prefs.get("RecipeCreateLocation"), developer) if recipe_type: path = os.path.join(path, "{}.{}.recipe".format(app_name, recipe_type))...
0bfe4c0fb3176c86c7352be27d9fdb05a0b32e83
634,014
from typing import OrderedDict import os def get_throughput(tp_file): """ Read the log of emitted tuples per component in each time interval and then creates a timeseries of the total throughput between readings (usually 5 seconds). """ timeseries = OrderedDict() last_counts = {} if not o...
2c16e500ef8e296342f06009124973e8b82606e3
634,015
from pathlib import Path def test_models(): """The folder where test models can be found.""" return Path(__file__).parent.parent / "test-models"
e3697a42f80953c5c2c7f472db58fa2d17cef24b
634,016
import functools def count_recursion(f): """Function decorator, prints how many times a function calls itself.""" start_time = 0 @functools.wraps(f) def count_recursion_wrapper(*args, **kwargs): nonlocal start_time p = (start_time == 0) start_time += 1 r = f(*args, **k...
5762387f9ebdf065623e35d1ac33a0b1c6567a50
634,017
def transpose(data): """ Transpose the data. In case the data are in rows, not columns """ return [*zip(*data)]
ad23a087d20ad94e0e31763fea77a844deaeba04
634,018
def generate_report(rates_to_watch): """ Generates a report on tracked rates and emails them. :param rates_to_watch: A list of CurrencyTrackers. :param email: The email to send report to. :param password: The password for the email account. """ # Create email report. complete_report = "" ...
2dc8e2964fa3bf080b932721589a9bc5056a5bf9
634,019
def _cgi_FieldStorage__repr__patch(self): """ monkey patch for FieldStorage.__repr__ Unbelievably, the default __repr__ on FieldStorage reads the entire file content instead of being sane about it. This is a simple replacement that doesn't do that """ if self.file: return "FieldStorage(...
6e70261393035ad7608107f953cb56da98920b61
634,020