content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def calculate_deltaangle_distance(
org_ligs,
smiles_keys,
fg_factory,
file_prefix=None
):
"""
Calculate the change of bite angle of each ligand in the cage.
This function will not work for cages built from FGs other than
metals + AromaticCNC and metals + AromaticCNN.
Parameters
... | dfc367300b92561c8b167081121c90e5313187a1 | 3,636,571 |
import logging
import time
def wait_for_file_to_finish_writing(**args) -> tuple:
"""
This wait shouldn't be required but appears to be help with larger files.
"""
config = args.get('config')
logging.info("waiting {} seconds for file to finish writing and unlock".format(config.BULK_IMPORT_WAIT))
... | 915c5b159030c5860891e95f09ffc725f755c584 | 3,636,572 |
def get_max_id(connection, generic_sensor_type: str) -> int:
"""
Get the max id of a given generic sensor type.
:param generic_sensor_type: "asset", "market", or "weather_sensor"
"""
t_generic_sensor = sa.Table(
generic_sensor_type,
sa.MetaData(),
sa.Column("id", sa.Integer),... | 11a35d9e43e7c403271675fd7b6207d6e16e0c80 | 3,636,573 |
def _temp_dict_file_name():
"""Name of the expected python dictionary as a json file from run_external_python().
.. versionadded:: 9.1
"""
return '__shared_dictionary__' | 94f33562d775b041387b477d838a5efadfe38f00 | 3,636,574 |
def anisotropic_Gaussian(ksize=25, theta=np.pi, l1=6, l2=6):
"""
https://github.com/cszn/KAIR/blob/master/utils/utils_sisr.py
Generate an anisotropic Gaussian kernel
Args:
ksize : e.g., 25, kernel size
theta : [0, pi], rotation angle range
l1 : [0.1,50], scaling of eigenvalue... | 259ae1590807e11d5805c1065fed82acf430b60b | 3,636,577 |
import warnings
def fakemag_to_parallax(fakemag, mag, fakemag_err=None):
"""
To convert fakemag to parallax, Magic Number will be preserved
:param fakemag: astroNN fakemag
:type fakemag: Union[float, ndarray]
:param mag: apparent magnitude
:type mag: Union[float, ndarray]
:param fakemag_e... | 0086436f41707a74974d6358d101eacc3149777a | 3,636,581 |
def provenance_stamp(routine):
"""Return dictionary satisfying QCSchema,
https://github.com/MolSSI/QCSchema/blob/master/qcschema/dev/definitions.py#L23-L41
with QCElemental's credentials for creator and version. The
generating routine's name is passed in through `routine`.
"""
return {'creator'... | 34c1e11c69d0b0354e356bd0463a9f89cd438d51 | 3,636,582 |
def index_of(y):
"""
A helper function to get the index of an input to plot
against if x values are not explicitly given.
Tries to get `y.index` (works if this is a pd.Series), if that
fails, return np.arange(y.shape[0]).
This will be extended in the future to deal with more types of
label... | fae630e18bf20f1c9762e6c6f9d2d1b2f5cf93e2 | 3,636,583 |
def get_centered_box(center: np.ndarray, box_size: np.ndarray):
"""
Get box of size ``box_size``, centered in the ``center``.
If ``box_size`` is odd, ``center`` will be closer to the right.
"""
start = center - box_size // 2
stop = center + box_size // 2 + box_size % 2
return start, stop | 4d5ce84547281b27d8405894ce280139696329ba | 3,636,584 |
def _make_context(frames, cameras):
"""
Generate Context named tuple using camera, frame information
Args:
- cameras:
- frames:
Returns: A Context named tuple encapsulating given information
"""
return Context(cameras=cameras, frames=frames) | b338795bf367c7e12b769fa33049e3e52a0daf00 | 3,636,585 |
def get_list_from_file(filename):
"""
Returns a list of containers stored in a file (one on each line)
"""
with open(filename) as fh:
return [_ for _ in fh.read().splitlines() if _] | 8d9a271aa4adea81f62bf74bb1d3c308870f1baf | 3,636,587 |
def import_recipe():
"""Import recipe from base64 encoded text."""
form = Import()
errors = None
if form.validate_on_submit():
encoded = request.form["encoded"]
try:
decoded = loads(b64decode(encoded.encode("utf-8")).decode("utf-8"))
# recipe table
ti... | 7665af330f029c29e3cf5a2667204a3ba94409c2 | 3,636,588 |
def parse_xyz(filename, nbits):
"""Read xyz format point data and return header, points and points data."""
pointstrings = []
with open(filename) as points_file:
for line in points_file:
if not line.startswith('#'):
if not line.isspace():
line = line.r... | 51a9f7f34bbae5eeddd8b97139ed59ec53e43939 | 3,636,589 |
def compare_vecs(est, truth, zero_tol=0):
"""
Parameters
----------
est: array-like
The estimated vector.
truth: array-like
The true vector parameter.
zero_tol: float
Zero tolerance for declaring an element equal to zero.
Output
------
out: dict
Di... | ef977c31bbca818809f7d708d0ed6f754912239e | 3,636,590 |
def accumulator(init, update):
"""
Generic accumulator function.
.. code-block:: python
# Simplest Form
>>> a = 'this' + ' '
>>> b = 'that'
>>> c = functools.reduce(accumulator, a, b)
>>> c
'this that'
# The type of the initial value determines outp... | 6a4962932c8dba4d5c01aa8936787b1332a6323f | 3,636,591 |
def process_po_folder(domain, folder, extra=''):
""" Process each PO file in folder """
result = True
for fname in glob.glob(os.path.join(folder, '*.po')):
basename = os.path.split(fname)[1]
name = os.path.splitext(basename)[0]
mo_path = os.path.normpath('%s/%s%s' % (MO_DIR, name, MO... | c89a7952d9961ec096dac98f1d830a24b4d62ecd | 3,636,592 |
def create_service(
*,
db_session: Session = Depends(get_db),
service_in: ServiceCreate = Body(
...,
example={
"name": "myService",
"type": "pagerduty",
"is_active": True,
"external_id": "234234",
},
),
):
"""
Create a new s... | 890928f0a5b1a990ea27594886031bf6ede1a0db | 3,636,593 |
import json
def get_handler(event, context): # pylint: disable=unused-argument
"""REST API GET method to get data about a Minecraft game server."""
# gather the server data
name = event.get('pathParameters', {}).get('name')
server = gather(name)
# return the HTTP payload
return {
'st... | 61326050cbac4ad3a7a727ebef01bd7e496a254c | 3,636,597 |
def get_item(dataframe: DataFrame, col: str, new_col: str, index: any) -> DataFrame:
"""Return DF with a column that contains one item for an array
:param str col: name of the column
:param str new_col: type of the new column
:param any index: the index key
Examples:
```
SectionName:
... | e06090dad60f7522b1727d69926994bb94f669d6 | 3,636,598 |
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 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 |
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 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_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 |
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 |
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 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 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 |
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 |
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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.