content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Union
from re import T
from typing import Sequence
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 b... | ba2524875d13c388e157c9994ae4c380aafe9e52 | 3,636,600 |
import os
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.int3... | fd0901783dc747f0b54e125c6417188b9bacc789 | 3,636,601 |
import logging
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, ... | f066d6e738dfd2ae4b503f8416fc5df6384f7a5d | 3,636,602 |
import logging
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:
retu... | 16643b499162226d65f217d2bdc9c78f64424507 | 3,636,603 |
def get_storage_client():
"""Return storage client."""
global _client
if not _client:
_client = storage.Client()
return _client | fe54dd0c0f922a2b6413cab792feda9313e15e02 | 3,636,604 |
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... | f8505858fa341cc9d7420cc04817c9169f10d182 | 3,636,605 |
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... | c447dba04864b6eb8a9312135cd656e13a40c971 | 3,636,606 |
import itertools
import six
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_ma... | 17f3465485ef5388fcacd0c8aeeac9ff4eb89651 | 3,636,607 |
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... | 63e8bfa1e226cf2247e01e0fa5c6aa30365256bc | 3,636,608 |
from pathlib import Path
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, acc... | 257156c63d3ea06f53ed904dcddcc3c60bf9d937 | 3,636,609 |
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
... | 2fcf348e01f33a54d847dfc7f9a225ed043e36a4 | 3,636,610 |
def get_deb_architecture():
"""
Returns the deb architecture of the local system, e.g. amd64, i386, arm
"""
return local('dpkg --print-architecture', capture=True) | a2c4ac9845bb395210043b8ebd7447596203a55b | 3,636,611 |
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 ... | e10d95eb36051da7e87540ebe24a02c092861b36 | 3,636,612 |
import os
import tqdm
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... | 038fe5004c943c53afffda9efc10cb7913646075 | 3,636,613 |
import os
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 calib... | c6b52318e6c3a579c969a75592b4282223f51bfc | 3,636,614 |
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 ZhongZhuangAdj... | 1fcc4a00015a3b8c1dadfc414455eab626704366 | 3,636,615 |
import requests
import random
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... | 39a74a766f77e66ae0fa33ac62b9ad09698a83be | 3,636,616 |
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... | 42fbc45f1e3ace3f1774ac631cef9811f01a2915 | 3,636,617 |
from typing import Callable
from typing import Any
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)
r... | fb94e4f0ed1e0477e5b058c6adfd48712b7bfb12 | 3,636,618 |
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... | bab831238025584a275595a8b6c038f52704047e | 3,636,619 |
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) | 9e6936432e4a7b7317560d6b2e32ac8a576d2d22 | 3,636,620 |
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_... | de4c60c590e4444e15189ac59883bf2535f1c510 | 3,636,621 |
import sys
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,
... | a4eda6057276fbaaf4734bf132fb1e003fb7e296 | 3,636,622 |
import json
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']
... | 72de0064dbfad0e4692c2c0ffb240111432fc8e8 | 3,636,623 |
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
#======================================... | fd7e8cfac2046a31ceafe830f330a84cc8732292 | 3,636,624 |
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... | b559b767ffa8a8f87d7aad571f2c88fbc49f3ec1 | 3,636,625 |
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())
... | ef0161f27d00e762afa5164c23c5e0030c2e7093 | 3,636,626 |
import random
import time
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... | dcb2bc13dc0a6ecaf1b16d69bd166fd2fb1d8ffc | 3,636,627 |
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] [... | 7d65d01cce313ed0517fd685045978dee6d7cb08 | 3,636,628 |
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 | 0f8e67eb8fa3267ec341d17440270ce68ca8b446 | 3,636,629 |
import re
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'... | 004bef4ac50f3ebd859cb35086c6e820f4c6e231 | 3,636,630 |
import torch
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... | 36a5d2fc9d229dca98f1a36f588436ab60a92754 | 3,636,631 |
from datetime import datetime
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 == DEVI... | bae16743c389a8b4bd760b458f187bc4130970ca | 3,636,632 |
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... | ec6c1107547b444923bab904ce79c848228320be | 3,636,633 |
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... | 638ec26ffd08ccc24bd5dea288cae55466d50c67 | 3,636,634 |
from datetime import datetime
import time
import logging
import os
import sys
from contextlib import suppress
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, defau... | 2e5c246d771b4efb385ad7bbd364508445cbd6ef | 3,636,635 |
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 provided
if o... | 5647edc622c23445c6e3d8cae5f602f2a5167516 | 3,636,636 |
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... | ddf718d16ce6a13f48b1032988ec0b0a43aa2b47 | 3,636,637 |
def tran_canny(image):
"""消除噪声"""
image = cv2.GaussianBlur(image, (3, 3), 0)
return cv2.Canny(image, 50, 150) | d9c308b43a25e714a8ddd66bdc4a700c6ec926f0 | 3,636,638 |
import math
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))
nu... | bec71099fae94f43af14327ab8c5549586f3bab2 | 3,636,639 |
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... | d3523510ee29b0cc12138da93001635f5ffe6a11 | 3,636,640 |
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... | 6e9e1e28a8e057a164b7385e87836dd280efdb9d | 3,636,641 |
import collections
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 ge... | 137a17ba0dbec6ce4e3fcd661709c9a166312e2a | 3,636,642 |
from re import T
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... | 1993d33c8d2d5ece26d2ac804dfb0961d02d24e2 | 3,636,643 |
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)) | 69827028a856248c50e958761e4d106a304076e3 | 3,636,644 |
import torch
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 mat... | ace8bca2b2e512b499dcc8ebac382226699262d2 | 3,636,645 |
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_... | 1f4bfa5d719be1e856efbea8d51df2af092dc119 | 3,636,646 |
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... | 37147b5a30614b8e822ec56ec4f8e9c000691c80 | 3,636,647 |
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... | 445adabf927614dea23131a973b12d98117d79e5 | 3,636,648 |
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 ... | 7e7a3111515f9da625c554f283aa5d948fd45080 | 3,636,649 |
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'
... | af0e853defb95005ece8727d58b8f58db8411afe | 3,636,650 |
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... | 9b01070fb62e0d28dc5961d84fac311a549e258f | 3,636,651 |
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... | 9b7e101cb055ee561ad54beb9b2c15c43044f2fc | 3,636,652 |
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,... | 43bd8148ccaa5625cbec91fff9fa16eb20f991d6 | 3,636,653 |
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)
... | 9e3b44602a0dce55516947768ad136e47397af86 | 3,636,654 |
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... | 2cb9c12a1d3efb7885f1f4d34d0eb3fc9b4d35c0 | 3,636,655 |
def read_google(url,**kwargs):
"""
Reads a google sheet
"""
if url[-1]!='/':
url+='/'
return pd.read_csv(url+'export?gid=0&format=csv',**kwargs) | 286158dc007378eef84ed048cda54a93c41dc140 | 3,636,656 |
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... | 34bd33ac53622c2b5441613fed9b8573d019dfcb | 3,636,657 |
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:
... | 521a2f6779ae8fa3f3a53801e0f935844245cffc | 3,636,658 |
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 != '']) | 1f04adea6c080bf5800e86dea559207048c345f3 | 3,636,659 |
import re
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:... | 9fef07ac7a6f035b536c105d401b1f9f4413f629 | 3,636,660 |
from typing import Union
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 == PublishTy... | bbe5a8d5e7971b335334aef8e6b158df6fa42146 | 3,636,661 |
from matplotlib.path import Path
def points_inside_poly(points, all_verts):
"""Return bool array of points inside a polygon """
return Path(all_verts).contains_points(points) | 1271045ae4230345da4bec6b81f4eeebe34826d5 | 3,636,662 |
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... | 9c6f1aa2943436d75c9a7735b4efa2c44c8a08d1 | 3,636,663 |
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... | 9f302bccd63c43bcf685851550f553ea1283de51 | 3,636,664 |
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) | 2e23f456972a7a617be1edd86bcf990286c0638b | 3,636,665 |
import sqlite3
def user_has_registered(userID):
"""Checks if a particular user has been registered in database"""
database = sqlite3.connect("users.db")
cursor = database.cursor()
cursor.execute(f"SELECT user_id FROM profile WHERE user_id = {userID}")
result = cursor.fetchone()
if result ... | e98f83b272a52828638f276575596489bebe1fcf | 3,636,666 |
def prepare_ocp(
biorbd_model_path: str,
final_time: float,
n_shooting: int,
marker_velocity_or_displacement: str,
marker_in_first_coordinates_system: bool,
control_type: ControlType,
ode_solver: OdeSolver = OdeSolver.RK4(),
) -> OptimalControlProgram:
"""
Prepare an ocp that targets... | 6a991931b7cd458611a9467e6c6c7ba4f0235150 | 3,636,667 |
def key_gen(**kwargs):
"""
Key generator for linux. Determines key based on
parameters supplied in kwargs.
Keyword Parameters:
@keyword geounit1: portable_id of a geounit
@keyword geounit2: portable_id of a geounit
@keyword region: region abbreviation
"""
if 'geounit1' in kwargs and... | 02426fbf49e7a4d85094896546980828e2c6bc20 | 3,636,668 |
from typing import List
from typing import Optional
def find(bindings: List[Binding], name: str) -> Optional[Binding]:
"""
Returns a Binding with a given name. Comparison is case-insensitive.
:param bindings: the Bindings to find in
:param name: the name of the Binding to find
:return: the Bindi... | b5efb45c6c9ca982ffa0949a599dc3e6b1f8a948 | 3,636,669 |
def computeResult():
"""Allows download of asset data result file.
---
tags:
- services
consumes:
- application/json
parameters:
- name: consumerAddress
in: query
description: The consumer address.
required: true
type: string
- name: jobId
... | 85cf900bdde0d2e95c5c14c7a18abaaf592bce99 | 3,636,670 |
from typing import Dict
async def init_menu_perms(request: Request) -> Dict:
"""
初始化菜单和权限
"""
return await services.init_menu_perms(request) | d863d89a857097434885d59b037cd4ff1cf5fe8f | 3,636,671 |
def bert_process_sentence(example_tokens, max_seq_length, tokenizer):
"""
Tokenization and pre-processing of text as expected by Bert
Parameters
----------
example_tokens
max_seq_length
tokenizer
Returns
-------
"""
# Account for [CLS] and [SEP] with "- 2"
if len(examp... | 992f6ccbdcfdb4498a6aa226efee8d26844d435a | 3,636,672 |
def weight_diff(w1, w2):
""" Calculates the array of differences between the weights in arrays """
# Expand and flatten arrays
_w1 = np.hstack([x.flatten() for x in w1])
_w2 = np.hstack([x.flatten() for x in w2])
return _w1 - _w2 | 0e9154aa723335a6d6d53382c67abe25523508e9 | 3,636,673 |
import sys
import time
def get_root_modules():
"""
Returns a list containing the names of all the modules available in the
folders of the pythonpath.
"""
rootmodules_cache = XSH.modules_cache
rootmodules = list(sys.builtin_module_names)
start_time = time()
for path in sys.path:
... | fa4f04c79583e851d68b66906d8672db4db3052d | 3,636,674 |
def advect_salinity(vs):
"""
integrate salinity
"""
return advect_tracer(vs, vs.salt[..., vs.tau], vs.dsalt[..., vs.tau]) | b760f4bc9144db1ea1bc6a80c075f392a4c0acb1 | 3,636,675 |
import math
def lafferty_wyatt_point(lowedge, highedge, expo_slope):
"""calculates the l-w point for a bin where the true distribution is an
exponential characterized by expo_slope.
"""
rhs = (math.exp(expo_slope*highedge) - math.exp(expo_slope*lowedge))
rhs /= expo_slope
rhs /= (highedge - l... | 326acddc1926f1a142f34e8cff9109554ec850d3 | 3,636,676 |
def init_critical_cases_20():
"""
Real Name: b'init Critical Cases 20'
Original Eqn: b'0'
Units: b'person'
Limits: (None, None)
Type: constant
b''
"""
return 0 | 735a4df9c2ee5777c7c15dcf4fb4a3830cb5e0b6 | 3,636,677 |
def build_doc(pic_dic):
"""
Gets dict {'image-name':['image-path',text]} ==> doc obj
"""
doc = word_obj()
# Add footer
doc.sections[0].footer.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
add_page_number(doc.sections[0].footer.paragraphs[0].add_run())
# Started Page
starter... | 1172f4b83e678fd2b363914c374667059af6ccbb | 3,636,678 |
def dispatch_every_hour(one_time_password):
""" This is the receiving point of start_every_hour's post request. It
checks that the one time password is correct and then dispatches
every_hour. """
EveryHourOTP.check_password(one_time_password)
Process(target=every_hour).start()
return "s... | e03f6bccbfb76fd25572bebde78151832b994928 | 3,636,679 |
def check_list(data):
"""check if data is a list, if it is not a list, it will return a list as [data]"""
if type(data) is not list:
return [data]
else:
return data | 00ae7a857c3f969ca435928edf98ed5bb36c1c34 | 3,636,680 |
def nfvi_reinitialize(config):
"""
Re-initialize the NFVI package
"""
global _task_worker_pools
init_complete = True
compute_plugin_disabled = (config.get('compute_plugin_disabled',
'False') in DISABLED_LIST)
if not compute_plugin_disabled:
... | a8f76bf228b94fadc18dbe0e97a21109ee607935 | 3,636,681 |
import re
def parse_freqs(lines, parameters):
"""Parse the basepair frequencies.
"""
root_re = re.compile("Note: node (\d+) is root.")
branch_freqs_found = False
base_freqs_found = False
for line in lines:
# Find all floating point numbers in this line
line_floats_res = line_fl... | b0940b15aba9387e9257fd47bd5cbbd8dbf821ea | 3,636,682 |
def student2nation(id_num):
"""
Takes student id, returns nation id of the student.
"""
return school2nation(id_num) | 9453a6b2b9f31bbeb6c319cc450a757f3c8585b0 | 3,636,683 |
def get_projects_with_builds(only_public=True, only_active_versions=True):
"""Returns a queryset of Projects with active only public by default builds."""
builds = Build.objects.filter(
success=True,
state='finished',
version__active=True
)
if only_public:
builds = builds... | e1ae057fa983741fb291ac3c47cc5be628fe1711 | 3,636,684 |
import base64
def encode_base64(filename):
"""encode image to string.
Args
filename: image file path.
Returns:
a bites string.
"""
with open(filename, "rb")as f:
bs64 = base64.b64encode(f.read()).decode()
return bs64 | 9eab28ec1cb9619411ea28a9640a2fa8b02e61a3 | 3,636,685 |
def transfer_from_taoyuanagrichannel_to_taoyuanagriwaterdemand():
"""
Real Name: Transfer From TaoYuanAgriChannel To TaoYuanAgriWaterDemand
Original Eqn: (Transfer From ShiMenReservoir To HouChiWeir*Ratio AgriWater ShiMenReservoir To HouChiWeir In TaoYuanAgriChannel)*(1-Channel Transfer Loss Rate )
Unit... | 7bd77945002ed9217485dcf1f412cf333c666e30 | 3,636,686 |
def Doxyfile_emitter(target, source, env):
"""
Modify the target and source lists to use the defaults if nothing
else has been specified.
Dependencies on external HTML documentation references are also
appended to the source list.
"""
doxyfile_template = env.File(env['DOXYFILE_FILE'])
source.in... | 41928a8c837d7eb00d6b4a4a2f407e2d75217620 | 3,636,687 |
def _recursive_make_immutable(o):
"""Recursively transform an object into an immutable form
This is a cdev core specific transformation that is used to convert Dict and List and other native python
types into frozendict, frozenset, etc. The purpose is that the later set of objects are immutable in python
... | 270dc2aaa07edf2f0f57aa298ea0f619e7412b80 | 3,636,688 |
def retry_condition(exception):
"""Return True if we should retry (in this case when it's an IOError), False otherwise"""
if isinstance(exception, (HTTPError, AttributeError)):
print(f'HTTP error occurred: {exception}') # Python 3.6
return True
return False | c6de8b160c071ed8055ed4dd1268ac97958166dd | 3,636,689 |
def mergesort(input_arr):
"""
Sort the array by application of merge sort
Time complexity: O(n log(n))
Space Complexity: O(n)
Args:
input_arr(array): Input array with numbers to be sorted
Returns:
sorted_arr(array) Sorted array with numbers in ascending order
... | 433348035ea2bc41aef11dc3eaa8c51d16fffc81 | 3,636,690 |
def _clean_annotated_text(text):
"""Cleans text from the format that it was presented to annotators in the
S.M.A.R.T data annotation tool. Splits the title from the abstract text
and strips any trailing whitespace.
Returns:
title (str): The project title
text (str): The project abstra... | 356cdf893225c41d303e83f1cf2f3418544c76ae | 3,636,691 |
def get_or_create_event_loop():
"""
Tries to get the current event loop. If not found creates a new one.
Returns
-------
event_loop : ``EventThread``
"""
try:
event_loop = get_event_loop()
except RuntimeError:
event_loop = create_event_loop(daemon=False)
ret... | 1dacd2172a0bffd2e5632ec48b90a1c1ee31800d | 3,636,692 |
def tnaming_Displace(*args):
"""
* Application de la Location sur les shapes du label et de ses sous labels.
:param label:
:type label: TDF_Label &
:param aLocation:
:type aLocation: TopLoc_Location &
:param WithOld: default value is Standard_True
:type WithOld: bool
:rtype: void
... | 91d2550b5ecb108a2ddcceb6a3a227e48ab16f24 | 3,636,693 |
def get_capital_np(markets,signals,size,commiRate,climit = 4, wlimit = 2, op=True):
"""使用numpy回测,标签的盈亏, op 表示是否延迟一个tick以后撮合"""
postions = np.zeros(len(signals))
actions = np.zeros(len(signals))
costs = np.zeros(len(signals))
pnls = np.zeros(len(signals))
lastsignal = 0
l... | 4604bb16c298e4ea32d2fca5f8332e5d21e4aada | 3,636,694 |
def slicename_to_hostname(vs_name):
"""Converts a vserver slice name into a canonical FQDN.
Slice names use a pattern like: <some site>_<some name>.
Example:
If vs_name is 'mlab_utility' and the system hostname is
'mlab4.nuq01.measurement-lab.org', then slicename_to_hostname will return
'utility.m... | 7f8b6ff17ab402cfa89ee732f1e4c61ddffee7c2 | 3,636,695 |
from typing import Dict
def swim_for_a_day(life_counts: Dict[int, int]):
"""Process the shoal, decrement the life_counts:
any that get to -1 have procreated in the last day, their offspring are
created with 8 day life_counts, whilst they get reset to 6 days… and are
added to the count of any fish that... | 3d5d3f48942a5a1f4eba3100e903df592d933e23 | 3,636,696 |
def page_not_found (error):
"""
Generic Error Message
"""
return "Unable to find Distill." | ed764c2c2814487c33f9945b17b85a234ae45645 | 3,636,697 |
def dict_to_obj(our_dict):
"""
Function that takes in a dict and returns a custom object associated with
the dict. This function makes use of the "__module__" and "__class__"
metadata in the dictionary to know which object type to create.
"""
if "__class__" in our_dict:
# Pop ensures we... | 4ad11ff943d2055d37643b6d7058175f504f8271 | 3,636,698 |
def display_fips( collection_of_fips, fig, **kwargs ):
"""
Method that is very similar to :py:meth:`display_fips_geom <covid19_stats.engine.viz.display_fips_geom>`, except this *also* displays the FIPS code of each county. For example, for `Rhode Island`_, this is.
.. _viz_display_fips_rhodeisland:
... | ea609e19f4f42032a0533c12ea8ebc9ded6412aa | 3,636,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.