content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def _find_available_share_drive_letter(share_ignores: List[str] = None) -> str:
"""Find an available drive letter for a share.
This function iterates backwards through the ASCII uppercase letters trying
and checks them against the current net use drive mappings. Once it finds
... | 0b74d17660e2b7f2d2ca92b23b5e67dac9b58f61 | 11,900 |
def integrate(sde=None, *, q=None, sources=None, log=False, addaxis=False):
"""Decorator for Ito Stochastic Differential Equation (SDE)
integration.
Decorates a function representing the SDE or SDEs into the corresponding
``sdepy`` integrator.
Parameters
----------
sde : function
F... | 3914a3dffae1f148459cb72ec6f23547c2dbff97 | 11,901 |
import pymbar
def calculate_statistical_inefficiency_runs(traj_l):
"""
Using fast autocorrelation calculation to estimate statistical inefficiency. This code wraps
a function from pymbar.
References
----------
[1] Shirts MR and Chodera JD. Statistically optimal analysis of samples from
... | e146820d28258a8b6b5bc60420cbf56fdade328b | 11,902 |
import torch
def dataio_prep(hparams):
"""Creates the datasets and their data processing pipelines"""
# 1. define tokenizer and load it
modelpath = download_to_dir(hparams["tok_mdl_file"], hparams["save_folder"])
download_to_dir(hparams["tok_voc_file"], hparams["save_folder"])
tokenizer = Sentenc... | 0cb89799b58e0ba68781a538f17d525749ab4796 | 11,903 |
def get_superlative_type(question_normal):
"""What TV series was Mark Harmon the star of that ran the least amount of time on TV ?"""
result = 'argmax'
question_normal = question_normal.lower()
superlative_serialization_list = superlative_serialization(question=question_normal)
for element in superl... | 8129fcf104dd49117d3ffb49f73752902c1a27f4 | 11,904 |
from re import L
def coord_net_spec(ks=3, stride=1, pad=0, pool=2, dstride=2, dpad=0):
"""
Define net spec for simple conv-pool-deconv pattern common to all
coordinate mapping tests.
"""
n = caffe.NetSpec()
n.data = L.Input(shape=dict(dim=[2, 1, 100, 100]))
n.aux = L.Input(shape=dict(dim=[... | 3ee824372d99ae12cb3318d2e17dbfa67abbd31c | 11,905 |
def note_favorite(note):
"""
get the status of the note as a favorite
returns True if the note is marked as a favorite
False otherwise
"""
if 'favorite' in note:
return note['favorite']
return False | 503f4e3abaab9d759070c725cdf783d62d7c05d2 | 11,906 |
import itertools
def _crossproduct(template: CheckListTemplate):
"""
Takes the output of editor.template and does the cross product of contexts and qas
"""
ret = []
ret_labels = []
for instance in template.data:
cs = instance["contexts"]
qas = instance["qas"]
d = list(i... | 6f2bfd9b3c1aa392179c377e1a87c0d2221f0a45 | 11,907 |
def thread(function):
"""Runs the decorated function within a concurrent thread,
taking care of the result and error management.
Decorated functions will return a concurrent.futures.Future object
once called.
"""
@wraps(function)
def wrapper(*args, **kwargs):
future = Future()
... | dd3d7d15281a6821e7235695e6311f9aabf96ea9 | 11,908 |
def collapse_range(arg, value_delimiter=',', range_delimiter='-'):
"""
Collapses a list of values into a range set
:param arg: The list of values to collapse
:param value_delimiter: The delimiter that separates values
:param range_delimiter: The delimiter that separates a value range
:return: ... | 5caeb8609ab83e52041cc83bbe53d9aa2316dd01 | 11,909 |
def compute_diag_mog_params(M=int(4), snr=3.):
"""Returns diagonal mixture of Gaussian target distribution settings for d=2
Args:
M: (Optional) Integer, number of components
snr: (Optional) Scaling of the means
"""
d = int(2)
weights = np.ones(M)
weights /= np.sum(weights)
... | 4247889dcf8bddc93e4433d685ec81fd59e591a7 | 11,910 |
def has_ifm2(npu_op: NpuBlockOperation) -> bool:
"""Checks if op has non-scalar IFM2"""
return npu_op.ifm2 is not None and npu_op.ifm2_scalar is None | b51092fa486979fbd53d0b1c70ac4390f22df87f | 11,911 |
def ilsvrc_fix_args(args):
"""
Update the args with fixed parameter in ilsvrc
"""
args.ds_name="ilsvrc"
args.num_classes == 1000
# GPU will handle mean std transformation to save CPU-GPU communication
args.do_mean_std_gpu_process = True
args.input_type = 'uint8'
args.mean = get_a... | 64e956a78fc4e64040efa42fd5b6215642430d69 | 11,912 |
def get_mock_adapter() -> Adapter:
"""Get a requests-mock Adapter with some URLs mocked by default"""
adapter = Adapter()
adapter.register_uri(
ANY_METHOD,
MOCKED_URL,
headers={'Content-Type': 'text/plain'},
text='mock response',
status_code=200,
)
adapter.reg... | bede0a72fa8336663d81eeb352a9191280f9f2d6 | 11,913 |
def eqtls_weights_summing(eqtl_occurrence_log_likelihood, ens_gene_id, target_species_hit, converted_eqtls, gtex_weights_dict, chr_start, chr_end, gtex_variants, tf_len, gene_len):
"""
Identify if any of the eQTLs associated with this gene overlap this predicted TFBS.
Retrieve the log-likelihood scores for ... | 1ac37a4eed54c282e8f086b50ffc96946a1bdb29 | 11,914 |
def get_file_chunks_in_range(context, filediff, interfilediff,
first_line, num_lines):
"""
A generator that yields chunks within a range of lines in the specified
filediff/interfilediff.
This is primarily intended for use with templates. It takes a
RequestContext for lo... | 85e96d7c1a0c09880c865e1ea9f5e3eb29dca122 | 11,915 |
import urllib
import sys
def urlread(url):
"""Return the contents of a url. Raises IOError if couldn't read url."""
try:
urlfile = urllib.request.urlopen(url)
return urlfile.read()
except IOError as e:
print("[!] Error reading url:", url)
print(e.message)
sys.exit(1... | 5c62161106003524809f4b40ab5e0c8a6dbe65d7 | 11,916 |
def parse_metric(y_train, goal):
"""
Parse the metric to the dictionary
"""
y_array = np.array(y_train, dtype=np.float64)
if goal == api_pb2.MINIMIZE:
y_array *= -1
return y_array | 164518c4ba84e0fef450ec9e4196ec90de269fd3 | 11,917 |
import math
def erfc(x):
"""Complementary error function (via `http://bit.ly/zOLqbc`_)"""
z = abs(x)
t = 1. / (1. + z / 2.)
r = t * math.exp(-z * z - 1.26551223 + t * (1.00002368 + t * (
0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (
0.27886807 + t * (-1.13520398 + t * (1.... | fd2a44142042e81ef1fc5f649186a41ae4a152b0 | 11,918 |
import urllib
import logging
import time
import json
def request_until_success(url, max_attempts=5, wait=5):
"""Makes a request a few times in case of a 500 error.
Should use exponential backoff?
"""
req = urllib.request.Request(url)
success = False
num_tries = 0
while not success:
... | 639371539df5daabffaf3c3978c8677cbf2f8b4e | 11,919 |
from typing import Optional
def uuid(name, value) -> "Optional[str]":
"""Validate that the value is a UUID
Args:
name (str): Name of the argument
value (any): A UUID string value
Returns:
The value, or None if value is None
Raises:
InvalidParameterValue: if the value... | 3e6ca1211c9ebbba5889917ee252d21aebaac74e | 11,920 |
import re
def expandall(text):
"""
Search for abbreviations in text using re_abbr (defined in utils.get_res).
For each abbreviation, find likely full term. Replace each instance of the
abbreviation in the text with the full term.
Parameters
----------
text : str
Text to search for... | 0c229ec32ef5d9315c39eff6f4a8fad427ccdb07 | 11,921 |
def get_source_fields(client, source_table):
"""
Gets column names of a table in bigquery
:param client: BigQuery client
:param source_table: fully qualified table name.
returns as a list of column names.
"""
return [f'{field.name}' for field in client.get_table(source_table).schema] | abc161f252c03647a99a6d2151c00288b176a4e7 | 11,922 |
def has_user_based_permission(obj, user, allow_superuser=True, allow_staff=False):
"""
Based on obj.get_user(), checks if provided user is that user.
Accounts for superusers and staff.
"""
if hasattr(obj, "get_user"):
obj_user = obj.get_user()
# User is logged in
if user.is... | bcedf697280a75575e9d0202d1a6a65161a873ad | 11,923 |
from typing import Optional
from typing import Any
def trace_stack_top(trace_stack_var: ContextVar) -> Optional[Any]:
"""Return the element at the top of a trace stack."""
trace_stack = trace_stack_var.get()
return trace_stack[-1] if trace_stack else None | 4258a4247a8b40e5cf61a39e94bb30fed936b1de | 11,924 |
def fbconnect():
"""This allows users to use facebook account to sign in."""
if request.args.get("state") != login_session["state"]:
response = make_response(json.dumps("Invalid state parameter."), 401)
response.headers["Content-Type"] = "application/json"
return response
access_toke... | a4a1ec728ce6bfc7a9c8f3fff02896f63eed6dea | 11,925 |
def _get_current_task():
"""
Stub to make it easier to test without actually running Celery.
This is a wrapper around celery.current_task, which provides access
to the top of the stack of Celery's tasks. When running tests, however,
it doesn't seem to work to mock current_task directly, so this wr... | 8b8b3c4abdb8ae75fcfb2907010965e36bd1dfe5 | 11,926 |
def naiveMP(tsA, m, tsB=None):
"""
Calculate the Matrix Profile using the naive all-pairs calculation.
Parameters
----------
tsA: Time series containing the queries for which to calculate the Matrix Profile.
m: Length of subsequence to compare.
tsB: Time series to compare the query against.... | 9d38e4384d3ad8581862df388c32ea17bd02734f | 11,927 |
from typing import Mapping
from typing import Union
from typing import Iterable
from typing import Sized
import json
import sys
def markdown_list(
handle: Jira,
jql_text: str,
column_fields=None,
list_type: str = 'ul',
data: Mapping[str, Union[object, Iterable, Sized]] = None,
) -> str:
"""Yes... | 39bc4a1b12293c30cf906cb709872349a34c4418 | 11,928 |
def render_html(data):
"""
"""
data.setdefault('domain', DOMAIN)
template = '''
<table border="1" cellspacing="0" cellpadding="0">
<tr><td>类型</td><td>{type}</td></tr>
<tr><td>团队</td><td>{team}</td></tr>
<tr><td>项目</td><td>{project}</td></tr>
<tr><td>名称</td><td>{n... | 92371e4e7589853fef167ea12f2e0461e39fcae4 | 11,929 |
from operator import invert
def segment_cells(image, max_cell_size):
"""Return segmented cells."""
image = identity(image)
wall = threshold_adaptive_median(image, block_size=101)
seeds = remove_small_objects(wall, min_size=100)
seeds = dilate_binary(seeds)
seeds = invert(seeds)
seeds = re... | 5479b04595b10e903e56b2a546c44e583b324c94 | 11,930 |
import string
def encrypt(message, key):
"""
>>> encrypt("Hello world",12)
'Tqxxa iadxp'
>>> encrypt("We are Penn State!!!",6)
'Ck gxk Vktt Yzgzk!!!'
>>> encrypt("We are Penn State!!!",5)
'Bj fwj Ujss Xyfyj!!!'
>>> encrypt(5.6,3)
'error'
>>> ... | 991449aac78fba9a348a1c3b1d1d7b1f14faff11 | 11,931 |
import os
def extraction_closure(video_root, frame_root):
"""Closure that returns function to extract frames for video list."""
def func(video_list):
for video in video_list:
frame_dir = video.rstrip('.mp4')
frame_path = os.path.join(frame_root, frame_dir)
os.maked... | a8cdf26c8b4ed6078f7888cf156b2c78a66058d3 | 11,932 |
def std(input, axis=None, keepdim=False, unbiased=True, out=None, name=None):
"""
:alias_main: paddle.std
:alias: paddle.std,paddle.tensor.std,paddle.tensor.stat.std
Computes the standard-deviation of the input Variable's elements along the specified
axis.
Args:
input (Variable): The input... | b2710442ccf0377dd1d84521f5666c8253390e35 | 11,933 |
import os
import joblib
def predict_model(model_name, data_file_name):
"""This function predicts house prices based on input data"""
model_path = os.path.join(config.TRAINED_MODEL_DIR, model_name)
data_file_path = os.path.join(os.path.join(config.DATA_DIR, data_file_name))
pipe = joblib.load(model_pat... | aa49ad5f5076ad57aa3a0e3f7c1dffdfc95f5c51 | 11,934 |
def check_file_behaviour(file_hash):
"""
Returns the file execution report.
"""
params = {
'hash': file_hash
}
api_endpoint = 'file/behaviour'
return http_request('GET', api_endpoint, params, DEFAULT_HEADERS) | 87bb4539e948683cfea05f75741d26e1063073d9 | 11,935 |
def is_access_group(outter_key, inner_key) -> None:
"""Prints access-group """
values = {}
if outter_key == "access-group":
if inner_key.get('index') is not None:
values['index'] = ', '.join(is_instance(inner_key.get('index', {})))
elif inner_key.get('name') is not None:
... | 96ef5ab1f0b48f7a43b4ebd96d728ff7ad552964 | 11,936 |
def lidar_to_cam_frame(xyz_lidar, frame_calib):
"""Transforms points in lidar frame to the reference camera (cam 0) frame
Args:
xyz_lidar: points in lidar frame
frame_calib: FrameCalib frame calibration
Returns:
ret_xyz: (N, 3) points in reference camera (cam 0) frame
"""
... | 6b42a52ccca1101cd0f64ed6fadbcdc974a67b0f | 11,937 |
import logging
def create_logger(model_name: str, saved_path: str):
"""Create logger for both console info and saved info
"""
logger = logging.getLogger(model_name)
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler(f"{saved_path}/{mode... | 3703cee522fcef8bcd383a8703bef92252435b5b | 11,938 |
import torch
def hann_sinc_low_pass(x: Tensor, N: int, fs: int, fc: float) -> Tensor:
"""Hann windowed ideal low pass filter.
Args:
x: [n_batch, 1, n_sample]
N: the window will be [-N, N], totally 2N+1 samples.
Returns:
y: [n_batch, 1, n_sample]
"""
w = continuous_hann_sinc... | 93ba44fd351d7c53e151c812cc6458433c916216 | 11,939 |
import copy
def ask_for_missing_options(arguments: CommandLineArguments, root: tk.Tk) -> ProgramOptions:
"""
Complete the missing information by askin the user interactively.
"""
values = copy.deepcopy(arguments)
if values.source_directory is None:
values.source_directory = insist_for_dire... | 6be882199bee5abaef9b3362522b508e90222150 | 11,940 |
import math
def matrix2quaternion(m):
"""Returns quaternion of given rotation matrix.
Parameters
----------
m : list or numpy.ndarray
3x3 rotation matrix
Returns
-------
quaternion : numpy.ndarray
quaternion [w, x, y, z] order
Examples
--------
>>> import num... | 97a7a9c9c7a92bc2269c9ec9fee4e9e462168e50 | 11,941 |
def paging_forward(data_func, *args):
"""
Создает кнопку вперед для переключения страницы списка
:param data_func: func from UI.buttons. Действие, которое будет возвращать кнопка
:return: InlineKeyboardButton
"""
g_data = loads(data_func(*args).callback_data)
g_data['page'] += 1
text =... | 4e1ef26c005e47422b86658814cb3336b51d296f | 11,942 |
from threading import RLock
def synchronized(func):
"""Synchronizes method invocation on an object using the method name as the mutex"""
def wrapper(self,*__args,**__kw):
try:
rlock = self.__get__('_sync_lock_%s' % func.__name__)
#rlock = self._sync_lock
except Att... | 8db95217e8e5e37d0e7457c0808163fd6ddc007f | 11,943 |
def vector(location_1, location_2):
"""
Returns the unit vector from location_1 to location_2
location_1, location_2: carla.Location objects
"""
x = location_2.x - location_1.x
y = location_2.y - location_1.y
z = location_2.z - location_1.z
norm = np.linalg.norm([x, y, z]) + np.finfo(f... | 453e35f91984458e0022f7576ef17902063ee1ed | 11,944 |
import json
import requests
import sys
def test_pandas_code_snippets(
app, client, tmpdir, monkeypatch,
template_name, script_name, expected_columns
):
"""Bit of a complicated test, but TLDR: test that the API example Python
scripts work.
This test is a bit complicated and is pretty low i... | 5b48ec267ad653dd51380ac5909062eab1456d33 | 11,945 |
def getOpenOCO(recvWindow=""):
"""# Query Open OCO (USER_DATA)
#### `GET /api/v3/openOrderList (HMAC SHA256)`
### Weight: 3
### Parameters:
Name |Type |Mandatory |Description
--------|--------|--------|--------
recvWindow |LONG |NO |The value cannot be greater than <code>60000</code>
timestamp |LONG |YES |
<stro... | ea82f7441f57efd5ebf99ad4cff370f68cbcb367 | 11,946 |
def pixel_unshuffle(scale):
""" Pixel unshuffle.
Args:
x (Tensor): Input feature with shape (b, c, hh, hw).
scale (int): Downsample ratio.
Returns:
Tensor: the pixel unshuffled feature.
"""
if scale == 1:
return lambda x: x
def f(x):
b, c, hh, hw = x.size()
out_channel = c * (s... | 28802c2014e5a3c28de6b751c40ad4787de8e80c | 11,947 |
import attr
def flag(name, thing=None):
"""Generate an Attribute with that name which is valued True or False."""
if thing is None:
thing = Keyword(name)
return attr(name, thing, "Flag") | 02f32444eb927dd61f0e08da7579e47d1b4a580d | 11,948 |
def select_id_from_scores_dic(id1, id2, sc_dic,
get_worse=False,
rev_filter=False):
"""
Based on ID to score mapping, return better (or worse) scoring ID.
>>> id1 = "id1"
>>> id2 = "id2"
>>> id3 = "id3"
>>> sc_dic = {'id1' : 5, 'id2': ... | f2fa5f33eead47288c92715ce358581a72f18361 | 11,949 |
def add_args(parser):
"""Add arguments to the argparse.ArgumentParser
Args:
parser: argparse.ArgumentParser
Returns:
parser: a parser added with args
"""
# Training settings
parser.add_argument(
"--task",
type=str,
default="train",
metavar="T",
... | cfebbfb6e9821290efdc96aaf0f7a7470e927c70 | 11,950 |
from typing import Any
def run_interactive(package: str, action: str, *args: Any, **_kwargs: Any) -> Any:
"""Call the given action's run"""
action_cls = get(package, action)
app, interaction = args
return action_cls(app.args).run(app=app, interaction=interaction) | 5423d67b61441aaea2162042feeffe68e1d79a0c | 11,951 |
from typing import Tuple
def pythagorean_heuristic(start_point: Tuple[int, int], end_point: Tuple[int, int]) -> float:
"""Return the distance between start_point and end_point using the pythagorean distance
"""
x1, y1 = start_point
x2, y2 = end_point
distance = (((x2 - x1) ** 2) + ((y2 - y1) ** 2)... | b22369d3860cb0969d43c5e7eb0290a757f5c692 | 11,952 |
def run_simulation(x, simulation_time, dt, rates, sampling_time):
"""
Runs a simulation and stores the sampled sequences the matrix sequences (nb_nucleotide * nb_sequences).
x is modified during the simulation. The original sequence is included in the sequences matrix, in the first row.
"""
ii = 0
... | b04e36fba421e9931a78f42502d69d5432b5add9 | 11,953 |
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username"... | db06fe7b5f99be9ca0957c769f783ec182cc7e24 | 11,954 |
def process_item(item_soup):
"""Parse information about a single podcast episode.
@param item_soup: Soup containing information about a single podcast
episode.
@type item_soup: bs4.BeautifulSoup
@return: Dictionary describing the episode. Contains keys name (str value),
date (datetime.d... | f83c98516d1a573c11c6affbe04122f6eac32918 | 11,955 |
def update_webhook(request, log, tenantId, groupId, policyId, webhookId, data):
"""
Update a particular webhook.
A webhook may (but do not need to) include some arbitrary medata, and must
include a name.
If successful, no response body will be returned.
Example request::
{
... | ee33bc3a63ebe13c920288ba56a0771a10d8e2c4 | 11,956 |
def covariance_from_internal(internal_values, constr):
"""Undo a cholesky reparametrization."""
chol = chol_params_to_lower_triangular_matrix(internal_values)
cov = chol @ chol.T
return cov[np.tril_indices(len(chol))] | 04d6385f32c8d89e283be89d4f17e7fa5770115e | 11,957 |
def find_result_node(desc, xml_tree):
"""
Returns the <result> node with a <desc> child matching the given text.
Eg: if desc = "text to match", this function will find the following
result node:
<result>
<desc>text to match</desc>
</result>
Parameters
-----
... | 44ecfae4cd80a04e656bffbcdfbcf686c1e825f2 | 11,958 |
def y(instance):
"""Syntactic sugar to find all y-coordinates of a given class instance.
Convenience function to return all associated x-coordinates
of a given class instance.
Parameters
----------
instance : DataContainer, Mesh, R3Vector, np.array, list(RVector3)
Return the associated... | aa0362148bd65427ac27f0e0e875a1cab0fd3057 | 11,959 |
import numpy
def interp_xzplane(y, u, y_target=0.0):
"""Perform linear interpolation of the 3D data at given y-location.
Parameters
----------
y : numpy.ndarray of floats
The y-coordinates along a vertical gridline as a 1D array.
u : numpy.ndarray of floats
The 3D data.
y_targ... | 77f8b559c64eb2b33723a2a8e540f4d783364c84 | 11,960 |
from datetime import datetime
import os
import csv
def train_transfer(x_train, y_train, vocab_processor, pretrain_emb, x_dev, y_dev,
source_ckpt, target_ckpt, pretrained_values=None):
"""
Train a transfer model on target task: must pass "pretrained_values"
Build model architecture using... | b8758eb2442d5473f014671a89f6e198854017c7 | 11,961 |
def liste_vers_paires(l):
"""
Passer d'une structure en list(list(str)) ) list([str, str])
:param l:
:return:
"""
res = []
for i in l:
taille_i = len(i)
for j in range(taille_i-1):
for k in range(j+1, taille_i):
res.append([i[j], i[k]])
return ... | 5f40e032fb9aba22656565d958ccfac828512b77 | 11,962 |
from typing import List
from typing import Dict
from typing import Any
def assert_typing(
input_text_word_predictions: List[Dict[str, Any]]
) -> List[Dict[str, str]]:
"""
this is only to ensure correct typing, it does not actually change anything
Args:
input_text_word_predictions: e.g. [
... | 0835bad510241eeb2ee1f69ac8abeca711ebbf53 | 11,963 |
import urllib
import time
def download(file):
"""Download files from live server, delete recerds of those that 404.
"""
url = 'https://www.' + settings.DOMAIN.partition('.')[2] + file.url()
try:
print(url)
return urllib.request.urlopen(url, timeout=15).read()
except urllib.error.HT... | f1eb0bc35f3a4afa40b22e9ff4db69740b273d31 | 11,964 |
from corehq.apps.commtrack.models import StockState
def get_current_ledger_state(case_ids, ensure_form_id=False):
"""
Given a list of cases returns a dict of all current ledger data of the following format:
{
"case_id": {
"section_id": {
"product_id": StockState,
... | 807cd430a29c7a8c377ad1822435a344d95daa7c | 11,965 |
def _FlattenPadding(padding):
"""Returns padding reduced to have only the time dimension."""
if padding is None:
return padding
r = tf.rank(padding)
return tf.reduce_min(padding, axis=tf.range(1, r)) | 0a757e3bb84ec89c0959de8a1d06667373501c9d | 11,966 |
def revive_custom_object(identifier, metadata):
"""Revives object from SavedModel."""
if ops.executing_eagerly_outside_functions():
model_class = training_lib.Model
else:
model_class = training_lib_v1.Model
revived_classes = {
'_tf_keras_layer': (RevivedLayer, base_layer.Layer),
'_tf_keras_... | 870db96ed17fdfe1dc535a3b38541de5a0f34688 | 11,967 |
def all_users():
"""Returns all users in database sorted by name
Returns:
QuerySet[User]: List containing each User instance
"""
# Return all unique users in Database.
# sorted by full name
# returns query set. same as python list. Each index in user_list is a user model.
user_list... | f952b7b1134429e9473da339bbb881011c7bb0b8 | 11,968 |
def plugin_func_list(tree):
"""Return a list of expected reports."""
return [EXPECTED_REPORT + (type(plugin_func_list),)] | 236054789507d64f1593ea13b5333b2c7db2a1aa | 11,969 |
def entity_ids(value):
"""Validate Entity IDs."""
if value is None:
raise vol.Invalid('Entity IDs can not be None')
if isinstance(value, str):
value = [ent_id.strip() for ent_id in value.split(',')]
return [entity_id(ent_id) for ent_id in value] | 21ab0ca35dc6b727b57e1dcd472de38a81c92d88 | 11,970 |
import math
def random_unitary(dim, seed=None):
"""
Return a random dim x dim unitary Operator from the Haar measure.
Args:
dim (int): the dim of the state space.
seed (int): Optional. To set a random seed.
Returns:
Operator: (dim, dim) unitary operator.
Raises:
... | fd0599fe0a03036fee5ae31ea00b9ba0277b035d | 11,971 |
def allc(IL, IR):
"""
Compute the all-chain set (ALLC).
Parameters
----------
IL : ndarray
Left matrix profile indices
IR : ndarray
Right matrix profile indices
Returns
-------
S : list(ndarray)
All-chain set
C : ndarray
Anchored time series ch... | 4ec01a2f3718430c2965173a48a0d3f8bd84f0e1 | 11,972 |
def build_resilient_url(host, port):
"""
Build basic url to resilient instance
:param host: host name
:type host: str
:param port: port
:type port: str|int
:return: base url
:rtype: str
"""
if host.lower().startswith("http"):
return "{0}:{1}".format(host, port)
retu... | 33be03c5417aa41fdc888d856e760107843096e9 | 11,973 |
def relative_angle(pos1, pos2):
""" Angle between agents. An element (k,i,j) from the output is the angle at kth sample between ith (reference head) and jth (target base).
arg:
pos1: positions of the thoraces for all flies. [time, flies, y/x]
pos2: positions of the heads for all flies. [time, fl... | cceb6e2e2007399b7479e7ec7c7237d554905b62 | 11,974 |
def run_value_iteration(env):
"""Run a random policy for the given environment.
Logs the total reward and the number of steps until the terminal
state was reached.
Parameters
----------
env: gym.envs.Environment
Instance of an OpenAI gym.
Returns
-------
(float, int)
F... | 829c3288325520fe5b36fdbcd1d76c8178ace710 | 11,975 |
def get_shape(dset):
"""
Extract the shape of a (possibly constant) dataset
Parameters:
-----------
dset: an h5py.Dataset or h5py.Group (when constant)
The object whose shape is extracted
Returns:
--------
A tuple corresponding to the shape
"""
# Case of a constant data... | fd1f1ed59542cd1a6527d9c45dd64ee4c7b47cb4 | 11,976 |
from sklearn.metrics import mean_absolute_error
import os
import pickle
def predict(reaction_mech, T_list, pressure_0, CCl4_X_0, mass_flow_rate,
n_steps, n_pfr, length, area, save_fig=False, name='predict',fold_no=None,iter_CCl4=False):
"""
Load the saved parameters of StandardScaler() and rebuil... | 5152c14facb28aa78625a6d5064a7e54094ef55f | 11,977 |
import socket
import sys
def server_params_test(client_context, server_context, indata=b"FOO\n",
chatty=True, connectionchatty=False, sni_name=None,
session=None):
"""
Launch a server, connect a client to it and try various reads
and writes.
"""
stats ... | 0eebef4fea6e80353f9e1ecc5c73f7b2d74b3ef6 | 11,978 |
import typing
def _sanitize_bool(val: typing.Any, /) -> bool:
"""Sanitize argument values to boolean."""
if isinstance(val, str):
return val.lower() == 'true'
return bool(val) | b41c52b6e61bcc6ec8b78138f4a5ee58f7284ca3 | 11,979 |
def isSameLinkedList(linked_list1, linked_list2):
"""
Check whether two linked lists are the same.
Args:
linked_list1: -
linked_list2: -
"""
while linked_list1:
if linked_list1.val != linked_list2.val:
return False
linked_list1, linked_list... | cb41ed64b61f49c97104939fc1b1869e872f8234 | 11,980 |
from typing import Any
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: ConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
coordinator: SolcastUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
return {
"info": async_redact_... | e8a75709612426a70c94ff30d740a6ca1ff53972 | 11,981 |
def calculate_value_function(transition_costs):
"""Recursively apply the bellman equation from the end to the start. """
state_dim = [tc.shape[0] for tc in transition_costs]
state_dim.append(transition_costs[-1].shape[1])
V = [np.zeros(d) for d in state_dim]
V_ind = [np.zeros(d) for d in state_dim]... | 14ef732e45581b407d9c19618c7c18b1e9bdbc4e | 11,982 |
def load_config(fname: str) -> JSON_TYPE:
"""Load a YAML file."""
return load_yaml(fname) | 6d4bab8da8853a3ec4ca47afc7d16b1b519343ab | 11,983 |
import os
import re
def get_date_folders():
"""
Return a list of the directories used for backing up the database.
"""
directories_in_curdir = list(filter(os.path.isdir, os.listdir(os.getcwd())))
date_folders = [
d for d in directories_in_curdir if re.match(r"([0-9]+(-[0-9]+)+)", d)
]
... | 127d087888a6cd2dc2786365206a20e495a092ff | 11,984 |
def read_tree_color_map(filename):
"""Reads a tree colormap from a file"""
infile = util.open_stream(filename)
maps = []
for line in infile:
expr, red, green, blue = line.rstrip().split("\t")
maps.append([expr, map(float, (red, green, blue))])
name2color = make_expr_mapping(maps)
... | 82ebbe7b14785a5e766efe40096d94a6867c46b3 | 11,985 |
def sin_cos_encoding(arr):
""" Encode an array of angle value to correspongding Sines and Cosines, avoiding value jump in 2PI measure like from PI to -PI. """
return np.concatenate((np.sin(arr), np.cos(arr))) | ada587fc811748a01d1769385cced60cb678cf15 | 11,986 |
def atom_free_electrons(mgrph, idx):
""" number of unbound valence electrons for an atom in a molecular graph
"""
atms = atoms(mgrph)
vlnc = valence(atms[idx])
bcnt = atom_bond_count(mgrph, idx)
return vlnc - bcnt | 41989063c18f5f9d30da165528a2969fd728f4eb | 11,987 |
def identify_guest():
"""Returns with an App Engine user or an anonymous user.
"""
app_engine_user = users.get_current_user()
if app_engine_user:
return Guest.app_engine_user(app_engine_user)
ip_address = ip_address_from_request(request)
if ip_address:
return Guest.ip_address(... | 5bb857a9477e6f7d22f3c675fc2db92935088121 | 11,988 |
def compute_placevalues(tokens):
"""Compute the placevalues for each token in the list tokens"""
pvs = []
for tok in tokens:
if tok == "point":
pvs.append(0)
else:
pvs.append(placevalue(get_value(tok)[0]))
return pvs | af67660675c3d8f55a621a300c530975bffe87ac | 11,989 |
def get_model_damping(global_step, damping_init, decay_rate, total_epochs, steps_per_epoch):
"""get_model_damping"""
damping_each_step = []
total_steps = steps_per_epoch * total_epochs
for step in range(total_steps):
epoch = (step + 1) / steps_per_epoch
damping_here = damping_init * (dec... | 9aeb0fff36b458886c7b38a3f0072927d2660e47 | 11,990 |
def transformData(Z,Time,Spec):
# transformData Transforms each data series based on Spec.Transformation
#
# Input Arguments:
#
# Z : T x N numeric array, raw (untransformed) observed data
# Spec : structure , model specification
#
# Output Arguments:
#
# X ... | a56b6ecd4ae408cbc9e3873ba10833bd902c3249 | 11,991 |
def torch_fn():
"""Create a ReLU layer in torch."""
return ReLU() | 35ae9fe99a641768f109b8ba216271730941892e | 11,992 |
def all_user_tickets(uid, conference):
"""
Versione cache-friendly della user_tickets, restituisce un elenco di
(ticket_id, fare_type, fare_code, complete)
per ogni biglietto associato all'utente
"""
qs = _user_ticket(User.objects.get(id=uid), conference)
output = []
for t in qs:
... | 7778d4fa0eac0c311db8965f8bd449ad31bd49db | 11,993 |
from typing import List
def get_hardconcrete_linear_modules(module: nn.Module) -> List[nn.Module]:
"""Get all HardConcrete*Linear modules.
Parameters
----------
module : nn.Module
The input module
Returns
-------
List[nn.Module]
A list of the HardConcrete*Linear module.
... | bc821bb2fc41dbf7385b6e319323a65e0372e218 | 11,994 |
import torch
def approx_partial(model, ori_target, param, current_val, params, loss_list, information_loss_list, xs_list, ys_list, train=False, optimizer=None):
"""Compute the approximate partial derivative using the finite-difference method.
:param param:
:param current_val:
:param params:
:retur... | 5cf3eff7880d2405a1dfa01a4296a974deeef70d | 11,995 |
import time
def check_successful_connections(_ctx: Context) -> bool:
"""Checks if there are no successful connections more than SUCCESSFUL_CONNECTIONS_CHECK_PERIOD sec.
Returns True if there was successful connection for last NO_SUCCESSFUL_CONNECTIONS_DIE_PERIOD_SEC sec.
:parameter _ctx: Context
"""
... | 19a3b9ee66ad8a3a6c2b4677116616ccdd5a452b | 11,996 |
def float_or_none(string):
""" Returns float number iff string represents one, else return None. TESTS OK 2020-10-24. """
try:
return float(string)
except (ValueError, TypeError):
return None | 8cc4437841f67e5b2f884ca566f3e6870dcd7649 | 11,997 |
import requests
def move_release_to_another_collection_folder(user: UserWithUserTokenBasedAuthentication,
username: str,
source_folder_id: int,
destination_folder_id: int,
... | 47434146219d323b176db76905a6b5ffb4c25955 | 11,998 |
def load_region_maps(region_file):
"""Extracts creates a map from PHI region id to a continuous region id."""
region_ids = [] # Used mainly for eval
region_ids_inv = {} # Used in data loader
region_names_inv = {} # Used in eval
for l in region_file.read().strip().split('\n'):
tok_name_id, _ = l.strip()... | 201240ce485b4039b12741bb03c547de7976c99a | 11,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.