content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import warnings
def load_tree(tree,fmt=None):
"""
Load a tree into an ete3 tree data structure.
tree: some sort of tree. can be an ete3.Tree (returns self), a dendropy
Tree (converts to newick and drops root), a newick file or a newick
string.
fmt: format for reading tree from new... | efc727fee6f12b4a8bc0e8c2b2319be2a820df13 | 11,100 |
from typing import Dict
def load_extract(context, extract: Dict) -> str:
"""
Upload extract to Google Cloud Storage.
Return GCS file path of uploaded file.
"""
return context.resources.data_lake.upload_df(
folder_name="nwea_map",
file_name=extract["filename"],
df=extract["v... | c9d5fedf6f2adcb871abf4d9cead057b0627267a | 11,101 |
def _make_default_colormap():
"""Return the default colormap, with custom first colors."""
colormap = np.array(cc.glasbey_bw_minc_20_minl_30)
# Reorder first colors.
colormap[[0, 1, 2, 3, 4, 5]] = colormap[[3, 0, 4, 5, 2, 1]]
# Replace first two colors.
colormap[0] = [0.03137, 0.5725, 0.9882]
... | ca6275fc60efe198be5a89662d791f6c47e45b24 | 11,102 |
def poly_to_box(poly):
"""Convert a polygon into an array of tight bounding box."""
box = np.zeros(4, dtype=np.float32)
box[0] = min(poly[:, 0])
box[2] = max(poly[:, 0])
box[1] = min(poly[:, 1])
box[3] = max(poly[:, 1])
return box | 4fb8cea86494c34832f43dbf7f942a214dc2e010 | 11,103 |
import torch
def default_collate(batch):
"""Puts each data field into a tensor with outer dimension batch size"""
error_msg = "batch must contain tensors, numbers, dicts or lists; found {}"
elem_type = type(batch[0])
if isinstance(batch[0], torch.Tensor):
return torch.stack(batch, 0)
elif... | 576366ac5e57a84a015ffa3e5e80e8d4b62ac329 | 11,104 |
def updatestatus(requestdata, authinfo, acldata, supportchan, session):
"""Update the /Status page of a user."""
if requestdata[2] in acldata['wikis']:
wikiurl = str('https://' + acldata['wikis'][requestdata[2]]['url'] + '/w/api.php')
sulgroup = acldata['wikis'][requestdata[2]]['sulgroup']
e... | f305f1c4ceb6b4cfd949a1005a961b710e81740f | 11,105 |
def sortByTimeStamps(paths):
"""Sorts the given list of file paths by their time-stamp
:paths: The file paths to sort by time-stamp
:returns: A sorted list of file paths
"""
sortedPaths = []
timeStamps = []
# Extract the YYYYMMDD & HHMMSS timestamps from the file paths
for p in paths:... | 01d60e0f3d793ca17f04462911406d03a6c3ddf0 | 11,106 |
def get_xml_nk_bands(xml_tree):
"""
Function to specifically get kpoint (cartesian) coordinates and corresponding eigenvalues (in Hartree)
"""
k_points_car = []
k_eigenvalues = []
k_occupations = []
for ks_energies in xml_tree.iter(tag='ks_energies'):
k_points_car.append( get_x... | e510995ee468552d395c179aa8713f159b1ad0e1 | 11,107 |
def enumerate(server, directory_list, filenames):
"""
Enumerate directories and files on the web server.
"""
print('\n[*] Enumerating resources.')
to_search = [server]
directories = []
resources = []
print('[*] Recursively searching for directories.')
while len(to_search) != 0:
... | e9b2eb94b71b48dcc032448369a413cc4c1790ba | 11,108 |
def deep_equals(x, y):
"""Test two objects for equality in value.
Correct if x/y are one of the following valid types:
types compatible with != comparison
pd.Series, pd.DataFrame, np.ndarray
lists, tuples, or dicts of a valid type (recursive)
Important note:
this function w... | 27f5dc79e5c3b9e8a08a4bbd0db847995f0fa9ef | 11,109 |
import os
import pandas
def get_local_log(date, which="completed", safeout=False):
""" """
filein = get_log_filepath(date, which=which)
if not os.path.isfile(filein):
if safeout:
return None
raise IOError(f"No {which}_log locally stored for {date}. see download_log()")
... | cc7f16fedf8de4d343e4ab3d4013aa0dc5799133 | 11,110 |
def get_asan_options(redzone_size, malloc_context_size, quarantine_size_mb,
bot_platform, leaks):
"""Generates default ASAN options."""
asan_options = {}
# Default options needed for all cases.
asan_options['alloc_dealloc_mismatch'] = 0
asan_options['print_scariness'] = 1
asan_options[... | a3d06902dcad73dd265d865683bd95004babc867 | 11,111 |
def get_onelinepred_results(pred_file, thred=0.1):
""""from pred_file parse pred_results
Args:
# TODO save format of pred_file still unknown
pred_file (str): pred_file path
thred: pred_box's score less than it could be ignored
Return:
pred_dict (dict(list)) : output predict... | 989ab4160f4e675fd781a751a02e218c98b2355e | 11,112 |
import re
def _is_valid_img_uri(uri: str) -> bool:
"""
Returns true if a string is a valid uri that can be saved in the database.
"""
regex = "data:image/jpeg;base64*."
return not uri or re.match(regex, uri) | 0836bfa447b42fb7ed24fc897de8fb40c6e593b2 | 11,113 |
def update_config(a, b, mode="default"):
"""Update the configuration a with b."""
if not b:
return a
from_version = get_config_version(a)
to_version = get_config_version(b)
if from_version == 1 and to_version == 2:
# When updating the configuration to a newer version, we clear all u... | 464adc3a4daeedb246d911caab5477ff4d55841e | 11,114 |
import os
def disk_partitions(disk_ntuple, all=False):
"""Return all mountd partitions as a named tuple.
If all == False return physical partitions only.
"""
phydevs = []
if os.path.exists('/proc/filesystems'):
my_file = open('/proc/filesystems', 'r')
for line in my_file:
... | 1c46fe7efab860c4fe9f3be7745d3ef2c24eafa1 | 11,115 |
def create_app(config_name='DevelopmentConfig'):
"""Create the Flask application from a given config object type.
Args:
config_name (string): Config instance name.
Returns:
Flask Application with config instance scope.
"""
app = Flask(__name__)
{{cookiecutter.package_name | up... | 6022c976ffa2bf6afa692bb96c5c53bfed4a7d32 | 11,116 |
def label_accuracy_score(hist):
"""Returns accuracy score evaluation result.
- overall accuracy
- mean accuracy
- mean IU
- fwavacc
"""
with np.errstate(divide='ignore', invalid='ignore'):
iu = np.diag(hist) / (
hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist)
... | 5e129604d476f17e0cfd7a30f785775266763432 | 11,117 |
def get_page_title(title: str):
""" Возвращает заголовок, отображаемый на вкладках """
return f'{title} | NeuraHS' | 3df2de16325cf0c4c849e7d09111ea87e36c309a | 11,118 |
def make_pointer_union_printer(val):
"""Factory for an llvm::PointerUnion printer."""
pointer, value = get_pointer_int_pair(val['Val'])
if not pointer or not value:
return None
pointer_type = val.type.template_argument(int(value))
string = 'llvm::PointerUnion containing %s' % pointer_type
return make_pr... | 40d12a45a05fb49dd32b1a450b7dff23ab0ece7c | 11,119 |
def get_paramvals_percentile(table, percentile, chi2_arr):
"""
Isolates 68th percentile lowest chi^2 values and takes random 1000 sample
Parameters
----------
table: pandas dataframe
Mcmc chain dataframe
pctl: int
Percentile to use
chi2_arr: array
Array of chi^2 va... | 1d83c54b61446aecf0a7fcbf4d8ae49e96a25b3f | 11,120 |
def get_text_from_span(s, (start, end)):
"""
Return the text from a given indices of text (list of words)
"""
return " ".join(s[start: end]) | df58cf8056039b183dc421c94baa22176fe23e84 | 11,121 |
import time
import struct
def __timestamp():
"""Generate timestamp data for pyc header."""
today = time.time()
ret = struct.pack(b'=L', int(today))
return ret | 477c8473026c706785b4091bbbf647b86eaa560f | 11,122 |
def reverse_index(alist, value):
"""Finding the index of last occurence of an element"""
return len(alist) - alist[-1::-1].index(value) -1 | 21fc4e17a91000085123ea4be42c72cb27a3482c | 11,123 |
def generate_twist(loops, non_interacting=False):
"""Generate initial configuration to start braid moves where the active end has crossed outside the loops and they have an initial twist.
Format: ' │ │ │┃'
'┏━━━━━┛'
'┃│ │ │ '
'┗━┓│ │ '
' │┃│ │ '
'┏│┛│... | fdeb58b49d2e559c4d0ccfc24e439057683f7e96 | 11,124 |
def get_pathway_id_names_dict():
"""
Given a pathway ID get its name
:return: pathway_id_names_dict
"""
# Fixme: This is not analysis specfic (I think, KmcL) I believe any analysis should do
# A fix is for this is probably wise.
analysis = Analysis.objects.get(name='Tissue Compari... | 4764280666108a291809558cf22984d44539a3d3 | 11,125 |
def IsShuttingDown(_shutting_down=_shutting_down):
"""
Whether the interpreter is currently shutting down.
For use in finalizers, __del__ methods, and similar; it is advised
to early bind this function rather than look it up when calling it,
since at shutdown module globals may be cleared.
"""
... | 6cbc5d3388ee8eb0cabbb740fc5e0b8f2ac4714a | 11,126 |
def ellipse_center(a):
"""
Parameters
----------
a : fitted_ellipse_obj
"""
b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]
num = b*b-a*c
x0=(c*d-b*f)/num
y0=(a*f-b*d)/num
return np.array([x0,y0]) | 66487a641c35d2c1c1c8a8c7c0bb129eda55f4c4 | 11,127 |
def _to_average_temp(name, temperature_map):
"""
Converts the list of temperatures associated to a label to a list of average temperatures.
If the sensor does not exist, it will return _default_temperature. If the high or critical temperature thresholds
are invalid, it will use the values from _default_... | 88c3b5d0bdd64f782a26a7dc11d44dc39e6efc82 | 11,128 |
def segments_decode(aseg):
"""
Decode segments.
Parameters
----------
aseg : numpy.ndarra of uint32
Returns
-------
segments : list of list of int
"""
max = 2 ** 32 - 1
segments = []
l = []
for x in list(aseg):
if x == max:
segments.append(l)
... | d5edf85ae489b62c8820c3616a75a9ca305f06ec | 11,129 |
def cvGetReal3D(*args):
"""cvGetReal3D(CvArr arr, int idx0, int idx1, int idx2) -> double"""
return _cv.cvGetReal3D(*args) | 4130a4f9571bdea1c9e54b5fcf7d1d0f5c3ce083 | 11,130 |
def get_wf_double_FF_opt(
molecule,
pcm_dielectric,
linked=False,
qchem_input_params=None,
name="douple_FF_opt",
db_file=">>db_file<<",
**kwargs,
):
"""
Firework 1 : write QChem input for an FF optimization,
run FF_opt QCJob,
parse directory and inse... | d21b04035d41beb3a24e9cbba45c420bd8d9b727 | 11,131 |
import sys
import traceback
def return_stack():
"""
Create the stack of the obtained exception
:return: string stacktrace.
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
return lines[0] + lines[1] | 8dd58917ffe378cf88c38429d63ed8d553df4ffb | 11,132 |
def get_element_action_names(element):
"""Get a list of all the actions the specified accessibility object can perform.
Args:
element: The AXUIElementRef representing the accessibility object
Returns: an array of actions the accessibility object can perform
(empty if the accessibility objec... | f906f9565eb72b060d9e4c69ab052dc6001f192a | 11,133 |
import re
def ParseFile(fname):
"""Parse a micrcode.dat file and return the component parts
Args:
fname: Filename to parse
Returns:
3-Tuple:
date: String containing date from the file's header
license_text: List of text lines for the license file
... | 2774157dd256f11268a7ea4ee3d941e7aea1ca4f | 11,134 |
import numpy
def cal_q_vel(guidance_v):
"""
暂时使用默认参考速度进行优化,等调试成熟再使用粗糙速度来优化
:return:
"""
q_vel = numpy.zeros((1, n_t + 1))
if flag_obs == 0:
q_vel[0][0] = -ref_v
q_vel[0][n_t] = ref_v
if flag_obs == 1:
for i in range(n_t + 1):
if i < 1:
q_vel[0][i] = -guidance_v[0][i]
elif i >= n_t:
q_vel... | b7551e7b911c5e0fd27a1e90f00c1e1a3a60f53f | 11,135 |
def tf_decode(
ref_pts,
ref_theta,
bin_x,
res_x_norm,
bin_z,
res_z_norm,
bin_theta,
res_theta_norm,
res_y,
res_size_norm,
mean_sizes,
Ss,
DELTAs,
R,
DELTA_THETA,
):
"""Turns bin-based box3d format into an box_3d
Input:
ref_pts: (B,p,3) [x,y,z]... | 720252aaad2b8d380d30d871e97d47b2c9309a68 | 11,136 |
def _histogram_discretize(target, num_bins=gin.REQUIRED):
"""Discretization based on histograms."""
discretized = np.zeros_like(target)
for i in range(target.shape[0]):
discretized[i, :] = np.digitize(target[i, :], np.histogram(
target[i, :], num_bins)[1][:-1])
return discretized | 14108b9208dca586f7fd39dac3a5a17f1e5a2928 | 11,137 |
def apply_acl(instance, content):
"""Apply ACLs."""
any_acl_applied = False
if not isinstance(instance, roleable.Roleable):
return any_acl_applied
instance_acl_dict = {(l.ac_role_id, p.id): l
for p, l in instance.access_control_list}
person_ids = set()
for role_id, data in content... | 134f4ae98018626712c2f918ce5b501129169a30 | 11,138 |
import json
def serialize(results):
"""Serialize a ``QueryDict`` into json."""
serialized = {}
for result in results:
serialized.update(result.to_dict())
return json.dumps(serialized, indent=4) | 1ce996e1172344ba72ccbb9487b51b0efc30fa5c | 11,139 |
def allowed_once (cave, visited):
"""Only allows small caves to be visited once. Returns False if `cave`
is small and already in `visited`.
"""
return big(cave) or (small(cave) and cave not in visited) | f3619c1d230de50fab539103084457413f30a74e | 11,140 |
from datetime import datetime
import json
def _serialize_examstruct(exam):
""" Serialize the exam structure for, eg. cache.
The dates, especially, need work before JSON
"""
assert isinstance(exam, dict)
date_fmt = '%Y-%m-%d %H:%M:%S'
assert isinstance(exam['start'], datetime.datetime)
... | 3c553986bfd6b565bbdc34218ca01d984d3aab69 | 11,141 |
def _analysis_test_impl(ctx):
"""Implementation function for analysis_test. """
_ignore = [ctx]
return [AnalysisTestResultInfo(
success = True,
message = "All targets succeeded analysis",
)] | 5f006c817581b771bf3d1f5b3cc7861cd98e8958 | 11,142 |
import os
def filename_to_scienceurl(filename, suffix=None, source="irsa", verbose=False, check_suffix=True):
"""
"""
_, filefracday, paddedfield, filtercode, ccd_, imgtypecode, qid_, *suffix_ = os.path.basename(filename).split("_")
suffix_ = "_".join(suffix_)
year,month, day, fracday = file... | c78fa2150b45b2ccd7b347d7cbe24f1760e55450 | 11,143 |
import warnings
def CD_Joint(CD_J_AS = None,
Ypred = None,
beta = None,
zeta = None,
active_set = None,
lam = None,
P = None,
P_interaction = None,
Y = None,
B = None,
B_interaction = None... | 780bbd6a44dcfacf55a22390a6f7ee8c98e2d2f0 | 11,144 |
from typing import Tuple
def testAllCallbacksSmokeTest(
args_count: int, type_checker: TypeCheckerFixture
) -> None:
"""
Parametrized test to do basic checking over all Callbacks (except Callback0).
We generate functions with too much arguments, too few, and correct number, and check
that the err... | 8459b040f2c7dc145a6a41ddebd4edb24873d704 | 11,145 |
def transform_unnamed_cols_range(df: pd.DataFrame, columns_range: range,
new_column_name_prefix: str, inplace=False) -> object:
"""
This function transforms a range of columns based assuming the presence of following schema in dataframe:
|base_column_name|Unnamed_n|Unnamed_... | c54394531cec3aeef6e1717d3db0be17852ade9b | 11,146 |
def shingles(tokens, n):
"""
Return n-sized shingles from a list of tokens.
>>> assert list(shingles([1, 2, 3, 4], 2)) == [(1, 2), (2, 3), (3, 4)]
"""
return zip(*[tokens[i:-n + i + 1 or None] for i in range(n)]) | 93e8f3828bf4b49397e09cb46565199dcd7a68be | 11,147 |
import json
def load_json(filename):
"""Load JSON file as dict."""
with open(join(dirname(__file__), filename), "rb") as fp:
return json.load(fp) | 3ce3a92b4a11a005709ea3fab003d73133627183 | 11,148 |
def getLayerList(layer_list, criterionFn):
"""Returns a list of all of the layers in the stack that match the given criterion function, including substacks."""
matching_layer = []
for layer in layer_list:
if criterionFn(layer):
matching_layer.append(layer)
if hasattr(layer, 'laye... | 5e09065b350f1305a2fcd45379751fac6552031e | 11,149 |
def getBiLinearMap(edge0, edge1, edge2, edge3):
"""Get the UV coordinates on a square defined from spacing on the edges"""
if len(edge0) != len(edge1):
raise ValueError("getBiLinearMap: The len of edge0 and edge1 are not the same")
if len(edge2) != len(edge3):
raise ValueError("getBiLinearM... | a75626a846c18418db8dbb98afdb25ab0c903969 | 11,150 |
import argparse
def _parse_args():
"""parse arguments"""
parser = argparse.ArgumentParser(description='train and export wdsr on modelarts')
# train output path
parser.add_argument('--train_url', type=str, default='', help='where training log and ckpts saved')
# dataset dir
parser.add_argument(... | 8147e3d2c7bc60cb2ed379308118bcf7ef8157b6 | 11,151 |
def _parse_orientation(response: HtmlResponse):
"""Parse Orientation.
Returns None if not available or is unknown.
"""
value = response.css('th:contains("Ausrichtung") + td ::text').get()
if value:
if value == "unbekannt" or value == "verschieden":
return None
fk_value =... | 338fb6dbc8e3f1c0e116f766f86a01b110c922f2 | 11,152 |
def binaryread(file, vartype, shape=(1,), charlen=16):
"""
Uses numpy to read from binary file. This was found to be faster than the
struct approach and is used as the default.
"""
# read a string variable of length charlen
if vartype == str:
result = file.read(charlen * 1)
el... | 221e0a71271eea4a31423a94244c12784af7fef2 | 11,153 |
def subsample_data(neuron_data, sample_size = 10000):
"""
Acquires a subsample of the Neuron dataset.
This function samples a set of neurons without replacement.
Params
-----------
Returns
-----------
rand_ix (array-like):
Array containing the chosen indices
sample_neu... | 801d0d618576e14b67b33bf9071c135409362bfe | 11,154 |
import sys
def appGet(*args, **kwargs):
"""
.. deprecated:: 0.42.0
Use :func:`app_get()` instead.
"""
print("dxpy.appGet is deprecated; please use app_get instead.", file=sys.stderr)
return app_get(*args, **kwargs) | fd1f11b7a0d1af18faa4177e537fae8c7146eeae | 11,155 |
def connect_db():
"""Connects to the specific database."""
mongo = MongoClient(DATABASE_URL,replicaset=MONGO_REPLICASET)
#if COLLECTION_NAME in mongo[DATABASE_NAME].collection_names():
collection = mongo[DATABASE_NAME][COLLECTION_NAME]
#else:
# mongo[DATABASE_NAME].create_collection(COLLECTIO... | 0e037a2bfb8687d4ff2b477a59c3f5ba99335c44 | 11,156 |
def transient(func):
"""
decorator to make a function execution transient.
meaning that before starting the execution of the function, a new session with a
new transaction will be started, and after the completion of that function, the
new transaction will be rolled back without the consideration o... | 454c808d15bbdddd800db70ec56d228f432921f8 | 11,157 |
def make_mapping(environ, start_response):
"""
Establishing a mapping, storing the provided URI
as a field on a tiddler in the PRIVATEER bag.
Accepted data is either a json dictory with a uri
key or a POST CGI form with a uri query paramter.
Respond with a location header containing the uri
... | e90a72bce2132d703504230d41f3e807ea77d7a2 | 11,158 |
def create_space_magnitude_region(region, magnitudes):
"""Simple wrapper to create space-magnitude region """
if not (isinstance(region, CartesianGrid2D) or isinstance(region, QuadtreeGrid2D)) :
raise TypeError("region must be CartesianGrid2D")
# bind to region class
if magnitudes is None:
... | 64f4606c74ad38bd34ade7673074124e3d3faa48 | 11,159 |
import matplotlib.pyplot as plt
def autocorrelation_plot(series, label, lower_lim=1, n_samples=None, ax=None, **kwds):
"""Autocorrelation plot for time series.
Parameters:
-----------
series: Time series
ax: Matplotlib axis object, optional
kwds : keywords
Options to pass to matplotli... | 18254d8bf263c50d059921b682606700dd51ab5a | 11,160 |
def get_productivity(coin_endowments):
"""Returns the total coin inside the simulated economy.
Args:
coin_endowments (ndarray): The array of coin endowments for each of the
agents in the simulated economy.
Returns:
Total coin endowment (float).
"""
return np.sum(coin_en... | e6dfe2485bce54599bc919d9a2b2235b90166702 | 11,161 |
def prefix_attrs(source, keys, prefix):
"""Rename some of the keys of a dictionary by adding a prefix.
Parameters
----------
source : dict
Source dictionary, for example data attributes.
keys : sequence
Names of keys to prefix.
prefix : str
Prefix to prepend to keys.
Retu... | e1c8102fddf51cd7af620f9158419bff4b3f0c57 | 11,162 |
import logging
def add_polygon_to_image(image: np.ndarray, object: dict) -> np.ndarray:
""" Add the polynom of the given object to the image.
Since using CV, order is (B,G,R)
Parameters
----------
img : np.ndarray
Opencv image
object : dict
Dictionary of the polynom with meta ... | e598e80ab23df2e15c96d6ed1453b95ec10e5451 | 11,163 |
def add(coefficient_1, value_1, coefficient_2, value_2):
"""Provides an addition algebra for various types, including scalars and
histogram objects.
Incoming values are not modified.
Args:
coefficient_1: The first coefficient, a scalar
value_1: The first value, a histogram or scalar
... | 70bccba3d504325a66090104ffc4d464649f2b32 | 11,164 |
import time
def kotlin_object_type_summary(lldb_val, internal_dict = {}):
"""Hook that is run by lldb to display a Kotlin object."""
start = time.monotonic()
log(lambda: f"kotlin_object_type_summary({lldb_val.unsigned:#x}: {lldb_val.GetTypeName()})")
fallback = lldb_val.GetValue()
if lldb_val.GetT... | 79883644017bfc35c77a17a3e5da4b5913864ef2 | 11,165 |
import argparse
import os
import sys
def parse_arguments(root_dir):
""" Will parse the command line arguments arnd return the arg object.
"""
# Create top level parser. TODO: add description, usage, etc
parser = argparse.ArgumentParser(prog="aware.py",
description="Probabilistic demultiplexer... | 6fc9c8e9e138d0745d41f098c8833aff217cb78d | 11,166 |
def _grep_first_pair_of_parentheses(s):
"""
Return the first matching pair of parentheses in a code string.
INPUT:
A string
OUTPUT:
A substring of the input, namely the part between the first
(outmost) matching pair of parentheses (including the
parentheses).
Parentheses between... | 7441c1b8734c211b9b320e195155719452cf7407 | 11,167 |
import requests
def login():
"""
"""
url = "http://127.0.0.1:5001/rest/login"
data = {"username": "kivanc", "password": "1234"}
r = requests.post(url, json=data)
output = r.json()
return output["access_token"] | a2b4bd68110fd053c48988f7cc490c88f148bc1f | 11,168 |
def get_all_ops(ifshortcut=True, ifse=True, strides=[1, 2, 2, 2, 1, 2, 1]):
"""Get all possible ops of current search space
Args:
ifshortcut: bool, shortcut or not
ifse: bool, se or not
strides: list, list of strides for bottlenecks
Returns:
op_params: list, a list of all pos... | 7830a330da8709179096fb8b6e789107e0de66cf | 11,169 |
import tqdm
import torch
def evaluation_per_relation(triples: dict, model: EvaluationModel, batch_size: int = 4):
"""
:param triples: It should be a dict in form (Relation id):[(s_1,p_1,o_1)...(s_n,p_n,o_n)]
"""
# Evaluate per relation and store scores/evaluation measures
score_per_rel = dict()
... | 73262587c181fa285b97479110f49ea4dd178946 | 11,170 |
from datetime import datetime
def check_upload():
"""
判断今天的代码是否上传
:return:
"""
ctime = datetime.date.today() # 当前日期
data = db_helper.fetchone('select id from record where ctime = %s and user_id = %s',
(ctime, session['user_info']['id']))
return data | 2dfceb7cc91668b3a41920b931e946188332c6e4 | 11,171 |
def get_package_object():
"""Gets a sample package for the submission in Dev Center."""
package = {
# The file name is relative to the root of the uploaded ZIP file.
"fileName" : "bin/super_dev_ctr_api_sim.appxupload",
# If you haven't begun to upload the file yet, set this value to "Pen... | d65329372f356325c08ecb814f48ad856b9509bc | 11,172 |
def check_for_cmd():
""" Returns tuple of [Type] [Data] where type is the shuffle type and data
will contain either random shuffle parameters or the top deck order required """
try:
with open(CMD_FILE, 'r+') as f:
data = f.readline()
f.truncate(0)
# DEBUGGIN TODO REM... | 42fe4831f910751c8f7760a5a7eed5dc0580d7b4 | 11,173 |
from satchmo_store.shop.models import Config
def _set_quantity(request, force_delete=False):
"""Set the quantity for a specific cartitem.
Checks to make sure the item is actually in the user's cart.
"""
cart = Cart.objects.from_request(request, create=False)
if isinstance(cart, NullCart):
... | 066314ac9689739ab12518e1049122390808221c | 11,174 |
import os
def load_typos_file(file_name, char_vocab = {}, filter_OOA_chars = False):
"""
Loads typos from a given file.
Optionally, filters all entries that contain out-of-alphabet characters.
"""
basename, ext = os.path.splitext(file_name)
replacement_rules = list()
if ext == ".tsv":
... | 6d5a54c0cea6751affa4ccd343632d1d7e20fd21 | 11,175 |
def load_config(config_file="config.yaml"):
"""Load config file to initialize fragment factories.
A config file is a Python file, loaded as a module.
Example config file:
# config.yaml
name: My LDF server
maintainer: chuck Norris <me@gmail.com>
datasets:
-
name: DBpedia-2016-04... | b5ee03a3b30f4374da05469cd3a289566eb26540 | 11,176 |
import os
import socket
import timeit
import time
def execute_actor(actor_id,
worker_id,
execution_id,
image,
msg,
user=None,
d={},
privileged=False,
mounts=[],
... | aab6a06de32737d6146945f365433e4b946ee659 | 11,177 |
def find_start_end(grid):
"""
Finds the source and destination block indexes from the list.
Args
grid: <list> the world grid blocks represented as a list of blocks (see Tutorial.pdf)
Returns
start: <int> source block index in the list
end: <int> destination block index... | d617af3d6ebf9a2c9f42250214e3fe52d2017170 | 11,178 |
from typing import Optional
import inspect
def find_method_signature(klass, method: str) -> Optional[inspect.Signature]:
"""Look through a class' ancestors and fill out the methods signature.
A class method has a signature. But it might now always be complete. When a parameter is not
annotated, we might ... | 17d3e7d554720766ca62cb4ad7a66c42f947fc1c | 11,179 |
def format_long_calc_line(line: LongCalcLine) -> LongCalcLine:
"""
Return line with .latex attribute formatted with line breaks suitable
for positioning within the "\aligned" latex environment.
"""
latex_code = line.latex
long_latex = latex_code.replace("=", "\\\\&=") # Change all...
long_l... | a6f19b7f3a1876f3b6b0c88baddfd02b16901b41 | 11,180 |
from riddle import emr, feature_importance
from riddle.models import MLP
import time
import pickle
def run(data_fn, prop_missing=0., max_num_feature=-1,
feature_selection='random', k=10, data_dir='_data', out_dir='_out'):
"""Run RIDDLE classification interpretation pipeline.
Arguments:
data_f... | ac28216cbea67b0bdc6d2b3f617c24c975623415 | 11,181 |
def h_lgn(t, mu, sigma, normalize=False):
""" Log-normal density
Args:
t: input argument (array)
mu: mean parameter (-infty,infty)
sigma: std parameter > 0
normalize: trapz integral normalization over t
Returns:
function values
"""
y = np.ze... | 63bd6ea48f5ea28c5631b3ce259066d3624d038b | 11,182 |
from .background import set_background_alignment
import copy
def align_background(data, align='auto'):
"""
Determine the Qz value associated with the background measurement.
The *align* flag determines which background points are matched
to the sample points. It can be 'sample' if background is
... | a8b33aa5440cf6c212d964d58720bef771fe2083 | 11,183 |
def get_bounds_from_config(b, state, base_units):
"""
Method to take a 3- or 4-tuple state definition config argument and return
tuples for the bounds and default value of the Var object.
Expects the form (lower, default, upper, units) where units is optional
Args:
b - StateBlock on which ... | c9e757a2032178e656f7bbc27519bd1650eb9a79 | 11,184 |
def read_train_data():
"""
train_data.shape = (73257, 32, 32, 3)
train_label.shape = (73257,)
extra_data.shape = (531131, 32, 32, 3)
extra_label.shape = (531131,)
data.shape = (604388, 32, 32, 3)
labels.shape = (604388,)
"""
train_data, train_label = read_images(full_data_dir+'train... | d6e5c06ceb3a95e20e8ae301d83e1f480fc48591 | 11,185 |
def laguerreFunction(n, alpha, t, normalized=True):
"""Evaluate Laguerre function using scipy.special"""
if normalized:
Z = np.exp( .5*sps.gammaln(n+1) - .5*sps.gammaln(n+alpha+1) )
else:
Z = 1
return Z * np.sqrt(mu(alpha,t)) * sps.eval_genlaguerre(n, alpha, t) | 6c48f3ddaed9db7d748ad8fc972a132795ad3916 | 11,186 |
def end(s):
"""Select the mobile or weight hanging at the end of a side."""
assert is_side(s), "must call end on a side"
return branches(s)[0] | 2bcbc61e989287d714e9401660e58bd2f54c6fe6 | 11,187 |
def get_ca_pos_from_atoms(df, atoms):
"""Look up alpha carbon positions of provided atoms."""
ca = df[df['atom_name'] == 'CA'].reset_index()
nb = ca.reindex(atoms)
nb = nb.reset_index().set_index('index')
return nb | c069db751d94f6626be5d56e7b286ef3c873c04e | 11,188 |
def split_inline_box(context, box, position_x, max_x, skip_stack, containing_block, containing_page, absolute_boxes,
fixed_boxes, line_placeholders, waiting_floats, line_children):
"""Same behavior as split_inline_level."""
# In some cases (shrink-to-fit result being the preferred width)
... | b1c7c0b7b831e8a7b4cb8d743690abfedc90685e | 11,189 |
def LoadComponent(self,filename): # real signature unknown; restored from __doc__
"""
LoadComponent(self: object,filename: str) -> object
LoadComponent(self: object,stream: Stream) -> object
LoadComponent(self: object,xmlReader: XmlReader) -> object
LoadComponent(self: object,filename: TextReader) -> object
L... | 17b893a6e91f4ef62b8ba18646d9dc2005c52ccd | 11,190 |
def split_bits(word : int, amounts : list):
"""
takes in a word and a list of bit amounts and returns
the bits in the word split up. See the doctests for concrete examples
>>> [bin(x) for x in split_bits(0b1001111010000001, [16])]
['0b1001111010000001']
>>> [bin(x) for x in split_bits(... | 556a389bb673af12a8b11d8381914bf56f7e0599 | 11,191 |
def global_tracer(ot_tracer):
"""A function similar to one OpenTracing users would write to initialize
their OpenTracing tracer.
"""
set_global_tracer(ot_tracer)
return ot_tracer | 87207d92179a0b23f20806e3e93ec7e78b1b31f1 | 11,192 |
import requests
def getListProjectsInGroup(config, grp):
"""
Get list of issue in group
"""
print("Retrieve project of group: %s " % grp.name)
data = None
__prjLst = gitlabProjectList(grp)
if (DUMMY_DATA):
testFile = getFullFilePath(ISSUES_GRP_TEST_FILE)
with open (testFile... | 1c926e8b855cba502229ab1c31c9706c20882a1c | 11,193 |
def group_naptan_datatypes(gdf, naptan_column='LocalityName'):
"""[summary] groups together naptan datasets into subsets that are grouped
by the given naptan column.
Args:
gdf ([type]): [description]
naptan_column (str, optional): [description]. Defaults to 'LocalityName'.
Returns:
... | d4cca1180f1b3d6622c7c2fd5df1cdd1b369c5b3 | 11,194 |
def get_facts_by_name_and_value(api_url=None, fact_name=None, fact_value=None, verify=False, cert=list()):
"""
Returns facts by name and value
:param api_url: Base PuppetDB API url
:param fact_name: Name of fact
:param fact_value: Value of fact
"""
return utils._make_api_request(api_url, '... | bdce7473bff944609ffdb191948b008ca4a1422a | 11,195 |
def produce_phase(pipeline_run):
"""Produce result with Produce phase data."""
scores = pipeline_run['run']['results']['scores']
if len(scores) > 1:
raise ValueError('This run has more than one score!')
scores = scores[0]
return {
'metric': scores['metric']['metric'],
'con... | 7ed003281eac240a407dac1d03a5e3f5a6e5b2cd | 11,196 |
import json
from unittest.mock import patch
async def init_integration(hass: HomeAssistant, use_nickname=True) -> MockConfigEntry:
"""Set up the Mazda Connected Services integration in Home Assistant."""
get_vehicles_fixture = json.loads(load_fixture("mazda/get_vehicles.json"))
if not use_nickname:
... | 96756b011f66786c0c8a8704446546c0751de13f | 11,197 |
def get_app_domain():
"""
Returns the full URL to the domain. The output from this function gets
generally appended with a path string.
"""
url = settings.INCOMEPROPERTYEVALUATOR_APP_HTTP_PROTOCOL
url += settings.INCOMEPROPERTYEVALUATOR_APP_HTTP_DOMAIN
return url | 0a9c58a179c281072104fb5b7859b2d0ef8426ae | 11,198 |
import inspect
def deprecated(removal_version, hint_message=None, subject=None, ensure_stderr=False):
"""Marks a function or method as deprecated.
A removal version must be supplied and it must be greater than the current 'pantsbuild.pants'
version.
When choosing a removal version there is a natural tension... | 84b2ef33a40d8f28eba27e29679338093875eb25 | 11,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.