content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def inject(
dependency: Union[T, str],
*,
namespace: str = None,
group: str = None,
exclude_groups: Sequence[str] = None,
lazy: bool = False,
optional: bool = False,
) -> T:
"""
Injects the requested dependency by instantiating a new instance of it or a
singleton instance if spec... | 5,325,300 |
def load_dataset_simple(src):
"""
读取整合数据
训练 40 * 2 张正脸(男女)
测试 10 * 2 张正脸(男女)
训练和测试数据不重复,数据内部不重复
"""
file_names = os.listdir(src)
# 用 dict 来存每一个数据,初始化同上
datasets = {"train_images": np.array([], dtype=np.float32),
"train_labels": np.array([], dtype=np.int32),
... | 5,325,301 |
def load2(file, collapsed=True, index=None):
"""Loads Laue diffraction data."""
if file['stacked'] is True:
files = loadstack(file)
if file['ext'] == 'h5':
vals = loadh5files(files, file['h5']['key'])
else:
if file['ext'] == 'h5':
begin, end, step = file['rang... | 5,325,302 |
def create_bookmark(record_settings):
"""Write record_settings to quickstreams.txt under bookmark name."""
bookmark_name = record_settings['bookmark']
# Set bookmark to None to avoid future loading attempting to bookmark
record_settings['bookmark'] = None
quickstreams = read_quickstreams()
while... | 5,325,303 |
def get_api_user(name):
"""
Check if the user is registered on faceit
:returns 1 Ok
:returns None nOk
"""
try:
logging.info("get_api_data_user")
faceit_data = FaceitData(FACEIT_API)
user = faceit_data.player_details(name)
if user:
return 1
... | 5,325,304 |
def removeDeliveredUSPSTracking(context: CallbackContext) -> None:
"""Send the alarm message."""
job = context.job
global deliveredUSPSTrackingNumbers
timenow = datetime.now()
recordsToRemove = []
for key in deliveredUSPSTrackingNumbers:
if ((timenow - deliveredUSPSTrackingNumbers[key]).... | 5,325,305 |
def get_storage_client():
"""Return storage client."""
global _client
if not _client:
_client = storage.Client()
return _client | 5,325,306 |
def upload_file_to_s3(image, fileStoreObj, acl="public-read"):
"""S3 file uploader."""
app = current_app._get_current_object()
s3 = boto3.client(
"s3",
aws_access_key_id=app.config['S3_KEY'],
aws_secret_access_key=app.config['S3_SECRET']
)
try:
s3.put_object(Body=im... | 5,325,307 |
def vae_bc(
transitions=None,
# Adam optimizer settings
lr_enc=1e-3,
lr_dec=1e-3,
# Training settings
minibatch_size=100,
):
"""
VAE Behavioral Cloning (VAE-BC) control preset
Args:
transitions:
dictionary of transitions generated by cpprb... | 5,325,308 |
def get_mode_fn(num_gpus, variable_strategy, num_workers):
"""Returns a function that will build shadownet model."""
def _mode_fun(features, labels, mode, params):
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
tower_features = features
tower_score_maps = labels[0]
tower_g... | 5,325,309 |
def link_to_profile(request):
"""
If the user is a temporary one who was logged in via
an institution (not through a Uniauth profile), offers
them the choice between logging to an existing Uniauth
account or creating a new one.
The institution account is (eventually) linked to the
Uniauth p... | 5,325,310 |
def obtain_fea_im_subset(Row_range, Col_range, tsList, ts_stack_foler, fC_hdr, fC_img, bandName):
"""
fea_im_subset = eng.zeros(int(tsLen),int(num_fea),int(d2),int(d1)) # this is matlab.double type
to convert matlab.double to ndarray
For one-dimensional arrays, access only the "_data" proper... | 5,325,311 |
def himmelblau(individual):
"""The Himmelblau's function is multimodal with 4 defined minimums in
:math:`[-6, 6]^2`.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- :math:`x_i \in [-6, 6]`
* - Global optima
... | 5,325,312 |
def get_deb_architecture():
"""
Returns the deb architecture of the local system, e.g. amd64, i386, arm
"""
return local('dpkg --print-architecture', capture=True) | 5,325,313 |
def Ry(angle, degrees=False):
"""Generate the :math:`3\\times3` rotation matrix :math:`R_y(\\theta)` \
for a rotation about the :math:`y` axis by an angle :math:`\\theta`.
Parameters
----------
angle : float
The rotation angle :math:`\\theta` in *radians*. If the angle is
given ... | 5,325,314 |
def augment_subdataset_split(args, subfolder, id_list, data_suffixes, aug_name, augment=True, multiplier=1):
"""
augment specific dataset split
:param args: command line arguments with data_dir and aug_data_dir
:param subfolder: sub-dataset folder. Either hgg or lgg
:param id_list: list of sequences... | 5,325,315 |
def compute_ibaq_1sample(df, organism='human'):
"""IBAQ values computed for total intensities of all proteins
Parameters
----------
df : pandas dataframe
proteomics dataset with columns as samples and rows as proteins
organism : str
organism (human, rat, or mouse) to calibrate each pr... | 5,325,316 |
def zhongzhuang_adjustment_reservoir():
"""
Real Name: ZhongZhuang Adjustment Reservoir
Original Eqn: INTEG ( IF THEN ELSE(Transfer From ZhongZhuangWeir To ZhongZhuangAdjustmentReservoir+ZhongZhuang Adjustment Reservoir\ -Transfer From ZhongZhuangAdjustmentReservoir To BanXinWPP-Transfer From ZhongZhuang... | 5,325,317 |
def _request_esi_status() -> requests.Response:
"""Make request to ESI about curren status with retries."""
max_retries = 3
retries = 0
while True:
try:
r = requests.get(
"https://esi.evetech.net/latest/status/",
timeout=(5, 30),
header... | 5,325,318 |
def RunExampleConsumer(serialized_file_graph):
"""Runs the example consumer on the serialized_file_graph.
Args:
serialized_file_graph: mojom_files.MojomFileGraph as output by the mojom
parser.
Returns:
The integer exit code of the example consumer.
"""
examples_dir = os.path.dirname(os.path.ab... | 5,325,319 |
def linnworks_api_session(func: Callable) -> Callable:
"""Use a Linnworks API session as a method decorator."""
def wrapper_linnapi_session(*args: Any, **kwargs: Any) -> Any:
with LinnworksAPISession():
return func(*args, **kwargs)
return wrapper_linnapi_session | 5,325,320 |
def check_if_phone_number_is_opted_out(phoneNumber=None):
"""
Accepts a phone number and indicates whether the phone holder has opted out of receiving SMS messages from your account. You cannot send SMS messages to a number that is opted out.
To resume sending messages, you can opt in the number by using th... | 5,325,321 |
def test_csv_to_layer_data_raises(tmp_path):
"""Test various exception raising circumstances with csv_to_layer_data."""
temp = tmp_path / 'points.csv'
# test that points data is detected with require_type == points, any, None
# but raises for other shape types.
data = [['index', 'axis-0', 'axis-1']... | 5,325,322 |
def threads():
"""Run multiply threads"""
try:
_thread.start_new_thread(counter, ("Thread 1", 10, 2))
_thread.start_new_thread(counter, ("Thread 2", 20, 0.5))
_thread.start_new_thread(counter, ("Thread 3", 5, 4))
_thread.start_new_thread(counter, ("Thread 4", 10, 0.1))
... | 5,325,323 |
def test_case_change_remote(m: Maestral) -> None:
"""
Tests the download sync of a remote rename which only changes the casing of the file
name.
"""
# Start with nested folders.
os.mkdir(m.dropbox_path + "/folder")
os.mkdir(m.dropbox_path + "/folder/Subfolder")
wait_for_idle(m)
ass... | 5,325,324 |
def series_quat2euler(q0, q1, q2, q3, msg_name=""):
"""Given pandas series q0-q4, compute series roll, pitch, yaw.
Arguments:
q0-q4 -- quaternion entries
Keyword arguments:
msg_name -- name of the message for which the euler angles should be computed (default "")
"""
yaw, pitch, roll = np... | 5,325,325 |
def addScaleBars(axis, dT, dF, T_value=-0.1, F_value=-0.4):
"""Add scale bars to plot or image."""
axis.plot(T_value * np.ones((2)), np.array([F_value, F_value + dF]), 'k-', alpha=0.9)
axis.plot(np.array([T_value, dT + T_value]), F_value * np.ones((2)), 'k-', alpha=0.9) | 5,325,326 |
def _ShiftRight(x0, xs):
"""Shifts xs[:-1] one step to the right and attaches x0 on the left."""
return tf.concat([[x0], xs[:-1]], axis=0) | 5,325,327 |
def compute_connected_components(self, compute_nx=True, probed_node=None, comps_to_merge=None, current_norm_vals=None):
"""
Computes the NORMALIZED connected components of the selfwork.
If compute_nx is True, actually computes components from scratch using selfworkx.
Otherwise, we update self.connected_... | 5,325,328 |
def process_method(oneway=False):
"""Decorator for process_xxx methods for asyncio."""
def _decorator(func):
def nested(self, seqid, iprot, oprot, server_ctx):
fn_name = func.__name__.split('_', 1)[-1]
handler_ctx = self._event_handler.getHandlerContext(fn_name,
... | 5,325,329 |
def search_salary(request):
""" This function will be called by search API """
logger.info("Received a salary request {}".format(request.method))
if request.method == 'GET':
try:
request_json_body = json.loads(request.body)
title = request_json_body['title']
loc... | 5,325,330 |
def Get_interp_header_dx2ser(df_raw, header_search, value_ask_raw, logger=mod_logger): # Vlookup. return row (series) at [value_ask, header_search]
""""
Most robust interpolator
#===========================================================================
# USE
#======================================... | 5,325,331 |
def get_wordnet_pos(treebank_tag):
"""Function to translate TreeBank PoS tags into PoS tags that WordNet
understands."""
if treebank_tag.startswith('J'):
return wordnet.ADJ
elif treebank_tag.startswith('V'):
return wordnet.VERB
elif treebank_tag.startswith('N'):
return wordn... | 5,325,332 |
def from_newick(string):
"""
Returns a tree sequence representation of the specified newick string.
"""
tree = dendropy.Tree.get(data=string, schema="newick")
tables = tskit.TableCollection(1)
id_map = {}
for node in tree.ageorder_node_iter():
children = list(node.child_nodes())
... | 5,325,333 |
def benchmark(problem_file, test_set_file):
""" Evaluates planners with a random problem from a given problem set and world map.
Assumes feasible paths can be calculated.
:param problem_file: A string of map file with .map extension
:param test_set_file: A string of problem set file with .s... | 5,325,334 |
def _recursive_pairwise_outer_join(
dataframes_to_merge, on, lsuffix, rsuffix, npartitions, shuffle
):
"""
Schedule the merging of a list of dataframes in a pairwise method. This is a recursive function that results
in a much more efficient scheduling of merges than a simple loop
from:
[A] [B] [... | 5,325,335 |
def signum(x):
"""cal signum
:param x:
:return:
"""
if x > 0:
return 1.0
if x < 0:
return -1.0
if x == 0:
return 0 | 5,325,336 |
def test_nodes_controller_wrapper(_nodes_controller, _transfer_file):
"""Check nodes controller wrapper command.
Wrapper should be a valid stringified nuke command.
"""
expected = "nuke.nodePaste('{}')".format(_transfer_file)
result = _nodes_controller._paste_nodes_wrapper(_transfer_file)
asse... | 5,325,337 |
def is_date(word):
"""
is_date()
Purpose: Checks if word is a date.
@param word. A string.
@return the matched object if it is a date, otherwise None.
>>> is_date('2015-03-1') is not None
True
>>> is_date('2014-02-19') is not None
True
>>> is_date('03-27-1995') is not Non... | 5,325,338 |
def create_pg_db_and_user(context, su_passwd=None, config_types=[]):
"""
根据配置新建postgresql数据库以及用户
"""
import getpass
if su_passwd is None:
su_passwd = getpass.getpass("sudo password:")
if len(config_types) == 0:
config_types = ["development", "testing"]
for config_type in con... | 5,325,339 |
def test_epoch(model, base_dist, test_loader, epoch,
device=None, annealing=False):
"""Calculate validation loss.
Args:
model: instance of CVAE
base_dist: r1(z) prior distribution
test_loader: instance of pytorch DataLoader
device: devic... | 5,325,340 |
def get_rest_value_from_path(status, device_class, path: str):
"""Parser for REST path from device status."""
if "/" not in path:
attribute_value = status[path]
else:
attribute_value = status[path.split("/")[0]][path.split("/")[1]]
if device_class == DEVICE_CLASS_TIMESTAMP:
last... | 5,325,341 |
def submit(request):
""" View for the submit page.
"""
if request.user.is_active:
user = UserSocialAuth.objects.filter(provider='github').get(user_id=request.user.id)
github = Github(user.tokens[u'access_token'])
repos = [repo for repo in github.get_user().get_repos()]
return... | 5,325,342 |
def all_combined_threshold(input_image):
"""
Apply all thresholds to undistorted image
:param input_image: Undistorted image
:return: Combined binary image
Ref: Course notes
"""
# Apply Gausiian blur to the input image
kernel_size = 5
input_image = cv2.GaussianBlur(input_image, (kern... | 5,325,343 |
def get_root_logger(profile='panoptes', log_config=None):
"""Creates a root logger for PANOPTES used by the PanBase object.
Args:
profile (str, optional): The name of the logger to use, defaults
to 'panoptes'.
log_config (dict|None, optional): Configuration options for the logger.
... | 5,325,344 |
def visualize_lidar_of_sample(level5data, sample_token: str, axes_limit=80):
"""Helper to visualize sample lidar data"""
sample = level5data.get("sample", sample_token)
sample_lidar_token = sample["data"]["LIDAR_TOP"]
level5data.render_sample_data(sample_lidar_token, axes_limit=axes_limit) | 5,325,345 |
async def run(rest_client, debug=False):
"""
Actual runtime / loop.
Args:
rest_client (:py:class:`iceprod.core.rest_client.Client`): rest client
debug (bool): debug flag to propagate exceptions
"""
start_time = time.time()
time_limit = datetime.utcnow() - timedelta(days=14)
... | 5,325,346 |
def sbol_cds (ax, type, num, start, end, prev_end, scale, linewidth, opts):
""" Built-in SBOL coding sequence renderer.
"""
# Default options
color = (0.7,0.7,0.7)
hatch = ''
start_pad = 1.0
end_pad = 1.0
y_extent = 5
x_extent = 30
arrowhead_height = 4
arrowhead_length = 8
# Reset defaults if pr... | 5,325,347 |
def convert_halo_to_array_form(halo, ndim):
"""
Converts the :samp:`{halo}` argument to a :samp:`(ndim, 2)`
shaped array.
:type halo: :samp:`None`, :obj:`int`, an :samp:`{ndim}` length sequence
of :samp:`int` or :samp:`({ndim}, 2)` shaped array
of :samp:`int`
:param halo: Halo to be... | 5,325,348 |
def keys(key_file,
gen_key,
show_vk):
"""
This set of commands support creation of signing key (private) and showing the verification key (public)
from a previously loaded signing key. Signing key is stored in PEM format
"""
if not gen_key and show_vk is None:
raise nRFExce... | 5,325,349 |
def update_all_users():
""""
Updates all tweets for all users in the user table
"""
for yan in User.query.all():
add_or_update_user(yan.name) | 5,325,350 |
def tran_canny(image):
"""消除噪声"""
image = cv2.GaussianBlur(image, (3, 3), 0)
return cv2.Canny(image, 50, 150) | 5,325,351 |
def draw_star(img_size, num_frames, bg_config, nb_branches=6):
""" Draw a star and output the interest points
Parameters:
nb_branches: number of branches of the star
"""
images = generate_background(img_size, num_frames=num_frames)
background_color = int(np.mean(images))
num_branches = r... | 5,325,352 |
def forestvar(z_in):
""" Return intrinsic variance of LyaF variance for weighting. This
estimate is roughly from McDonald et al 2006
Parameters
----------
z_in : float or ndarray
Returns
-------
fvar : float or ndarray
Variance
"""
fvar = 0.065 * ((1.+z_in)/(1.+2.25))**3... | 5,325,353 |
def _process_image_file(fobj):
"""Process image files from the dataset."""
# We need to read the image files and convert them to JPEG, since some files
# actually contain GIF, PNG or BMP data (despite having a .jpg extension) and
# some encoding options that will make TF crash in general.
image = _decode_imag... | 5,325,354 |
def main() -> None:
"""Use read_orgmode_file() to read in a file, then operate on the resulting notes."""
parser = argparse.ArgumentParser(description='Reads in an org-mode file and generates a ' +
'matching Anki card with HTML formatting.')
parser.add_argument('-i', '--... | 5,325,355 |
def normalize_contract_type(
contract_type_data: Dict[str, Any],
source_id: str,
) -> Iterable[Tuple[str, Any]]:
"""
Serialize contract_data found in compiler output to the defined fields.
"""
yield "abi", contract_type_data["abi"]
yield "sourceId", source_id
if "evm" in contract_type_da... | 5,325,356 |
def test_SetView_ge(testcase, obj1, obj2, exp_gt, exp_lt, exp_ge, exp_le):
# pylint: disable=unused-argument
"""
Test function for SetView.__ge__()
"""
# Double check they are different objects
assert id(obj1) != id(obj2)
# The code to be tested
ge = (obj1 >= obj2)
# Ensure that e... | 5,325,357 |
def compute_v2g_scores(reg, cisreg):
"""
Goes through evidence and scores associations to a SNP
Args:
* [ Regulatory_Evidence ]
* [ Cisregulatory_Evidence ]
Returntype: dict(Gene: dict(string: float)), dict(Gene: float)
"""
intermediary_scores = dict()
gene_scores = dict()
for gene in cisreg:
inter... | 5,325,358 |
def _old_normalize_batch_in_training(x, gamma, beta,
reduction_axes, epsilon=1e-3):
"""Computes mean and std for batch then apply batch_normalization on batch.
"""
if gamma is None:
gamma = ones_like(x)
if beta is None:
beta = zeros_like(x)
dev =... | 5,325,359 |
def ceil_to_batch_size(num, batch_size):
"""Calculate how many full batches in num.
Parameters
----------
num : int
batch_size : int
"""
return int(batch_size * ceil(num / batch_size)) | 5,325,360 |
def write_run_record(message_text):
"""对程式的运行及文件处理过程写入日志文件,已备后续查询"""
# 检测日志文件夹是否存在
if not os.path.exists("./record/"):
os.makedirs("./record/")
# 获取日志路径&需写入的信息
message = message_text
# 打开日志并写入
with open(f"./record/{str(datetime.datetime.now().strftime('%Y_%m_%d'))}.txt", 'a') as fi... | 5,325,361 |
def test_session_ca_bundle():
"""
test salt.utils.https.session when setting ca_bundle
"""
fpath = "/tmp/test_bundle"
patch_os = patch("os.path.exists", MagicMock(return_value=True))
with patch_os:
ret = salt.utils.http.session(ca_bundle=fpath)
assert ret.verify == fpath | 5,325,362 |
def error(msg, error_type=None):
"""Exit with an error message."""
if error_type is None:
error_type = _("error")
sys.exit("qastetray-cli: {}: {}".format(error_type, msg)) | 5,325,363 |
def quaternion_to_rotation_matrix(quaternion):
"""
This function transforms a quaternion into a 3x3 rotation matrix.
Parameters
----------
:param quaternion: a quaternion or a batch of quaternion N x [scalar term, vector term]
Returns
-------
:return: 3x3 rotation matrices
"""
... | 5,325,364 |
def recreate():
"""Recreate the database"""
drop()
create() | 5,325,365 |
def test_protids():
"""Pdom r1.2: extract protein IDs from GFF3"""
db = genhub.test_registry.genome('Pdtl')
protids = ['PdomMRNAr1.2-08518.1', 'PdomMRNAr1.2-11420.1',
'PdomMRNAr1.2-08519.1']
infile = 'testdata/gff3/pdom-266.gff3'
testids = list()
with open(infile, 'r') as instream... | 5,325,366 |
def session_end(bot):
""":crossed_flags: *TRPGのセッションを終わります*\n`/cc kp end`"""
target_status = "pc_id"
user_data = {}
lst_end_content = []
lst_player_data = get_lst_player_data(bot.team_id, bot.user_id, target_status)
msg_return = "| 名前 | PC | 備考 |\n|--|--|--|\n"
for player_data in lst_player_... | 5,325,367 |
def log_json(req_context, params=None, err=None):
"""
:param req_context:
:param params:
:param err:
:return:
"""
context = Util.get_context()
dict_items = dict(req_context)
dict_items.update(context)
logMsg = {key: value for (key, value) in (dict_items.items())}
if params o... | 5,325,368 |
def _anonymize_file(dicom_file_in, dicom_file_out, fields_to_keep):
"""
Anonimize a single dicomfile
:param dicom_file_in: filepath for input file
:param dicom_file_out: filepath for output file
:param fields_to_keep: dicom tags to keep
"""
# Default meta_fields
# Required fields accordi... | 5,325,369 |
def colored_print(text, use_color=True, color_name='white'):
"""Print with or without color codes"""
if use_color:
print(color(text, fg=color_name))
else:
print(text) | 5,325,370 |
def make_input_signature(inputs, include_tensor_ranks_only,
encode_variables_by_resource_id):
"""Generates an input signature representation.
Args:
inputs: The function inputs that need to be formed into a signature
include_tensor_ranks_only: If Tensors should be considered by rank... | 5,325,371 |
def _activities_from_datasets_followed_by_user_query(
user_id: str, limit: int
) -> QActivity:
"""Return a query for all activities from datasets that user_id follows."""
# Get a list of the datasets that the user is following.
follower_objects = model.UserFollowingDataset.followee_list(user_id)
if ... | 5,325,372 |
def getRowType(row):
"""Infers types for each row"""
d = row
for col, data in enumerate(row):
try:
if isNone(data):
d[col] = 'none'
else:
num = float(data)
if num.is_integer():
d[col] = 'int'
... | 5,325,373 |
def fetch_lawschool_gpa(subset="all", usecols=[], dropcols=[],
numeric_only=False, dropna=False):
"""Load the Law School GPA dataset
Note:
By default, the data is downloaded from tempeh. See
https://github.com/microsoft/tempeh for details.
Args:
subset ({'tr... | 5,325,374 |
def sync(obj_prim, obj: bpy.types.Object, mesh: bpy.types.Mesh = None, **kwargs):
""" Creates pyrpr.Shape from obj.data:bpy.types.Mesh """
if not mesh:
mesh = obj.data
log("sync", mesh, obj)
data = MeshData.init_from_mesh(mesh, obj=obj)
if not data:
return
stage = obj_prim.Get... | 5,325,375 |
def test_ba_validation_right_size_invalid_number_8_digits_and_second_digit_equal_6_7_9():
"""Test if an invalid number is really invalid with 8 digits"""
invalid_number = '61234559'
assert ba.start(invalid_number) == False | 5,325,376 |
def check_ref_exons(exon_seqs, mask_stops):
"""Check if the reference sequence is correct.
Should start with ATG and end with a stop.
Mask_stops controls handling of inframe stops.
"""
sec_codons = set() # in case there are TGA codons in the ref seq -> collect them
gene_seq = "".join([exon... | 5,325,377 |
def campaign(args):
"""Repeatedly inject bitflips into system and then fast-forwards."""
args = args.strip().split(" ")
if len(args) < 2 or len(args) > 4:
print("usage: campaign <iterations> <mtbf> [<address>] [<bytewidth>]")
print("bytewidth defaults to 4 bytes if address specified")
... | 5,325,378 |
def measure_fluxline_crosstalk(
dev, target_qubit, crosstalk_qubits, amplitudes,
crosstalk_qubits_amplitudes=None, phases=None,
target_fluxpulse_length=500e-9, crosstalk_fluxpulse_length=None,
skip_qb_freq_fits=False, n_cal_points_per_state=2,
cal_states='auto', prep_params=None,... | 5,325,379 |
def resistancedistances(graph):
"""
Returns the pairwise resistance distances on the given graph.
Args:
network: networkx graph
Returns:
Dictionary of pairwise resistance distances,
accessed by the (i,j) node labels
"""
nodes = graph.nodes()
nodecount = len(nodes)
... | 5,325,380 |
def upd_token_exp(req_token, expt=60 * 15):
"""
更新token过期时间
:param req_token:
:param expt: 过期时间(秒)
:return:
"""
r = RedisCtrl()
user_info = r.get_one(REDIS_KEY_PRE_TOKEN + req_token)
if user_info:
r.set_one(REDIS_KEY_PRE_TOKEN + req_token, user_info, expt=expt) | 5,325,381 |
def flatten_to_raster(data):
""" Flatten numpy array of various dimensions to RGB raster image.
:param data: numpy array of one of following sizes.
1) H x W x C (color/gray image)
2) N x Y x X x C (array of color/gray images)
3) nY x nX x Y x X x C (2d array of color/gray images... | 5,325,382 |
def VMObjectWalkPages(cmd_args=None, cmd_options={}):
""" Print the resident pages contained in the provided object. If a vm_page_t is provided as well, we
specifically look for this page, highlighting it in the output or noting if it was not found. For
each page, we confirm that it points to the ob... | 5,325,383 |
def read_google(url,**kwargs):
"""
Reads a google sheet
"""
if url[-1]!='/':
url+='/'
return pd.read_csv(url+'export?gid=0&format=csv',**kwargs) | 5,325,384 |
def ts_inspect_2d(target, *preds, start_date=None, freq=None):
"""
Builds TSMertics for point predictions only, creating internal representation for it.
"""
return TSMetrics(
xr_2d_factory(target, start_date=start_date, freq=freq),
*[xr_2d_factory(p, start_date=start_date, freq=freq) for... | 5,325,385 |
def is_numeric_dtype(arr_or_dtype: List[Literal["b", "a"]]):
"""
usage.seaborn: 2
"""
... | 5,325,386 |
def adjust_age_groups(age_labels):
"""
for each pair of cols to aggregate, takes the first number of the first element, and the last number for the last element
for instance: ["0-4",'5-10'] -> ['0-10']
"""
i=0
new_age_labels=[]
label=""
for element in age_labels:
if i%2==0:
... | 5,325,387 |
def tablize5(soup, hdr):
"""
:param soup: [bs4.BeautifulSoup] document context
:param hdr: [dict] header node to process
"""
hdrs3 = hdr['children']
assert len(hdrs3) > 0
table = soup.new_tag('table', border="1", style="max-width:75%")
# insert the table this way so we don't disturb any ... | 5,325,388 |
def get_kni_ports():
"""
A KNI port is a list of string of format vEth0_%d where %d is the port index.
"""
kni_ports = run_local_cmd('ifconfig | grep vEth0_ | cut -d\':\' -f1 ', get_output = True).split('\n')
return set([port for port in kni_ports if port != '']) | 5,325,389 |
def parse_log(file_abspath):
"""Parse warning and error info from TRNSYS generated log file.
Parses warning and error count when simulation ends with errors.
If simulation ends successfully, counts number of warnings and return
successful completion message.
Args:
file_abspath: absolute pa... | 5,325,390 |
def test_close_private_issue(mock_mr):
"""Test issue state and API request that is sent to GitHub."""
mock_mr.return_value.status_code == 200
json_event, signature = event_data('private_issue_opened.json')
payload = json.loads(json_event)
issue = WebHookIssue.from_dict(payload)
issue.close_priva... | 5,325,391 |
def extract_publish_info_from_issue(
issue: "Issue", publish_type: PublishType
) -> Union[PublishInfo, MyValidationError]:
"""从议题中提取发布所需数据"""
try:
if publish_type == PublishType.BOT:
return BotPublishInfo.from_issue(issue)
elif publish_type == PublishType.PLUGIN:
retu... | 5,325,392 |
def points_inside_poly(points, all_verts):
"""Return bool array of points inside a polygon """
from matplotlib.path import Path
return Path(all_verts).contains_points(points) | 5,325,393 |
def write_links():
"""Add or update a cell in each notebook with a Google Colab link"""
for nb_name, link in iter_links():
notebook = nbformat.read(nb_name, as_version=4)
nb_file = os.path.basename(nb_name)
is_comment = lambda cell: cell.source.startswith(LINK_COMMENT)
if is_co... | 5,325,394 |
async def test_properties_v3(event_loop, v3_server):
"""Test that v3 sensor properties are created properly."""
async with v3_server:
async with aiohttp.ClientSession(loop=event_loop) as websession:
[system] = await get_systems(TEST_EMAIL, TEST_PASSWORD, websession)
entry_sensor... | 5,325,395 |
def exploration_function(q_space, x_space, index_, action_space_n, k):
"""returns exploration value"""
x_value = float('-inf')
for i in range(action_space_n):
x_value = max(x_value, q_space[index_][i] + k/(1 + x_space[index_][i]))
#print("q={}, q+x_bonus={}".format(max(q_space[index_]), x_value... | 5,325,396 |
def remove_docker_image(repo: str, tag: str, dc: DockerClient):
"""Remove docker image"""
image_name = f"{repo}:{tag}"
for container in dc.containers.list(filters=dict(ancestor=image_name)):
with suppress_docker_wait_error():
container.wait(condition="removed", timeout=30)
retry_call... | 5,325,397 |
def get_vectors(model_dm, model_dbow):
"""
将训练完成的数据转换为vectors
:param model_dm:
:param model_dbow:
:return:
"""
# 获取训练数据集的文档向量
train_vecs_dm = getVecs(model_dm, x_train, size)
train_vecs_dbow = getVecs(model_dbow, x_train, size)
train_vecs = np.hstack((train_vecs_dm, train_vecs... | 5,325,398 |
def test_profile_queue(db, test_profile, test_project_data):
"""A queue with test data, associated with the first test profile."""
return add_queue(test_project_data, TEST_QUEUE_LEN, profile=test_profile) | 5,325,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.