content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def data():
"""Length-100 PeriodArray for semantics test."""
data = make_data()
# Why the while loop? NumPy is unable to construct an ndarray from
# equal-length ndarrays. Many of our operations involve coercing the
# EA to an ndarray of objects. To avoid random test failures, we ensure
# that ... | b15347eabc29efeae835f314b2716cc5551a3b51 | 77,019 |
def gauss_cross_entropy(mu1, var1, mu2, var2):
"""
Computes the element-wise cross entropy
Given q(z) ~ N(z| mu1, var1)
returns E_q[ log N(z| mu2, var2) ]
args:
mu1: mean of expectation (batch, tmax, 2) tf variable
var1: var of expectation (batch, tmax, 2) tf variable
mu2: ... | deee609c800b0d8935f1f1aa70d7b709a5d4fd54 | 77,020 |
from pathlib import Path
def get_table_id(ckd_dir, bin_table_name):
"""
Quick en dirty implementation to obtain table_id from binning-table CKD
"""
if not Path(ckd_dir).is_dir():
ckd_dir = environ.get('CKD_DIR', '.')
# only read the latest version of the binning-table CKD
bin_tables =... | 1abc4697eb040511ca8e704bee87955dc2beb5a9 | 77,021 |
from typing import Union
from typing import List
from typing import Optional
from typing import Dict
def pandas_table(
columns: Union[str, List[str]] = "all",
infer_schema: bool = True,
table_name: Optional[str] = None,
ignore: List[str] = None,
types: Dict = None,
bool_as_cat: bool = True,
... | a5486338e816a4cbf12e0fc9e94a65f26e36c99a | 77,022 |
from typing import Callable
import math
def get_exponential_schedule(num_epochs: int, learning_rate: float,
num_training_obs: int,
batch_size: int) -> Callable[[int], float]:
"""Returns an exponential learning rate schedule, without warm up.
Args:
num... | 7d975dd257b2c322e5700d26ba73e2fed56bdaa5 | 77,023 |
def widont_html(value):
"""
Adds an HTML non-breaking space between the final two words at the end of
(and in sentences just outside of) block level tags to avoid "widowed"
words.
Examples:
>>> print(widont_html('<h2>Here is a simple example </h2> <p>Single</p>'))
<h2>Here is a simple&nb... | 6e61012ae78be63f1ac7e571b2f674cbb70e83eb | 77,024 |
def score_time_cost(event, attributes):
"""
Score based on indicators of time cost (WIP)
Key indicators of resource cost will be numbers of targets and analysis effort
"""
score = 0
for attribute in attributes:
if attribute["category"] == "Network activity":
ty = attribute[... | f1eb3054c1178b162204997cc490f69865ee1df7 | 77,025 |
def _validator_events(desc, key, validator, include_removes, include_backrefs):
"""Runs a validation method on an attribute value to be set or
appended.
"""
if not include_backrefs:
def detect_is_backref(state, initiator):
impl = state.manager[key].impl
return initiator... | d7835650f2311c0f7c97a572d0828896bdc7c993 | 77,026 |
def is_kt(v) -> bool:
""" Check if value is a KT address.
"""
try:
_validate(v, prefixes=[b'KT1'])
except (ValueError, TypeError):
return False
return True | 12bbac38fc73b558045295eb33847e0ac4bd938c | 77,027 |
import torch
def tanh_clip(x, clip_val=10.0):
"""soft clip values to the range [-clip_val, +clip_val]"""
if clip_val is not None:
x_clip = clip_val * torch.tanh((1.0 / clip_val) * x)
else:
x_clip = x
return x_clip | 48205e984549b1bdf38b66155a1fd7f57c1bafa9 | 77,028 |
def fitradius(radius, data):
"""Fit a line to the data"""
it=interfit(radius, data, function='polynomial', order=3)
it.interfit()
d=it(radius)
return radius[d.argmax()] | db2307aaeb9c8ce935a3de5880eb30fb29f171f8 | 77,029 |
def _category_errmsg(particle, category: str) -> str:
"""
Return an error message when an attribute raises an
`~plasmapy.utils.InvalidElementError`,
`~plasmapy.utils.InvalidIonError`, or
`~plasmapy.utils.InvalidIsotopeError`.
"""
article = 'an' if category[0] in 'aeiouAEIOU' else 'a'
err... | c9d916f6808d989aee3b9523f2322c5a2586367a | 77,030 |
def _crt(m1, m2, v1, v2):
"""
Chinese Remainder Theorem
Returns x such that x = v1 (mod m1) and x = v2 (mod m2), or None if no
such solution exists.
"""
# Avoid calling crt in the cases where the inputs would be arrays.
if m1 == 1:
return v2 % m2
if m2 == 1:
return v1 %... | 2a603a6b2447a6aafc03ac5431bc8e7455a4fe1c | 77,031 |
def GetBuildDependency(sysroot_path, board=None, packages=None):
"""Return the build dependency and package -> source path map for |board|.
Args:
sysroot_path (str): The path to the sysroot, or None if no sysroot is being
used.
board (str): The name of the board whose artifacts are being created, o... | 47d28300ae59e634d3088322351b6874bf483466 | 77,033 |
from typing import Iterable
def get_matrix_from_quaternion(q, convention='wxyz'):
"""
Returns rotation matrix from quaternion
"""
if isinstance(q, Iterable):
if convention == 'xyzw':
x, y, z, w = q
elif convention == 'wxyz':
w, x, y, z = q
else:
rais... | edeb55e32b3a7a560ccdd499c38b8aa06cfc74ae | 77,037 |
def datasets(request):
"""
"""
template = 'curation/dashboard.html'
context = {
'curation_section':'datasets',
}
return render(request, template, context) | e9e05c4ea625224c0499bb232d797ec665f01d06 | 77,038 |
def generate_hhblits_profile(protein):
"""Compute the HHblits MSA profile if not already present."""
if 'hhblits_profile' in protein:
return protein
# Compute the profile for every residue (over all MSA sequences).
protein['hhblits_profile'] = np.mean(one_hot(22, protein['msa']), axis=0)
ret... | 6c5f8057333e9a28dc2a2b39061c771ce9548d57 | 77,039 |
def create_questions_for_submission_sample(submission_id, sample_batch_id):
"""
Produces questions for a submission, based on what's in the
database.
"""
# Group by doc_id, subject, object
question_groups = {}
for q in db.select("""
SELECT DISTINCT ON (s.doc_id, LEAST(s.subject, s.ob... | 75969074bf817eeb4b7d28f59f05acc729f1e44a | 77,040 |
def Run(benchmark_spec):
"""Runs cloudharmony block storage and reports the results."""
vm = benchmark_spec.vms[0]
target = ' '.join(['--target=%s' % _PrepareDevicePath(vm, dev.GetDevicePath())
for dev in vm.scratch_disks])
tests = ' '.join(['--test=%s' % test for test in FLAGS.ch_block_tes... | 1cfdac27184390a0c0fbb4931228ed42093a5a41 | 77,041 |
def get_by_id(id: int):
"""
:param id: ID of the item (in-game item ID).
"""
antenna = antenna_dao.get(id)
if antenna is None:
raise NotFoundException('Wheel not found')
return jsonify(antenna.to_dict()), 200 | 18c42ba7ecb324a72d3e7f3e2018aa6f81a08294 | 77,042 |
def add_album(request):
""" Add an album to the store """
if not request.user.is_superuser:
messages.error(request, 'Sorry, only store owners can do that.')
return redirect(reverse('home'))
if request.method == 'POST':
form = AlbumForm(request.POST, request.FILES)
if form.is... | e45a47492cf98ea96e6bd275726f926883804c0e | 77,045 |
def inner(x, y):
"""
Inner product of two arrays.
See syntax here: https://numpy.org/doc/stable/reference/generated/numpy.inner.html
"""
if not is_casadi_type([x, y], recursive=True):
return _onp.inner(x, y)
else:
return _cas.dot(x, y) | 7ee10ce4a557ef69613d6b2445e10571097c4edf | 77,046 |
def add_hidden_layers(features, architecture, FLAGS, train_flag, act=tf.nn.relu):
"""Add hidden layers to the model using the architecture parameters."""
hidden_out = features
jit_scope = tf.contrib.compiler.jit.experimental_jit_scope #JIT compiler compiles and runs parts of TF graphs via XLA, fusing multip... | 1b97d067fc8de0c7c4c8d65315306c2fe67e2e54 | 77,047 |
def get_causx_partial_csv(calc_params):
"""causx-specific partial csv. returns all expected headings,
attempts to fill in information available even if valid statements not present yet
"""
count = calc_params.part_count
columns = ["dataset_id", "variable", "main_subject", "value",
... | a3506b4db8a10fdfae76320b39093d097053e2ac | 77,048 |
def get_species_units(input):
"""
Retrieve units for GEOS-CF species and derived values
"""
if 'NOy/' in input:
units = 'unitless'
elif 'pm25' in input:
units = '$\mu$g m$^{-3}$'
elif 'Dust' in input:
units = '$\mu$g m$^{-3}$'
elif 'NOy' in input:
units = 'ppb... | 5daa3a065afd99cc713e3084c4e694d9fa789ccc | 77,049 |
def _list_networks():
"""Return a dictionary of network name to active status bools.
Sample virsh net-list output::
Name State Autostart
-----------------------------------------
default active yes
juju-test inactive no
foobar ... | e54c59f94df8793c5bde956a8207059607367c50 | 77,050 |
def firefox(cookie_file=None):
"""Returns a cookiejar of the cookies and sessions used by Firefox
"""
return Firefox(cookie_file).load() | 0691877b6372895f18032468d89709e32fbd0aa8 | 77,052 |
import copy
def gaussianize_single(X_single):
"""
Transforms a single (proxy) timeseries to Gaussian distribution.
Originator: Michael Erb, Univ. of Southern California - April 2017
"""
# Count only elements with data.
n = X_single[~np.isnan(X_single)].shape[0]
# Create a blank copy of... | 0fd69a0b54eccc22de478474b236c1e24b316719 | 77,053 |
def sample(signal_idx):
"""Samples cached value of a single signal that has been pushed via
the push_signal() function and returns the value read.
Args:
signal_idx (int): Index returned by a previous call to the
push_signal() function.
Returns:
float: Value of signal read w... | a1e6ee1250027f6e283b6fbec5ba0d685b8c3df4 | 77,054 |
from functools import reduce
def solution(input_data):
""" Solution to the problem """
return reduce(lambda acc, line: acc + (1 if is_valid(line) else 0), input_data.split("\n"), 0) | f6e23cc263bde6d1d8ea6b064701b9458832129a | 77,055 |
import json
def all():
"""Return a list of sample stations."""
# Use Pandas to perform the sql query
# stmt = db.session.query(Samples).statement
# df = pd.read_sql_query(stmt, db.session.bind)
# # Return a list of the column names (sample names)
# return jsonify(list(df.columns)[2:])
d... | 46eb5f468fc4083e0652e07bdddbc65a1d3d1e27 | 77,056 |
def get_git_sha_from_dockerurl(docker_url: str, long: bool = False) -> str:
""" We encode the sha of the code that built a docker image *in* the docker
url. This function takes that url as input and outputs the sha.
"""
parts = docker_url.split("/")
parts = parts[-1].split("-")
sha = parts[-1]
... | 4bb598da76ada2fdf34fdc3ff24bf046dbeaf9bf | 77,057 |
def get_class_name(obj):
"""
Dunders in python are ugly, this gets the class name of an object
"""
return obj.__class__.__name__ | ad1940f84f58031751be503dc686adef3cfcb48f | 77,060 |
def transform(x, Jmin=2):
"""
Compute the wavelet transform of x
"""
h = compute_wavelet_filter("Daubechies",10)
return perform_wavortho_transf(x, Jmin, +1, h) | e60286fe9ba1f33c827f57bb4cde3177622ba2db | 77,061 |
def _split(start, end, count, min_interval_sec=120):
"""
Split section from `start` to `end` into `count` pieces,
and returns the beginning of each piece.
The `count` is adjusted so that the length of each piece
is no smaller than `min_interval`.
Returns:
--------
List of the offset... | 5da9c59fdc2b00e9ba31db0b9c82db5bb30f74cb | 77,062 |
def send_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
... | ceef089c27e980c62bcb7b0d17ad15e8433939f7 | 77,063 |
def _step(sess, data, train_op, model, keep_prob):
"""
Make a single gradient update for batch data.
"""
# Make a minibatch of training data
minibatch = sample_coco_minibatch(data,
batch_size=model_config.batch_size,
split='train')
captions, features, urls = ... | 1de477e893f2918e7946c858082b40d7358d6bc0 | 77,064 |
def get_by_id(post_id):
"""Get the post with the given database ID."""
post = Post.query.get(post_id)
if post is not None:
return jsonify(post.to_dict()), 200
else:
raise APIError(404, "Post with ID {id} does not exist on this server".format(id=post_id)) | b8bf13804f31a705c41506a1aa9dae2cf3f96cff | 77,065 |
def get_epw_dictionary():
"""
Extract sequences of phonemes and primary stress vectors for each word from the CELEX database.
Store this information in a dictionary, and return it when you have gone through the entire database.
"""
# replace keys with values in sequences of phonemes
replace_to_... | 8b87424866bba7df4ce768332526c414e3e4c609 | 77,066 |
import urllib
def CreateBuildUrl(master_name, builder_name, build_number):
"""Creates the url for the given build."""
builder_name = urllib.quote(builder_name)
return 'https://luci-milo.appspot.com/buildbot/%s/%s/%s' % (
master_name, builder_name, build_number) | ab0bada5f3bd33b4409800de2814431e3efe26b4 | 77,067 |
def get_token(context):
"""
Retrieves the token the lambda was assigned when it was invoked.
:param context: AWS Lambda context
:type context: object
:return: Lambda token, usually a UUID
:rtype: str
"""
# If that fails, fall back to the requestID
# http://docs.aws.amazon.com/lambd... | 83fced7364d6fad8d632edfb0d82efb7bb7cf5de | 77,068 |
def nonlinearitywarning(band, bin_ix, events, verbose=0):
"""
Flag count rates above the 10% local nonlinearty dropoff, per the
calibration paper.
:param band: The band that is being used, either 'FUV' or 'NUV'.
:type band: str
:param bin_ix: Array indices designating which events are in ... | 2a85bf6c6100e39caef169f57b26c72b6d22e257 | 77,069 |
def compute_beta(Q, a2, b2):
"""
Given the second moment matrix, a^2, and b^2
compute the angle between the axis with length a
and e_1
"""
Q12 = Q[0, 1]
beta = 0.5 * np.arcsin(2 * Q12 / (a2 - b2))
return beta | 3bd90b1b292abbd3986ff8f7c4ea0e746ba8d6ee | 77,070 |
def select(condlist, choicelist, default=0):
"""Return an array composed of different elements in choicelist,
depending on the list of conditions.
:Parameters:
condlist : list of N boolean arrays of length M
The conditions C_0 through C_(N-1) which determine
from which vecto... | 151f36aa63bee679fb3f9d620cb5917a24fa4b07 | 77,071 |
def construct_api_url(input, representation, resolvers=None, get3d=False, tautomers=False, xml=True, **kwargs):
"""Return the URL for the desired API endpoint.
:param string input: Chemical identifier to resolve
:param string representation: Desired output representation
:param list(str) resolvers: (Op... | 002ca0e9ae41fb889803e9b9b96ae91d2347a43f | 77,073 |
def func(U, epsilon):
"""
Computes if any U_i is less than epsilon
Used to compute the conflict probability
that a variable (distance between planes)
is less than 0.1 i.e. collition
"""
ind = np.any(U < epsilon, axis = 1)
return ind | 306db07d5364ea27501b9f95eaa4f37905716e69 | 77,074 |
from typing import Optional
def parse_object(psr: ParserData, schema: Optional[JsonObjectSchema]) -> JsonObject:
"""Parses an object out of JSON tokens"""
objData: OrderedMultiDict[str, JsonProperty] = OrderedMultiDict()
isObjectSchema = isinstance(schema, JsonObjectSchema)
start = psr.lastToken
token = psr.ac... | 1129e21ec4ffdcec2ddfd8973ef376ef76b348b4 | 77,075 |
def type_to_ast(graphql_type):
"""
https://github.com/apollographql/graphql-tools/blob/0046a0e3bf2a120a59e4f4e392d4ddc3728e4f3c/src/transforms/AddArgumentsAsVariables.ts#L171
"""
if isinstance(graphql_type, graphql.GraphQLNonNull):
inner_type = type_to_ast(graphql_type.of_type)
if inner_... | a3b577e2f8274d6dc10045c8ab3f990e77b8501b | 77,076 |
def split_inventory_presamples(samples, indices):
"""Split technosphere and biosphere presamples.
``samples`` is a Numpy array with rows of exchanges and columns of samples. ``indices`` is a list of ``[(input key, output key, type)]``, where ``type`` is like "biosphere" or "technosphere". Everything which isn'... | c6139367b5c4414161f421b2737d1d0c5d39f330 | 77,077 |
import itertools
def get_resample_sweep() -> hyper.Sweep:
"""Sweep over the resampling operation of the different datasets."""
ratios = [1e-3]
n_samples = [1_000_000]
ratio_samples = list(itertools.product(ratios, n_samples))
ratio_samples_sweep = hyper.sweep(
f'{_EXP}.data.train_kwargs.load_kwargs.nu... | cb8c0e61d55b90735319b1e3356024d7f03b2f51 | 77,078 |
def convert_to_cog(cog):
"""Populate ConvertedImageFile with COG file."""
if not isinstance(cog, ConvertedImageFile):
cog = ConvertedImageFile.objects.get(id=cog)
else:
cog.refresh_from_db()
if not cog.converted_file:
cog.converted_file = ChecksumFile()
src = cog.source_image... | d174f257f06fee76fcfae02529ee771cb0a96d15 | 77,079 |
from typing import Union
import scipy
def chi2(data: Union[np.ndarray, pd.Series],
distribution: Union[HyperDistribution, scipy.stats.rv_continuous],
numbins: int = 0):
"""Compute chi2 test for distributions fit. Note that this is favorable for
discrete random variables, but can be problemat... | ee5d578e061b10a8635cc84d083d9ff1f24120a0 | 77,080 |
def h1vp(v,z,n=1):
"""Return the nth derivative of H1v(z) with respect to z.
"""
if not isinstance(n,int) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if n == 0:
return hankel1(v,z)
else:
return bessel_diff_formula(v, z, n, hankel1, -1) | aee2be470a2e7b91f101a2eb988482858bdbd889 | 77,081 |
from typing import List
from typing import Tuple
from typing import Dict
def uind_histogram(dataframes: List[Tuple[str, DataFrame]], alphas: List[float]) -> Dict[
float, Tuple[np.ndarray, np.ndarray]]:
"""
Compute an histogram of how many matching columns each of the columns of the first dataframe
has... | 7b76174624c4d16be917e0b45dc4a06645a8356c | 77,082 |
def user_list(request):
"""
List all code users, or create a new snippet.
"""
if not request.user.is_superuser:
return JSONResponse({'error': 'unauthorized request'}, status=status.HTTP_401_UNAUTHORIZED)
if request.method == 'GET':
users = CustomUser.objects.all()
serializer ... | e1057f41f0642bbe08963df2c22b7cd1df8beef3 | 77,083 |
def ParseMakefile(infile):
"""Parses a Makefile object from a Makefile.
Args:
infile: file object containing Makefile contents
Returns:
a Makefile object
"""
makefile = Makefile(infile.name)
var_name = None
definition = None
multiline_target_name = []
target_name = None
prerequisites = None... | cd5c37a938659083b47630bc1ce9a23fa294cf23 | 77,084 |
def get_encoding(filename, try_cchardet=True):
"""Get the encoding of the file
This function uses the chardet package for detecting the encoding of a
file.
Parameters
----------
filename: str
Path to a file
try_cchardet: bool
Whether to run detection using cChardet if it i... | 860122ee922cb8efc2a3539f13d746ee3b86f5f7 | 77,085 |
def not_found(_):
"""404 status wrapper"""
return make_response(jsonify({'error': 'Not Found'}), 404) | f57f6e987b121141a79dd44dddcbee8fe1af7824 | 77,086 |
from rx.core.operators.subscribeon import _subscribe_on
import typing
from typing import Callable
def subscribe_on(scheduler: typing.Scheduler) -> Callable[[Observable], Observable]:
"""Subscribe on the specified scheduler.
Wrap the source sequence in order to run its subscription and
unsubscription logi... | d924af17b0b6edb2f00cc08f4ac4fecd7267348c | 77,087 |
def get_categories(limit=20, offset=0, last_id=None):
"""Return a list of registered categories.
:param limit: Number of returned items, default 20
:type limit: integer
:param offset: Offset for the query, default 0
:type offset: integer
:param last_id: id of the last category, used for paginat... | 83c676f1780ee58a5d1e7d2b1e379299ed7d3cf8 | 77,088 |
def thermal_integrand(theta, phi, alpha, P, Ab, eps, f, Ts, Rs, semi_a, res=12):
"""Integrand of the thermal phase dependency of the planet's
thermal emission.
Note:
This function's theta is NOT the mcmc parameter tuple. See Args.
Args:
theta (array): planetary latitude in radians
phi (array): planetary lon... | 612cc08db5b4f2142b0fd0a2204eecf503c03d62 | 77,089 |
def student_json(user):
""" Only send student information to staff. """
can_see_details = current_user.is_authenticated and (
current_user.is_staff or user.id == current_user.id
)
if not can_see_details:
return None
return user_json(user) | 7ac5881c669bf9914e65a51208a84acbbc6a4272 | 77,091 |
import logging
def mem_estimate_coclustering_numpy(n_rows,
n_cols,
nclusters_row,
nclusters_col,
out_unit=None):
"""
Estimate the maximum memory usage of `cgc.coclust... | 2d197f236f4c644b37ca627c4add5a0651ded670 | 77,092 |
def load_linear(
long=False,
shape=None,
start_date: str = "2021-01-01",
introduce_nan: float = None,
introduce_random: float = None,
random_seed: int = 123,
):
"""Create a dataset of just zeroes for testing edge case.
Args:
long (bool): whether to make long or wide
shap... | 0b7a17d85035162b817beed6b734230e8062a0a8 | 77,093 |
async def is_supported_for_autodiscovery(
hass: HomeAssistantType, entity_entry: er.RegistryEntry | None
):
"""See if we have enough information in device registry to automatically setup the power sensor"""
if entity_entry is None:
return False
device_registry = await dr.async_get_registry(has... | f36c214c3431738e02672d21a8163ce5511f4521 | 77,095 |
def cx2x(cx, e):
"""Transform from *x* index value to *x* index value, using the
*e.css('cw')* (column width) as column measure."""
if cx is None:
x = 0
else:
x = e.parent.pl + cx * (e.css('cw', 0) + e.gw)
return x | 5d04d7f017c0fa54e19c649133139b2e4439562f | 77,096 |
def sim_start_val1(models, df, cluster_by, meth ='newton', numb_it = '100', up_bound = 1, low_bound = -1):
"""Function to create different parameter values for random starting values of the models used in section 5.
Args:
models: list of models to evaluate the parameters for
meth: optim... | 6b1fde4cbc544894ce921657896a20e9121e2024 | 77,097 |
def _read_ghcnd(station_file,
variable_name):
"""
Reads a GHCN-D ASCII file into a Pandas DataFrame, sorted by date and with all non-valid dates removed.
:param station_file: GHCN-Daily ASCII file
:param variable_name: climatological variable name to use for the output DataFrame's c... | 6edd2fe7732978a91f2dff93cbafec6b43c571e9 | 77,098 |
def q(s):
""" Quote the given string """
return "'" + str(s) + "'" | 0c0a1477e740b430d5e6997c0115ef317457526c | 77,099 |
def get_dtype(df):
"""
A function to get the datatype for each column in a dataframe
Parameters
----------
df: pandas.DataFrame
A dataframe to extract datatypes from
Returns
-------
dtype: dict
A dictionary containing 2 lists: column and dtype - datatype
"... | ee3c88fec93e6753eb9340ea1360ad31864eb63c | 77,100 |
from typing import Any
from typing import Optional
def build_obs_act_forward_conv(
n_out: int,
depth: int,
hidden: int,
act_layer: Any,
last_layer: Optional[Any] = None,
) -> hk.Transformed:
"""Build a simple cnn forward step that takes an observation & an action.
Args:
n_out (int... | 91b2075d9a9d29d21f0ade2bad58f8708597ed26 | 77,102 |
def gather_rows(A):
"""
Concatenates (hstacks) the checkerboard-distributed matrix A within each
pcol, so that each pcol now stores a copy of the same data.
If A had local shape (m_l, n_l), the result has local shape
(m_l, grid[1] * n_l).
"""
groups = _axis_index_prows()
A = jax.lax.all_gather(A, axis_... | 512a9bbafe04f6b155f26053c318f420c1c33fb1 | 77,103 |
def calc_doppler_diff(x0, v0, x1, v1, x2, v2, f):
"""
Computes the difference in Doppler shift between reference and test
sensor pairs and a source. The two sets of sensor positions (x1 and x2)
must have the same size. Corresponding pairs will be compared.
Ported from MATLAB Code.
Nicholas O... | 21fd256d4f6597f54098650103317122f2aec298 | 77,104 |
def dotenv_kwargs() -> tuple[tuple[dict[str, str], str, str], ...]:
"""Provide example keyword input arguments and their expected outputs."""
return _dotenv_kwargs | 304b33eb2874d868ac3099c71571bd91da8294a2 | 77,105 |
def parse_file(fn, timeout_limit=30, silent=True):
"""
Parse SMT-LIB file.
:fn: path to SMT-LIB file.
:silent: if silent=True the parser will withhold stacktrace from user
on crash.
:returns: Script object representing AST of SMT-LIB file. None if timeout
or crash occurre... | e2217fc5d443f895cb7a4eccf2bf2ebc88e6386a | 77,106 |
def _name_value_data(dbms, col_name, cases=None):
"""
@param dbms: <db> dbms object
@param col_name: <str> name of col
@param cases: <list> list of cases eg. ['male', 'female']
@return: <json> data
"""
query_str = """select {}, count(*) as count from {} group by {}""".format(col_name, TABLE_... | d9be3baa2a26abd39108e38c72f2714078b59c68 | 77,107 |
def speaker_companies(talk):
""" Return a set of the companies of the speakers of the talk."""
companies = sorted(
set(speaker.user.attendeeprofile.company
for speaker in talk.speakers.all()
if speaker.user.attendeeprofile))
return companies | 39a1cbf046779dd3ad2e798c950fa3d8211a08e1 | 77,108 |
def get_veranstaltung_by_iq_id(veranst_iq_id):
""" liefert eine Einzelveranstaltung """
#query = session.query(Veranstaltung).join('rel_anbieter').add_entity(Anbieter)
query = session.query(Veranstaltung).add_entity(Anbieter).join('rel_anbieter')
query = query.add_entity(Veranstaltungsart).join('rel_v_art')
q... | 957b62c21824d59a3445e5ea0b513a21c2522a0c | 77,109 |
def webhook():
"""C'est la fonction principale utilisée par flask pour
écouter au point de terminaison `/ webhook`"""
if request.method == 'GET':
return verify_webhook(request)
elif request.method == "POST":
payload = request.json
event = payload['entry'][0]['messaging']
... | 1d35a9b7c9575e2fe730e60fa3cd073a4b0a7882 | 77,110 |
import re
def info(entry: BibItem) -> str:
"""Given a bibliography entry, describe it for human readers."""
return "{title}{author}{date}".format(
title=(
"Title: {}\n".format(re.sub(r"[}{]", "", entry["title"]))
if "title" in entry
else ""
),
author... | c32f1cd7f37475a0d11ea13d2f940c08e1d99a32 | 77,111 |
import colorsys
def colorsys_RGB2HSV(img_arr):
"""
Function to convert RGBA to HSV
"""
rgb_to_hsv = np.vectorize(colorsys.rgb_to_hsv) # Vectorize the function for efficiency
r, g, b, a = np.rollaxis(img_arr, axis=-1) # Get r, g, b, a
h, s, v = rgb_to_hsv(r, g, b) # Convert rgb to hsv
retu... | 689dd0a60f11276ffaddf95fe87d9699d3706f65 | 77,112 |
def build_sox_noise(
audio_file,
amod_lowpass_cutoff=0.1,
lowpass_cutoff=MAX_FREQ,
highpass_cutoff=1,
noise_gain=-4,
):
"""
play original.wav synth whitenoise lowpass 0.1 synth whitenoise amod gain -n 0 lowpass 100 highpass 1
"""
sox_params = "sox {audio_file} -p synth whitenoise lo... | 6d41c211628d865fb6c71fa93790797aaef579ec | 77,113 |
def cpfclamp(f, min_, max_):
"""Clamp f between min and max"""
return min(max(f, min_), max_) | 0fa974c3680817fe8df15331940693d5a07f2232 | 77,114 |
def extract_section_from_text(conc_search_terms_path: str, covid19_df: pd.DataFrame):
"""
Extract title, abstract, and conclusion sections from publication text.
:param conc_search_terms_path: file path for search terms for putative conclusion section headers
:param covid19_df: pandas dataframe of publ... | 89ee35970b5a8c28f23916be0fef39202805f5b4 | 77,117 |
from corpkit.constants import transshow, transobjs
import numpy as np
import pandas as pd
from corpkit.interrogation import Interrodict, Interrogation
import pandas as pd
import numpy as np
def make_multi(interrogation, indexnames=None):
"""
make pd.multiindex version of an interrogation (for pandas geeks)
... | b8ab9ef18116811c0613dbadca91fe5692c4eb96 | 77,118 |
def split_ids(ids, n=2):
"""Split each id in n, creating n tuples (id, k) for each id"""
return ((id, i) for id in ids for i in range(n)) | 3fb977cdf08fa7a41e36067d0826633f8fc1d42a | 77,119 |
def save_randomly_initialized_version(config_name: str, save_dir: str, **config_kwargs):
"""Save a randomly initialized version of a model using a pretrained config.
Args:
config_name: which config to use
save_dir: where to save the resulting model and tokenizer
config_kwargs: Passed to ... | 5f19d6cc3fa8e72e9f0086ee6d1a9d1feb8ea8e8 | 77,120 |
import urllib
import logging
def parse_variation(variation_elem):
"""Parses the <variation> element and returns a dict containing meta-information about the given variation."""
variation = {
'id': attr_val(variation_elem, 'id'),
'name': '',
'description': '',
'references': [],... | e63707636e52e45a82d6d956c164f43f048e9be9 | 77,121 |
import inspect
def get_custom_song(class_module_name):
"""Get the customized Song class.
Args:
class_module_name (str): Python name of the custom Song class to import. It
can designate a class in a module, or a module. In this case,
the guessed class name is "Song".
Retur... | 1e1f734efdb4635d006b17303634f1da9546752a | 77,122 |
def _diff_count(string1, string2):
"""
Count the number of characters by which two strings differ.
"""
assert isinstance(string1, str)
assert isinstance(string2, str)
if string1 == string2:
return 0
minlen = min(len(string1), len(string2))
diffcount = abs(len(string1) -... | 82c9ef604db3afee79266e4eb7851164ff43bfd1 | 77,123 |
def create_guest_account(session):
"""
Creates a guest account/character for this session, if one is available.
Args:
session (Session): the session which will use the guest account/character.
Returns:
GUEST_ENABLED (boolean), account (Account):
the boolean is whether guest... | add1eb990de56a97ecb9b0f275cae26ead4abdbd | 77,124 |
def generate_problem_description(dataset, task=None, *, task_keywords=None, performance_metrics=None):
"""
A function that simplifies the generation of a problem description.
Parameters
----------
dataset : Dataset
Dataset to be use for pipeline search.
task : str
A string that ... | cc3375804646898d3b321c018b98dad700188f61 | 77,126 |
import requests
import json
def reverse_location_parse(lat=0, lng=0):
"""
逆地理编码服务, 将经纬度解析成中文地址
文档地址: http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-geocoding
:return:
"""
assert lat > 0 and lng > 0
url = r"http://api.map.baidu.com/geocoder/v2/"
params = {
... | c313471e1435cabe1ccc5ccb0021103b21fea0dc | 77,127 |
def random_useragent():
# type: ()-> str
"""
Returns a random useragent
:return: A seemingly valid useragent.
"""
return sample(useragents, 1)[0] | 76e0ebfdb4dc68ff3be785d6a4e0bd40b232177c | 77,128 |
def findParam(directory, paramname=None):
"""
Find and return a .param file in the directory
"""
if paramname is None:
results = findInDir(directory, '*.param')
if len(results) != 1:
raise RuntimeError, "Could not find .param file"
... | a65f1ccd2c556e9f05f38ace7a8b76b59a648a1c | 77,129 |
def mapquest(location):
"""
# MapQuest
The geocoding service enables you to take an address and get the
associated latitude and longitude. You can also use any latitude
and longitude pair and get the associated address. Three types of
geocoding are offered: address, reverse, and batch.
Usin... | 3c006b194a7129a4446a480864e78da3f0120ff8 | 77,130 |
def chunks(l, n):
""" Yield successive n-sized chunks from l."""
return tuple(l[i:i+n] for i in xrange(0, len(l), n)) | 7e36bebf6776377972db4786897e3b6b0684833a | 77,131 |
import json
def plotly_plot_trace(track: pd.DataFrame) -> str:
"""Prepare a plot of the run with a map background.
Returns a Plotly JSON.
"""
movs = track_2_movements(track)
movs = movs.reset_index()
movs["run_full_km"] = movs["run_distance_km"].astype(int)
movs["diff_full_km"] = movs["ru... | 188e7d63f68e9359d377aa07048e7c30c5892899 | 77,132 |
def calc_basic_indispensability(p, n):
"""
>>> calc_basic_indispensability(3, 0)
2
>>> calc_basic_indispensability(2, 1)
0
>>> calc_basic_indispensability(5, 4)
2
>>> calc_basic_indispensability(7, 5)
2
>>> calc_basic_indispensability(13, 4)
10
"""
table = {
... | 44189ce2c5244bed5e56d9efde616afebc47c1f2 | 77,133 |
import random
def make_ball():
"""
Function to make a new, random ball.
"""
ball = Ball()
# Starting position of the ball.
# Take into account the ball size so we don't spawn on the edge.
ball.x = random.randrange(BALL_SIZE, SCREEN_WIDTH - BALL_SIZE)
ball.y = random.randrange(BALL_SIZE... | e28dbd50a4f9076a3f0c49b568e6d04009b4fc87 | 77,134 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.