content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def select(con, id):
""" 指定したキーのデータをSELECTする """
cur = con.execute(
'select id, title_en, title_ja, description_en, description_ja, author, created from suggestions where id=?',
(id,))
return cur.fetchone() | 64f7f96c04dc533446835f6b6d06f7cc4530285e | 3,618,911 |
def save_params(net, best_metric, current_metric, epoch, save_interval, prefix):
"""Logic for if/when to save/checkpoint model parameters"""
if current_metric < best_metric:
best_metric = current_metric
net.save_parameters('{:s}_best.params'.format(prefix, epoch, current_metric))
with op... | 9af251965a4facc598c9a3d833f967511cc7b0ec | 3,618,912 |
def resize(data, number_rows=None, number_columns=None, lower=None, upper=None, categories=None, weights=None, distribution=None, shift=None, scale=None, sample_proportion=None, minimum_rows=None, **kwargs):
"""
Resize Component
Resizes the data in question to be consistent with a provided sample size,... | 458d6fd940655058622e4e6acbb38395036837ac | 3,618,913 |
def svn_uri_dirname(*args):
"""svn_uri_dirname(char const * uri, apr_pool_t result_pool) -> char *"""
return _core.svn_uri_dirname(*args) | b06fa82c95206bf0de6a53b37286752e962f53b1 | 3,618,914 |
from typing import Optional
def create_test_dl(df:pd.DataFrame, b:Optional[np.array]=None,
t_scaler:MaxAbsScaler=None, x_scaler:StandardScaler=None,
bs:int=128, only_x:bool=False) -> DataLoader:
"""
Take dataframe and return a pytorch dataloader.
parameters:
- df:... | 384de2ac68547e48be1a86cbee5293178f8d885a | 3,618,915 |
import math
def initialize_bot_settings(settings: Config) -> Config:
"""
Initialises the settings that are used within the bot to manage the contextual reminders
"""
settings.define_section("ctxreminders", ContextualRemindersSection)
settings.ctxreminders.configure_setting(
"persistence_... | 15ac9073e8cafdb2a604072014a8a9ae12ba260e | 3,618,916 |
from mturk.models import Experiment
from mturk.cubam import update_votes_cubam
from photos.tasks import update_photos_num_intrinsic
def update_votes_cubam(show_progress=False):
""" This function is automatically called by
mturk.tasks.mturk_update_votes_cubam_task """
# responses that we will consider
... | 00d2c20f56f9cc82f5c8f5c0f8a01dc8858c6c69 | 3,618,917 |
from models.yolo import Detect
import torch
def from_pretrained(chkpt, model_dir=None, force_reload=False, **kwargs):
"""
Kwargs:
bucket(str): S3 bucket name
key(str): path in an S3 bucket
"""
stem, suffix = chkpt.split('.')
tag = kwargs.get('tag', 'v6.0')
s3 = kwargs.get('s3'... | 811a0a0f57e03ca30f84c512d3b1252b8bcb25b3 | 3,618,918 |
def generate_multilabel_ensemble_classification_outputs(classifiers, n_classes, n_samples, continuous_out=False,
parallelize=True):
"""
Generate random multilabel crisp classification outputs (assignments) for the given ensemble of classifiers with
th... | cfae74cb5185c98370da81666c0fc65be21d04fb | 3,618,919 |
from ActiveLearning import prepare_for_inference
from io import StringIO
def test_prepare_for_inference(monkeypatch):
"""
There are only 2 records in the input.manifest and they both are sent to batch transform.
"""
def mock_copy(*args, **kwargs):
source = args[0]
dest = args[1]
... | d05f95232b0e86a23c14371562d2b8a63007f6b4 | 3,618,920 |
def nvisitsM5Maps(colmap=None, runName='opsim',
extraSql=None, extraMetadata=None,
nside=64, runLength=10.,
ditherStacker=None, ditherkwargs=None):
"""Generate number of visits and Coadded depth per RA/Dec point in all and per filters.
Parameters
------... | 2122caded6dacb8ff8cef4b5ed07070f4130f066 | 3,618,921 |
def create_3d_trap(radius, height, delta):
"""Creates a 3D surface plot showing the trap and the beach.
Args:
radius: the radius of the trap
height: the height of the trap
delta: how far along the beach the center of radius r circle the semicircular trap could be in
returns:
... | 10d7001fbb04c151f28aa94096411e93501a0527 | 3,618,923 |
import logging
def get_logger(name, log_file=None, log_level=logging.INFO):
"""Initialize and get a logger by name.
If the logger has not been initialized, this method will initialize the
logger by adding one or two handlers, otherwise the initialized logger will
be directly returned. During initializ... | 15d38780c68b4a8d667b7bbfb2cc9b1085a7b637 | 3,618,924 |
def convert_pyte_buffer_to_colormap(buffer, lines):
"""
Convert a pyte buffer to a simple colors
"""
color_map = {}
for line_index in lines:
# There may be lines outside the buffer after terminal was resized.
# These are considered blank.
if line_index > len(buffer) - 1:
... | d16e8aeeb327bfa75af3ba76d339c0a2538dcfa7 | 3,618,925 |
def find_offsets_local_direction(
centered_patches: tf.Tensor, delta: float
) -> tf.Tensor:
"""Computes subpixel offsets from the direction of the pixels around the peak.
This function finds the delta-offset from the center pixel of peak-centered patches
by finding the direction of the gradient around ... | 6f9ddcbb1ef799d0a51631057bf0b731fedccc78 | 3,618,926 |
def to_device(data, device):
"""Move tensor (s) to chosen device"""
if isinstance(data, (list, tuple)):
return [to_device(x, device) for x in data]
return data.to(device, non_blocking=True) | 15f8af4512bf110fa5c8364a7d223725a8c00ce5 | 3,618,927 |
def push_branch_set_upstream(git_dir, branch_name):
""" Push new branch to remote.
"""
try:
# this will ask username/password
git('-C', git_dir, 'push', '--set-upstream', 'origin', branch_name)
except ErrorReturnCode as e:
return failed_util_call_results(e)
else:
retu... | 3ab68134a1d326f752a65b2bc161dc6c6ffa918a | 3,618,928 |
import array
def interpolate_g(xi,yi,zi,xx,yy,knots=10, error=False,mask=None):
"""Create a grid of zi values interpolating the values from xi,yi,zi
xi,yi,zi 1D Lists or arrays containing the values to use as base for the interpolation
xx,yy 1D vectors or lists containing the output coordinates... | 2c14aa5dfd7b968480fe58fb25c69fdaf37b7890 | 3,618,929 |
def knownTypes():
"""
Returns known types.
@ In, None
@ Out, __knownTypes, list, list of known types
"""
return __knownTypes | 19f327ec8167d5390986cf669d2609b0b0c78d57 | 3,618,930 |
def histogram_reads(bam_file, windowsize, chromosomes='all', exclude_chroms=['chrM', 'chrY', 'chrX'],
skip_qc_fail=True):
"""Histogram the counts along bam_file, resulting in a vector.
This will concatenate all chromosomes, together, so to get the
counts for a particular chromosome, pas... | 04838104e02d577285061d150e689d8b975cbfd4 | 3,618,931 |
def single_load(input_, ac_parser=None, ac_template=False,
ac_context=None, **options):
"""
Load single configuration file.
.. note::
:func:`load` is a preferable alternative and this API should be used
only if there is a need to emphasize given input `input_` is single one.
... | d77a3001c0c522571488f5b189f2ef616087f84b | 3,618,932 |
from typing import IO
from typing import List
def read_abbrevs(abbrevs: IO[str]) -> List[Abbrev]:
"""Parse the XML from `abbrevs` into a list of `Abbrev` objects."""
root = ET.parse(abbrevs).getroot()
r = [] # type: List[Abbrev]
for node in root.findall('source'):
spellouts = [
no... | c4db816b311157910bac1fa1924ea833e0a6df1d | 3,618,933 |
def deleteTemplate(**kargs):
""" Delete Template (OS Image) of Your VM
* Args:
- zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2]
- id(String, Required) : Template ID
* Examples : print(server.deleteSnapshot(zone='KR-M', id='6a59215f-df8b-4633-9a55-c42ac41b3467'))
"""
my_apik... | 6c05397b612121afda5ebadf1f6f449a69a62bd8 | 3,618,934 |
def create_session(checkpoint_path, target_device):
"""Create ONNX runtime session"""
if target_device == 'GPU':
providers = ['CUDAExecutionProvider']
elif target_device == 'CPU':
providers = ['CPUExecutionProvider']
else:
raise ValueError(
f'Unsupported target device... | cec11aeca9c3c5ca974e2d290bf2652cf7f1c6eb | 3,618,935 |
def support_vector_regressor(x_train: list, x_test: list, train_user: list) -> float:
"""
Third method: Support vector regressor
svr is quite the same with svm(support vector machine)
it uses the same principles as the SVM for classification,
with only a few minor differences and the only different ... | d820aa66a1a63a1974d1ab9bb0aa2d43a4c917d1 | 3,618,936 |
def _get_default_session():
"""
Get the default session, creating one if needed.
:rtype: :py:class:`~boto3.session.Session`
:return: The default session
"""
if DEFAULT_SESSION is None:
setup_default_session()
_warn_deprecated_python()
return DEFAULT_SESSION | 33fd60704fba9cbc03aa8be1ee18d5dc29c047e6 | 3,618,937 |
import random
def read_meminfo():
"""
Mocks read_meminfo as this is a Linux-specific operation.
"""
return {
"MemTotal": random.randint(0, 999999999),
"MemFree": random.randint(0, 999999999),
"MemAvailable": random.randint(0, 999999999),
"HugePages_Total": random.randin... | 6bdf66ded424748736875d70eae4b54d4a820c28 | 3,618,938 |
def irfft(x, axes):
"""
like np.fft.irfft
"""
return core.Result(core.IRFFT(axes),[x]) | 1b178a85b63562fbefea5b19bd9e512205f7df9d | 3,618,939 |
def set_tmin(ndvar, tmin=0.):
"""Change the time axis of an :class:`NDVar`
Parameters
----------
tmin : scalar
New ``tmin`` value (default 0).
Returns
-------
out_ndvar : NDVar
Shallow copy of ``ndvar`` with updated time axis.
"""
axis = ndvar.get_axis('time')
o... | 9c7e6423c8362d98f1bfa0f0e9abbad4c4e54dcd | 3,618,940 |
import requests
import logging
def place_by_name(place, key, FIND_PLACE=FIND_PLACE):
"""Finds a Google Place ID by searching with its name.
Args:
place (str): Name of the place. It can be a restaurant, bar, monument,
whatever you would normally search in Google Maps.
key (str): Ke... | 5b645b50f9401a42b0a08f20ab7d1e18df4322e2 | 3,618,941 |
import torch
def spearmanr(pred, target, eps=1e-6):
"""
Spearman correlation between target and prediction.
Implement in PyTorch, but non-diffierentiable. (validation metric only)
Parameters:
pred (Tensor): prediction of shape :math: `(N,)`
target (Tensor): target of shape :math: `(N,... | 683810c611288bd4d6c0fa08b8da8005f7ef10ce | 3,618,942 |
def kappa_adj_err_fn(speed, a, b):
"""
:param a: the slope parameter of the adjustment function
:param b: the bias parameter of the adjustment function
"""
global good_a
global good_b
simulator = SingleCue(cue="wind")
rel_model = ReliabilityModel()
iterations = 100
r_averages =... | 56fa4681fe41e826809f5a66944a097ea243d476 | 3,618,943 |
import bisect
import numpy
import traceback
import pdb
def matchTimes(primary_dt,dt,tol_s=1,tol_us=4e5,fail_on_duplicates=True,allow_duplicates=False,warn_no_match=False):
"""
Finds a matching timestamp in primary_dt
within tolerance tol_us (given in microseconds)
for every value in dt.
Inputs:
-------
dt - ... | 1245e1a24e4c521eb9d56319bf3889b99ba99c72 | 3,618,947 |
import tokenize
import warnings
def build_model():
"""
- Build model with GridSearch
Returns:
Trained model with GridSearch
"""
pipeline = Pipeline([
('features', FeatureUnion([
('text_pipeline', Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
... | e2017e5c99b0d2629393e045e0b50cf48f0bf5e9 | 3,618,948 |
import attr
def _get_field_default(field: attr.ib):
"""
Return a marshmallow default value given a dataclass default value
>>> @dataclass
... class A:
... x: int = attr.ib()
>>> _get_field_default(attr.fields(A).x)
<marshmallow.missing>
"""
if isinstance(field.default, attr.Fa... | 13ab7ac7edaa020b3bc32024def093d20e8f5d6e | 3,618,949 |
def str_to_vec(sequences):
"""converts nucleotide strings into vectors using a 2-bit encoding scheme."""
vecs = []
nuc2bit = {"A": (0, 0),
"C": (0, 1),
"T": (1, 0),
"G": (1, 1)}
for seq in sequences:
vec = []
for nuc in seq:
vec.ap... | 952e35253c275ef4424410b024338da1a11b20e7 | 3,618,950 |
import operator
def vector_add(a, b):
"""Component-wise addition of two vectors.
>>> vector_add((0, 1), (8, 9))
(8, 10)
"""
return tuple(map(operator.add, a, b)) | 2144a02128ffa8712cfb998045ede1ca9308650f | 3,618,951 |
def gen_fill_suffix_row(row, name_to_suffix_dict,
street_name_col, street_suffix_col,
suggested_name_col=None, suggested_suffix_col=None):
""" Returns a callable that suggests suffix based on row information
Args:
row: a row in DataFrame
name_to_su... | 388a801a88d8067a94dd9e8354a792713dad36df | 3,618,952 |
def from_angle(theta: float) -> Vector2:
"""
Create a unit vector from an angle relative to the positive x-axis.
"""
return Vector2(cos(theta), sin(theta)) | 35f510f4cdcaa05500ee27f7defc0c12d97d131a | 3,618,954 |
def neg(left):
"""
Negative of a distribution.
Args:
dist (Dist) : distribution.
"""
if not isinstance(left, Dist):
return -left
return Neg(left) | 5543ae8d3367fa9f92f3daba8855ae053dfdf234 | 3,618,955 |
import configparser
def initialize_from_tar(tar_path, is_full=False, clean_up=False):
"""Initialize from a remote TAR"""
# Step 1 is to unpack our TAR. Let's delete what was there first.
utils.delete_tree(dtfglobals.DTF_INCLUDED_DIR)
__unpack_included(tar_path)
# Next, we do the the auto config... | a0c8637a49212b4263bff905a7ba4b47a8896076 | 3,618,956 |
import json
def get_aws_key_and_secret(aws_creds_file_path):
""" Given a filename containing AWS credentials (see README.md),
return a 2-tuple (access key, secret key).
"""
with open(aws_creds_file_path, 'r') as f:
creds_dict = json.load(f)
return creds_dict['accessKeyId'], creds_dict[... | b3eae6ee0283a7245d37f92b5a5f4ef1102e248d | 3,618,957 |
def group_service(app):
"""Group service."""
return current_groups_service | cb484b9664bd21ca5706a085ba8e9cc2e002b72c | 3,618,958 |
import copy
def iterate(q, A_unrestrained, B, resp_a, resp_b, ihfree, symbols, toler, maxit, num_conformers):
"""Iterates the RESP fitting procedure
Parameters
----------
q : ndarray
array of initial charges
A_unrestrained : ndarray
array of unrestrained A matrix
B : ndarray
... | 3b477be0bdb0e8bcfd17404342f46f27a45839d2 | 3,618,959 |
import email
def get_filename(part):
"""
Find the filename of a mail part. Many MUA send attachments with the
filename in the I{name} parameter of the I{Content-type} header instead
of in the I{filename} parameter of the I{Content-Disposition} header.
@type part: inherit from email.mime.bas... | 638690299167e6025826372bdccfb207acdd788c | 3,618,960 |
def next_frame_stochastic_emily():
"""Emily's model."""
hparams = next_frame_stochastic()
hparams.latent_loss_multiplier = 1e-4
hparams.learning_rate_constant = 0.002
hparams.add_hparam("z_dim", 10)
hparams.add_hparam("g_dim", 128)
hparams.add_hparam("rnn_size", 256)
hparams.add_hparam("posterior_rnn_la... | 35cf839326ebfa5be3c0f6ef84d15537640441f4 | 3,618,961 |
import json
def test_get_vim_info(get_vim_info_keys):
"""Tests API call to get the information about individual vim"""
osm_admin = OSMClient.Admin(HOST_URL)
osm_auth = OSMClient.Auth(HOST_URL)
_token = json.loads(osm_auth.auth(username=USERNAME, password=PASSWORD))
_token = json.loads(_token["data... | 075eab419e614ec640a495f50d0ffc87abdb8b70 | 3,618,962 |
def twix2DCMOrientation(mapVBVDHdr, force_svs=False, verbose=False):
""" Convert twix orientation information to DICOM equivalent.
Convert orientation to DICOM imageOrientationPatient, imagePositionPatient,
pixelSpacing and sliceThickness field values.
Args:
mapVBVDHdr (dict): Header info inte... | b3346b399b8ed0b1f4066eaf8a3d71ca6c4991a7 | 3,618,963 |
def axial_mixture_unidir(x, config, is_training=True, causal=True):
"""Full attention matrix with axial pattern as local and mixture for global summary."""
del is_training
assert causal
bsize = x.shape[0]
query, key, value = attention.get_qkv(x, x, x, hidden_size=config.model_size,
... | 9ce028def7dc4e48585764333554ba7cb2cd55b9 | 3,618,964 |
def get_git_hash():
""" Return the current git hash """
repo = git.Repo(search_parent_directories=True)
return repo.head.object.hexsha | 7483ae16acb43dab1774c5b5a505f7ce95b4a9d1 | 3,618,965 |
import pickle
def _eval_once(session_creator, ops_dict, summary_writer, merged_summary,
global_step, num_examples, input_data, labels, unique_groups, fair_margin_over_epochs, FLAGS, config):
"""Runs evaluation on the full data and saves results.
Args:
session_creator: session creator.
ops_... | 4e60d450e4a11bf1e9ceb370c4d247c59709916b | 3,618,966 |
def project_ABA(A, B):
"""
Project matrix of K vectors, a_k, onto Hermitian matrix B
Projects each of K vectors, a_k, in matrix, A, of dimension K x M
onto a Hermitian matrix, B, of dimension M x M producing a
vector of scalars, c, of length K
Parameters
----------
... | 3ef84870ce3ac2a1a7cc62eccfc14024da585af1 | 3,618,967 |
def plcc_loss(x, y):
"""Loss version of `plcc_tf`"""
return (1. - plcc(x, y)) / 2. | f457389775d6d46ef55eeae97282c6c5c026458a | 3,618,968 |
def replicas_to_qps(num_replicas, processing_time, max_qp_replica=1, target_utilization=0.7):
"""Provide a rough estimate of the queries per second supported by a number of replicas
Args:
num_replicas (int): number of replicas
processing_time (float): the estimated amount of time (in secon... | a944ca4b6bbc60279c18360f396f2660be23f599 | 3,618,969 |
async def retrieve_address_by_id(
address_id: int, db: MSSQLConnection = Depends(get_db)
) -> AddressResponse:
"""
**Retrieves an address with the id from the `address_id` path parameter.**
"""
address = await AddressService(db).get(address_id)
if address is None:
raise HTTPException(sta... | 2c6d75ea860bfb67bcbec5e65af81e942104a661 | 3,618,970 |
from typing import Optional
def sqrt(x: VariableLike, *, out: Optional[VariableLike] = None) -> VariableLike:
"""Element-wise square-root.
:param x: Input data.
:param out: Optional output buffer.
:raises: If the dtype has no square-root, e.g., if it is a string.
:return: The square-root values o... | 216085ed06420f71cd7aaaff2db7d5272534920d | 3,618,971 |
def filter_tree(tree: pd.DataFrame, filterids: list or str or None = None,
root: str = "1", ignoreinvalid: bool = True, sep: str = None, indx: int = 0) -> pd.DataFrame:
"""
Filters an existing pandas DataFrame based on a List of TaxIDs.
:param tree: pandas DataFrame
:param filterids: li... | dfc542fbcc49dd75ecae6d35bf9f2462f2923ebd | 3,618,972 |
def multinomial_coeffs_of_power_of_nd_linear_monomial(num_vars, degree):
""" Compute the multinomial coefficients of the individual terms
obtained when taking the power of a linear polynomial
(without constant term).
Given a linear multivariate polynomial e.g.
e.g. (x1+x2+x3)**2 = x1**2+2*x1*x2+2*... | 05b402488616452c72445505aa07bae2bbf973ec | 3,618,973 |
def _get_split_rows(input_array, num_of_sections):
""" Split array by the number of valid cells (not NaNs) on each rows
input_array : an array with some NaNs
num_of_sections : (int) number of sections that the array to be splited
return split_rows : a list of row subscripts to split the array
Split ... | 1efe71bb83f97365fb0a6d5e09df726d0b0d2bcb | 3,618,974 |
def probability(df, features):
"""
Calculates the occurence probability of all the categories for every feature.
Parameters
----------
df : panda dataframe
the dataset of the population
features : dictionary
a dictionary of features with keys as feature name and val... | 7f46f2ec0fa69b22fea0a2b4a0e9ffc691630b1d | 3,618,975 |
from typing import Deque
import collections
import fractions
from typing import cast
def clip_to_timecodes(src_clip: vs.VideoNode) -> Deque[float]:
"""
Cached function to return a list of timecodes for vfr clips.
The first call to this function can be `very` expensive depending on the `src_clip`
leng... | b331e6de49a1fb768775c6559d1b18a3169d12b0 | 3,618,976 |
def numeric_map(lookup, numeric_stops, default=0.0):
"""Return a number value interpolated from given numeric_stops
"""
# if no numeric_stops, use default
if len(numeric_stops) == 0:
return default
# dictionary to lookup value from match-type numeric_stops
match_map = dict((x, y) fo... | 0f9868fb8e0e1036cd9581cbf3babe0f8ec86b43 | 3,618,977 |
import logging
def index():
"""
code and variables for when the page refreshes
"""
logging.info("Loading updated Website")
#calls the function which calls the functions which are needed to perform the tasks which the user specifies
manage_url()
#runs the scheduler
s.run(blo... | 2b3667b302f3e70467da7263ee3f78f5d4dfda84 | 3,618,978 |
def greedy_remove(text_before, guesses_before, n_keep):
"""Remove words from the question while trying to keep the original
predictions
Args:
text_before: the text before removal
guesses_before: a dictionary of scores of guesses as the starting point
n_keep: number of words to ke... | eef589ec7793c00473ff180574b809ce1df81eb8 | 3,618,979 |
def freq_id_to_stream_id(f_id):
""" Convert a frequency ID to a stream ID. """
pre_encode = (0, (f_id % 16), (f_id // 16), (f_id // 256))
stream_id = (
(pre_encode[0] & 0xF)
+ ((pre_encode[1] & 0xF) << 4)
+ ((pre_encode[2] & 0xF) << 8)
+ ((pre_encode[3] & 0xF) << 12)
)
... | f89d52adf4390f665e069c2b5f4f5accc22709b8 | 3,618,982 |
def paypal_cancel(request):
""" Render paypal_cancel.html template when the user click cancel during a purchase process in PayPal."""
args = {'post': request.POST, 'get': request.GET}
return render(request, 'paypal/paypal_cancel.html', args) | 869a011f3e58385dfd1dc78b5319e63df3e0a940 | 3,618,983 |
def contourf(x, y, z, xlabel='x', ylabel='y', xlim=None, ylim=None,
legend=None, **kwargs):
"""Plots a filled countour plot of z vs. x and y in a single frame."""
fig, ax = plt.subplots()
lvls = np.linspace(np.min(z), np.max(z), 150)
l1 = ax.contourf(x, y, z, levels=lvls, zorder=-9, **kwarg... | 52f300cf044bb170d9a20f36d512f9d8e01e7875 | 3,618,984 |
def convolve2d(imagee, kernell):
"""
This function which takes an image and a kernel and returns the convolution of them.
:param image: a numpy array of size [image_height, image_width].
:param kernel: a numpy array of size [kernel_height, kernel_width].
:return: a numpy array of size [image_heigh... | c24fd944d19336ebb2ac6094ac6123e5c416eb5a | 3,618,985 |
def text_format(text: str, text_size: int, text_color: tuple, text_font_location: str = font):
"""Template for creating text in pygame. Reformation of the size and color
Parameters:
text (str): The input text to be formatted
text_size (int): The text size of the formatted text
text_colo... | 7ffd56953967304f42925d37317a1b30bb5ef907 | 3,618,986 |
import math
def _weight_fn(x, weight=None, inverse=False):
"""
Implement the polynomial weight function described in the paper.
Y = X^weight and
Y = X^(1 / weight) as the inverse.
>>> _weight_fn(2)
2.2973967099940698
>>> _weight_fn(2, weight=2)
4.0
>>> _weight_fn(2, weight=2, inv... | 36b342e209b7805c164b0d9a6f450b70c807bfc6 | 3,618,987 |
from typing import Counter
def id_to_name(transcription, mapping={}, composed=False):
"""Takes transcription annotated with entities and updates/outputs a dict mapping
entity identifier and counted proper names
"""
for i, token in enumerate(transcription):
# keep only proper names
if p... | 125b0c1aaeb251023d4e0a7c438aee7842ba0b46 | 3,618,988 |
def cgtransformation_to_rgtransform(cgT):
# type: (compas.geometry.Transformation) -> Rhino.Geometry.Transform
"""Convert :class:`compas.geometry.Transformation` to :class:`Rhino.Geometry.Transform`.""" # noqa: E501
_ensure_rhino()
M = cgT.matrix
return matrix_to_rgtransform(M) | 6000f87064030ccbe35c7ea74509c63af4bfb745 | 3,618,990 |
def fadein(clip, duration, initial_color=None):
"""
Makes the clip progressively appear from some color (black by default),
over ``duration`` seconds at the beginning of the clip. Can be used for
masks too, where the initial color must be a number between 0 and 1.
For cross-fading (progressive appea... | 3b17b1090a7fa1bab789d6da7d9ac862d099e88a | 3,618,991 |
def count_occupied_fields(window, player):
"""" Count number of occupied fields by 'player' in 'window'. """
count = np.count_nonzero(window == player)
return 0 if count is None else count | 68d6a7216292638d919a7c121821050cadf8c610 | 3,618,993 |
def covariance(x):
"""Compute array covariance matrix.
:param x: narrowband complex timeseries data for multiple sensors (row per sensor)
"""
cov_mtx = _np.zeros((x.shape[0], x.shape[0]), dtype=_np.complex)
for j in range(x.shape[1]):
cov_mtx += _np.outer(x[:,j], x[:,j].conj())
cov_mtx ... | 9a91875f694dba23c2f06341b878991f1a2528eb | 3,618,994 |
def fix_trimap(trimap, lower_threshold=0.1, upper_threshold=0.9):
"""Fixes broken trimap :math:`T` by thresholding the values
.. math::
T^{\\text{fixed}}_{ij}=
\\begin{cases}
0,&\\text{if } T_{ij}<\\text{lower_threshold}\\\\
1,&\\text{if }T_{ij}>\\text{upper_threshold}\\... | 2d6ab770d9bedc1cb9ba5cc6fe2b51ce0bcff28d | 3,618,995 |
import random
def get_hash_tags(sentence, be_class_verb, subj_obj_list, seed=0, max_outputs=1, nlp=None):
"""method for appending hashtags to sentence"""
verb, hashtag_list = extract_hashtags(sentence, nlp, be_class_verb, subj_obj_list)
transformation_list = []
for _ in range(max_outputs):
ran... | f39f8041b7693a451f8aefb1aa65f72154413cb2 | 3,618,996 |
def get_tune(tune):
"""
Convert a tune value to a frequency.
"""
if isinstance(tune,str):
try:
tune = _TUNE_A * 2.**(_NOTES[tune]/12.)
except KeyError as e:
raise ValueError("If `tune` is provided as a string, it has to be any of "+str(list(_NOTES.keys())))
... | f78b4fecb7ce90a8288931466ecd66f1f7583f1c | 3,618,997 |
def aspheric_surface_equation(r, d, k, radius_of_curvature):
"""
Representation of the aspheric surface function.
"""
l = np.sqrt((radius_of_curvature * radius_of_curvature) - ((1 + k) * np.multiply(r, r)))
num = np.multiply(r, r)
den = radius_of_curvature + l
z = num / den + d
return ... | 5f598f7c45a994c0d29ce4c4be58aa3a2fd11fc5 | 3,618,998 |
import doctest
from crds.core import utils
def test():
"""Run doctests."""
return doctest.testmod(utils) | 09409cae8aa5708907b177a455a66df6a94c6c77 | 3,618,999 |
def get_matcher(obj):
"""Return an object suitable for comparing against other objects
using the "==" operator.
If special comparison handling is implemented, a MatcherObject or
MatcherTuple will be returned. If the object is already suitable
for this purpose, the original object will be returned u... | c0ac74d0ec43c974c17080a35eaeaeaefffaeb07 | 3,619,001 |
def _ns(tag, namespace=NAMESPACES['phy']):
"""Format an XML tag with the given namespace (PRIVATE)."""
return '{%s}%s' % (namespace, tag) | 2724c1af73b78b4cb8e8fb27205c8d0a257a79f1 | 3,619,002 |
from typing import Union
def get(key: str, locale: str = config.get('locale')) -> Union[dict, list, str]:
"""Get the translation corresponding to that key and language"""
return container[locale][key] | 66699e3c4016775ad4712da86398a6324d775da3 | 3,619,004 |
import dateutil.parser
def get_entry_end_date(e):
"""Returns end date for entry"""
return dateutil.parser.parse(e['time_end']) | a9b8bdae873de0ef97de49e342cd4f3bbd8117f6 | 3,619,005 |
def remove_stripe_based_sorting(sinogram, size, dim=1):
"""
Algorithm 3 in the paper. Remove stripes using the sorting technique.
Work particularly well for removing partial stripes.
Angular direction is along the axis 0.
Parameters
----------
sinogram : float
2D array
size : in... | e47a8ea1c4b62262301f6066814af892b3a03626 | 3,619,006 |
def index(request):
"""Chat index page."""
return HttpResponse("Testing") | d3d2db1e11e443ad32119431a6cc9b201a051b1d | 3,619,007 |
from typing import Dict
def compress_counts(
counts: Dict[StateTuple, float], tol: float = 1e-6, round_to_int: bool = False
) -> CountsDict:
"""Filter counts to remove states that have a count value (which can be a
floating-point number) below a tolerance, and optionally round to an
integer.
:par... | fd9d8865ba864ed8155ef9317d01ab0636a491bc | 3,619,008 |
import torch
from typing import Optional
def allreduce_nonblocking(tensor: torch.Tensor, average: bool = True,
is_hierarchical_local=False, name: Optional[str] = None) -> int:
"""
A function that performs nonblocking averaging or summation of the input tensor
over all the Bluefog... | 9d87df05da876d8567105309532c1e33f1c3a4e4 | 3,619,009 |
def _streaming_false_negatives(predictions, labels, weights=None,
metrics_collections=None,
updates_collections=None,
name=None):
"""Computes the total number of false positives.
If `weights` is `None`, weights default to ... | d582f4f6169de573a8989eebe5c7619ac476eec9 | 3,619,010 |
def getOneFilter(psi, count, scale, mode):
""" Methdod used to visualize one filter
parameters:
psi -- dictionnary that contains all the wavelet filters
count -- key to identify one wavelet filter in the psi dictionnary
scale -- scattering scale
mode -- mode between fouri... | dc833c40fb64fddf4172ecb485ace1de4d44d221 | 3,619,012 |
from pathlib import Path
def get_launch_agents_dir() -> Path:
"""Returns user LaunchAgents directory."""
launch_agents_dir = Path.home() / "Library" / "LaunchAgents"
assert launch_agents_dir.is_dir()
return launch_agents_dir | d11bc00c986bd5440549e71fdae9ed1f98f18d21 | 3,619,013 |
def sample_categorical_crossentropy(y_true,
y_pred,
class_weights=None,
axis=None,
from_logits=False):
"""Categorical crossentropy between an output tensor and a target ten... | b5d430494b46b9e84fb429f260f6b759361fe858 | 3,619,014 |
from typing import Callable
def ope(actual_series: TimeSeries,
pred_series: TimeSeries,
intersect: bool = True,
reduction: Callable[[np.ndarray], float] = np.mean) -> float:
""" Overall Percentage Error (OPE).
Given a time series of actual values :math:`y_t` and a time series of predi... | 2b99e9e3cd9d44519be22c901909effc9468d50b | 3,619,015 |
def build_constraint_matrix(cons, d):
"""
Build constraint matrix.
The constraint matrix is a matrix P that is the vertical stack
of all the preserved marginals.
Parameters
----------
cons : iter of iter
List of variable indices to preserve.
d : dit.Distribution
Distrib... | 53d5d015ecbad46381c6337bf2d87a608a949153 | 3,619,016 |
import random
def randomStrategy(G, k, l, randomSeed=None):
"""
title::
randomStrategy
description::
Generate random initial strategy. See compare_heuristic_script.py
for example use.
attributes::
G
Graph object (networkx)
k
Number of ... | 2479224d5f67fe02bb8f4740b74c99c3ad89c936 | 3,619,017 |
def eddy_loss(i, t=0.31*1e-6, w=4.29*1e-6, f=50, I_c=115):
"""
:param t: thickness of the conductor
:param w: width of the conductor
:param f: Hz
:param Ic: A
:return:
"""
return 4*mu_0**2./pi*t*w*f**2/C_RHO*I_c**2 | 6aadaa2189fb467c0c23b550a0930a3fbdc73021 | 3,619,018 |
import random
def get_hashtag() -> str:
"""
Create string with special and random hashtags
"""
hash_tags = ""
for item in SPECIALHASHTAGS:
hash_tags += " " + item
hash_tags += " " + random.choice(HASHTAGS)
return hash_tags | 5c25a021701bc8307be805d2872bbc9e581b9277 | 3,619,019 |
def count_pos_BAM(rw, path_bam_tumoral, path_bam_normal):
"""
Adds read counts of dinucleotide positions calling another function that runs samtools
:param rw: row with the variant info
:param path_bam_tumoral: path to the tumoral BAM
:param path_bam_normal: path to the normal BAM
:return: row ... | a732124c796528445b149d58c50f32dba37612ff | 3,619,020 |
import pandas
def find_centers_of_ordered_list(ls):
"""
to find label positions for plotting.
ls must be ordered!
"""
uniqs = pandas.unique(ls)
positions = []
for u in uniqs:
idxs = [] # list of indices of corresponding values
for index, elements in enumerate(ls):
... | 4ecfceeddb1017bbd88ac79531b1c099b76d557d | 3,619,021 |
import aiohttp
async def get_url(bot, urls, headers={}, read_response=True, get_bytes=False):
"""Uses aiohttp to asynchronously get a url response, or multiple."""
async def fetch(url, read_method='text'):
if not url: # Why
return (None, None)
async with session.get(str(url)) as ... | 70e2a5c67623db0f4b53d1acac6e11da7cd797d4 | 3,619,022 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.