content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _input_file_to_arg(input_file):
"""Converts a File object to string for --input_file argument to wheelmaker"""
return "%s;%s" % (_path_inside_wheel(input_file), input_file.path) | a5abe5324cebdac6cd9fdd1a69c4ff7980ddc997 | 3,604,644 |
def Spurious_Fourier_train(sample):
""" Spurious Fourier model hparam definition
Args:
sample (bool): If ''True'', hyper parameters are gonna be sampled randomly according to their given distributions. Defaults to ''False'' where the default value is chosen.
"""
if sample:
return {... | 1d165c405476e690d785efd6764cea618cc9244d | 3,604,645 |
from typing import List
from typing import Optional
import types
def rnn_step_with_state(
model,
initial_state: List[tf.Tensor],
modify_state: bool,
step_args=None,
step_kwargs=None,
state_scope_name: Optional[str] = None) -> types.ForwardFunctionReturns:
"""Step through RNN with persistent ... | c42af7584239fc8bed0952fd34089ad360ff4a32 | 3,604,646 |
from io import StringIO
def convert_vector_drawable_stream(input_stream, color_map_stream=None) -> str:
"""
Convert Android Drawable XML to SVG with use of the optional color map.
:param input_stream: A binary stream containing Android vector drawable
:param color_map_stream: An optional color schema... | 6045503884178507c907593c40c1850568469f6f | 3,604,647 |
from typing import Sequence
from typing import Optional
def tensor_buffer_to_tensor(
x: oneflow._oneflow_internal.BlobDesc,
dtype: flow.dtype,
instance_shape: Sequence[int],
name: Optional[str] = None,
) -> oneflow._oneflow_internal.BlobDesc:
"""This operator converts the Blob's type from TensorBu... | 4cf0dc4c55db1014e2327e8e64fc2bae5aa2b912 | 3,604,648 |
def read_epi_params(item_basename):
"""Read all the necessary EPI parameters from text files with the given basename.
Args:
item_basename (str): The basename for all the files we need to read.
In particular the following files should exist:
- basename + '.read_out_time.txt' ... | 3af788073607df214c447f2b87606b2d3e1638fd | 3,604,649 |
import select
def api_private_asn_by_month():
"""Network count by month
---
responses:
'200':
description: [{"date":"2018-08-31","value":4411}, ... ]
"""
# OLAP-use-case
cols = [sql.text("networks_by_month"), sql.text("month")]
q = select(cols).select_from(sql.table("global_b... | 34930770818d19733505a8c9162934f0559cb735 | 3,604,650 |
import logging
def remove_duplicate_called_graphs(comp):
"""Deduplicates called graphs for a subset of TFF AST constructs.
Args:
comp: Instance of `building_blocks.ComputationBuildingBlock` whose called
graphs we wish to deduplicate, according to `tree_analysis.trees_equal`.
For `comp` to be elig... | 78582e96f78093c780a8f63e2c3190cdf9fd2271 | 3,604,652 |
import inspect
def _commands(cli):
"""Extracts all public functions from `cli`
Args:
cli (module): where commands are executed from
Returns:
list of function: public functions sorted alphabetically
"""
res = []
for n, t in inspect.getmembers(cli):
if _is_command(t, cl... | a6aaa462d5e414803df0838bb04380960c92052f | 3,604,653 |
def from_tensor(tensor_to_convert):
"""Convert a tensor of tfq primitives back to Python objects.
Convert a tensor representing `cirq.PauliSum` or `cirq.Circuit`
objects back to Python objects.
>>> my_qubits = cirq.GridQubit.rect(1, 2)
>>> my_circuits = [cirq.Circuit(cirq.X(my_qubits[0])),
..... | 8a96d2a8e695decc7ae245fdce74f28bcf2062aa | 3,604,654 |
def filled_int(val, length):
"""
Takes a value and returns a zero padded representation of the integer component.
:param val: The original value.
:param length: Minimum length of the returned string
:return: Zero-padded integer representation (if possible) of string. Original string used if integer... | 55da47570ab03c5964f3af167bb8a4f27656a660 | 3,604,655 |
def get_dut_links_remote(dut, remote_dut, local_interface):
"""
API to get remote port using dut, remote dut and local interface
Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param dut:
:param remote_dut:
:param local_interface:
:return:
"""
if "PortChannel" in local_... | f5de8d04312561d3992ed7b1091867b1b982e020 | 3,604,656 |
def connect(host="localhost", user=None, password="",
db=None, port=3306, unix_socket=None,
charset='', sql_mode=None,
read_default_file=None, conv=decoders, use_unicode=None,
client_flag=0, cursorclass=Cursor, init_command=None,
connect_timeout=None, read_def... | 4d843d70b555ae20d3526f345761b047984116df | 3,604,657 |
import requests
def get_config():
"""Return a baseURI and session"""
s = requests.Session()
s.headers={'Content-Type': 'application/json'}
print("\nEnter the information to connect to your Elasticsearch cluster.\n")
ipHost = input("Hostname or IP: ")
port = input_int("Port")
auth = input... | 36c6511903da31c1e910f497c54a8c1f60fd6c51 | 3,604,658 |
import torch
def sph2cart_unit(u):
"""
:param u: N x 2 in [azimuth, inclination]
:return:
"""
"""
:param phi: azimuth, i.e., angle between x-axis and xy proj of vector r * sin(theta)
:param theta: inclination, i.e., angle between vector and z-axis
:return: [x, y, z]
"""
phi, t... | 59b119dbb629a98057d051a1370385f450d3fae3 | 3,604,659 |
from typing import Callable
from typing import Any
from typing import Tuple
def _jax_encode(
message: jnp.ndarray, cdf_fun: Callable, init_cdf_state: Any, buffer_oversize: float
) -> Tuple[ndarray, int]:
"""JAX encoding backend function."""
# array initialization
idx = jnp.array(0, jnp.int32)
bit_... | 2cad97cd3e98dd8809a5aa1d585374a98d373f3e | 3,604,660 |
def coroutine(func):
"""
Decorator that allows to forget about the first call of a coroutine .next()
method or .send(None)
This call is done inside the decorator
:param func: the coroutine to decorate
"""
def start(*args,**kwargs):
cr = func(*args,**kwargs)
next(cr)
r... | 1ab7a10c369f4882541ee81614e94d31f7acc528 | 3,604,661 |
def _scale_enum(anchor, scales):
"""
生成3个不同大小的矩阵
根据给定的anchor(box), 枚举其所有可能scales的anchors(boxes)
"""
w, h, x_ctr, y_ctr = _whctrs(anchor)
# print(w)
ws = w * scales
hs = h * scales
anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
return anchors | 2a3f567fa64b187a7510be97cdc8f259f9a255ad | 3,604,662 |
def FBP_grain( g, flt, ymin, ystep, omegastep, number_y_scans ):
"""
Reconstruct a 2d grain shape from diffraction data using Filtered-Back-projection.
"""
# Measured relevant data for the considered grain
omega = flt.omega[ g.mask ].copy()
dty = flt.dty[g.mask].copy()
sum_intensity = flt.s... | 13cc9f66f03cb44fa15ec4f56de8ba9a898ba070 | 3,604,663 |
def v7_group_by(iterable, key_func=None):
"""Group iterable by key_func.
PEP8, the Python style guide, says that we should never write
"key_func = lamdba x: x". Specifically it says that if we're using
lambda to make a function and then assign it to a variable,
we should use a def statement to mak... | 5a33c8b518b33806ff64694e21601264739ee658 | 3,604,665 |
import pickle
def _load_batch(fpath, label_key='labels'):
"""Internal utility for parsing CIFAR data.
Arguments:
fpath: path the file to parse.
label_key: key for label data in the retrieve
dictionary.
Returns:
A tuple `(data, labels)`.
"""
with open(fpath, 'rb') as f:
d = ... | 4311566594ac6f0f6c9573bdb3ccf162205991ae | 3,604,666 |
def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string int)
returns: integer
"""
result = 0
for item in hand.keys():
result += hand[item]
return result | 11a5161225a5cd60a00812435b00ca407338846a | 3,604,667 |
from datetime import datetime
def ajax_audit():
"""
报价审核
:return:
"""
ajax_success_msg = AJAX_SUCCESS_MSG.copy()
ajax_failure_msg = AJAX_FAILURE_MSG.copy()
# 检查审核权限
if not permission_quotation_section_audit.can():
ext_msg = _('Permission Denied')
ajax_failure_msg['msg'... | 8dabf1b461cf89bfe9eb42ef72466bdd4fc43c00 | 3,604,668 |
def get_welcome_response():
""" If we wanted to initialize the session to have some attributes we could
add those here
"""
session_attributes = {}
card_title = "Welcome"
speech_output = "Johnny Pi is at your command, " \
"what would you like him to do?"
# If the user eit... | b11c0c1a2ae63e7c3a0e3247a98075f1cc884f8e | 3,604,669 |
def validate_entity_predicate_structure(predicate_file: dict) -> bool:
"""
validate predicate, entity, and entity predicate link file structure
assumed structure
{ "entity/predicate-1": {"another-simple-id-no-0": {"0": "simple-id-no-1"}},
"entity/predicate-2": {
"another-simple/c... | 3241fbe68d1080a3bd967b45f48c09ec9a3cb83f | 3,604,670 |
def _make_rnn_cell_fn(units, cell_type=_SIMPLE_RNN_KEY):
"""Convenience function to create `rnn_cell_fn` for canned RNN Estimators.
Args:
units: Iterable of integer number of hidden units per RNN layer.
cell_type: A class producing a RNN cell or a string specifying the cell
type. Supported strings ar... | da8c643abb2a284145997e0662f24c5092c93fbd | 3,604,671 |
def pkcs1Digest(data, messageLength):
"""
Create a message digest using the SHA1 hash algorithm according to the
PKCS#1 standard.
@type data: C{str}
@type messageLength: C{str}
"""
digest = sha1(data).digest()
return pkcs1Pad(ID_SHA1+digest, messageLength) | 6f649c8359e40fd5d7c2aa4baebbac2918dcfbad | 3,604,672 |
def distance_shower_camera_center(shower, tel):
"""
Compute the distance between all shower particles and the telescope camera center
Parameters
----------
shower: class shower
tel: class telescope
Returns
-------
numpy array of the distances. size = number of particles in the showe... | e3e953e78c0274af5962e25db4e635ffef1151c7 | 3,604,673 |
def _time_ago(t: int) -> str:
"""Get time ago information from duration."""
if t < 3600:
return f'{int(t/ 60)} minutes ago'
else:
return f'{int(t / 3600)} hours and {int(t/60) - int(int(t/60)/60)*60} minutes ago' | 2451197f458df9b7c2ac6f5e9b1487b7e6f8211d | 3,604,675 |
import json
def fixture_building_id():
"""Return Fixture Building ID from Payload."""
return json.loads(carson_load_fixture("carson_me.json"))["data"]["properties"][0][
"id"
] | a7f550203d0e5e8104a3a876036e3a757a562a3c | 3,604,676 |
def make_shell_context():
"""
Create a python CLI.
return:Default import object
type:'Dict'
"""
return dict(app=main.app, db=models.db, User=models.User,Post=models.Post) | 3d11895133df5bf8f495be77fd140251cfa31166 | 3,604,677 |
def preprocess(text, min_token_length = 0, join = False):
""" Method for preprocessing text
Args:
text: string of text
min_token_length: integer value indicating min number of characters in a token
join: boolean indicating if function should join the list of tokens into the str... | 740fc73f7712aa630bbf0d79765fc574d1642fa8 | 3,604,678 |
def create_model(image_height, image_width, loss, optimizer):
"""Creates the cat face locator model.
Args:
image_height: The height of the input images.
image_width: The width of the input images.
loss: Keras loss function (name or object), e.g. "mse".
optimizer: Keras optimizer... | 764abfc68511c818697bd4e2f637da4d5176f348 | 3,604,679 |
def nli_url(filename='urls.ini', section='URLS'):
"""
The config file for URLS contains sites of interest to my research
"""
parser = ConfigParser()
parser.read(filename)
urls = {}
if parser.has_section(section):
links = parser.items(section)
for link in links:
... | 0e4c8a9379d92d21c2473dd05c79a99442d54a75 | 3,604,681 |
def make_matrix_coord_map(
dx, dy, serpentine=True, offset=0, rotation=0, y_flip=False):
"""Helper method to generate X,Y coordinate maps for strips"""
result = []
for y in range(dy):
if not serpentine or y % 2 == 0:
result.append([(dx * y) + x + offset for x in range(dx)])
... | b18a7bcbfae42e2cdbe2f364e6b96947b2354d32 | 3,604,682 |
def categories_to_json(categories):
"""
categories_to_json converts categories SQLAlchemy object to json object
works by simply looping over collection of objects and manually mapping
each Object key to a native Python dict
"""
main = {}
main['categories'] = []
for cat in categories:
... | 34702fb12d1398395826bae71d39edd558199498 | 3,604,684 |
def call_prob(mut_cluster, r1_mappos, r2_mappos, r1_qual, r2_qual, mut_rate, base, cut_off, adjustthred):
"""
"""
pos_prob = {"m": [], "prob": [], "read": []}
for c in mut_cluster.keys():
mutcall = mut_cluster[c]
# each mutcall is a df with columns:
# m_r1,read,pos,ref_r1,alt_... | fcb44b438d40fdec681ec7ed03d9d22cd1fcb199 | 3,604,685 |
from typing import Sequence
def get_padding_values(input_dataset_types, label_padding=-100):
"""Get a tensor of padding values fitting input_dataset_types.
Here we pad everything with 0. and the labels with `label_padding`. This
allows us to be able to recognize them later during the evaluation, even
... | b1ecf5f545f770274a4fef9eb1c2ff7c8357f817 | 3,604,686 |
def median(data, scheme=1):
"""Returns the median (middle) value of an iterable of numbers.
>>> median([3.0, 5.0, 2.0])
3.0
The median is the middle data point in a sorted sequence of values, and
is commonly used as an average or estimate of central tendency. It is
more robust than the mean fo... | c9db3f14fab717ea5cebdd2b6918db14493033f8 | 3,604,687 |
from typing import Sequence
from typing import Callable
from typing import Tuple
from typing import Counter
def _bleu_score_update(
preds: Sequence[str],
target: Sequence[Sequence[str]],
numerator: Tensor,
denominator: Tensor,
preds_len: Tensor,
target_len: Tensor,
n_gram: int = 4,
tok... | de2d1990f0f58b8b3b9590312e278464119e9198 | 3,604,688 |
def resolve_sky_coords_frame(frame, observer=None, time_obs=None):
"""
Return frame with appropriate attributes set for `observer` at `time_obs`.
"""
if isinstance(frame, str):
frame_cls = _get_frame_class(frame)
elif isinstance(frame, BaseCoordinateFrame):
frame_cls = frame.__class_... | 70674a91806d9d397574129d0f4dc1eac54d3ed4 | 3,604,689 |
def accuracy_score(df, col_true=None, col_pred=None, normalize=True):
"""
Compute accuracy of a predicted data set.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true label
:type col_true:... | 470abd7d94ff3a49dd64cacfb3afb877c7aa73df | 3,604,690 |
def axis_aligned_iou_loss(pred, target):
"""Calculate the IoU loss (1-IoU) of two set of axis aligned bounding
boxes. Note that predictions and targets are one-to-one corresponded.
Args:
pred (torch.Tensor): Bbox predictions with shape [..., 3].
target (torch.Tensor): Bbox targets (gt) with... | 66762cda10cde427d3b1ce5e1d1da89da28383f4 | 3,604,691 |
import ctypes
def despeckle(input_list_data, bad, a_speckle, dgi_clip_gate=None, boundary_mask=None):
"""
Performs a despeckle operation on a list of data (a single ray)
Args:
input_list_data: A list containing float data,
bad: A float that represents a missing/invalid dat... | 36abc83ecc6e077a2d710925744034e12880749f | 3,604,692 |
def velocity(estimate, actual, times=60):
"""Calculate velocity.
>>> velocity(2, 160, times=60)
0.75
>>> velocity(3, 160, times=60)
1.125
>>> velocity(3, 160, times=80)
1.5
"""
return (estimate*times)/(actual*1.) | ffdb12c7aea05f9fc8aa9e354e8db2320cbf431a | 3,604,693 |
def _GetCurrentInjectionInfo():
"""Returns a dict contains the required injections' information.
This method is used to provide information for filling injection and
calculating scope dependency.
"""
if not hasattr(_DATA, 'injection_scope_map'):
injection_scope_map = {}
for idx, scope in enumerate(re... | 14cd486ad011bcbabd11d9ae24bac1e32ceec7f7 | 3,604,694 |
import importlib
def import_from_string(val, setting_name):
"""
Attempt to import a class from a string representation.
"""
try:
parts = val.split('.')
module_path, class_name = '.'.join(parts[:-1]), parts[-1]
module = importlib.import_module(module_path)
return getattr... | 71af0db959d089eb92baf885c4580fa04b6b8b87 | 3,604,695 |
def register():
"""
Registers a user in the database.
Before registering, checks if the username is not already in the database.
The username is used to show who reviewed a book,
so username has to be unique.
"""
if request.method == "POST":
user_exists = mongo.db.users.find_one(
... | addce07f91c74c4c39ce62870974ce8e378618f6 | 3,604,696 |
def my_gaussian(x_points, mu, sigma):
"""
Returns normalized Gaussian estimated at points `x_points`, with parameters:
mean `mu` and std `sigma`
Args:
x_points (numpy array of floats): points at which the gaussian is
evaluated
mu (scalar): ... | aa10bdcef788c534405baca7ab0a868a5a9502ef | 3,604,698 |
def _resolve(exe):
"""Resolve alias, raise exception if not found.
:returns:
``list`` -- Argv to pass execv
"""
resolved = resolve_argv(exe)
if not resolved:
raise CommandAliasError('Unable to resolve: {}'.format(exe))
return resolved | 70050ca7551e7d72edfdaa3b99ff83ce93911ca8 | 3,604,699 |
from pathlib import Path
def _node_does_not_exist(node_path):
"""
Determine whether module already exists for node
:param node_path: full path to node module
:return: bool; True if node does not exist; False if it does exist
"""
try:
# noinspection PyArgumentList
Path(node_pa... | 242f9895cb6e7ef4441b6d76b013cbdc88f8de45 | 3,604,701 |
def mock_config_entry1(opp):
"""Mock a config entry."""
return create_config_entry() | fd462a8291e3a2f9a9bd92fde97ac58953b6fff0 | 3,604,703 |
def choose_question():
"""Choose a random answer"""
random_index_question = randint(1, question.num_question + 1)
random_question = question.question[random_index_question]
correct_answer = question.answer[random_index_question]
return random_question, correct_answer | 7ed6cd12110b5fa8ee5f0baea17a5fa833031d21 | 3,604,704 |
def produtividade(inicio, fim):
"""
Recebe dois anos e retorna uma lista de strings que
informam a quantidade de filmes produzidos em cada ano
dentro do intervalo recebido
Parâmetros: Dois inteiros -> Um intervalo de anos
Retorna: Uma lista de strings com a quantidade de filmes
do ano co... | 9bc539c5a8bdfe7d63a937e4fb5c716b82e643a1 | 3,604,706 |
def db_memory(con, detail=1):
"""
detail: 0, 1 or 2.
"""
reports = {x: con._client.get_memory(con._session, x) for x in ["cpu", "gpu"]}
# print('reports', reports)
d = []
for device_type, report in reports.items():
for i, info in enumerate(report):
for node in info.node... | ba5d403500a539ed8dae4fa027a5d719c5b5e5bf | 3,604,707 |
import multiprocessing
def acquire_mpi_lock(cpu_count: int) -> bool:
"""
returns True if successfull
Will try to acquire a distributed shared lock.
"""
reply_queue = multiprocessing.Queue()
multiprocessing.Process(
target=_process_worker, args=(reply_queue, cpu_count), daemon=True
... | 2776394bd4f278e250937258b4bbe9b74b549916 | 3,604,708 |
def test_map_methods(webgroup):
"""Map methods behave as expected"""
def func():
return dict(answer=42)
@webgroup.register
class Fake:
name = 'fake'
@webgroup.register
class TestParent:
pass
name = 'name'
xpath = '/hello'
parent = TestParent()
w = Com... | 18794540aa3569fc575cb63e9caf7a752ed62fd1 | 3,604,709 |
from datetime import datetime
import tqdm
def real_section(path):
"""Downloads section data and runs fibermorph_section analysis.
Returns
-------
bool
True.
"""
fibermorph_demo_dir = create_results_cache(path)
input_directory = get_data(fibermorph_demo_dir, "section")
... | 3d9f9da3086feb49f217cb77a2381729a2d5d187 | 3,604,711 |
def load_description():
"""Return description"""
with open("README.md") as buffer:
return buffer.read() | b167638602c4d5f662ccc72e34dc042b7d9e63bb | 3,604,712 |
from typing import List
def batch_predict(batch_features: List[Features]):
"""Endpoint for getting scores for a batch of record."""
num_features = len(model.feature_name())
rows = np.zeros((len(batch_features), num_features))
for i, features in enumerate(batch_features):
row = np.array([getat... | 9990343e7cdd47d58cb8472ddcd40241efe590f5 | 3,604,713 |
def check_task(request, tid):
"""Check the status of a task"""
try:
slogger.glob.info("check task #{}".format(tid))
response = task.check(tid)
except Exception as e:
slogger.glob.error("cannot check task #{}".format(tid), exc_info=True)
return HttpResponseBadRequest(str(e))
... | 94fa6aad582c2d530d1e743b0093d26577e339d8 | 3,604,714 |
def indent(s, depth):
# type: (str, int) -> str
"""
Indent a string of text with *depth* additional spaces on each line.
"""
spaces = " "*depth
interline_separator = "\n" + spaces
return spaces + interline_separator.join(s.split("\n")) | 69d509761cc6ab2f861f8b8c7fe7097ce8deff13 | 3,604,715 |
def get_value(key, obj, default=missing):
"""Helper for pulling a keyed value off various types of objects"""
if isinstance(key, int):
return _get_value_for_key(key, obj, default)
return _get_value_for_keys(key.split("."), obj, default) | 79e58dcadf8adf917dee92cd75a374c803195cb0 | 3,604,716 |
def joint_pdf_mean_y(pdf, binsx, binsy):
"""From a joint PDF, calculate the mean along the y-direction for each x-bin.
Parameters
----------
pdf : np.ndarray
Array of shape (binsy.size - 1, binsx.size - 1). This is the probability density function
binsx : np.ndarray
Array of bin edg... | 275fcdf920ec23b4ab74e2e48d0af952a3980348 | 3,604,717 |
def project_to_image(point_cloud, p):
""" Projects a 3D point cloud to 2D points for plotting
:param point_cloud: 3D point cloud (3, N)
:param p: Camera matrix (3, 4)
:return: pts_2d: the image coordinates of the 3D points in the shape (2, N)
"""
pts_2d = np.dot(p, np.append(point_cloud,
... | e4f81251c4fe2f79277a41fde969e05469a14bcd | 3,604,718 |
def prior_transform(u):
"""Flat prior between -10. and 10."""
return 10. * (2. * u - 1.) | 4dd488a76a08361f1c7d833eaef96a7dfdf51ca6 | 3,604,720 |
def show_graph(selected_node, selected_edge):
"""
Based on the selected element this generates the correct dot file
for component update.
"""
# dictionary of all the nodes and if they are selected
nodes = {node: node == selected_node for edge in edges for node in edge}
lines = [
"di... | bebec227108fa321506ddb6ebc7f9f9b32cf44e2 | 3,604,721 |
import numpy
def custom_decode(obj):
"""
Custom function to enchance msgpack decoding.
obj::{} A dictionary representition of an object already unwrapped by msgpack
return::Object The decoded object if a custom object
"""
if '__decimal__' in obj:
return Decimal(obj['as_str'])
if '... | 97e09a732a701340b31aeb8b26d093086c1473e8 | 3,604,722 |
import importlib
def import_from_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
... | 1010e9d3563cec163ff2cad7299f79ffcc39f8fc | 3,604,723 |
def student_tryout_apply_result():
"""
swagger-doc: 'do view_homework query'
required: []
req:
page_limit:
description: 'records in one page'
type: 'integer'
page_no:
description: 'page no'
type: 'integer'
study_appointment_id:
description: '学生预约... | a360de23a208f63205f75f93fc8462c7b16cf45c | 3,604,724 |
def chan3(rhow, mc, T, dt, nt):
"""
rhow = wood density, kg/m^3
mc = moisture content, %
T = temperature, K
dt = time step, s
nt = total number of time steps
"""
# vector for initial wood concentration, kg/m^3
pw = np.ones(nt)*rhow
# vector for initial moisture content ... | b7e1ad237f172c20d1f0a1490e94137a5f2cb803 | 3,604,726 |
def create_cdb(concept_csv_file, medcat_config):
"""Create concept database from csv.
Args:
concept_csv_file (pathlib.Path):
Path to CSV file containing all concepts and synonyms.
medcat_config (medcat.config.Config):
MedCAT configuration file.
Returns:
cdb (... | 60896516d8fef7b6c5b3c19fe33186db0331630c | 3,604,727 |
import functools
import operator
def get(dic, path, seps=PATH_SEPS, idx_reg=_JSNP_GET_ARRAY_IDX_REG):
"""getter for nested dicts.
:param dic: a dict[-like] object
:param path: Path expression to point object wanted
:param seps: Separator char candidates
:return: A tuple of (result_object, error_m... | 770c6bb8fb6c0056f0dc96acd414b04fade609a0 | 3,604,729 |
def create_mixes(mtrack, mix_path, mix_path_noguitar, mix_path_nosynth,
stem_indices, stem_indices_guitar, stem_indices_piano,
altfiles):
"""Render artificial mixes to `mix_path', `mix_path_noguitar', and
`mix_path_nosynth'.
Parameters
----------
mtrack : MultiTrac... | 15fa745f6de3779bc95c5634dda0b7f272917230 | 3,604,730 |
def check_value_types(vars, argv):
"""
This checks that all the user variables loaded in use that same or comparable
datatypes as the defaults in vars. This prevents type issues later in the
simulation.
Given the many uservars and the possibility for intentional differences,
especially as the p... | 395c4927f3b8b8ab169ad488b21a07b3db26ffbb | 3,604,732 |
def adjust_array_data_type(array, scaling_factor=None, value_offset=None):
"""
Converts the input *array* into a new large enough data type if adjusting said array as-is by
*scaling_factor* or *value_offset* would result in an overflow. This can be necessary both
if the array is data from a PDS4 Array o... | c64e06b52b031a63954b1c5abf01c6598dc1609d | 3,604,733 |
def ensure_components(model_tracer_list):
"""If a CO2 flavor is detected for a model, ensure all flavors are present."""
co2_components = {'CO2', 'CO2_OCN', 'CO2_LND', 'CO2_FFF'}
models = set(m for m, t in model_tracer_list)
new_list = []
for model in models:
m_tracers = set(t for m, t in mo... | 8cb7f4e14f51718c8db75779ea02f6a73917323d | 3,604,734 |
def split(Text):
"""Function to Spilt individual words"""
return list(Text) | 4b69f7eeb7e4b1856275b74f81e20015ba2ae172 | 3,604,735 |
def parse_cfg_to_sections(config, level=0):
"""
Функция парсит конфигурацию и возвращает словарь.
Рекурсивно парсит каждую секцию в которой не все команды на одном уровне.
"""
config_dict = {}
while True:
try:
line = next(config)
except StopIteration:
bre... | 1824415b41f48f614ebbb9a7dd11a63590c08111 | 3,604,736 |
import http
def UpdateUserTestBeaconCounts(request):
"""Starts mapreducer.UserTestBeaconCount."""
mr_id = control.start_map(
'UserTest beacon_count update',
'base.mapreducer.UserTestBeaconCount',
'mapreduce.input_readers.DatastoreInputReader',
{'entity_kind': 'models.user_test.Test'})
re... | 7a0ff33d6129cb2e2e1e429320ad503885e1013f | 3,604,738 |
def enthalpy(compound, enthalpy_name, value_index=0):
"""Returns the value of an enthalpy for a given compound"""
table = enthalpy_table(compound, enthalpy_name)
return list(table.loc[:, 'value'])[value_index] | a1e71cb7c4b2cd9d6a2f3eb912925511ede8dee0 | 3,604,740 |
import re
def get_rules(regexp):
"""Get acl rules from regular expression.
Returns:
List[str]
"""
regexp = re.sub(r'\^?https?\??://', '^', regexp)
regexp = re.sub(r'(\.\*)+$', '', regexp)
regexp = re.sub(r'/$', '$', regexp)
# Exclude pathname rule, since ssr only accept domain m... | a939538e5e7e299b90ad95eaba9508cd45b6ebf5 | 3,604,741 |
def calc_optical_params(
side_length,
depth,
reals,
imags,
wavelengths,
plots=False,
report_dims=False,
):
"""Calculates single scattering optical properties.
Van Diedenhoven's parameterisation is used to calculate
the single scatterign optical properties of hexagonal
ice co... | 270750ca2c830b2a5de943d72fe67c65d80f07d1 | 3,604,742 |
import io
def annual():
"""
Returns the html with the annual Catalonia forecast until 2024
"""
f=io.open("Annual_Forecast.html", 'r')
html = f.read()
return html | 5321febc4c09de97893c30b6a27a30a089b18079 | 3,604,746 |
def evaluate(descriptions, worker_fn, gpu_indices):
"""
Launch the workers to evaluate descriptions in parallel.
Args:
descriptions (list): descriptions to be evaluated
worker_fn (callable): worker callable
gpu_indices (list): list of gpu indices to run on
Returns:
list... | f4c42746a66b456a5fa0a05f64be35400448c22a | 3,604,747 |
def calibration_camera(**kwargs):
"""Dynamic creationg of Camera models"""
def _calibration_camera(**kwargs):
return Camera.from_calibration_config(**kwargs)
return _calibration_camera | 0f286b21a33bc57ebc1735901ba1f5326d5b95f7 | 3,604,748 |
import urllib
def display_url(url):
"""Display a URL like the browser URL bar would.
Note: returns a Unicode object, not a valid URL.
"""
url = force_bytes(url, errors='replace')
return urllib.unquote(url).decode('utf-8', errors='replace') | 2d05384a4fe80222fe4df2175d8952d75f3e5c2c | 3,604,749 |
async def get_suggested(request: Request):
"""
POST method endpoint to return 'returnCount' suggested books.
"""
json_data = await request.json()
keys = [int(x) for x in json_data["keys"]]
return_count = int(json_data["returnCount"])
recommendations = analysis.get_suggestions(keys)
score... | 43eda8cf3563fc4008efd62a0e8761d169257c14 | 3,604,750 |
from datetime import datetime
def default_time_e():
"""
Returns datetime set to today with a time of 23:59:59
"""
now = datetime.datetime.now()
return now.replace(hour=23, minute=59, second=59, tzinfo=UTC()) | 5e4e3f986ada680e38ad49dfceee44e33134541e | 3,604,751 |
def subtraction(a, b):
"""subtraction: subtracts b from a, return result c"""
a = float(a)
b = float(b)
c = b - a
return c | 0115222efc08588a12a6fbc1965441b83a7eaff0 | 3,604,752 |
import yaml
def get_new_mc(role, name_suffix, priority=99):
"""
Initialize new (almost empty) MachineConfig dict.
Args:
role (string): name of ``MachineConfig`` role
name_suffix (string): suffix of resulting MachineConfig name
"""
mcd = yaml.safe_load(MACHINECONFIG_SKELL)
mcd[... | b612cbcd042f68f720ba7e070835da1592b3ab0b | 3,604,753 |
def text_to_number(recipe, texts):
"""
function to transform written numbers in a string ("one hundred horses") to
their integer form ("100 horses"). Works for English, Spanish and French.
It takes advantage of the fact that the Google Vision API recognises
the language of the text in the pictur... | cfaac11b758505ab9df91329af24f323db99bd7d | 3,604,754 |
import time
def sec_to_datetime(timestamp):
""" Convert secondes since epoch to a date and time
"""
return time.strftime("%d/%m/%Y %H:%M:%S %Z", time.localtime(timestamp)) | e1e72e2e9e34259fcf2e2d3fcd6a6598dc77e3ae | 3,604,755 |
def return_rugraph() -> Graph:
""" Returns Random Unweighted graph (rugraph) """
# Init. possible node names, & integer array to chose nodes
node_names = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
"L", "M"]
int_arr = [x for x in range(randint(6, len(node_names) - 1))]
... | aa24bb62052b86544a7c09c4d5b1e08f45aee882 | 3,604,757 |
def contains_failure(lines):
"""Check if any line starts with 'FAILED'."""
for line in lines:
if line.startswith('FAILED'):
return True
return False | c3a74373f351a946e7d8f9d9497c8ee9af32282e | 3,604,758 |
def parse_pattern(lines, dimension_names):
"""
This function is used for the hyperrectangle file parsers. It will take
a list of the lines for a specific pattern and the dimension names
associated with the pattern and construct a HyperrectanglePattern.
Args:
lines (list[str]): The list of l... | b4f0a82a43cd73951869b379be91175f0264414b | 3,604,759 |
def get_duplicates_ktree(s: Structure, threshold: float = 0.2) -> list:
"""
Args:
s:
Returns:
"""
x = s.cart_coords
tree = cKDTree(x)
groups = tree.query_ball_point(x, threshold)
groups = [g for g in groups if len(g) >= 2]
del x
del tree
duplicates = []
for g... | cf4f1a6206c27f6d7d9356271b1ad832ef86d96e | 3,604,760 |
def connect(self, arg):
"""
1. Connect to database via arg, which could be url or dbalias
2. Set prompt
3. load schema to QueryBuilder
"""
if arg == '' or arg.lower() == 'help':
return dbhelp(self, 'connect')
DB.connect(arg)
set_prompt(DB.dbname(arg))
tables = DB.load_tables(... | f0b0c8cb2a69358269790b1d24f60bb5db515e55 | 3,604,761 |
import random
def shuffle_list(lista, seed=42):
"""
Shuffle two list with the same seed.
:param lista: List of elements
:type lista: List
:param listb: List of elements
:type listb: List
:param seed: Seed number
:type seed: int
:return: lista and listb shuffled
:rtype: (List, ... | 743d2ae479422020dcaef8111b2ad12dc635dbcd | 3,604,762 |
import types
def _extract_vals(data, streamlines, affine=None, threedvec=False):
"""
Helper function for use with `values_from_volume`.
Parameters
----------
data : 3D or 4D array
Scalar (for 3D) and vector (for 4D) values to be extracted. For 4D
data, interpolation will be done o... | 4fbe396a0205161824aa9a2037c4d45f09c66470 | 3,604,763 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.