content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def attrdict(d: dict) -> AttrDict:
"""Add attribute access to a dict.
This function takes a dict with nested dicts as input and convert into an AttrDict
object which allows attribute access to keys.
Returns:
A dict-like object with attribute access to keys.
"""
def addattrs(d):
... | c4d8a102ff3bab5fb75b76fb08f4040248c48053 | 24,107 |
def form(cik, year):
"""Returns form 13F for specified CIK number. From https://fmpcloud.io/documentation#thirteenForm
Input:
cik : CIK number for which you'd like the 13F form
year = year for which you'd like the 13F form.
Returns:
Form 13F for specified company
""" ... | e5bcc58251456f15ba31f6b468b6aa934fddc7f1 | 24,108 |
def check_bel_script_line_by_line(bel_script_path, error_report_file_path, bel_version):
"""Check statements in file or string for correct.
result['trees'][line_number] = {'statement': statement, 'tree': tree}
result['errors'][line_number] = {'statement': statement, 'error': ex}
# can be used as comme... | 5502c0ef9adbcde9fe6feb50aeee51c1600fd5a8 | 24,109 |
def create(cls, **data):
"""Create a single instance of a Resource.
Arguments:
cls (Resource class): The resource to create.
All other keyword arguments will be provided to the request
when POSTing. For example::
create(Foo, name="bar", email="baz@foo.com")
...would try to create... | 6dd5f76446974c4e9f37422bf1f7036a099bd576 | 24,110 |
def get_cluster_role_template_binding(cluster_id=None,name=None,role_template_id=None,opts=None):
"""
Use this data source to retrieve information about a Rancher v2 cluster role template binding.
> This content is derived from https://github.com/terraform-providers/terraform-provider-rancher2/blob/master/... | 3e84ac201e141c28549d44fff609897afb1fbb73 | 24,112 |
def np_where(cond, x, y):
"""
Wrap np.where() to allow for keyword arguments
"""
return np.where(cond, x, y) | 32627e5e38625148c0193d74b04390098be1d631 | 24,113 |
def score_feedback_comp_micro_shujun(pred_df, gt_df, discourse_type):
"""
A function that scores for the kaggle
Student Writing Competition
Uses the steps in the evaluation page here:
https://www.kaggle.com/c/feedback-prize-2021/overview/evaluation
"""
gt_df = gt_df.loc[gt_df['disco... | 24854d61ac5afa701c89a1382ade52df8dd53714 | 24,114 |
def _url_for_language_resolve_view(url, new_language):
"""
Figure out the new URL by resolving the old URL and re-reversing it using
the new language.
"""
view = urlresolvers.resolve(url)
with language_context(new_language):
new_url = urlresolvers.reverse(view.url_name, args=view.args, k... | 8cbf1d5c7be7bf782d1dc1206f0e3075c022c4ad | 24,115 |
def rsp_matrix(m,k):
"""
Description: This function creates the matrix used for finding the parameters of reals signal perceptron using a system of linear equations
is_Implemented:
True
Args:
(m:int): The domain size , the amount of possible variables that each variable can take
... | 00d327b5f3a1726337a90d31955d37fc3b2c1e5f | 24,116 |
import json
def pretty_format_dict(dct):
"""
Parameters
----------
dct: dict[Any, Any]
Returns
-------
str
"""
return "{}".format(json.dumps(dct, indent=4)) | 60d9c09da62d7035bd89a6fb52e6f0a1f142f89e | 24,117 |
def session_try_readonly(dbtype, dbfile, echo=False):
"""Creates a read-only session to an SQLite database.
If read-only sessions are not supported by the underlying sqlite3 python DB
driver, then a normal session is returned. A warning is emitted in case the
underlying filesystem does not support locking prop... | 2be571a27e3f876e5961557d776448104cb9246b | 24,120 |
def generate_lab_saliva(directory, file_date, records):
"""
Generate lab saliva file.
"""
lab_saliva_description = (
lambda: {
'ORDPATNAME': _('random.custom_code', mask='SIS########', digit='#'),
'SAMPLEID': _('random.custom_code', mask='H#########', digit='#'),
... | bc8b81e9a83cbe8f4ac3d23ff272172d3424f459 | 24,121 |
def rebuild_field_path(sort_field, resource):
"""
convert dot connected fields into a valid field reference
:param sort_field:
:return: path_to_field
"""
sorted = strip_sort_indicator(sort_field)
split_sorted = sorted.split()
sort_with_this = ""
for s in split_sorted:
if s... | 98bdc18b2147babc35119ba6c61ec1dd3e32ccd8 | 24,123 |
def load_data(pkl_paths, use_attr, no_img, batch_size, uncertain_label=False, n_class_attr=2, image_dir='images', resampling=False, resol=299):
"""
Note: Inception needs (299,299,3) images with inputs scaled between -1 and 1
Loads data with transformations applied, and upsample the minority class if there i... | 79e6d5cfa8cd7a8204fcef102585f25b3d4f0442 | 24,124 |
def scalar_function(x, y):
"""
Returns the f(x,y) defined in the problem statement.
"""
#Your code here
if x <= y:
out = x*y
else:
out = x/y
return out
raise NotImplementedError | f305a5f2680dbebda9322a6fbd17f7dc3ce8a072 | 24,125 |
def getImageParticles(imagedata,stackid,noDie=True):
"""
Provided a Stack Id & imagedata, to find particles
"""
particleq = appiondata.ApParticleData(image=imagedata)
stackpdata = appiondata.ApStackParticleData()
stackpdata['particle'] = particleq
stackpdata['stack'] = appiondata.ApStackData.direct_query(stacki... | 4764b25c7830ae58023b7bc0ac9d148844604e50 | 24,126 |
import json
def build_evaluation(
resource_id,
compliance_type,
event,
resource_type=DEFAULT_RESOURCE_TYPE,
annotation=None,
):
"""Form an evaluation as a dictionary. Usually suited to report on scheduled rules.
Keyword arguments:
resource_id -- the unique id of the resource to report
... | d814e8f0d965cc36b40c0b33efbce043d43ef098 | 24,127 |
def match_countries(df_to_match, olympics):
"""Changes the names of the countries in the df_to_match df so that they match
the names of the countries in the olympics df.
Parameters
-----------
df_to_match : either of the two dataframes:
- gdp
- pop
olympics ... | 256eaac81daee5c621e7dac4c8c27d0b96868418 | 24,128 |
import requests
import logging
def get_reply(session, url, post=False, data=None, headers=None, quiet=False):
"""
Download an HTML page using the requests session. Low-level function
that allows for flexible request configuration.
@param session: Requests session.
@type session: requests.Session
... | 4baa985db090d0f88762c8f6cfadff084f2b88ad | 24,129 |
def get_stock_rack_size():
"""
Returns the number of available positions in a stock rack.
"""
return get_stock_rack_shape().size | d41361ae2817e6b6de78b2ae6e2f7b7765c3bfcd | 24,130 |
def is_valid_constant_type(x):
"""
@return: True if the name is a legal constant type. Only simple types are allowed.
@rtype: bool
"""
return x in PRIMITIVE_TYPES | 373a4c5d5a35e250ed19c06fc3ae0b6d30f8ec7a | 24,131 |
import torch
def logsumexp(tensor: torch.Tensor, dim: int = -1, keepdim: bool = False) -> torch.Tensor:
"""
A numerically stable computation of logsumexp.
This is mathematically equivalent to `tensor.exp().sum(dim, keep=keepdim).log()`.
This function is typically used for summing log probabilities.
... | 2bcbf60369e359daa7bc5aaaceef45f753fd4f00 | 24,132 |
def shrink_piecwise_linear(r,rvar,theta):
"""Implement the piecewise linear shrinkage function.
With minor modifications and variance normalization.
theta[...,0] : abscissa of first vertex, scaled by sqrt(rvar)
theta[...,1] : abscissa of second vertex, scaled by sqrt(rvar)
theta[...,... | b47690d151dcfac2104c58637628aa78fbeb7d63 | 24,133 |
def LoadAuth(decoratee):
"""Decorator to check if the auth is valid and loads auth if not."""
@wraps(decoratee)
def _decorated(self, *args, **kwargs):
if self.auth is None: # Initialize auth if needed.
self.auth = GoogleAuth()
if self.auth.access_token_expired:
self.auth.LocalWebserverAuth()
... | 87097fc527ee47af3a91a904881bc62e46181754 | 24,134 |
def cols_with_nulls(df):
""" Convert whitespace entries to NaN, Return columns with NaN
"""
# Note: Empty string will be converted to NaN automatically,
df.replace(r'^\s*$', np.nan, regex=True, inplace=True)
return list(df.isnull().any().index) | 5c7121c920c4db09f78d648a271337bf45e7f994 | 24,135 |
def recursive_feature_selection_roc_auc(clf,
X,
y,
sample_weight=None,
n_features=10,
cv_steps=10,
... | 49073354f5f4292716fccdcaa33ec423da18c7d9 | 24,136 |
def mermin_klyshko_quantum_bound(n):
"""The quantum bound for the Mermin-Klyshko inequality is :math:`2^{3(n-1)/2}`.
:param n: The number of measurement nodes.
:type n: Int
:returns: The quantum bound.
:rtype: Float
"""
return 2 ** (3 * (n - 1) / 2) | 721ca41b19ef72cae77baf1ad6dea5377b6eb67d | 24,137 |
def get_serial_port_selected():
"""Get the selected serial port from the Settings.
:return: The currently selected serial port in the Settings.
"""
return ServerCompilerSettings().serial_port | 03273c1e522a7699c7fdbd1522367f9f08a42b9f | 24,138 |
import platform
def main(args):
"""Produce library bundle"""
if platform.system() == "Darwin":
res = gen_archive_darwin(args.output, args.libs)
else:
ar_script = gen_archive_script(
args.output, [expand_path(lpath) for lpath in args.libs]
)
res = gen_archive(ar... | 029f4eacabcd881827ec89dc76025b889116d02b | 24,139 |
def run_in_background(func: callable, *args, **kwargs) -> Future:
""" run func(*args, **kwargs) in background and return Future for its outputs """
return GLOBAL_EXECUTOR.submit(func, *args, **kwargs) | 1ef74344e63b508eb31a3ccc3cbd80e7ba2f5c4a | 24,140 |
from typing import Union
def get_eigenvectors(
q,
dm: Union[DynamicalMatrix, DynamicalMatrixNAC],
ddm: DerivativeOfDynamicalMatrix,
perturbation=None,
derivative_order=None,
nac_q_direction=None,
):
"""Return degenerated eigenvalues and rotated eigenvalues."""
if nac_q_direction is not... | 8f869f00df9666dc4d343ffd030db93634e42a5a | 24,141 |
def _get_formatted_atom_types_names_for(connection):
"""Return formatted atom_type names for a connection."""
names = []
for member in connection.connection_members:
if not member.atom_type:
label = ""
else:
label = member.atom_type.name
names.append(label)
... | b9b21cb37706aa05f7807df1c252985f09fe6fad | 24,142 |
def anti_commutator(H1,H2):
""" Calculates the anticommutator of two Hamiltonians :math:`H_1` and :math:`H_2`.
.. math::
\\{H_1,H_2\\}_+ = H_1 H_2 + H_2 H_1
Examples
--------
The following script shows how to compute the anticommutator of two `hamiltonian` objects.
.. literalinclude:: ../../doc_examples/ant... | 78f3adf2b9e7934a2a84b1ea6611ce615be7b013 | 24,143 |
def download(self, auth=False):
"""
needs source url (from webs ite) and destination save location
"""
source_url = 'http://www.spitzer.caltech.edu/uploaded_files/images/0006/3034/ssc2008-11a12_Huge.jpg'
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) C... | ded4cbef19c4c498793006af9044ca2fb504a287 | 24,144 |
def windowed_dataset(dataset, size, shift=None, stride=1, drop_remainder=True):
"""Create a windowed `Dataset`.
Arguments:
dataset: A `Dataset` of output shape ((...), (...), ... (...)) or a `dict`
of the same.
size: A `tf.int64` scalar `tf.Tensor`, representing the n... | 0e7fd8a4ba603e54e63622d5609fea7d6bddfceb | 24,145 |
def dnds(seq1, seq2):
"""Main function to calculate dN/dS between two DNA sequences per Nei &
Gojobori 1986. This includes the per site conversion adapted from Jukes &
Cantor 1967.
"""
# Strip any whitespace from both strings
seq1 = clean_sequence(seq1)
seq2 = clean_sequence(seq2)
# Chec... | e3631efb181fc390d8ca47b64c54d03bc3924a98 | 24,146 |
def create_LED_indicator_rect(**kwargs) -> QPushButton:
"""
False: dim red
True : green
"""
# fmt: off
SS = (
"QPushButton {"
"background-color: " + COLOR_INDIAN_RED_2 + ";"
"color: black;"
"border: 1px solid black;"
"border-radius: 0px;"
... | 6d1727bfa7afbf26a92f49d51e0888f104b6b0c0 | 24,147 |
def bind(task):
"""Bind a task method for use in a pipeline
This decorator method adapts a task method to work
in a pipeline. Specifically, it routes successful
Result input to the task logic, and passes through
failure Result input without performing any
additional actions.
Args:
... | 8353c22239b92b86f144d9f449c425016f1b037d | 24,148 |
def optimal_kernel_bandwidth(spiketimes, times=None, bandwidth=None,
bootstrap=False):
"""
Calculates optimal fixed kernel bandwidth, given as the standard deviation
sigma.
Parameters
----------
spiketimes : np.ndarray
Sequence of spike times (sorted to be a... | 0613665f9365c95330e766cdbf95557ef94c4d08 | 24,149 |
import logging
import time
def run_lsh_omp_coder(data, dictionary, sparsity, num_buckets=1):
"""Solve the orthogonal matching pursuit problem with LSH bucketing.
Use sklearn.linear_model.orthogonal_mp to solve the following optimization
program:
argmin ||y - X*gamma||^2,
subject to ||gamma||_0 ... | 597930ec0c7da4ea4699d087ab89ebe7cd11143f | 24,150 |
def hamming_options(seq1, seq2):
"""Calculate Hamming distance between two sequences.
Interpret ambiguity as options.
"""
sequence1 = convert_to_nosegment(seq1)
sequence2 = convert_to_nosegment(seq2)
distance = 0
for i, segment1 in enumerate(sequence1.segments):
segment2 = sequenc... | db8379961ebe37e5490b7622bb3162faf5388eda | 24,151 |
from typing import Tuple
import struct
def __getgyro_decoder__(port: serial.Serial, *args, **kwargs) -> Tuple[int, int, int]:
"""
Reads the gyro state from the serial port and decodes it as a (x, y, z) tuple.
"""
val = port.read(8)
if(val[7] != 0xAA):
raise Exception("Updating configuratio... | 3e77e550b79dceac22d806c9f0cdf9bdedbb2b3b | 24,152 |
def spatial_knn(coords, expression, n_neighbors=14, n_sp_neighbors=7, radius=None,
which_exprs_dims=None, sample_id=None):
"""
A variant on the standard knn neighbor graph inference procedure that also includes the spatial neighbors of each spot.
With help from Krzysztof Polanski.
:para... | 0ed0052890b8ae5925d39bb001dedff47d824677 | 24,153 |
def parse_q(s):
"""Parse the value of query string q (?q=) into a search sub-term."""
if '=' not in s:
names = s.split()
term = '/'.join(map(lambda x: 'n.name=' + x, names))
return term
else:
subterms = s.split()
res = []
for subterm in subterms:
i... | eae907fcb42be4a2c4be26316721ea63aa0284d6 | 24,154 |
def getCompleteData(client , response ,comp):
"""
This function is useful to receive missing data in tcp packet
Input :
Client = Tcp Object which interact with host end and client
response = received response from the host end
comp = comparitive struct defined by... | 0f3ff5785046771f295a65116e0f79b5c7e45525 | 24,155 |
from sage.rings import sum_of_squares
from sage.rings.finite_rings.integer_mod import Mod
def two_squares(n):
"""
Write the integer `n` as a sum of two integer squares if possible;
otherwise raise a ``ValueError``.
INPUT:
- ``n`` -- an integer
OUTPUT: a tuple `(a,b)` of non-negative integer... | d07edc88a6b4c264c3df910cdbcdd80ce93320ff | 24,156 |
def getattr_by_path(obj, attr, *default):
"""Like getattr(), but can go down a hierarchy like 'attr.subattr'"""
value = obj
for part in attr.split('.'):
if not hasattr(value, part) and len(default):
return default[0]
value = getattr(value, part)
if callable(value):
... | 3eccbb39e1781a75a6f0061c1c226cefdcfb17c8 | 24,157 |
def entries_to_files(entry_ids):
"""
Format file details (retrieved using the files' entry IDs) to API expectations to include files in API call.
parameter: (list) entry_ids
List of entry ID strings for files uploaded to the warroom
returns:
List of attachment field, value tuples forma... | da21da1f9068c55738b029e190e6206e63373a03 | 24,158 |
def g_mult(a, b, p):
"""Multiply two polynomials given the irreducible polynomial of a GF"""
c = [i % 2 for i in mult(a, b)]
c, p = lenshift(c, p)
return div(c, p) | f1fc9fe52381faaaf23b4fa3d4767aad1bf07d35 | 24,159 |
def data_augmentation_fn(input_image: tf.Tensor, label_image: tf.Tensor, flip_lr: bool=True,
flip_ud: bool=True, color: bool=True) -> (tf.Tensor, tf.Tensor):
"""Applies data augmentation to both images and label images.
Includes left-right flip, up-down flip and color change.
:para... | 512be3bb3bcce8e493aa930a0d76dc7232e372b8 | 24,160 |
def get_stack_value(stack, key):
"""Get metadata value from a cloudformation stack."""
for output in stack.outputs:
if output['OutputKey'] == key:
return output['OutputValue'] | a6b193c7d884bac78668dfd85bc2a5cbbb6b3f3b | 24,161 |
def cmd_example_cmd_as_module(mixcli: MixCli, **kwargs):
"""
This function would be called by the processing of ArgumentParser. The contract is the positional argument
would be a MixCli instance and the rest are passed as keyword arguments.
We recommend to name this function as cmd_<name_of_group>_<name... | 5e1450997fa439ae83c102d6ad80e903f47112fb | 24,162 |
def display_credentials(user_name):
"""
Function to display saved account credentials
"""
return Credentials.display_credentials(user_name) | 7f260b5a38847dcef0d50f5723f72044b77b824f | 24,163 |
import tqdm
def sk_learn_bootstrap(x, y, z, design_matrix, kf_reg, N_bs=100,
test_percent=0.4, print_results=True):
"""Sci-kit learn bootstrap method."""
x_train, x_test, y_train, y_test = sk_modsel.train_test_split(
np.c_[x.ravel(), y.ravel()], z.ravel(),
test_size=tes... | 38a22f6fdb2858efdf720f87c573dd7684b33000 | 24,165 |
def vAdd(v, w):
""" Return a new Vector, which is the result of v + w """
return Vector(v[0] + w[0], v[1] + w[1], v[2] + w[2]) | 9f8dcc6026093164f39479a02252dbab035bbde9 | 24,166 |
def dynamic_vm_values(trace, code_start=BADADDR, code_end=BADADDR, silent=False):
"""
Find the virtual machine context necessary for an automated static analysis.
code_start = the bytecode start -> often the param for vm_func and usually starts right after vm_func
code_end = the bytecode end -> bytecode... | f970275ad4a2df59f81fb1bbd1f80149e92a9faf | 24,167 |
def getAddresses(pkt):
"""
0: ('dst', 'src', 'bssid', None), from sta to sta
1: ('dst', 'bssid', 'src', None), out of ds
2: ('bssid', 'src', 'dst', None), in ds
3: ('recv', 'transl', 'dst', 'src') between dss
"""
f = pkt.FCfield & 3 # to-DS and from-DS
if f == 0:... | 39056a61992b4dce8d8e5f28e3d274526f940787 | 24,168 |
def _ldmodule_soversion(target, source, env, for_signature):
"""Function to determine what to use for SOVERSION"""
if 'SOVERSION' in env:
return '.$SOVERSION'
elif 'LDMODULEVERSION' in env:
ldmod_version = env.subst('$LDMODULEVERSION')
# We use only the most significant digit of LDM... | 21d84d9ed8bc4a186d4619b51318c4a2bd780adb | 24,169 |
def jitter(
grid: Grid,
min_variance: int = None,
max_variance: int = None,
size: int = None,
clamp: bool = False,
variance_list: list[int] = None,
) -> Grid:
"""Randomly jitter all points in a grid
Jitter will apply to both the x and y axises of the grid
If a variance list is given... | 968c601f4c9b3b214fb2c8444e2ea252a40e75a7 | 24,170 |
import re
def loadFasta(fa, sep=None, term=None, nfilter=None):
"""Returns a kapow.Array() with the contents of the file interpreted as a FASTA file, using sep if given."""
def _boundary2int(num, n, start=False):
if num == '': return 0 if start else n
mult = 1
if num[-1] == 'K': mult = 1000
elif num[-1] == ... | 982fa20121c089ed92e83f31590ad5313f6cda00 | 24,171 |
def reverse_bits(counter) -> int:
"""
Reverses the order of the bits in the given counter
:param counter: a 7bit value
:return:
"""
# From Elephant reference code (elephant160v2 > spongent.c > retnuoCl)
return ((counter & 0x01) << 7) | ((counter & 0x02) << 5) | ((counter & 0x04) << 3) \
... | 290f62d794e5d17c4b277a714151523835bc6c16 | 24,172 |
import requests
def check_quota():
"""
Check quota for the RANDOM.ORG API
:return: True if the request is successful AND there is remaining quota available
"""
resp = requests.request('GET', 'https://www.random.org/quota/?format=plain')
if resp.status_code != 200 or int(resp.text) <= 0:
... | ba882714a17dc70fcdc45de5695b139d4e766fbc | 24,173 |
def idwt2d(input_node, wavelet, levels=1):
"""
Constructs a TF graph that computes the 2D inverse DWT for a given wavelet.
Args:
input_node (tf.placeholder): Input signal. A 3D tensor with dimensions
as [rows, cols, channels]
wave... | e75e5b656216475d3148e3ffabb53cba1a509f82 | 24,174 |
def readin_rho(filename, rhofile=True, aniso=False):
"""Read in the values of the resistivity in Ohmm.
The format is variable: rho-file or mag-file.
"""
if aniso:
a = [[0, 1, 2], [2, 3, 4]]
else:
a = [0, 2]
if rhofile:
if filename is None:
filename = 'rho/rho.... | fb6a602ca2f3218b1feac755adf818f6b019894e | 24,175 |
from typing import Dict
def cofense_report_image_download_command(client: Client, args: Dict[str, str]) -> dict:
"""
Downloads the image for a specific report.
:type client: ``Client``
:param client: Client object to be used.
:type args: ``Dict[str, str]``
:param args: The command arguments ... | 3d1d13697a183f612e4b445e201b9abc620f82c8 | 24,176 |
def random_indices(batch_size, num_samples):
"""\
Generate a random sequence of indices for a batch.
:param batch_size: length of the random sequence to generate
:param num_samples: number of samples available, i.e., maximum value to
include in the random sequence + 1
:return: list of integer... | 027a4f964efa2741cdbec0f4c20cd8f873cdc420 | 24,177 |
def diff_first_last(L, *opArg):
"""
(list) -> boolean
Precondition: len(L) >= 2
Returns True if the first item of the list is different from the last; else returns False.
>>> diff_first_last([3, 4, 2, 8, 3])
False
>>> diff_first_last(['apple', 'banana', 'pear'])
True
>>> diff_first... | 30d6afe76c4fdf759d4a989a5c9cc8b4eb8c62c1 | 24,178 |
import time
def update_on_table(df: pd.DataFrame, keys: update_key_type, values: update_key_type, table_name: str,
engine: sa.engine.base.Engine, schema: str) -> int:
"""
:param df: a dataframe with data tha needs to be updated. Must have columns to be used as key and some for values
... | 661f07ab08a10119a8d018dcd652ca972b2385e5 | 24,179 |
def administrar_investigaciones(request,tipo):
"""Administrar investigaciones seleccionadas, para ser eliminadas o finalizadas"""
if request.method == 'POST':
ids = request.POST.getlist('checks[]')
if tipo == "incorrecto":
#Se han seleccionado investigaciones para ser finalizadas inc... | d2b5f02e051a51fe7993680e9015da77847e3f37 | 24,180 |
def container_images_prepare_defaults():
"""Return default dict for prepare substitutions
This can be used as the mapping_args argument to the
container_images_prepare function to get the same result as not specifying
any mapping_args.
"""
return KollaImageBuilder.container_images_template_inpu... | 511eed4f0582476264387dc875b2d3ac849d3772 | 24,181 |
def discriminantcontrast(x, y, con, w):
"""return discriminant contrast (LDC, crossnobis, CV-Mahalanobis, whatever)."""
betas = lsbetas(x, y)
conest = con @ betas
return np.sum(conest * w, axis=1) | aa3043a568cecedb5180f0618277c05b59cb11c9 | 24,182 |
def calculateCosine(point, origin):
"""
calculate the polar angle of the given point to the origin point
"""
x1, y1 = point
x0, y0 = origin
if y1 == y0:
return 1.0
return round((x1 - x0) / calculateDistance(point, origin), ROUND) | 19a31cc8318e54cca6c3475550cb29572bf6c2a3 | 24,183 |
def ValidClassWmi(class_name):
"""
Tells if this class for our ontology is in a given WMI server, whatever the namespace is.
This is used to display or not, the WMI url associated to a Survol object.
This is not an absolute rule.
"""
return class_name.startswith(("CIM_", "Win32_", "WMI_")) | f3fda0492bb42cefaba8a0226cb13558907bf995 | 24,184 |
def results():
"""Calculate results and route to results page"""
# get user input
user_input = dict(request.args)
user_titles = []
for x in user_input.keys():
if x == "algo":
algo_choice = user_input[x]
else:
user_titles.append(user_input[x])
# construct a... | 2ba067dd4fad484d6f098286f1b8e7a7d977b8f2 | 24,185 |
from typing import MutableMapping
def flatten(d, separator='_', parent_key=None):
"""
Converts a nested hierarchy of key/value object (e.g. a dict of dicts) into a flat (i.e. non-nested) dict.
:param d: the dict (or any other instance of collections.MutableMapping) to be flattened.
:param separator: ... | d07daba5007c4c4efee1ccb2033a42e9a52a7efb | 24,186 |
def _rendered_size(text, point_size, font_file):
"""
Return a (width, height) pair representing the size of *text* in English
Metric Units (EMU) when rendered at *point_size* in the font defined in
*font_file*.
"""
emu_per_inch = 914400
px_per_inch = 72.0
font = _Fonts.font(font_file, p... | f779899cba10fa135b7746421798cf91441984fc | 24,187 |
from typing import Tuple
def parse_args(args: str) -> Tuple[UFDLType]:
"""
Parses the string representation of a list of type arguments.
:param args:
The type arguments to parse.
:return:
The parsed types.
"""
if args == "":
return tuple()
return t... | 2e9f5383ab1a3e96e03cc9fd030071ad37ec12cd | 24,188 |
from typing import Iterable
import numpy
def pca_biplot(
predictor: Iterable, response: Iterable, labels: Iterable[str] = None
) -> pyplot.Figure:
"""
produces a pca projection and plot the 2 most significant component score and the component coefficients.
:param predictor:
:param response:
:... | b2e75749b2c3c504b703c4b7b849a14d2801b6d8 | 24,189 |
from typing import Tuple
import torch
def kb_spmat_interp_adjoint(
data: Tensor, interp_mats: Tuple[Tensor, Tensor], grid_size: Tensor
) -> Tensor:
"""Kaiser-Bessel sparse matrix interpolation adjoint.
See :py:class:`~torchkbnufft.KbInterpAdjoint` for an overall description of
adjoint interpolation.
... | 0c4b131e29138d8d2b1260617fd50b20b991b64b | 24,191 |
from typing import Callable
import inspect
def help_send(command: str, help_string_call: Callable[[], str]):
"""发送帮助信息"""
class _HELP(ArgAction):
def __init__(self):
super().__init__(HelpActionManager.send_action)
def handle(self, option_dict, varargs, kwargs, is_raise_exception)... | 444971ddd639cfd10ad8eee41d3bc35815cff5a2 | 24,192 |
def divide_list(array, number):
"""Create sub-lists of the list defined by number.
"""
if len(array) % number != 0:
raise Exception("len(alist) % number != 0")
else:
return [array[x:x+number] for x in range(0, len(array), number)] | 09882945b971ce13f7983c33562df0dfde77165c | 24,193 |
def _sympify(a):
"""Short version of sympify for internal usage for __add__ and __eq__
methods where it is ok to allow some things (like Python integers
and floats) in the expression. This excludes things (like strings)
that are unwise to allow into such an expression.
>>> from sympy im... | 2b383442f407fb932937d25fa9b32ac87bda2780 | 24,194 |
def process_value(setting_info, color):
"""Called by the :class:`rivalcfg.mouse.Mouse` class when processing a
"reactive_rgbcolor" type setting.
:param dict setting_info: The information dict of the setting from the
device profile.
:param str,tuple,list,None color: The rea... | 4fb3811456cf6740ff3f079d9391a4d2c9492427 | 24,195 |
def generate_ones(num_bits):
"""Returns a numpy array with N ones."""
return np.ones(num_bits, dtype=np.int) | 13601212494bd29bbe037c357d5ac8a95632fad4 | 24,196 |
def get_exception_message(exception: Exception) -> str:
"""Returns the message part of an exception as string"""
return str(exception).strip() | 6e002329425f716115a5fddb32cbf36cf568ee81 | 24,197 |
from typing import Tuple
def should_commit(kwargs: Kwargs) -> Tuple[bool, Kwargs]:
"""Function for if a schema class should create a document on instance."""
return kwargs.pop('create') if 'create' in kwargs else True, kwargs | 3e554d661b069e71da86dc8f3d43e754236a9037 | 24,200 |
def _get_frame_time(time_steps):
""" Compute average frame time.
:param time_steps: 1D array with cumulative frame times.
:type time_steps: numpy.ndarray
:return: The average length of each frame in seconds.
:rtype: float
"""
if len(time_steps.shape) != 1:
raise ValueError("ERRO... | e849e5d6bcbc14af357365b3e7f98f1c50d93ee4 | 24,202 |
import random
def next_symbol_to_learn(ls):
"""Returns the next symbol to learn. This always returns characters from the
training set, within those, gives higher probability to symbols the user
doesn't know very well yet. `ls` is the learn state. Returns a tuple like
("V", "...-")
"""
total = ... | d4b574a6f841ee3f2e1ce4be9f67a508ed6fb2de | 24,203 |
def query_table3(song):
"""
This function returns the SQL neccessary to get all users who listened to the song name passed as an argument to this function.
"""
return "select user_name from WHERE_SONG where song_name = '{}';".format(song) | ed9a3fb7eb369c17027871e28b02600b78d483a9 | 24,204 |
def train_test_data(x_,y_,z_,i):
"""
Takes in x,y and z arrays, and a array with random indesies iself.
returns learning arrays for x, y and z with (N-len(i)) dimetions
and test data with length (len(i))
"""
x_learn=np.delete(x_,i)
y_learn=np.delete(y_,i)
z_learn=np.delete(z_,i)
x_test=np.take(x_,i)
y_test=np... | 7430e9ea2c96356e9144d1689af03f50b36895c6 | 24,206 |
def construct_Tba(leads, tleads, Tba_=None):
"""
Constructs many-body tunneling amplitude matrix Tba from single particle
tunneling amplitudes.
Parameters
----------
leads : LeadsTunneling
LeadsTunneling object.
tleads : dict
Dictionary containing single particle tunneling a... | 83c582535435564b8132d3bd9216690c127ccb79 | 24,207 |
def inplace_update_i(tensor_BxL, updates_B, i):
"""Inplace update a tensor. B: batch_size, L: tensor length."""
batch_size = tensor_BxL.shape[0]
indices_Bx2 = tf.stack([
tf.range(batch_size, dtype=tf.int64),
tf.fill([batch_size], tf.cast(i, tf.int64))
],
axis=-1)
return tf... | 61cb7e8a030debf6ff26154d153de674645c23fe | 24,208 |
async def record_trade_volume() -> RecordTradeVolumeResponse:
"""
This api exists for demonstration purposes so you don't have to wait until the job runs again to pick up new data
"""
await deps.currency_trade_service.update_trade_volumes()
return RecordTradeVolumeResponse(success=True) | 2921353360c71e85d7d5d64f6aed505e5f9a66b9 | 24,211 |
def logged_in():
"""
Method called by Strava (redirect) that includes parameters.
- state
- code
- error
"""
error = request.args.get('error')
state = request.args.get('state')
if error:
return render_template('login_error.html',
error=error,
... | 71a2590f2f2fbcc67e73a2afb9180a5974d98252 | 24,213 |
def unit_string_to_cgs(string: str) -> float:
"""
Convert a unit string to cgs.
Parameters
----------
string
The string to convert.
Returns
-------
float
The value in cgs.
"""
# distance
if string.lower() == 'au':
return constants.au
# mass
... | 32b16bf6a9c08ee09a57670c82da05655cb3fd16 | 24,214 |
from operator import mul
def Mul(x, x_shape, y, y_shape, data_format=None):
"""mul"""
if data_format:
x_new = broadcast_by_format(x, x_shape, data_format[0], y_shape)
y_new = broadcast_by_format(y, y_shape, data_format[1], x_shape)
else:
x_new = x
y_new = y
return mul.... | b6bf343e8a3ceb5fe5a0dc8c7bd96b34ecb7ab2f | 24,216 |
import logging
def new_authentication_challenge(usr: User) -> str:
"""
Initiates an authentication challenge. The challenge proceeds as follows:
1. A user (:class:`sni.user`) asks to start a challenge by calling
this method.
2. This methods returns a UUID, and the user has 60 seconds to chang... | d0c27b211aadc94556dc285a1588ff908338b950 | 24,217 |
def create_channel(application_key):
"""Create a channel.
Args:
application_key: A key to identify this channel on the server side.
Returns:
A string id that the client can use to connect to the channel.
Raises:
InvalidChannelTimeoutError: if the specified timeout is invalid.
Other errors ret... | 8b54ac3204af4dbeaf603e788aa0b41829f4807b | 24,218 |
def generate_new_admin_class():
"""
we need to generate a new dashboard view for each `setup_admin` call.
"""
class MockDashboard(DashboardView):
pass
class MockAdmin(Admin):
dashboard_class = MockDashboard
return MockAdmin | 7f691e8f294bf6d678cb8f1ce59b4f12ca77c866 | 24,219 |
def for_default_graph(*args, **kwargs):
"""Creates a bookkeeper for the default graph.
Args:
*args: Arguments to pass into Bookkeeper's constructor.
**kwargs: Arguments to pass into Bookkeeper's constructor.
Returns:
A new Bookkeeper.
Raises:
ValueError: If args or kwargs are provided and the B... | 649f2c33c5cdedf4d08c2ac991c0d1a044c50fe4 | 24,220 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.