content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def put_backup_vault_access_policy(BackupVaultName=None, Policy=None):
"""
Sets a resource-based policy that is used to manage access permissions on the target backup vault. Requires a backup vault name and an access policy document in JSON format.
See also: AWS API Documentation
Exceptions
... | 77,500 |
def cloud_xfd():
"""The main function.
Please note that we are using processes instead of functions
because Flask prefers to be running in the main thread"""
lock = multiprocessing.Lock()
http_process = multiprocessing.Process(target=http_worker, args=(lock,))
http_process.daemon = True
htt... | 77,501 |
def request(url, method, session=None, **kw):
""" Makes an HTTP request following redirects. """
import os
user_agent = os.environ.get('WEX_USER_AGENT')
if session is None:
session = requests.Session()
session.stream = True
session.headers = {'User-Agent': user_agent} if user_... | 77,502 |
def notch_filter():
""" implements a notch filter with notches at 1/week and 2/week; assuming input signal sampling rate is 1/week"""
fs, f0, Q = 1, 1/7, 1
b1, a1 = iirnotch(f0, Q, fs)
b2, a2 = iirnotch(2*f0, 2*Q, fs)
# Frequency response
b = convolve(b1, b2)
a = convolve(a1, a2)
def fil... | 77,503 |
def monthly_file_name(var, model, rcp):
"""Function for creating file connections for different variables
scenarios and models. Preasently, ensemble member r1i1p1 is assumed, as
well as 200601-210012 dime span for the monthly data."""
# e.g. hfls_Amon_CNRM-CM5_rcp85_r1i1p1_200601-210012.nc
f = var + "_" + "Amon_... | 77,504 |
def extract_sum_of_products(cluster, template, *args):
"""
Extract sub-expressions in sum-of-product form, and assign them to temporaries.
"""
make = lambda: Scalar(name=template(), dtype=cluster.dtype).indexify()
rule = q_sum_of_product
costmodel = lambda e: not (q_leaf(e) or q_terminalop(e))
... | 77,505 |
def minimize(_mol, nsteps, opttol, func, minimizer):
""" Minimizes a single molecule
Arguments:
nstesp -- perform a maximum of nsteps steps
opttol -- the maximum rms gradient shall be below this value
func -- energy and gradient function
minimizer -- a minimizer
"""
... | 77,506 |
def _init_logger():
"""Initialize the Bempp logger."""
_logging.addLevelName(11, "TIMING")
logger = _logging.getLogger("bempp")
logger.setLevel(DEBUG)
logger.addHandler(_logging.NullHandler())
return logger | 77,507 |
def request(method, url, **kwargs):
"""
Central place to make any v1 api request.
:param (str) method: The request method ('get', 'put', 'delete', ...).
:param (str) url: The full api url to make the request to.
:param kwargs: These are passed along to requests.
:return: (requests.Response) The... | 77,508 |
def single_epoch_train(model, data_loader, criteria, optimizer, device, pad_idx, args, epoch=None):
"""
:param model:
:param data_loader:
:param criteria: (dict) holding all modules for computing the losses.
:param optimizer:
:param device:
:param pad_idx: (int)
:param args:
:return:... | 77,509 |
def default_key_provider(func: Callable, *args, **kwargs) -> str:
"""
Default cache key function. This uses cloudpickle to hash the function and all arguments.
"""
return cloudpickle.dumps({"function": func, "args": args, "kwargs": kwargs}) | 77,510 |
def fips_to_location_id(fips: str) -> str:
"""Converts a FIPS code to a location_id"""
try:
return dataset_utils.get_fips_to_location().at[fips]
except KeyError:
# This happens mostly (entirely?) in unittest data where the first two digits
# are not a valid state FIPS. See
# ... | 77,511 |
def new_database(aiida_profile):
"""Get a the database for the test and clean it up after it finishes"""
aiida_profile.reset_db()
return | 77,512 |
def test_pattern():
"""Test that the pattern() constructor produces the equivalent Pattern
instance"""
true_cond = lambda expr: True
patterns = [
(pattern(OperatorSymbol, 'O', hs=FullSpace),
Pattern(head=OperatorSymbol, args=['O', ], kwargs={'hs': FullSpace})
),
(patter... | 77,513 |
def check_asset_availability(start=None, end=None):
"""
Am I within the Asset's availablity window?
If "start" is defined, now >= start must be True
If "end" is defined, now <= end must be True.
Otherwise each condition is presumed TRUE
(e.g., no "end" date means that it doesn't expire, h... | 77,514 |
def test_none_prefix():
"""
Test for None prefix
"""
token = "asdashdsauh_8aeraerf"
tags = {"region": "us-east-1"}
registry = MetricsRegistry()
reporter = ApptuitReporter(sanitize_mode=None, registry=registry,
api_endpoint="http://localhost",
... | 77,515 |
def calc_distance(l):
"""Calculates distance between list items in two lists"""
# l needs to start from zero, get lowest number and substract it from all numbers
min_l = min([x[1] for x in l if x[1] != ''], default=0)
l = [[x[0], (x[1] - min_l)] for x in l if x[1] != '']
distance = 0
for id... | 77,516 |
def load_archive(task_name: str, hparam_set_name: str):
"""Load a precomputed archive file for `task_name` and `hparam_set_name`."""
path = get_baseline_archive_path(task_name, hparam_set_name)
return read_npz(path) | 77,517 |
def automake_substitution(name, src, out, substitutions = {}):
"""Replaces @VARIABLE_NAME@ occurences with values.
Note: The current implementation does not allow slashes in variable
values."""
substitution_pipe = " ".join([
"| sed 's/@%s@/%s/g'" % (variable_name, substitutions[variable_name])... | 77,518 |
def use_learned_model(model_file: str, remove_pattern: str = "", replace_pattern_file: str = "") -> pd.DataFrame:
"""標準入力から読み込んだ文字列に対して学習済みモデルによる推論を実施
:param model_file:
:param remove_pattern:
:param replace_pattern_file:
:returns:
:rtype:
"""
print("%inf:csv_text_tfidf:read text... | 77,519 |
def get_explanation_accuracy(model:torch.nn.Module,loader:torch.utils.data.DataLoader,mem_loader:torch.utils.data.DataLoader,device:torch.device)-> Tuple[float, float, float]:
""" Method to compute the explanation accuracy for different settings, as
described in the paper. Explanation accuracy checks how many t... | 77,520 |
def locale_convert(key):
"""Creates a converter for a locale key."""
def lc_converter(val):
try:
locale.setlocale(LOCALE_CATS[key], val)
val = locale.setlocale(LOCALE_CATS[key])
except (locale.Error, KeyError):
msg = 'Failed to set locale {0!r} to {1!r}'.forma... | 77,521 |
def upgrade():
"""Upgrade database schema and/or data, creating a new revision."""
conn = op.get_bind()
rel_data = load_relationships_data(conn)
proposal_data = load_proposal_data(conn)
create_old_rel_del_revisions(conn, rel_data)
create_old_proposal_del_revisions(conn, proposal_data)
remove_relationships... | 77,522 |
def get_offer_info(soup, offer_id):
"""get information about a specific offer according to its id
information: title, company name, published date, link
Parameters
----------
soup: BeautifulSoup
html code
offer_id: str
offer identifier
Returns
-------
dict:
... | 77,523 |
def to_csv(raw_data):
"""Converts a serialized TfStatsDatabase string to CSV."""
tf_stats_db = tf_stats_pb2.TfStatsDatabase()
tf_stats_db.ParseFromString(raw_data)
return generate_chart_table(tf_stats_db.with_idle,
tf_stats_db.device_type).ToCsv() | 77,524 |
def pca_plot(table_xy: pd.DataFrame, section: str, ax_i: plt.axes, color_col: str ="SVI"):
"""
Plots the PCA as desired.
Parameters
---------
table_xy: pd.DataFrame
table containing only one section of the data to plot in this axis.
section: str
section plotted
ax_i: plt.ax... | 77,525 |
def lam(x, lam0, alpha=4.0):
"""Return classic alpha model lambda value(s) for input value(s)."""
return lam0 * ( 1.0 - x**alpha ) | 77,526 |
def Add(left: Expr, right: Expr) -> BinaryExpr:
"""Add two numbers.
Produces left + right.
Args:
left: Must evaluate to uint64.
right: Must evaluate to uint64.
"""
return BinaryExpr(Op.add, TealType.uint64, TealType.uint64, left, right) | 77,527 |
def reduceCoefficients(polynomial : Polynomial) -> Polynomial:
"""
Initialize a Polynomial for the Kerner method:
Make the leading coefficient 1
"""
eq = polynomial.eq()
h_coeff = eq.get(max(eq))
return Polynomial([
coefficient / h_coeff for coefficient in polynomial.arr()
... | 77,528 |
def count():
"""
查询记录总数
"""
return Record.objects.owner().count() | 77,529 |
def campbell(caseFile, mainFst, tStart, nPerPeriod, workDir, toolboxDir, matlabExe, fastExe,
baseDict=None, generateInputs=True, runFast=True, runMBC=True, prefix='',sortedSuffix=None, ylim=None):
"""
Wrapper function to perform a Campbell diagram study
see: writeFASTLinInputs, matlabMBC,... | 77,530 |
def get_files_time_period(prefix, yr_s, yr_e):
"""
Get nc files within the time period, with the prefix
:param prefix: prefix of file names
:param yr_s: start year
:param yr_e: end year
:return: files in folder, max and min year
"""
# Get path and folder
path = directories.CLIMATE_D... | 77,531 |
def _iter_rewritable_modules(package_files):
"""
Given an iterable of file names in a source distribution, return the "names" that should
be marked for assertion rewrite (for example the package "pytest_mock/__init__.py" should
be added as "pytest_mock" in the assertion rewrite mechanism.
This func... | 77,532 |
def test_executor_log_predictor_version():
"""Confirm that the predictor.__version__ value is properly handled"""
predictor = DummyPredictorNoInputNoOutput()
queue_url = _get_queue_url(TEST_SQS_OUTPUT_QUEUENAME)
output_settings = {"sqs_queue_url": queue_url}
executor = PredictionExecutor(
pr... | 77,533 |
def subset(part, whole):
"""Test whether `part` is a subset of `whole`.
Both must be iterable. Note consumable iterables will be consumed
by the test!
This is a convenience function.
Examples::
assert subset([1, 2, 3], [1, 2, 3, 4, 5])
assert subset({"cat"}, {"cat", "lynx"})
... | 77,534 |
def kl_categorical_uniform(preds):
"""KL divergence between categorical distribution and uniform prior."""
kl_div = preds * jnp.log(preds + EPS) # Constant term omitted.
return kl_div.sum(1) | 77,535 |
def remove_proxy_vcs(session, quantity, return_type=None, **kwargs):
"""
Removes proxy vcs.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Required.
:type quantity: int
:param quantity: The number of vcs to be removed. Required.
:type re... | 77,536 |
def stem(fname, include_suffix=False):
"""/blah/my_file.json.gz --> my_file"""
path = Path(fname)
stem = path.stem
# If a filename has multiple suffixes, take them all off.
stem = stem[: stem.index(".")] if "." in stem else stem
if include_suffix:
stem = stem + "".join(path.suffixes)
... | 77,537 |
def abort_script(msg):
"""Aborts the script and outputs a message.
Parameters
----------
msg : str
The message which will be displayed when exiting.
"""
sys.exit("\n{} {}".format(symbol("err"), colored(msg, 'red', attrs=['bold']))) | 77,538 |
def compile(fmt, names=None):
"""Compile given format string `fmt` and return a compiled format
object that can be used to pack and/or unpack data multiple times.
Returns a :class:`~bitstruct.CompiledFormat` object if `names` is
``None``, and otherwise a :class:`~bitstruct.CompiledFormatDict`
objec... | 77,539 |
def username_lookup(userName):
""" Lookup user from availability.db by unique username """
# connect to db
conn = sqlite3.connect("availability.db")
# create cursor
c = conn.cursor()
# check if lookup initiated for specific user or for all users
if userName:
# query for username in... | 77,540 |
def allInfoTests(P, inIter=10, outIter=10):
"""
performs information theoretic tests on a tripartite behaviour
"""
results = []
# get marginal for X,Y
l = len(P.shape)
t = tuple(np.arange(2,l))
m = pr.marginal(P, t)
# calculate mutual information of the marginal X,Y
mutInf =... | 77,541 |
def Insert(head, data):
"""
>>> head = None
>>> node = Insert(head, 4)
>>> assert(node.data == 4)
>>> head = Node(6)
>>> node = Insert(head, 4)
>>> assert(node.next.data == 4)
>>> head = Node(6, Node(7))
>>> node = Insert(head, 4)
>>> assert(node.next.next.data == 4)
"""
... | 77,542 |
def important_features(model):
""" Get the most important features from some model """
invalid_features = ["count_","tf_idf_","word2vec_"]
feat_importances = pd.Series(model.feature_importances_, index=features).to_string()
feat_importances = [i for i in feat_importances if not any(feat in i for f... | 77,543 |
def get_backend(config):
"""
:param app: celery instance
:type app: celery.Celery
"""
klass = config.backend_class
kwargs = config.backend_kwargs
url = config.backend_url
return klass(url, **kwargs) | 77,544 |
def affine(f, T):
"""Applies the affine transformation on a given
image.
' g(r, c) = f(T^{-1}(r,c)) '
Direct mapping:
From image (f) map the values to image (g)
- g(T(r,c)) = f((r,c)) ,
(r,c) in [0,H-1]x[0, W-1]
- con: T(r,c) might not fill every pixel of G
Indirect Mapping
... | 77,545 |
def atol(s, base=None): # real signature unknown; restored from __doc__
"""
atol(s [,base]) -> long
Return the long integer represented by the string s in the
given base, which defaults to 10. The string s must consist
of one or more digits, possibly preceded by a sign. If base
is 0, it i... | 77,546 |
def open_or_std(file, std, *args, **kwargs):
"""
Opens the file in the specified mode unless file is STD_IDENTIFIER,
in which case it returns std.
"""
if file == STD_IDENTIFIER:
return std
return open(file, *args, **kwargs) | 77,547 |
def translate(
parsed_symbol_table: parse.SymbolTable,
atok: asttokens.ASTTokens,
) -> Tuple[Optional[SymbolTable], Optional[Error]]:
"""Translate the parsed symbols into intermediate symbols."""
underlying_errors = [] # type: List[Error]
def bundle_underlying_errors() -> Error:
"""Bundle ... | 77,548 |
def tokens_to_sovatoms(tokens: float) -> int:
"""Convert tokens to sovatoms."""
return int(tokens * 100000000) | 77,549 |
def setup_logging(
default_path='/home/augustomarinho/dev/workspace_python/homecircuit/logconfig.yml',
default_level=logging.INFO,
env_key='LOG_CFG'
):
"""Setup logging configuration
"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.e... | 77,550 |
def _frame_only(frame, skeleton_data):
"""
Save only one frame from skeleton data
"""
result = []
for raw_descriptor in skeleton_data:
if raw_descriptor[0] == frame:
result.append(raw_descriptor)
return result | 77,551 |
def sort_node_id(a, b):
"""
@param a, b: node pair to be sorted by id
@type treenode, treenode
"""
if a.id > b.id:
return 1
else:
return -1 | 77,552 |
def generate_steps(model_name, new_steps, generator='random(edge_coverage(100))'):
"""
This is the top level builder for making test steps.
Args:
model_name (str): The name of the model file - no extension needed.
new_steps (bool): Whether to recalculate the model steps.
generator (... | 77,553 |
def collect_trajectories(env,
policy_fun,
num_trajectories=1,
policy=env_problem_utils.CATEGORICAL_SAMPLING,
max_timestep=None,
boundary=20,
epsilon=0.1,
... | 77,554 |
def request_directions(start_location, end_location):
"""Request directions from start_location to end_location.
Args:
start_location: tuple of floats (lat, lon) for starting point
end_location: tuple of floats (lat, lon) for ending point
Returns:
a list of directions in the deserialized Maps API res... | 77,555 |
def read_csv(csv_file):
"""Reads data in from CSV-file."""
with open(csv_file[0], 'rb') as f:
reader = csv.reader(f, delimiter='|', quotechar='|')
for row in reader:
# row two is version file location
version_file_stripped = re.sub(r'\/mnt\/webroots\/[0-9]', '', row[2])
... | 77,556 |
def __Boundary_outside__(self):
"""Is the boundary is on the outside of the mesh."""
return self.leftCell() is not None and self.rightCell() is None | 77,557 |
def create_dataset_lookup(py_obj):
""" What type of object are we trying to pickle? This is a python
dictionary based equivalent of a case statement. It returns the correct
helper function for a given data type.
Args:
py_obj: python object to look-up what function to use to dump to disk
... | 77,558 |
def test_halt(web3, payment_forwarder, team_multisig, customer):
"""We can stop crowdsale."""
value = to_wei("1.0", "ether")
customer_id = int(uuid.uuid4().hex, 16) # Customer ids are 128-bit UUID v4
team_multisig_begin = web3.eth.getBalance(team_multisig)
payment_forwarder.transact({"from": team_... | 77,559 |
def data_iter_consecutive(corpus_indices, batch_size, num_steps, ctx=None):
"""Sample mini-batches in a consecutive order from sequential data."""
corpus_indices = nd.array(corpus_indices, ctx=ctx)
data_len = len(corpus_indices)
batch_len = data_len // batch_size
indices = corpus_indices[0: bat... | 77,560 |
def find_anagrams(s):
"""
:param s: search str
:return: a list of anagrams
"""
print('Searching...')
return find_anagrams_helper(s, '', []) | 77,561 |
def CreatePosixStubsForSigFiles(sig_files, stub_name, out_dir,
intermediate_dir, path_from_source,
extra_stub_header, export_macro,
logging_function, logging_include):
"""Create a POSIX stub library with a module for each ... | 77,562 |
def follow_directions(start: Cell, directions: List[Direction]) -> Cell:
"""
Walk the ``directions`` from the ``start``.
:return: The final :py:class:`Cell` of the journey
"""
cursor = start
for direction in directions:
cursor = next_cell(cell=cursor, direction=direction)
return cu... | 77,563 |
def mongo_dump(server, args_array, **kwargs):
"""Method: mongo_dump
Description: Function stub holder for mongo_db_dump.mongo_dump.
Arguments:
(input) server -> Server instance.
(input) args_array -> Dictionary of arguments.
"""
status = False
err_msg = None
if server... | 77,564 |
def majority(taxa, th=0.8):
"""Select taxon from list by majority rule.
Parameters
----------
taxa : list of str
Input taxon list.
th : float, optional
Threshold of majority, range = (0.5, 1.0].
Returns
-------
str or None
Selected taxon.
"""
for taxon, ... | 77,565 |
def version(serial=None):
"""
Returns version information for MicroPython running on the connected
device.
If such information is not available or the device is not running
MicroPython, raise a ValueError.
If any other exception is thrown, the device was running MicroPython but
there was a... | 77,566 |
def plot_roc_curve(fpr, tpr, roc_auc=None, backend="plotly", **kwargs):
"""Plots a receiver operating characteristic (ROC) curve.
Args:
fpr: an array of false postive rates
tpr: an array of true postive rates
roc_auc (None): the area under the ROC curve
backend ("plotly"): the p... | 77,567 |
def send(draw, min_value=0, max_value=None):
"""Generates the send for Blast+6 file format.
Arguments:
- `min_value`: Minimum value of send to generate.
- `max_value`: Maximum value of send to generate.
"""
return draw(integers(min_value=min_value, max_value=max_value)) | 77,568 |
def flow_cell_mode(info_reads):
"""Return flow cell sequencing mode."""
res = ''
if info_reads:
read_lens = [
a['num_cycles'] for a in info_reads if not a['is_indexed_read']]
if len(read_lens) == 1:
res = '1x{}'.format(read_lens[0])
elif len(set(read_lens)) ==... | 77,569 |
def wrap_references(cell, c2dmap):
""" Move all cell centers to the origin. """
for e in cell.references:
ref_device = deepcopy(c2dmap[e.ref_cell])
center = ref_device.center
D = ref_device.move(midpoint=center, destination=(0,0))
midpoint = Coord(e.origin[0], e.origin[1])
... | 77,570 |
def dynamic_module_wrapper(wrapped_module: nn.Module):
"""
Wrapped module must locate on one single device, but could be moved around.
Input device and output device are automatically detected.
"""
wrapper = NeuralNetworkModule()
wrapper.add_module("wrapped_module", wrapped_module)
wrapper.... | 77,571 |
def fixture_conf2():
"""Instance of loaded config_test2.ini."""
return md.FrontMatter("./tests/config_test2.ini") | 77,572 |
def cache_set_trace(trace):
"""Turn on libvips cache tracing."""
vips_lib.vips_cache_set_trace(trace) | 77,573 |
def find_best_match(row, scopus_url):
"""Splits the name and surnames and tries to find some combination
of them, that still matches the country."""
# Prepare the parameters
csv_name = row['firstName'].replace(",","").replace(" or ", " ")
csv_surname = row['lastName'].replace(",","")
csv_org_co... | 77,574 |
def _quote_dict_to_embed(quote: dict) -> discord.Embed:
"""Changes a given quote dict to an embed format
Args:
quote (dict): The quote in `dict` format
Returns:
discord.Embed: The embed itself.
"""
message_link = quote["Message Link"]
title = f"***Quote #{quote['Number']}***"
... | 77,575 |
def git_get_tags_by_referred_object(context: RepoContext, obj_name: str) -> list:
"""
:param context:
:param obj_name:
:rtype: list of Ref
"""
commit_tags = git_get_tag_map(context).get(obj_name)
return commit_tags if commit_tags is not None else [] | 77,576 |
def sortKey(e):
"""
This sorts the chores based on their start time.
e[0] is the start time for all the chores in my array of chores.
"""
return int(e[0]) | 77,577 |
def merge_into_dict(original, secondary):
"""Merge two dictionaries into the first and return it.
This is simply a conveinence wrapper around the dictionary update method. In
addition to the update it returns the original dict to allow for chaining.
Args:
original: The dict which will be updated.
seco... | 77,578 |
def drop_cols(dataset: pd.DataFrame,
cols: tuple = ('ConnID', 'Repseudonym',
'siteid', 'visdat', 'IDs', "prmdiag")) -> pd.DataFrame:
"""
Drops the columns which are not needed for further modelling
Args:
dataset: dataset on which the cols should be dropped... | 77,579 |
def matchXandYbyIndex(clr_x, model_proc_df):
"""
This fxn drops rows in the design matrix & response vector
according to index equivalency.
"""
# drop all rows in x that don't match to y
x_bool = clr_x.index.isin(model_proc_df.index)
x_1 = clr_x[x_bool]
# drop all values in y that don't... | 77,580 |
def conic_sag(c, kappa, rhosq, phi=None):
"""Sag of a spherical surface.
Parameters
----------
c : float
surface curvature
kappa : float
conic constant
rhosq : numpy.ndarray
radial coordinate squared
e.g. for a 15 mm half-diameter optic,
rho = 0 .. 15
... | 77,581 |
def get_nba_player_name(div_name: list, tag_name: str, class_name: str) -> list:
"""For getting the names of NBA player and return the names as a list
Arguments:
div_name {list} -- [The div that contain all the players name]
tag_name {str} -- [The tag name which contain the name of the Play... | 77,582 |
def verify_author(author, connection):
"""Given an author id, check it."""
database = connection['test']
collection = database['users']
try:
post = collection.find_one({"_id" : ObjectId(author)})
except InvalidId:
post = None
if post is None:
return False
return T... | 77,583 |
def quatfrom_m43(m):
""" Convert the top of an m33 matrix into a quaternion."""
(m0, m1, m2, m3, m4, m5, m6, m7, m8, _, _, _) = m
trace = m0 + m4 + m8 + 1
if trace > PRECISION:
w = math.sqrt(trace) / 2
x = (m5 - m7) / (4*w)
y = (m6 - m2) / (4*w)
z = (m1 - m3) / (4*w)
... | 77,584 |
def license_fallback(vendor_dir, sdist_name):
"""Hardcoded license URLs. Check when updating if those are still needed"""
libname = libname_from_dir(sdist_name)
if libname not in HARDCODED_LICENSE_URLS:
raise ValueError('No hardcoded URL for {} license'.format(libname))
url = HARDCODED_LICENSE_... | 77,585 |
def simulate_simple_tree_static_multiple_runs(sim, setting):
"""
Does a a number of runs with the same number of users, plots the distribution of throughput and prints out the
theoretical throughput
"""
today_folder = file_helpers.create_today_folder(trial_no=1)
sys.stdout = Logger(today_f... | 77,586 |
def plot_nn_roc():
"""
Plot the ROC curve for the deep neural network algorithm.
:return:
"""
nn_df = read_nn_positions()
plot_roc_curve(nn_df, label="Deep neural network")
plt.show() | 77,587 |
def simulated_get_actions(seed_value=0, number_created_agents=1):
""" Simulates the function which
"""
#Returns a random actions list for each robot
np.random.seed(seed_value)
action_list = list(np.random.randint(low=0, high=5, size=number_created_agents))
print(action_list)
return action... | 77,588 |
def readAlignments(filename, name):
"""
reads alignment from alignment file
"""
FOUND = False
alignment = ""
alignments = []
text = []
file = open(filename)
# searching for correct protein entry
while True:
line = file.readline()
if line == "":
break
... | 77,589 |
def get_v_left(g_or_n, v_list):
"""Return vertices from graph not in v_list"""
V, n = get_set_vertices(g_or_n)
v_left = [x for x in V if x not in v_list]
return v_left | 77,590 |
def research_as_feed() -> None:
"""Function to be passed to a Django-APScheduler job"""
logger.info("Parsing ankylosing spondylitis PUBMED feed...")
parse_pubmed_feed(PUBMED_FEEDS["ankylosing spondylitis"]) | 77,591 |
def normalize_obs(obs_dict, obs_normalization_stats):
"""
Normalize observations using the provided "mean" and "std" entries
for each observation key. The observation dictionary will be
modified in-place.
Args:
obs_dict (dict): dictionary mapping observation key to np.array or
... | 77,592 |
def get_closest_language(differences):
"""[summary]
Args:
differences ([list]): [contains tuples with language and difference score]
Returns:
[tuple]: [containing 3 closest possible languages to given input]
"""
# print(differences)
differences_sorted = sorted(differences, key=... | 77,593 |
def apply_trace_attribute(log: EventLog, values: List[str], parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> EventLog:
"""
Filter a log on the trace attribute values
Parameters
--------------
log
Event log
values
Allowed/forbidden values
parameters
... | 77,594 |
def cross_product(X1, X2):
""" Cross product of features in matrices X1 and X2
"""
n = np.shape(X1)[0]
assert n == np.shape(X2)[0]
return (X1.reshape(n,1,-1) * X2.reshape(n,-1,1)).reshape(n,-1) | 77,595 |
def getAtomType(atom, bonds):
"""
Determine the appropriate atom type for an :class:`Atom` object `atom`
with local bond structure `bonds`, a ``dict`` containing atom-bond pairs.
"""
cython.declare(atomSymbol=str)
cython.declare(molFeatureList=cython.list, atomTypeFeatureList=cython.list)
... | 77,596 |
def impute_rare_titles(df: pd.DataFrame, tresh: int = 100) -> pd.DataFrame:
"""Substitutes rare titles with closest ones by Elo
Parameters:
thresh: threshold for title to be considered as rare
"""
for color in ['White', 'Black']:
title_column_name = f'{color}Title'
elo_column_name =... | 77,597 |
def calculate_most_mistaken_heatmap(label_classifiers: Dict[str, pandas.DataFrame], labels) -> pandas.DataFrame:
"""
Generates a 2d table describing how many times each column is mistaken for a given index.
:param label_classifiers: A number of classifiers over the labels.
:param labels: A DataFrame w... | 77,598 |
def write_csv(outbody, path):
"""Write CSV file to the path.
:param outbody: A list of lists containing the header and rows.
:type List: A list of lists.
:param path: Full path name including the file. (c:\output.csv)
:type string: File path
...
:raises Error: Print... | 77,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.