content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def do_encoding(encoder_inputs, seq_len, sett):
"""
"""
rand_unif_init = tf.random_uniform_initializer(-sett.rand_unif_init_mag,
sett.rand_unif_init_mag,
seed=123)
#
with tf.variable_scope('encoder'... | 721466390c58332a365a1562bf7b5d121e995be1 | 49,364 |
import math
def branch_and_bound(c, A_ub, b_ub, A_eq, b_eq, bounds, bnbTreeNode=None):
"""
branch_and_bound 对整数规划问题使用「分支定界法」进行*递归*求解。
底层对松弛问题求解使用 scipy.optimize.linprog 完成,
该算法只是在 scipy.optimize.linprog 求解的基础上加以整数约束,
所以求解问题的模型、参数中的 c, A_ub, b_ub, A_eq, b_eq, bounds
与 scipy.optimize.linprog 的完... | 20521f906600c070b8ea7b7f67c30abedeffc391 | 49,365 |
import math
def nn_layer_fn(in_dim, out_dim, layer_name, fn=tf.nn.relu):
"""Builds a function of an nn layer, fully connected to the previous layer."""
with tf.name_scope(layer_name + '_vars'):
weights_shape = [in_dim, out_dim]
weights_stddev = 1.0 / math.sqrt(float(in_dim)) #Xavier initializa... | ac095171174aeacc8185d6d1d65354d074f98f7d | 49,366 |
def resolve_float_or_constant(input_value, accept_none = True):
"""Resolves an input as either a float or chemistry constant."""
if input_value is None:
if accept_none:
return None
else:
raise ValueError(
f"Received invalid value {type(input_value)}."
)
if isi... | 07ee0a76dcec441a8425837f21053ac1fa241e4d | 49,367 |
def nextfile():
"""
Close the current file so that the next iteration will read the first
line from the next file (if any); lines not read from the file will
not count towards the cumulative line count. The filename is not
changed until after the first line of the next file has been read.
Before... | 24b01cfbd82396885afa65829c0757ae1aefe091 | 49,368 |
def get_output_metadata(packer, sample_dim_name):
"""
Retrieve xarray metadata for a packer's values, assuming arrays are [sample(, z)].
"""
metadata = []
for name in packer.pack_names:
n_features = packer.feature_counts[name]
if n_features == 1:
dims = [sample_dim_name]
... | 7a16ed6878d58be45a3cd63b0a5bec515ab6475e | 49,370 |
def local_users_get(handle, dump=False):
"""
This method gets the list of local users configured on the server
Args:
handle (ImcHandle)
dump (bool)
Returns:
List of AaaUser objects corresponding to the local users
"""
aaa_users = _get_local_users(handle)
users = [x... | ba33f95408e6772c9649d744713393365f39cb87 | 49,371 |
def sort_data(PDB_files, data):
"""
Sorts data by name according to PDB files
"""
sort=natsort.natsorted(zip(PDB_files, data))
PDB_files=[tuple[0] for tuple in sort]
if type(data)==list:
data=[tuple[1] for tuple in sort]
else:
data=np.vstack([tuple[1] for tuple in sort])
... | ade7b27ef8a2217181bb3b60884ac8e361288de8 | 49,372 |
def _random_shuffle(*lsts):
"""Randomly shuffle a dataset. Applies the same permutation to each list
(to preserve mapping between inputs and targets).
:param *lsts: variable number of lists to shuffle.
:return: shuffled lsts.
"""
permutation = np.random.permutation(len(lsts[0]))
shuffled = ... | 8d5eea0e0e8d3caca89d0ac15afb3e7585676c27 | 49,373 |
def choose_report(account_type):
"""
Choose report object by account type
Args:
account_type(string): account type
"""
if account_type == SecuritiesType.futures:
report_obj = FuturesReport
else:
raise Errors.INVALID_ACCOUNT_TYPE
return report_obj | f3b583d9e0ff34202b4b84fa80dbfe2fdf96de3f | 49,375 |
def search_results(search_request):
"""
Search results from given search paramaters.
"""
ghh, _ = try_ghh(session)
search_users = session["search_users"]
search_orgs = session["search_orgs"]
search_repos = session["search_repos"]
ignore = session["ignore"]
if ghh is not None:
... | abc1ede8adbc01746618346dc6306bf84810f3dd | 49,376 |
def fproperty(func):
"""Decorator for a function that returns (fget, fset, fdel, doc)"""
return _property(*func()) | 43870a74c41d82ed6f8cec0312dc916f667e704f | 49,377 |
def connect_memdb():
"""
:return: Instance of an in memory database.
:rtype: SimpleSQLite
:Example:
:ref:`example-connect-sqlite-db-mem`
"""
return SimpleSQLite(MEMORY_DB_NAME, "w") | f6a31652d11b5133428a10309699757be71ac737 | 49,378 |
import torchvision
def deeplabv3_resnet50_features(pretrained=False, **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on Coco
"""
model = torchvision.models.segmentation.deeplabv3_resnet50(pretrained=pretrained)
model.classifier._mod... | 80a240e16588c126973358d794150ab5d66e0647 | 49,379 |
def get_multiclass_labels():
"""
0: normal
1: abnormal
2: notable findings/abnormalities that are not relevant or within normal limits (WNL)
:return:
"""
return [0, 1, 2] | 969b1d9a19cafc253eb6403d4e3672522211a9f3 | 49,381 |
def _boundary_spatial_dissim(data, group_pop_var, total_pop_var, standardize=False):
"""Calculation of Boundary Spatial Dissimilarity index.
Parameters
----------
data : a geopandas DataFrame with a geometry column.
group_pop_var : string
The name of variable in data that contains the popul... | db559ef83f6b74fc8e6b85d986ff31d5b25683ba | 49,382 |
def test_skill_template_variables():
"""
Test variable coverage for `parameters_skill.tpl`.
"""
allowed = base.ParametersSkillParser.FIELDS
def is_covered_variable(field):
"""
Check if a skill field is covered during parsing.
"""
# Check for a regularly allowed fie... | 0a70690ee53bfb52f2f4efa56b0d4ce1959896ea | 49,383 |
from typing import Optional
from typing import Dict
from typing import Union
from pathlib import Path
def prepare_switchboard(
audio_dir: Pathlike,
transcripts_dir: Optional[Pathlike] = None,
sentiment_dir: Optional[Pathlike] = None,
output_dir: Optional[Pathlike] = None,
omit_... | 8fcb5397c6f421aeb3c931a321dd8b44f2201cfe | 49,384 |
def k1_mean(success_tag, ms_results):
""" Reports the expected value of k1, the rate constant for
the bimolecular step of a resting-set reaction. """
success_kcolls = np.ma.array(ms_results['kcoll'], mask=(ms_results['tags']!=success_tag))
n = int(np.sum(ms_results['valid']))
n_s = int(np.sum(~success_kcolls.... | 4a3308b6cca33506d6d88e931477006893af44a0 | 49,385 |
def get_request(filename, persistent = True):
"""
Helper function to generate HTTP GET requests.
Not used in application due to python overhead
in string manipulation.
"""
data = 'GET /{} HTTP/1.1\r\n'.format(filename)
data += 'Host: {}:{}\r\n'.format(ADDR,PORT)
data += 'Connection:... | 530e09e1c0133edc8ee879461820624c70c807d9 | 49,386 |
def SendServerCommand(s, command):
""" Send a command to the server and get the response.
Send the command out to the server and pass the response back to the calling
function.
"""
# send the command to the server
s.sendall(command)
# get the response from the server
code, text = GetS... | a3de1396532d9472892d085fd418a05fc1ad354a | 49,389 |
def _or(self, other):
"""Compute the element-wise OR bitwise operation.
Parameters
----------
other : Union[dragon.Tensor, number]
The value to compute with.
Returns
-------
dragon.Tensor
The output tensor.
See Also
--------
`dragon.bitwise.bitwise_or(...)`_
... | 83cdbda4adc375ddd3c09b5cc087b61cd187ad58 | 49,390 |
import re
def find_vendor(macs: str, neigh: list):
"""
This function searches for the NIC vendors in the IEEE DB
"""
# local vars
clean_mac_db = []
# Creating MAC DB in Python dictionary format
for entry in macs.splitlines():
if re.match("^[A-Z0-9]+\-", entry):
tc = {}... | f0f95684e2aba25cd14f3923e980ebff530e9410 | 49,392 |
def build_image_features(network_fn, images):
"""Builds the CNN model and extract image features
Args:
network_fn : CNN network
images: images
Returns:
net: extracted image features
end_points: end points
"""
# Extract Image features from CNN networks
features, e... | b70a1935e588f10761e86c59f918f17ad8577005 | 49,393 |
def define_session(module_path=None, **kwargs):
"""Define a session object under ``module_path``."""
module_path = module_path or clients.__name__
module_labels = labels.make_labels(module_path, *SESSION_LABEL_NAMES)
setup_session(
module_labels,
parameters.define(
module_pat... | 9d79a0e3d565b980db3c5e011909d1dd2d5c772d | 49,394 |
def resolve_path_traits(thistrait, value, cwd):
"""Resolve a BasePath-derived trait given an interface spec."""
return _recurse_on_path_traits(_resolve_path, thistrait, value, cwd) | c072affa59a52078050367b8566e58d0ce4165bf | 49,395 |
def return_value(controller_fun):
"""
返回参数
:param controller_fun: 控制层函数
:return:
"""
def __decorator(*args, **kwargs):
ret_value = {
"version": server_config.version,
"success": 0,
"message": u"fail query"
}
ret_data, code = controller... | 4b3da4666612cffffb6ce6293b7c41f3562abf49 | 49,396 |
from ._buffer import buffer_toggle_
from typing import Any
from typing import Callable
from typing import List
def buffer_toggle(
openings: Observable[Any], closing_mapper: Callable[[Any], Observable[Any]]
) -> Callable[[Observable[_T]], Observable[List[_T]]]:
"""Projects each element of an observable sequenc... | af7ec63d77f1023e7568fa05010498eca5e08a0b | 49,397 |
def reverse(*args, **kwargs):
"""Now this is a crazy and silly hack, but it is basically here to
enforce that an empty path always takes precedence over an article_id
such that the root article doesn't get resolved to /ID/ but /.
Another crazy hack that this supports is transforming every wiki url
... | 08a8e5629cc9dddf7f96444f75e19260f6ee33f1 | 49,398 |
def locale_get(handle, name):
"""
Gets the locale
Args:
handle (UcscHandle)
name (string): name of ldap provider
Returns:
AaaLocale : Managed Object OR None
Example:
locale_get(handle, name="test_locale")
"""
dn = ucsc_base_dn + "/locale-" + name
retur... | 8e56ff45efdc533bdef48306087706e204f3ce9a | 49,399 |
import itertools
def euler38():
"""Solution for problem 38."""
# '123456789' will be decomposed in at least two elements,
# the smallest being 4 at most characters long
sol = 0
digits = {str(d) for d in range(1, 10)}
for n in range(10000):
s = ""
for i in itertools.count(1):
... | c757460b10b07379dd372a6a7b40b1536e16d407 | 49,400 |
def builtin_swap(a, b):
"""Modify the stack: ( a b -- b a )."""
return (b, a) | a288f5484d45edb64513ffd0afcab6d03609faf6 | 49,401 |
from typing import Union
from typing import Tuple
import re
def package_version(split: bool = False) -> Union[str, Tuple[str, str]]: # pragma: no cover
"""Get current package version.
Args:
split: Flag indicating whether to return the package version as a
single string or split into a tup... | 2d9e9a719c9a25053f78aa35b362875aaa166a60 | 49,402 |
import codecs
def _add_method(class_re, method_name, file_name=None):
"""
Loads a file ./ocrd_page_user_methods/{{ method_name }}.py and defines a MethodSpec applying to class_re
"""
source = []
if not file_name:
file_name = method_name
with codecs.open(join(dirname(__file__), 'ocrd_pa... | e66b07b98e32fd1db6b6e843ae28111e37de1e66 | 49,403 |
from operator import le
def makeServoSpeedPacket(ID, maxSpeed):
"""
Run servo between 0.0 to 1.0, where 1.0 is 100% (full) speed.
"""
if 0.0 > maxSpeed > 1.0:
raise Exception('makeServoSpeed: max speed is a percentage (0.0-1.0)')
speed = int(maxSpeed*1023)
pkt = makeWritePacket(ID, xl320.XL320_GOAL_VELOCITY, ... | 58f22a26711f17a993c0223b0e979981cbebfba6 | 49,404 |
from typing import Union
from typing import List
def rotate_translate(vertices: np.ndarray, translation: Union[np.array, List[float]], angle: Union[float, int])\
-> np.ndarray:
"""
First rotates the list of vertices around the origin and then translates the list of vertices.
:param vertices: arra... | 7fc98a491491fc366d8bd0350705d9275d5722e7 | 49,405 |
def check_set_dimension():
"""
Validate a SetDimension and return all errors and warnings.
:returns: A list of 'errors' and a list of 'warnings'
"""
return list(), list() | df27e2bac845ce1dad24c3c01388c397210a238d | 49,406 |
def slater(name):
"""In quantum chemistry, Slater's rules provide numerical values for the
effective nuclear charge concept. In a many-electron atom, each electron is
said to experience less than the actual nuclear charge owing to shielding
or screening by the other electrons.
Parameters
------... | 886fc109c9baa3dda66a3a2cb981c701fc03e211 | 49,407 |
from typing import List
from typing import Tuple
import math
def reidentify_by_pokeblink(rng:Xorshift, rawintervals:List[float], search_max=3*10**4, search_min=0, eps=0.1, dt = 0.01)->Tuple[Xorshift, float, float]:
"""Reidentify Xorshift state via intervals of Pokemon blinks
Args:
rng (Xorshift): _d... | 371ccdd57dfcaff10f4a3e2010d9a4cddc3df80e | 49,408 |
from pathlib import Path
from typing import Any
def read_gNB(
*,
db: Session = Depends(deps.get_db),
gNB_id: str = Path(..., description="The gNB id of the gNB you want to retrieve"),
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Get gNB by ID.
"""
gN... | dc48b6fe47e1ef3f4f45aa84d938625a727e78fd | 49,409 |
import torch
def make_batch(points: [np.ndarray], sdfs: [np.ndarray], number_sample: int) -> {str: torch.Tensor}:
"""Make two list of points and sdfs on to GPU.
Args:
points: The list of the points.
sdfs: The list of the signed distance fields.
number_sample: The number points to be s... | d744043febec24e8fe3d27d175424d619269bf8f | 49,412 |
def h5File(path, mode='r'):
""" open a HSDS domain or HDF5 file based on the path.
if path starts with "hdf5://", use HSDS, otherwise
use h5py on a regular file path """
if path.startswith("hdf5://"):
f = h5pyd.File(path, mode=mode)
else:
f = h5py.File(path, mode=mode)
re... | 95e00515aa7a2155500d3003c8428ff052ef976a | 49,413 |
def _build_galaxy_loc_line(env, dbkey, file_path, config, prefix, tool_name):
"""Prepare genome information to write to a Galaxy *.loc config file.
"""
if tool_name:
str_parts = []
tool_conf = _get_tool_conf(env, tool_name)
loc_cols = LocCols(config, dbkey, file_path)
# Compo... | e4c80543611326650510e563ded66201f51674d5 | 49,414 |
def norx_failure():
"""
Failed ```norx```.
"""
message = request.args.get('m')
response = make_response(
render_template(
"norx.html",
success=False,
message=message
)
)
response.headers.set('Irbox-Success', 'false')
... | c2fd0937543dfab4a72f7f61b76a43fd2d8b3ec6 | 49,415 |
def full(shape, fill_value, dtype=None):
"""Main code for operation full.
Arguments:
shape: a tuple of integers
fill_value: a scalar value
dtype: either a string (e.g. 'int32')
or a numpy dtype (e.g. np.int32)
Returns:
an array
"""
if dtype is None:
... | 40e5936340c60b7ef850ebe8e69d6ed682bbbb21 | 49,416 |
def pil_to_numpy(pil_image: PILImage.Image) -> np.ndarray:
"""
Convert a Pillow image to a Numpy array.
Parameters
----------
pil_image : PILImage
Pillow image to convert
Returns
-------
image
Array representation of Pillow image.
"""
return np.asarray(pil_image... | 6bbb86b18c7d5d00381cc86fc182ae692ab678a7 | 49,417 |
def search_sequence_numpy(arr, seq):
"""Find sequence positions within array.
Parameters
----------
arr : int array, shape (n_tokens_arr)
Token array, where n_tokens_arr is the number of tokens in the array.
seq : int array, shape (n_tokens_seq)
oken sequence to be located within t... | cb47b7660daae87e6ca6e5753b034b5f527ad439 | 49,418 |
import torch
def gradcam_distillation(gradients_a, gradients_b, activations_a, activations_b, factor=1):
"""Distillation loss between gradcam-generated attentions of two models.
References:
* Dhar et al.
Learning without Memorizing
CVPR 2019
:param base_logits: [description]
... | e52125991fefc7414174a3d602c001069e51c0bb | 49,419 |
def fixture_duthosts(enhance_inventory, ansible_adhoc, tbinfo, request):
"""
@summary: fixture to get DUT hosts defined in testbed.
@param ansible_adhoc: Fixture provided by the pytest-ansible package.
Source of the various device objects. It is
mandatory argument for the class constructors.... | c302a473254d69892868c293c6659bb3257e8616 | 49,420 |
def generateReactions(database, reactants, products=None, only_families=None):
"""
Generate the reactions (and associated kinetics) for a given set of
`reactants` and an optional set of `products`. A list of reactions is
returned, with a reaction for each matching kinetics entry in any part of
the d... | 2d082f08d0372c2640a0d3ce82eea0d0e7177013 | 49,421 |
import torch
def create_runs(args, elements, n_runs, num_classes, classe=None, sample=None, sample_is_support=True, elements_per_class=[]):
"""
Define runs either randomly or by specifying one sample to insert either as a query or as a support
"""
if classe == None and sample == None:
runs = l... | 4150fd581f7d02139c4c854476b3085b57c08af3 | 49,422 |
from dateutil import tz
def nordic2Arrival(data, arrival_id):
"""
Function for converting a nordic file into a Arrival string
:param NordicData data: NordicData object to be converted
:param int arrival_id: arrival id of the assoc
:param int origin_id: origin id of the origin
:returns: arriva... | e93be2e4767fd92ca66f6b35498d6ceec8f27658 | 49,423 |
from typing import Any
def is_jsonable_array(obj: Any) -> bool:
"""Return `True` if ``obj`` is a jsonable array"""
cls = obj if isinstance(obj, type) else type(obj)
return isinstance(getattr(cls, PHERES_ATTR, None), ArrayData) | a9df3e3eda7cdf4fb67346f9e3cb868d061bb6ae | 49,427 |
import torch
def deep_Q_Learning(alpha, gamma, epsilon, episodes, max_steps, n_tests, render = False, test=False):
"""
@param alpha learning rate
@param gamma decay factor
@param epsilon for exploration
@param max_steps for max step in each episode
@param n_tests number of test episodes
"""
env = gym.make(... | 51d3e2940319d9b41f0845ba8f02483253f657cb | 49,428 |
def readFASTA(text, results=dict()):
"""
@param text in FASTA format
@param results dict where results will be put. A new dict by default.
@return dictionnary with new entry like {sequence_name: sequence_str}
@note call this function only if biopython can't be used instead
"""
string = ''
... | 15413643afdc86d14b73a07371be82c08c7cf0e4 | 49,429 |
def get_choices_from_model(model_name, only_active=True):
"""
Return the values of a model as choices to be used in the form.
Args:
model_name: (str) The name of the model inside the ``configuration`` app
only_active: (bool) If True, a filter is set to return only instances of
the... | 8b49e542fa1d326f9a102089ca660eb09499fc91 | 49,430 |
def load_dictionaries_list():
"""loading the list of credentials dictionaries"""
dictionaries_list = [f for f in listdir(config_params.CREDENTIALS_DICTIONARIES_FOLDER)
if (isfile(join(config_params.CREDENTIALS_DICTIONARIES_FOLDER, f)) and f.lower().endswith('.dic'))]
return dictionaries_... | 7af5c6cd9cc3da0af932f448483f2e4943c3ff8b | 49,431 |
def getDbLogger():
"""
This function will return the logger for CEES database queries.
"""
return getLogger(DB_LOGGER) | f364d5cd8ef9583ee42ffd6e89e814311ca7aebe | 49,432 |
import sklearn.metrics
import numpy
def calc_class_accuracy_metrics(ref_samples, pred_samples, cls_area=None, cls_names=None):
"""
A function which calculates a set of classification accuracy metrics for a set
of reference and predicted samples. Optionally, the area classified for each
class can be pr... | 10ba5c7794e8231021ad66b59c9b90d5ed7f8e3e | 49,433 |
from functools import reduce
import operator
import glob
def _files_to_copy(directory):
"""Retrieve files that should be remotely copied.
"""
with utils.chdir(directory):
image_redo_files = reduce(operator.add,
[glob.glob("*.params"),
... | dd90d694b04a2ab5e4257b0b1ea7852a1146af4f | 49,434 |
def constFactor(i, transform):
"""经过 transform 变换后的密度矩阵第 i 个对角元表达式中的常数项
"""
return np.real(
np.conj(tensorElement(transform, i, 0)) *
tensorElement(transform, i, 0)) | 131ec932d4fea9326e27da4e8217aa03134246da | 49,436 |
import torch
import math
def positional_encoding_2d(d_model, height, width, device):
"""
reference: wzlxjtu/PositionalEncoding2D
:param d_model: dimension of the model
:param height: height of the positions
:param width: width of the positions
:return: d_model*height*width position matrix
... | 3cbe2a61024500c2b75204ee1155329d58cc9875 | 49,437 |
def initiate_validator_exit(state: BeaconState,
index: ValidatorIndex) -> BeaconState:
"""
Initiate exit for the validator with the given ``index``.
Return the updated state (immutable).
"""
validator = state.validator_registry[index]
validator = validator.copy(
... | 619a477dfb1602fd67cb4230aae98d7d84613132 | 49,439 |
import time
def wait_for_test_db():
"""Pings the localstack db with describe requests
for {some time} waiting for it to come up...
"""
print('####################################')
print('Waiting for database to start.......')
print('####################################')
def try_request(... | bc157738fa9c6322740282c1f98682f98ad79560 | 49,440 |
def SHAPE_FUNCTIONS(TYPE_ELEMENT, N_NODESELEMENT, ISO_COORDINATES):
"""
This function creates the matrix of the derivatives of the shape functions
Input:
TYPE_ELEMENT | Type element in Finito algorithm | Integer
| 0 - Frame bar element ... | 37180546eb58870f47df7f60c88f12e9c7b181e3 | 49,441 |
def build_app(conf):
""" Build application with the given information
:param conf: Configuration
:return: application
"""
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = conf.SQLALCHEMY_DATABASE_URL
app.config["TESTING"] = conf.TESTING
app.config["SQLALCHEMY_TRA... | 0d2becff424c5156b5d870dbd8d976a5b33f134c | 49,442 |
def two_props_hypothesis(values1: np.ndarray,
values2: np.ndarray,
alternative: str = "two-sided") -> tuple:
"""z test for comparing two proportions
Args:
values1 (np.array): sample 1 binary(0/1) values
values2 (np.array): sample 2 binaray(0/1) ... | acd9d06efb9230b28971db90b0721ceae0107fd3 | 49,443 |
import difflib
def compare_text(text1, text2):
"""
Compare two markdown texts and return the diff as annotated HTML.
"""
d1 = _markdown(text1)
d2 = _markdown(text2)
sm = difflib.SequenceMatcher(lambda x: x == " ", d1, d2)
output = []
for opcode, a0, a1, b0, b1 in sm.get_opcodes():
... | c4dfc7391f112259b2634dbd1d3f652d0bc80fbe | 49,444 |
from typing import Dict
from typing import OrderedDict
import warnings
def share_bi123_f15_v1(s: [Dict, OrderedDict]):
"""股票15分钟123"""
v = Factors.Other.value
freq = Freq.F15.value
for f_ in [freq]:
if f_ not in s['级别列表']:
warnings.warn(f"{f_} not in {s['级别列表']},默认返回 Other")
... | 158dc7ffd742616e777400d73a7bab841abc2ed7 | 49,445 |
def get_sample_interval(info, chan_info):
"""
Get sample interval for one channel
"""
if info['system_id'] in [1, 2, 3, 4, 5]: # Before version 5
sample_interval = (chan_info['divide'] * info['us_per_time'] *
info['time_per_adc']) * 1e-6
else:
sample_inter... | e1a397ad9221c30b70997f0cfb296305e0ca7355 | 49,447 |
def get_input_artifact_location(job):
"""
Returns the S3 location of the input artifact.
"""
input_artifact = job["data"]["inputArtifacts"][0]
input_location = input_artifact["location"]["s3Location"]
input_bucket = input_location["bucketName"]
input_key = input_location["objectKey"]
r... | 282881315313b88882f1df8019f60ae88f654cab | 49,448 |
def run_sparse_network(name, network, intersect_z_vals, intersect_pts,
intersect_ray_batch, use_random_lightdirs, **kwargs):
"""Runs a single network."""
if name.startswith('bkgd'):
intersect_light_ray_batch, intersect_raw = network_query_fn_helper_nodirs(
network=network,
... | 9cd2136e96f5a1e74d21ad81e1e5cff57aa28304 | 49,449 |
import io
def _load_individual_image(f_image, downscale_size, bool_crop=False, crop_size=None):
"""
Loads an individual image into numpy array and perform resizing
:param f_image: absolute path to a single image
:param downscale_size: desired final size of the loaded images, e.g. (256, 256)
:retu... | be699ef1d2d0be54f540b15befb7c646f75e9578 | 49,451 |
def appdomconf(appdom, appname):
"""
Return domain specific application configuration
"""
conf = appdom['applications']
for sub in appname.split('.'):
conf = conf[sub]
return conf | 340f26e3611e311ef5a13e91e86cfe772b8e43b7 | 49,452 |
def make_fcnet_with_skips(input_, sizes, skip_conns, vocab_size, l2_penalty):
"""
Adds skip connections between layers based on the parameter `skip_conns`,
which should be a list of pairs. A connection will be added from the
output of the source layer to the output of the target layer. The outputs
will be sum... | cd8e3e90116b537c30a643a568c842f192eb016e | 49,454 |
from typing import Union
def submatrix(tensor: Union[np.ndarray, tf.Tensor], row: int, column: int) -> tf.Tensor:
""" A submatrix of a matrix is obtained by deleting any collection of rows and/or columns.
For example, from the following 3-by-3 matrix, we can construct a 2-by-2 submatrix by
removin... | 87ff9bf3effc1eeb79e41385be6735c9cd21c46f | 49,455 |
def UDS_SessionEnumerator(sock, session_range=range(0x100), reset_wait=1.5):
""" Enumerates session ID's in given range
and returns list of UDS()/UDS_DSC() packets
with valid session types
Args:
sock: socket where packets are sent
session_range: range for session ID's
re... | d4b561e3fcd01ea42735948d56e885418c7b9e20 | 49,456 |
def remove_gap_traces(st):
"""Searches for gaps in seismic data and removes affected traces from
stream.
Parameters
----------
st : Stream
Obspy object containing seismic traces read from disk.
Returns
-------
st : Stream
Obspy object containing seismic traces read from... | 10bd08a664f929d648e2a8063cf8bda87ad96283 | 49,457 |
import requests
import urllib
import json
def get_turbot_vpc_subnets(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_account, api_version):
""" Gets the current turbot vpc configuration for an account
:return: Returns the current turbot VPC configuratio... | 8fb4f7a66486a976ad371bf7d71d9c9d33fe5167 | 49,458 |
def hanoi(n, a, b, c):
"""
>>> hanoi(5, "a", "b", "c")
[('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b'), ('c', 'a'), ('c', 'b'), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('b', 'a'), ('c', 'a'), ('b', 'c'), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b'), ('c', 'a'), ('c', 'b'), ('a', 'b'), ('c', 'a'), ('b', 'c'), ... | 8b7f2a56dadc09619c24d5bcd44e3286c2727ed1 | 49,460 |
def get_all(log):
"""get all documents"""
return log.all() | 197ad6548e4fa76a8781c780918bf37e96666024 | 49,461 |
def train():
"""
Takes No Parameter
trains the LUIS Model
"""
print "Training the LUIS Model"
try:
conn = httplib.HTTPSConnection("api.projectoxford.ai")
conn.request("POST", "/luis/v1.0/prog/apps/{0}/train".format(configData["appID"]), None,
headers)... | e028eceaaf231cfe5a6e4decee4f4d9300a6faeb | 49,462 |
def lag_to_z(x,lag,xunit='ang',avgbad=True):
"""
this converts an integer pixel lag for a given x-axis into a
redshift
currently the only supported unit for the x-axis is angstroms
avgbad replaces undeterminable velocities with the average of
the others, else they are set to 0
""... | 719c47f8c222327384fe30053520ce2da346f9fe | 49,463 |
def trainA3C(file_name="A3C", env=GridworldEnv(1), update_global_iter=10,
gamma=0.999, is_plot=False, num_episodes=500,
max_num_steps_per_episode=1000, learning_rate=0.0001 ):
"""
A3C training routine. Retuns rewards and durations logs.
Plot environment screen
"""
ns = env.... | be12863ce367bfe61607e1000c495b41ddd0ac84 | 49,464 |
def search_artist(query):
"""Search artists by query. Returns an ArtistSearch object.
Use get_next_page() to retrieve sequences of results."""
return ArtistSearch(query) | 06631762424a4a6575010c18bde76d44c85ba231 | 49,465 |
def key_expansion(k):
"""AES key expansion for 128/256-bit keys."""
w = list(map(list, zip(*k)))
Nk = len(w) # Nk is 4 or 8
Nr = 10 if Nk == 4 else 14
for i in range(Nk, 4 * (Nr + 1)):
t = w[-1]
if i % Nk in {0, 4}:
t = [sbox(x) for x in t]
if i % Nk == 0:
... | a08a03b3988b9b228c5f0c4c82dbd21e461eba55 | 49,466 |
def process_invitation_response(request, invitation_response_formset):
"""
Process an invitation response.
Helper function to view: project_home
"""
user = request.user
invitation_id = int(request.POST['invitation_response'])
for invitation_response_form in invitation_response_formset:
... | d3a964ecf54e44939e7aa094d7eb024e84971e42 | 49,468 |
def addParams(params, subparser):
"""Add params to the given subparser"""
if (params is not None):
for param in params:
flags = ["--{}".format(param.name)]
if (param.alt is not None):
flags.append("-{}".format(param.alt))
if param.choices:
... | 59fc44d9bcc18c7b2750a182f519ff3be85b20ba | 49,469 |
def getShaders(objects):
""" DEPRECATED, use getMaterials(objects) instead """
return getMaterials(objects) | 9ab3db2d4440ee6addf869fcc31ec7bf4bc9b80c | 49,470 |
import scipy
def upsample(x, factor):
"""Reverse decimation by polyphase upsampling
by the given (integer) factor"""
return scipy.signal.resample_poly(x, factor, 1) | dec67e9957ea510c540507cc8e1394623bfe0d25 | 49,471 |
def balance_conversion_plus_primary_constraint_rule(
backend_model, node, tech, timestep
):
"""
Balance energy carrier consumption and production for carrier_in and carrier_out
.. container:: scrolling-wrapper
.. math::
\\sum_{loc::tech::carrier \\in loc::tech::carriers_{out}}
... | 3e63c4cecb534a08a025e956125efaede01e2414 | 49,474 |
def create_objectness_label(anchor_center, resolution=0.5,
x=90, y=100, z=10, scale=4):
"""Create Objectness label"""
print(type(x[1] - x[0]))
obj_maps = np.zeros((int((x[1] - x[0]) / (resolution * scale)),
int((y[1] - y[0]) / (resolution * scale)),
... | b648047ccc21497b9f329b463f038b9f45b353b4 | 49,475 |
def weighted_rating(clean_anime, quantile, mean):
"""
:var term: gets the total users who rated each anime.
"""
term = clean_anime['members'] / (quantile + clean_anime['members'])
return clean_anime['rating'] * term + (1 - term) * mean | 757808adcce0cce5c71a79d200bbaa03b6ebb878 | 49,476 |
def mjd2doyyr(mjd):
"""
Convert mjd to (decimal) day-of-year and year
Mathew Owens, 16/10/20
"""
#convert to datetime and extract the necessary info
dt=mjd2datetime(mjd)
year=np.vectorize(lambda x: x.year)(dt)
year=year.astype(int)
doy=np.vectorize(lambda x: x.timetuple().tm_yday... | 8fb45ce62670a6aef53b7a9c22c465597a8a7da9 | 49,477 |
def map_remove_by_rank_range(bin_name, rank_start, remove_amt, return_type, inverted=False):
"""Creates a map_remove_by_rank_range operation to be used with operate or operate_ordered
The operation removes `remove_amt` items beginning with the item with the specified rank from the map.
Args:
bin_n... | 7d301f9d6fbf5955cbaac6a5c0e5aa900809dfe8 | 49,481 |
from typing import OrderedDict
def export_view_json(request):
"""
Custom view function to export full results for this game as JSON file
"""
def create_odict_from_object(obj, fieldnames):
"""
Small helper function to create an OrderedDict from an object <obj> using <fieldnames>
... | eaeec81489318f8b579a4b32e0412ec9e3cd8680 | 49,482 |
def _parse_sklearn_api(topology, model, inputs):
"""
This is a delegate function adding the model to the input topology.
It does nothing but invokes the correct parsing function according to the input model's type.
Args:
topology: The ``hummingbitd.ml._topology.Topology`` object where the model... | ca46335e5e0437e4095d2a2046637e70664337bf | 49,483 |
def even_value_doubler(array_to_double = [1,2,3,5,6,7,9,10,12]):
"""
This function allegedly takes an list array of numbers and doubles the value of every even value in the list.
"""
length = len(array_to_double)
for i in range(0, length):
if arr[i] % 2 == 0:
arr[i] *= 2
return arr | c6284beb73f3a0c8c277a281c714139457c61f93 | 49,484 |
from typing import Any
def _print_card(card: Any) -> str:
"""helper for ``_validate_msg``"""
try:
return card.write_card(size=8)
except RuntimeError:
return '' | 0d85f2b7bfec942b1ff6e5d0c80facd1bb4824a0 | 49,485 |
import hashlib
def getImageHash(img):
""" Calculates md5 hash for a given Pillow image. """
md5hash = hashlib.md5(img.tobytes())
return md5hash.hexdigest() | d7bd7e1857f6849143f07063c045ae206985d4a3 | 49,487 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.