content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os def namespace_default(): """ Get current namespace if running in a k8s cluster If not in a k8s cluster with service accounts enabled, default to 'default' Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125 """ ns_path = "/var/run/secret...
feae6848b6fb87dfec42cf8b1e12facc1ba1a4d9
643,098
def get_dx(p0, p1, smooth_line, cl_id, id_end, id_mid, id_start): """Get the displacement for the Voronoi point Args: p0 (ndarray): Point i on the old centerline. p1 (ndarray): Point i on the new centerline. smooth_line (bool): Turn on/off increasing curvuature. cl_id (int): ID ...
2dab59d1d7f28a87b63af95dbff222b4f406c19f
643,100
def has_outputfile(records: dict) -> list: """ Convenience function for finding output files in a dictionary of records""" keys, has_outputs = [], [] # check to see which records have outputfiles for key, record in records.items(): keys.append(key) has_outputs.append(record['output'] is ...
d6716d4bd33029fd857abfdb590480d3659af354
643,101
import os def valid_input_file(filename) : """ Validates that the given fine is a. accessible and b. not a directory. """ can_access = os.access(filename, os.R_OK) if not can_access : return (False, "Cannot access file: " + filename) is_directory = os.path.isdir(filename) if is_dir...
896103fe7f8ed1302ed70a6acf961dcf7cf6549b
643,102
def bytes_from_hex(value): """There are many ways to convert hex to binary in python. This function is here to attempt to standardize on a single method. Additionally, it will return None of None is passed to it instead of throwing an expected string exception """ if not value: return No...
574019f671d389f2dbf876156796266c57e9d550
643,103
import os def get_castro_dir(): """Return the location of the CASTRO directory.""" CASTRO_HOME = os.getenv('CASTRO_HOME') return CASTRO_HOME
df176c4e2261317b10f7bab591c5699e163d352b
643,104
def merge_dicts(dict_a, dict_b, default_key="default"): """ Recursively merge two nested dicts into a single dict. When keys match their values are merged using a recursive call to this function, otherwise they are just added to the output dict. """ if dict_a is None or dict_a == {}: ...
b7521cb36ae68c3cf317b50766b08fe76d6f76f0
643,105
def load_filelines(fullpath): """YG Develop March 10, 2018 Load all content from a file basepath, fname = os.path.split(os.path.abspath( fullpath )) Input: fullpath: str, full path of the file Return: list: str """ with open(fullpath, "r") as fin: p = fin.readline...
7784c98545207e175accced1cc124fdd3d221048
643,106
from typing import Optional import copy def _override_config_for_cube_id(config: dict, cube_id: str) -> Optional[dict]: """ Apply cube config overrides contained inside the `cubes` dictionary to get the config for the given `cube_id` """ # Need to do a deep-clone of the config to avoid side-effecs ...
19d3bd9823ed95214ffbf718550b5db3228b5307
643,107
def modes(nums): """Returns the most frequently occurring items in the given list, nums""" if len(nums) == 0: return [] # Create a dictionary of numbers to how many times they occur in the list frequencies = {} for num in nums: frequencies[num] = 1 + frequencies.get(num, 0) # How...
014f4833d917e55f2d7e9909c1356e9620441283
643,108
import argparse def parse_argument(): """guitarists or bands name""" parser = argparse.ArgumentParser( prog="This program checks for a band or a famuse guitarists in a band") parser.add_argument('n', help="insert the name of the guitarist or the band you would like to check") ...
5e1ec53fe757253de37f4143f9b3ac3515635a10
643,109
def get_search_params(params): """去掉为空的字段""" return {key: val for key, val in params.iteritems() if val}
d4c35d8f3dcb8a4ed96d21bb28ce1fb236a7751e
643,110
def get_degree_of(links: list, node_i: int) -> int: """ computes the degree of each node and maps the node id to its degree :param links: a list of tuples with [(src, dst), ...] :param node_i: index i of node :return: degree of node i """ deg_i = sum(1 if node_i == i else 0 for i, _ in link...
940f5942430d62091afd6ecdf668faa48621f017
643,111
import os import fnmatch def dame_arch_paths(path_to_folders, participants, test='architecture'): """Create dict of paths were architecture data will be stored """ arch_paths = dict() for participante in range(len(participants)): l1 = os.listdir(str(path_to_folders) + '\\' + participants[par...
4b82278050949d8e960859a1dc826c238478a06b
643,112
def vector_dot(v1,v2): """ Calculate vector dot product of two vectors. Parameters ---------- v1,v2 : ndarray The arrays to calculate the product from. The vectors are represented by the last axis. Returns ------- product : float or ndarray Scalar produc...
3f51c17f2aad5ebc1c788534177bf3fe89fd7a04
643,113
import torch def to_categorical(y, num_classes): """Converts a class vector made of integers to a categorical matrix. :param y: class vector of integers :type y: torch.Tensor :param num_classes: number of classes in y :type num_classes: int :rtype: torch.Tensor """ categorical = torch...
0266a7c98643834ec8a06239b9976a8f08a2db7a
643,114
def make_video_path(task_path, itr): """ Generate a video name based on a task name and iteration number :param task_path: the name of the task :param itr: the iteration number """ return "{}_tune_iter{}.mp4".format(task_path.replace("_center", ""), itr)
ff245ad4890863fd6cfec600071f8b10e4330e63
643,115
def season_results(*games): """make a dict of all teams with opponents""" #*games needs to be sorted by date holder = {g[0]:[] for g in games} for g in games: holder[g[0]].append([g[1], [x for x in holder[g[2]] if x[-1] < g[-1]]]+g[3:]) return holder
fcb9b61cd82ac38a73ec3c0554cbdedf6a848051
643,116
def get_label_name(node, dialogue_list): """ Takes a node and returns the name for its label """ for dialogue in dialogue_list: if dialogue["Id"] == node["Parent"]: label_name = "{}_{}".format(dialogue["DisplayName"], node["Id"]) return label_name
0971de9fac5861785edc97625ae9d331449403a3
643,117
def add_numbers(number1: int, number2: int) -> int: """Add two numbers together. Args: number1 (int): The first number. number2 (int): The second number. Returns: int: The sum of number1 + number2. Examples: >>> add_numbers(10, 5) 15 """ return number1 ...
52fc2bee6059e677d3d105e6ab9abe0720680b0d
643,118
import os def get_module_name(fullname): """Pull module name (eg. AIM) out of path (eg. /home/user/AIM.py)""" basename = os.path.basename(fullname) if basename.endswith("py"): return os.path.splitext(basename)[0] else: return basename[basename.rfind('.') + 1:]
4674bfd0443e6f264aba717f18c6e718ef1747d4
643,119
def _intersect(start,end, drops): """ helper function for overlap detection """ d = drops[drops['start'] < end] d['inter'] = d.apply(lambda row:len(list(set(range(start, end + 1)) & set(range(row['start'], row['end'] + 1)))), axis=1) #define pverlap as a minimun 1/3 cover if d[d['inter'] >= ...
1cf9622bff07ed33e303e0e6e79edd5e71779410
643,120
import math def find_pandigital(n): """Finds a 9 digit pandigital if possible, otherwise returns 0. Will also return 0 if the first digit is not 9 - can optimise to ignore less than current multiple Args: n (int): the number to multiply """ number_of_digits_left = 9 val = "" m = n...
75a5474af37d0bf3dd198114660042935b987be1
643,121
def get_info(info_proto): """Extract the shape from a ValueInfoProto.""" shape = [] shape_name = [] for dim in info_proto.type.tensor_type.shape.dim: name = dim.dim_param value = dim.dim_value if value is None or value == 0: shape_name.append(name) else: ...
a5a7fa5c83e41949e8568745c0d4a724cbc6c6ca
643,122
def cent_from_year(year): """ takes an integer and returns the matching century """ if year == 0: return 1 elif year < 0: return -(year - 1) // -100 else: return (year - 1) // 100 + 1
cfa372d9b21b7d6b56bfbd73be4518f485f1b8ce
643,123
def y_fitted_line(m_val, b_val, vec_x): """ This function returns the fitted baseline constructed by coeffecient m and b and x values. ---------- Parameters ---------- x : list Output of the split vector function. x value of the input. m : int/float inclination of the bas...
03913131167279428e48a60cef3a8c9035916f5b
643,126
def dissolve_footer(soup): """ Remove the BNN footer, generated date, build, etc. This is included with all OOTP pages. """ # Dissolve the BNN footer trs = soup.body.table.find_all('tr') last_tr = trs[-1] last_tr.decompose() # Dissolve the generated date and build tbls = soup.bo...
922e0c835ef1e6bd8e7924e449f8d61e6613e94e
643,127
def _compile_module(s, name='<string>'): """ Compiles a string representing a python module (file or code) and returns the resulting global objects as a dictionary mapping name->val. @param name: Optional name for better error message handling. """ gen_module = {} code = compile(s, name...
3b3ea8a428617adead44bec55b5f1638328e0148
643,128
def siqs_build_matrix_opt(M): """Convert the given matrix M of 0s and 1s into a list of numbers m that correspond to the columns of the matrix. The j-th number encodes the j-th column of matrix M in binary: The i-th bit of m[i] is equal to M[i][j]. """ m = len(M[0]) cols_binary = [""] * m ...
faac80e9d645e829f198b167ef8ee9c4cfa2df0a
643,129
def binary_to_int(binary: str) -> int: """Convert a binary string to an integer Args: binary (str): Binary string Returns: int: Integer value of binary string """ return int(binary, 2)
aa7d694facc18c3872d345c5c06dcd6ad3b51105
643,130
import random def assignRandomSigns(G): """ :param - G: Graph return type: dictionary (key = node pair (a,b), value = sign) return: For each edge, a sign (+, -) is chosen at random (p = 1/2). """ signs = {} ############################################################################ for edge in G.Edg...
7dc7432e13f58aa391f29768c1a0b77dc790c3a3
643,131
def is_timerange(item: str) -> bool: """Returns True if the item is a TAF to-from time range""" return ( len(item) == 9 and item[4] == "/" and item[:4].isdigit() and item[5:].isdigit() )
28961d8699574b1fca24dc0961a281f92d12aac3
643,132
import os def _looks_like_path(name: str) -> bool: """Checks whether the string ``name`` "looks like" a path on the filesystem. This does not check whether the target actually exists, only judge from the appearance. Returns true if any of the following conditions is true: * a path separator is ...
83eb9a7f304757bfc0e27349c023b38324e263a5
643,133
def lcr_regularizer(rewards): """ implements locally constant rate (LCR) regularizer from guided cost learning. This is basically a second derivative penalty. :param rewards: torch tensor stack of rewards, which must still contain backprop info. :type rewards: torch.tensor """ if len(rewar...
e0a6edbdeacf995613ce96bb35792919d8867f40
643,134
import math def _ppo_training_epochs(hparams, epoch, is_final_epoch, real_env_training): """Helper for PPO restarts.""" if hparams.gather_ppo_real_env_data: assert hparams.real_ppo_epochs_num is 0, ( "Should be put to 0 to enforce better readability") real_training_ppo_epochs_num = int(math.ceil( ...
91a7efe50cf7f96427ee3f75ccafda65a7acf522
643,136
def ensure_arg(args, arg, param=None): """Make sure the arg is present in the list of args. If arg is not present, adds the arg and the optional param. If present and param != None, sets the parameter following the arg to param. :param list args: strings representing an argument list. :param string arg: arg...
c65bec4c3352a2d7e197bd3c0f75d09b9b796722
643,137
def switch_part_context(token_list, carried_context): """ Notices can refer to multiple regulations (CFR parts). If the CFR part changes, empty out the context that we carry forward. """ def is_valid_label(label): return label and label[0] is not None if carried_context and carried_context[0] ...
e645494c825069513d41db7bef24f6998f165019
643,138
def ns_split(term): """ Take apart an ElementTree namespaced name, returning the namespace and a localpart. """ (ns, local) = term.split("}") assert ns[0] == "{" ns = ns[1:] return ns, local
ffadd295bb2bce5f2d39c6e8acdedfeb34682ba3
643,139
import argparse def create_parser(): """Create command line argument parser""" parser = argparse.ArgumentParser("Convert CSV to HDF") parser.add_argument( 'input', help = 'Input HDF file', metavar = 'input', type = str, nargs = '+' ) parser.add_arg...
18cbf0233d1ac5933bfdf3f387cf23a5fc1e02e5
643,140
import requests def get_request(url, headers): """ Method which makes a GET request to specified url :param url: url :param headers: headers :return: get response """ return requests.get(url, headers=headers)
d1b4c346d2382840de2197b0cc78e473bccbbbbf
643,141
def average(a, b): """ :param a: int, sum of total value :param b: int, the amount of temp information :return: a / b """ avg = a / b return avg
a07de5e11a53c0e10fad3c8a5cf0cfec5f83cb7c
643,142
import hashlib def genId(filename): """ Generates an identifier suitable for ingestion Based off of the Watson Discovery Tooling method of generating IDs """ return hashlib.md5(filename).hexdigest()
ca645809ba94f7d9d4e81a87f2ca8e643114a5ed
643,143
def validate_key_value_pairs(string): """ Validates key-value pairs in the following format: a=b;c=d """ result = None if string: kv_list = [x for x in string.split(';') if '=' in x] # key-value pairs result = dict(x.split('=', 1) for x in kv_list) return result
81713ae08bc096168843384aa79563f4737d4c41
643,144
def match_gene_txs_variant_txs(variant_gene, hgnc_gene): """Match gene transcript with variant transcript to extract primary and canonical tx info Args: variant_gene(dict): A gene dictionary with limited info present in variant.genes. contains info on which transcript is canonic...
1e14fa45bde9b6cab8610220436c62836d88f90e
643,145
from typing import Union from typing import Tuple def _to_tuple(value: Union[Tuple[float, float], float]) -> Tuple[float, float]: """Convert value to a tuple if it is not already a tuple. Args: value: input value Returns: value if value is a tuple, else (value, value) """ if isin...
1efad46b6ade7ab07aa5bf09fb18c6588d619246
643,147
import platform def is_linux_system(): """ | ##@函数目的: 获取系统是否为linux | ##@参数说明:True or False | ##@返回值: | ##@函数逻辑: | ##@开发人:jhuang | ##@时间: """ return platform.system() in ['Linux','Darwin']
3df0c96b3bbde11f0194811336444dce255fdc43
643,148
from typing import List import os def list_sub_dirs(path: str) -> List[str]: """ List sub-directories inside a directory Parameters ---------- path directory path Returns ------- list list of names of sub-directories """ return [f.name for f in os.scandir(path) if...
644c0c55d1c2abf86cfe432aad2e8d74ce58469f
643,149
import re def server_text_to_sendable_text(server_text): """Returns `server_text`, a string in Slack server message format, converted into a string in Slack sendable message format.""" assert isinstance(server_text, str), "`server_text` must be a string rather than \"{}\"".format(server_text) text_without...
c18d0ab13a24c07731fd11d8f3b2fa6b7199bddd
643,150
import os def _empty_dir(d): """return True if the directory d does not exist or if it contains no files/subdirectories.""" if not os.path.exists(d): return True for (root, subdirs, subfiles) in os.walk(d): if len(subfiles) or len(subdirs): return False return True
0c252a8bdd662d871d5dea822b61a920346b70f6
643,151
def argument(*args, **kwargs): """ Define how a single command-line argument should be parsed. *args* and *kwargs* have the same meaning as :meth:`argparse.ArgumentParser.add_argument` method. """ return args, kwargs
3158cff2996b290ea8e47170157147c65c65e65d
643,152
def walkable(grid_array: list) -> list: """Get a list of all the coordinates that are walkable Args: grid_array (list): map of the terrain Returns: list: all coordinates that are walkable """ walkable = [] for i, row in enumerate(grid_array): for j, cell in enumerate(ro...
848f2f3eec16086e235d4ea9e2181c8c7ba31375
643,153
def num(list): """ returns number of members in GQL list """ return list.count()
e1323e8577236a880160ec4cd00c0e167eeccbd9
643,155
def welcome(): """return simple welcome message""" html = "welcome" return html
61bad91741d6b89f25dab24777f0e6a2233ff6ca
643,156
import re def _sanitized_conf(parser): """Formats parser config, redacting database url password.""" out = parser.format_values() return re.sub(r'(?<=:)\w+(?=@)', '<redacted>', out)
580640d160c88ecaf9a5bc9df741df1d9056ae5c
643,157
def image(img): """Function to obtain image from tensor""" img = img / 2 + 0.5 # unnormalize return img.numpy()
bb53dde61db4b3af81e2e123ed9c6c2dd87fabaf
643,158
def StringLiteral(s): """Returns string literal for text.""" return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"'
fc130360a091d9eb99ebff38a97f1e3570318856
643,159
def total_consumption(consumption: float, area: float) -> float: """Get the total consumption of a building in a year. It's function of the energy consumption and total area. Args: consumption (float): The consumption of the building in kWh/m².year. area (float): The total area of the buil...
33ff23a3fff2a095c0800db5a36550f74047c418
643,160
import uuid def broker_proxy(event, expire=10): """ Прокси метод - отправляет входящее сообщение воркеру через брокера. Этот метод вызываетя из объекта класса RPCBrokerProxy(socket, 'broker_proxy', broker_address) """ agent = event.pool.context['server'] event.prevent_done() if 'event_...
77dce35758db2181a14014509cbeab18ce22d6ee
643,161
def OffsetList(inputList, offset): """ Return a list equal to the input list with all entries equal to the corresponding entries in the input list plus the supplied offset """ outputList = [] for entry in inputList: outputList.append(entry + offset) return outputList
66b1633791d3ca6ef91006e8cbca88a6dbe9db99
643,162
def make_weights_for_balanced_classes(images, nclasses): """ Function to obtain dataset dependent weights for the dataloader :param images: :param nclasses: :return: """ count = [0] * nclasses for item in images: count[item] += 1 weight_per_class = [0.] * nclasses N = flo...
3d03ff4af62f314f8a4a2f85b0091c012bf746a5
643,163
import re def set_filename_version(filename, version_number, pattern): """Write the given version number in the given (in filename) file, after the given pattern. E.g.: set_filename_version('setup.py', '1.0.0', 'version') Extracted from Flask source, see: - file: flask/scripts/make-r...
c2cd57e38809a4ff25ee8fcd4d722eadbb95ec9f
643,164
def create_end_repeat(nstep, iline, protocol, inrepeat): """ Given a line from a file with format: add to the protocol an [# : End repeat nstep steps :] line Parameters ----------- nstep : int Number of steps in a loop iline : int Counter for protocol lines protocol : ...
cb058834d0be6a147e1800a61a4381e837177f8e
643,165
import math def columnate(strings, separator=", ", chars=80): """ render a list of strings as a in a bunch of columns Positional arguments: strings - the strings to columnate Keyword arguments; separator - the separation between the columns chars - the maximum with of a row """ col_w...
eb205ba26b90c55d21502a3ffc758986b3ee54e8
643,166
def _before(node): """ Returns the set of all nodes that are before the given node. """ try: pos = node.treeposition() tree = node.root() except AttributeError: return [] return [tree[x] for x in tree.treepositions() if x[: len(pos)] < pos[: len(x)]]
63c0fef768c3ade922a834fba24c3797d5d0e932
643,167
import os def getSyslogAddress(): """find the address to use for syslog""" for dev in ("/dev/log", "/var/run/syslog"): if os.path.exists(dev): return dev return ("localhost", 514)
dedb6db51efa5405c2f00ffe0bf7bd14c92b70d4
643,168
def connect(user, passwd, host, port): """connect is a convenient shortcut to mysql.connector.connect. Also, it makes it reasonable to import mysql.connector in this file, so to make it self-complete as a template. """ return connect(user=user, passwd=passwd, host=host, port=port)
48f31f13ff1540ed2b5ee4a8db71bbefc80128e1
643,169
def calculate_immediate_dominators(nodes, _dom, _sdom): """ Determine immediate dominators from dominators and strict dominators. """ _idom = {} for node in nodes: if _sdom[node]: for x in _sdom[node]: if _dom[x] == _sdom[node]: # This must be th...
51775461134dc07993462c903c3d6a23b26199da
643,170
from typing import List def simulate_day(school: List[int]) -> List[int]: """Simulates a school of fish for one day and returns the school.""" return [*school[1:7], school[0] + school[7], school[8], school[0]]
126f430920474d54651bf7a19a18006f66792ff1
643,171
def chromedriver_path_of(system_name) -> str: """Gets system name and returns a string path :param string system_name: should be "Windows", "Linux" or "Darwin". System name can be obtained from "platform" module and "system" function """ if system_name == 'Windows': return "./chromedriver....
6fd114dc105e14de6abb7ecf6cc9e40cdc03d751
643,172
def extractResults(resultsDict): """ Return a list of dictionaries, one for each entry in the resultsDict. Each dictionary contains a few selected fields. """ outList = [] entryList = resultsDict['entry'] # ESA are nutters. If there is only a single entry, then instead of a list o...
2b21e93ccab71226c5a5197e54a2df622b6dbb19
643,173
import os def get_from_env(var_name: str) -> str: """ Get a value from an environment variable. Used in CI for testing. """ val = os.getenv(var_name, "") if val == "": print(f"Error: Missing environment variable {var_name}.") exit(1) return val
ec90ca09cb7d797e40690120eb3515ce01803780
643,174
def update_orb_spec(spec, param): """ Update an orbital specification. Enter: spec: the text specification. param: a dictionary of parameters to update. """ lines = [line for line in spec.replace('\r', '\n').split('\n') if line.strip()] out = [] for line in lines: parts = ...
4e4fae750f43c89754c56c3a84c2aac8726c4414
643,175
def mscb(t): """ Find the index of the most significant change bit, the bit that will change when t is incremented aka the power of 2 boundary we are at >>> mscb(0) 0 >>> mscb(1) 1 >>> mscb(7) 3 >>> mscb(8) 0 """ return (t^(t+1)).bit_length()-1
aedcd5501a83d872053582608552e841535e027b
643,176
def computeH(vertex, B_vertex): """Function for computing heuristic H(vertex). To compute H(vertex), use computeH(vertex,B_vertex)""" """Recall that the heuristic is an underestimate of the cost-to-go from a vertex to the goal""" H = abs(vertex.position[0] - B_vertex.position[0]) + abs(vertex.position[1] -...
a2c2c13af6b6d6c4a6f86c433638e32100c4bc94
643,177
def update_with_expectedkey(): """ function to return an object that simulates json update posted to the bot's fall back webhook url this data has the expected key and chat_id of typ int """ update = { 'update_id': 418763186, 'message': { ...
a0fb9e3514930609029509cd53d12ea025229f76
643,179
from typing import List from typing import Any def get_val_from_arg_list(args_list: List[str], key: str, default: Any): """Parse an argparse args list for keys and return their associated value.""" try: key_index = args_list.index(key) if len(args_list) > key_index: return args_lis...
903ecb6e3e9b79959e33f4ba7febec37005794ad
643,180
import random def genRandomUSAState(): """ Returns a random USA state """ state = random.sample(['AL', 'AK', 'DE', 'FL', 'GA', 'HI', 'AZ', 'CA', 'AR', 'OR', 'IN', 'IA', 'MI', 'CT', 'KS', 'KY', 'UT', 'LA', 'TX', 'TN', 'IL', 'WA', ...
efad41197c8079897ea6df915b36b7ca1ff5604b
643,181
def skip_instance(context, family_name): """ Skip process if instance exists. :param context: (obj) Instance context :param family_name: (str/list) F :return: bool """ if not isinstance(family_name, list): family_name = [family_name] _exists = False for instance in context: ...
6037312a127b5af862f5a054967f2d6e5846fe02
643,183
from typing import List def merge_sort(A: List) -> List: """Merge sort algorithm""" if len(A) > 1: mid = len(A) // 2 L, R = A[:mid], A[mid:] n1, n2 = len(L), len(R) merge_sort(L) merge_sort(R) i = j = k = 0 while i < n1 and j < n2: if L[i...
24d632ea3e6f1e15a6f33edc9778c7a820e621eb
643,184
from typing import List import re def get_terms(tickers: List[str]) -> List[str]: """Map tickers to bond terms, e.g. Brazil 5Y -> 5Y""" return re.findall(r"\d+[MYmy]", "|".join(tickers))
9ba1a9d348282a6202002c187346c7b95da4504a
643,185
def format_percent(n, baseline): """Format a ratio as a percentage (showing two decimal places). Returns a string. Accepts baseline zero and returns '??' or '--'. """ if baseline == 0: if n == 0: return "--" else: return "??" return "%.2f%%" % (100 * n ...
274c3dce2f88ec9fa5f0d4ea41890a8dfd7d79cb
643,186
def _gendesc(infiles): """ Generate a desc entity value. Examples -------- >>> _gendesc("f") 'coeff' >>> _gendesc(list("ab")) ['coeff0', 'coeff1'] """ if isinstance(infiles, (str, bytes)): infiles = [infiles] if len(infiles) == 1: return "coeff" retur...
81645b805f4d8e7a0ba110be53c30fdb4c7ac0c5
643,187
def _get_arguments(*args): """Helper function which prepares input data for custom myrange2 and myrange3 functions. It makes sure that at least one but no more than three integers were supplied. Returns tuple of three integers, where the last number is never zero. Can raise TypeError or ValueError exce...
234efb67c7b6c7aa879dd5f85f77f99e8abf1a3a
643,188
def as_form_type(form): """ Usage: ``{{ form|as_form_type }}`` """ return form._meta.model._meta.model_name
1e139f35aad6971dcf759c9a46d1405312bdb4c0
643,189
import re def parse_entities(line): """Parses a line for R numbers, EC numbers, or KGML internal reaction IDs. :param line: line in CoMetGeNe result file :return: list of reaction identifiers (KEGG R numbers), EC numbers, or KGML internal reaction IDs """ entities = line.split(':')[1].str...
850f155e3cda343e0ba2d53d0d7e6290eb3fc977
643,190
def take(n, seq): """Returns first n values from the given sequence.""" # seq = iter(seq) # seq = seq result = [] try: for i in range(n): result.append(seq.next()) except StopIteration: pass return result
d393e5e5203e79e0ba1fcd376e0471f3c9db32f1
643,191
def user_roles_helper(client, roles): """ Accepts list of role identifiers and converts them to named roles. Return list of names. """ data = client.list_roles() named_roles = [] for role in data.get('result'): if role.get('iden') in roles: named_roles.append(role.get('name'...
f8d80471e8e81b95356da9c3b2f02c3965cde034
643,192
import sys def _build_environ_dict(headers, stream): """ Build the WSGI environ dictionary for a given request. To do that, we'll temporarily create a dictionary for the headers. While this isn't actually a valid way to represent headers, we know that the special headers we need can only have one ...
7d391d0ce3f1f2b9d30ae7b995a418642f15c540
643,193
def _extact_field(object, name): """ Recursively search through a simple python object to find an element with the given name and return it. """ if object[0] == name: return object for child in object[2]: extracted = _extact_field(child, name) if extracted: re...
b05067dd938656219d67cf2b105733137851a2a1
643,194
import unittest def suiteFactory( *testcases, testSorter = None, suiteMaker = unittest.makeSuite, newTestSuite = unittest.TestSuite ): """ make a test suite from test cases, or generate test suites from test cases. *testcases = TestCase subclasses to work on ...
ba480bb95a77b4b6c152363e489f4cd0d62bd8bb
643,195
def has_empty_domains(csp) : """Returns True if the problem has one or more empty domains, otherwise False""" variables = csp.variables for var in variables: if len(csp.get_domain(var)) == 0: return True return False
a3506b1ffd73c1a26dcaa9fcd2428e8e1bc83875
643,196
def load_contcar(path): """ Loads CONTCAR file into an array of lists """ f = open(path, "r") # Initialise empty list 'rows' contcar = [] # Add POSCAR-file line by line into list 'rows' for line in f: contcar.append(line) f.close() return contcar
854cebd6861a00d78464b027b29153e59e56168d
643,197
import argparse def create_common_arg_parser(): """Create an argument parser for the root CLI command shared by subcommands.""" parser = argparse.ArgumentParser(prog='margipose', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # parser.add_argument('--device', ...
114e915c6f1485eef7296a931aa2c7495d8036e8
643,198
def setup_mocks(base_obj, mock_spec): """Setup mocking.""" restore = dict() for name, mock in mock_spec.iteritems(): obj = base_obj name_parts = name.split(u'.') for name_part in name_parts[:-1]: obj = getattr(obj, name_part) # save original object for restoring in tearDown restore[name]...
110e2456e0e7414b1153f7978ceab33964849f96
643,199
def github_paginate(session, url): """Combines return from GitHub pagination :param session: requests client instance :param url: start url to get the data from. See https://developer.github.com/v3/#pagination """ result = [] while url: r = session.get(url) result.extend(r....
6c951f0dadc3d6b8c0bae7ada61bbd46e085d544
643,200
import csv def get_stats(csv_path): """Parse aligned results csv file to get results. Args: csv_path: str, aligned result path, e.g., xx_corresp.txt Returns: stat_dict, dict, keys: true positive (TP), deletion (D), insertion (I), substitution (S), error rate (ER), ground truth numbe...
f453d5af9a8f77a9767ccbb1f78ee21d4122844c
643,202
import re def scrape_eps(soup, sngl=False): """Scrapes all episode names and numbers from a specified HTML page, in the form of a specified :class:`bs4.BeautifulSoup` object. :param soup: A :class:`bs4.BeautifulSoup` object containing the HTML of the Wikipedia page to be scraped. :para...
a9dcbe7e409ba36615048fd3d73dd8636a6c12b9
643,203
def read_file(filename): """ Return the contents of a file as a string. """ with open(filename) as f: str = f.read() return str
1adf083bf2d54c9ed07e7afa81ff746bc36b4303
643,204
def var_radrad(tsclass): """ Return boolean to see if fake wells are needed """ rad_rad = 'radical radical' in tsclass low_spin = 'high' not in tsclass # corr_rxn = 'addition' in tsclass or 'abstraction' in tsclass # return bool(rad_rad and low_spin and corr_rxn) return bool(rad_rad and lo...
f53b53155b569ba290535bfdaa3994146f6e255c
643,205
import os def get_backend(): """Get the name of the backend handling this request. Returns: string: The current backend, or None if this is not a backend. """ return os.environ.get('BACKEND_ID', None)
820f25604d4bd08affb90518b194c344f2ba9a86
643,206