content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def principal_axes(I):
"""
Returns the principal moments of inertia and the orientation.
Parameters
----------
I : ndarray, shape(3,3)
An inertia tensor.
Returns
-------
Ip : ndarray, shape(3,)
The principal moments of inertia. This is sorted smallest to largest.
C ... | b7c07f30be11ee16d55df6e6f209ca8f51e093c2 | 74,940 |
def normalize_probs(samples, smoothing=1e-8):
"""Normalize the probability of the samples (in each env) to sum to 1.0."""
sum_prob_dict = {}
for s in samples:
name = s.traj.env_name
if name in sum_prob_dict:
sum_prob_dict[name] += s.prob + smoothing
else:
sum_prob_dict[name] = s.prob + smo... | 2b6e7e8943d6a8bc0b416d91e04c50e2875872bd | 74,941 |
def get_lengths_of_chunks(index_list):
"""
Returns a list of integers.
Every integer corresponds to the number of how many times the same number appears in index_list.
:param index_list: List of numbers
:return: List of integers
"""
if len(index_list) == 0:
return [0]
lengths_of_... | 4a0f7f2dfca00cd617657f6446bd050a7775f193 | 74,942 |
import torch
def build_model(conv_width):
"""Build model."""
model = ConvNet(conv_height, conv_width).to(device)
# Loss and optimizer
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
return model, criterion, optimizer | 0a15675e0908d309e1f44ebeeceab1bc63842ddd | 74,943 |
def create_actions_file_msg(second_run: bool):
"""Actions File Message"""
article = "another" if second_run else "an"
return "Do you want to create %s action file?" % article | b3029285ac076049ea150155932044942ea3f5f7 | 74,944 |
def prompt_continuation(*args) -> str:
"""Prompt continuation method for prompt_toolkit."""
return Shell.prompt_continuation | 096d4a4dbb1c4550850731997bbd82182176b348 | 74,946 |
def preferential_attachment(set_one: list, set_two: list) -> int:
"""
Calculate Preferential attachment score for input lists
:param set_one: A list of graph nodes -> part one
:param set_two: A list of graph nodes -> part two
:return: Preferential attachment score
"""
return len(set(set_one)... | dd4baee5e78349db005dd65e6ac824e604b353bb | 74,947 |
import functools
import operator
def feed_forward_gaussian_fun(observation_space, action_space, config,
observations):
"""Feed-forward gaussian."""
assert isinstance(observation_space, gym.spaces.box.Box)
mean_weights_initializer = tf.contrib.layers.variance_scaling_initializer(
... | d1b25f1c3a4dc06dd5d63822e7de3c9185fba9cf | 74,948 |
def error_404(error):
"""Display error
Arguments:
error {object} -- Detects error
Returns:
HTML -- An error page for HTTP 404(not found) error code.Handles error and render custom HTML page for that error.
"""
return render_template("errors/404.html"), 404 | 3e960ddf21bd79f9b4caf10278593ad3365e39ba | 74,949 |
def multi_weighted_logloss(y_true, y_preds):
"""
@author olivier https://www.kaggle.com/ogrellier
multi logloss for PLAsTiCC challenge
"""
if y_preds.shape[1] != len(classes):
# No prediction for 99, pretend that it doesn't exist.
use_classes = classes[:-1]
else:
use_clas... | 0a7bae3a01126f44f69168886d10c3919d3920fa | 74,950 |
def process_img():
"""
This function is exposed to eel. It takes the image from tkinter, processes it and saves the image as a temp.
It also saves a copy of the shadow crushed image to prevent redundant computations when the threshold is being
tweaked later.
Returns:
int: 1 or 0 depending o... | 8fbabd4ec060a177cb3170619bed9271c8b780d3 | 74,951 |
import six
def render_df_table(data, col_width=3.0, row_height=0.625, font_size=14,
header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
bbox=[0, 0, 1, 1], header_columns=0,
ax=None, **kwargs):
"""
Method to print a Pandas DataFra... | e35def2a43eedb31298bbd099d14f1a1d6d20277 | 74,952 |
def algebraic_equasion_defunction(x):
"""
This function makes a calculation for an Algebraic equasion
It calculates f'(x) with the given equasion and x as a parameter
"""
formula = 2*x + 6
return formula | 94abb9860e5940ad330ef41ecb3627df73e53978 | 74,953 |
def passageplot(arr, cuts, basecut=None, nbins=100, lgcequaldensitybins=False,
xlims=None, ylims=(0, 1), lgceff=True, lgclegend=True,
labeldict=None, ax=None, cmap="viridis", showerrorbar=False,
nsigmaerrorbar=1):
"""
Function to plot histogram of RQ data with mul... | 4f178bf7f9696164d7ee1142d1ead4afc6cb2112 | 74,954 |
def build_ref2family2presence(families, genome2families, VERBOSE):
"""Build the dictionary from ref to gene family to presence
{ REF : { GENE FAMILY : PRESENCE(True or False) } }
"""
ref_genomes = sorted(genome2families.keys())
ref2family2presence = defaultdict(dict)
numof_ref = len(ref_genomes)... | d8e868001e1c60e76811d4df22d1f18387c78ac3 | 74,955 |
def get_variables_to_train(trainable_scopes=None):
"""Returns a list of variables to train.
Returns:
A list of variables to train by the optimizer.
"""
if trainable_scopes is None:
variables_to_train = tf.trainable_variables()
else:
scopes = [scope.strip() for scope in trainabl... | 5f13c1c87500de42aecb3ba16319381a935d461d | 74,956 |
def pr_curve(y_test, y_score):
"""
plot precision-recall curve and return AUC of it.
Parameters
----------
y_test = [n_samples] shape
y_score = [n_samples] shape
"""
precision, recall, _ = precision_recall_curve(y_test, y_score)
pr_auc = auc(recall, precision)
plt.figure()... | 47ac935e322ebfb9394923317b9e075fc31c9a79 | 74,957 |
def getMidpoint(pointA: (int, int), pointB: (int, int)) -> (int, int):
"""Gets the midpoint between two coordinates
Example:
>>> getMidpoint([1, 2],[3, 4])
2, 3
"""
x = (pointA[0] + pointB[0]) / 2
y = (pointA[1] + pointB[1]) / 2
return x, y | ee143596a7e2a214e82f3406cefc7477ab720e6c | 74,958 |
import json
def transaction(PARAMETER):
"""
Returns details of a specific transaction.
[PARAMETER] is required and should be a transaction hash.
"""
d = urllib2.urlopen(blockexplorer('transaction') + '/' + str(PARAMETER))
return json.loads(d.read()) | a5124056450f994616f23511f34046d25bc21fc5 | 74,959 |
def _json_object_hook(dat):
"""Json hook to convert json object to named tuple
DO NOT CALL DIRECTLY"""
return namedtuple('X', dat.keys())(*dat.values()) | 143442f31189994ed1abe08e0639dac712c2e03a | 74,961 |
import requests
def rest(method, path, query_params=None, data=None):
"""Makes JSON API request and returns response as dictionary.
Usage example::
>>> rest('get', 'Members')
"""
try:
resp = session.request(
method=method,
url=_api_url(path),
para... | 518c870798d31b0541352d32fb9720494c7a1a9b | 74,962 |
from typing import Union
def generate_virus(root_directory: Directory, virus_id: int = -1, n: int = 1) -> Union[str, dict]:
"""Randomly places virus files throughout the system
starting at the directory specified
:param root_directory: The directory to start placing the virus files at
:param virus_id... | 1f56a37eee88e06402a03cc8eedc0bce0ea1ea2a | 74,963 |
def delogo(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#delogo"""
return filter(stream, delogo.__name__, *args, **kwargs) | 4370cb704001f101be70aae4a59aa2b6f8d718ec | 74,964 |
def process_history(raw_history, ignore_domains=None):
"""
Filter and sort given history data.
:param raw_history: list of history events.
:param ignore_domains: list of domains to filter out (using exact match
on each event's domain value). Defaults to None to not remove matching
domai... | 5184375a8cd794f2b7ad38876ed11d8759aad901 | 74,965 |
def get_list_of(key, ch_groups):
"""
Return a list of values for key in ch_groups[groups]
key (str): a key of the ch_groups[groups] dict
ch_groups (dict): a group-name-indexed dict whose values are
dictionaries of group information (see expand_ch_groups)
Example: get_list_of('system', ch_g... | f5bbc32c836d0de5e9aa2c055d97bacdfc794d0e | 74,966 |
def isMAGPYNEWABS(filename):
"""
Checks whether a file is ASCII DIDD (Tihany) format.
"""
try:
temp = open(filename, 'rt')
line = temp.readline()
except:
return False
if not line.startswith('# MagPy Absolutes'):
return False
return True | a3400c9de868e82e1c99f05452721f09b8764508 | 74,967 |
def getAccessFromFlags(flags):
"""
Variant of fmtAccessFlags that returns only one
of (public, private, protected) and not the other flags (final, native,
static)
"""
if flags & ACC_PUBLIC:
return 'public'
if flags & ACC_PRIVATE:
return 'private'
if flags & ACC_PROTECTED:... | f00e0668cc9cac264f6ed5ff77db2a8455258b53 | 74,968 |
from datetime import datetime
def parse_datetime(string, type='datetime'):
"""
A simple dateparser that detects common datetime formats
Parameters
----------
string : str
a date string in format as denoted below.
Returns
-------
datetime.datetime
datetime object of a... | f923b944b7f652ec5841ac30264de083f7240392 | 74,969 |
def get_url(search_term: str, rank: int = 1, genre: str = None) -> str:
"""Return the first result URL for the search term.
Rank can be changed (default 1: first result).
Genre can be changed (default None. Possible choices in ["Morceaux", "Albums",
"Films", "Livres", "Séries", "BD", "Jeux"])
Retur... | da516fa6c46a2634e5baf693c0fd862528f51d19 | 74,970 |
def token_with_customer_balance(chain, team_multisig, token, customer) -> Contract:
"""Create a Crowdsale token where transfer restrictions have been lifted."""
# Make sure customer 1 has some token balance
token.functions.transfer(customer, 10000).transact({"from": team_multisig})
return token | dca412bccc32daefcaae7bb180845e465517a048 | 74,971 |
def g2(self) -> tuple:
"""
Solve domino reduction.
Returns
-------
tuple of (list of str, dict of {'G2': int})
Moves to solve domino reduction, statistics (move count in ETM).
Notes
-----
Brute-force method using `ida_star` to solve domino reduction.
This stage is complete... | 19ba47b27eb28e2cd6524d676ce5e7be31ae58ca | 74,972 |
async def bots_search_page(request: Request, query: str):
"""For any potential Android/iOS app, crawlers etc. Query is the query to search for"""
return await render_search(request = request, q = query, api = True) | 6ab926f82d47538b78a4913e169607288671a420 | 74,973 |
import logging
async def execute(ctx, cmd, cwd=None, log=False, shell=None):
"""Process: Call arbitrary command as a processing task
Args:
ctx (object): contextual configuration
cmd (str): see ``utils.execute_command``
cwd (str, optional): see ``utils.execute_command``
log (bo... | ba03c1f11d4647f73a3214dc5e54eadf5723b639 | 74,974 |
def array_from_graph(graph, attr):
"""
Parameters
----------
graph : networkx.Graph
attr : str or iterable
If str, then it specifies the an attribute of the graph's nodes.
If iterable of strings, then multiple attributes of the graph's nodes
are specified.
Returns
... | fe36870b9c5e23e0967aa7c6b78a8d664f684048 | 74,975 |
def d2_g2_mapping(dim):
"""
Map each d2 blcok to the g2 blocks
:param dim: rank of spatial single-particle basis
:return:
"""
krond = np.eye(dim)
# d2 -> g2
def g2d2map_aa_or_bb(p, q, r, s, dim, key, factor=1.0):
"""
Accept pqrs of G2 and map to D2
"""
d... | e7e5d50f49169081ad124e21ef452ef1310ee20e | 74,976 |
def KL(Q, P):
"""
Compute Kullback-Leibler (KL) divergence between distributions Q and P.
"""
return sum([ q*log(q/p) if q > 0. else 0. for q,p in zip(Q,P) ]) | 326977a73fc53139dbc2267f99723251850845af | 74,977 |
def get_interfaces(args):
"""
Connect to device over NETCONF protocol and obtain list of interfaces.
This uses jnpr.junos.op.phyport.PhyPortTable
"""
dev = Device(host=args['hostname'], user=args['user'],
ssh_private_key_file=args['sshkey'],
ssh_config=args['sshcon... | 6c031bf9953fdb5330d00ef9da5d8d47df1fe264 | 74,978 |
def _middle(values):
"""Lower bound of median, without using numpy (heavy reqs)"""
n = len(values)
is_odd = n % 2
middle_idx = int((n + is_odd) / 2) - 1
return sorted(values)[middle_idx] | 2b3f342c700ecfde20eb7ce41d0d071b8be6e281 | 74,980 |
def get_daily_spread(orderbook_df, start_time='09:30:00', end_time='16:00:00'):
""" Get mean spread for the day's trading.
:param orderbook_df: preprocessed orderbook (see __name__.make_orderbook_for_analysis) for data without execution agent.
:param start_time: time to "start" trading day -- in fo... | c753e5283248cfef14ed8e2c14db80c87e0f9a43 | 74,981 |
def popkey(dct,key,default=NotGiven):
"""Return dct[key] and delete dct[key].
If default is given, return it if dct[key] doesn't exist, otherwise raise
KeyError. """
try:
val = dct[key]
except KeyError:
if default is NotGiven:
raise
else:
return def... | 0973481f5f4731dcb9d5a244904433de896f21ff | 74,982 |
def finalize(tournament, **params):
"""Finalize a tournament that has had all match scores submitted,
rendering its results permanent.
"""
return api.fetch_and_parse(
"POST",
"tournaments/%s/finalize" % tournament,
**params) | c207d2125328ebaad2328c7835b168061932746a | 74,983 |
def multiindex_col_ix(df, col):
"""Get the index into df.index.levels[] corresponding to a given "column
name" in a multiindex."""
return df.index.names.index(col) | b3c8df1e9d0b36e871fbfaece537704ad13ab7f1 | 74,984 |
def _replace_units(container, definitions):
"""
Convert the references in a UnitsContainer into valid pint Units, using
positional data argument units for each reference.
"""
unit = ureg.dimensionless
for name, exponent in container.items():
if name in definitions:
unit *= de... | 509ba8a3d55547959d55e079d964ce3f15ff1715 | 74,985 |
import json
def get_PQWER(champion):
"""
Consumes a champion name in string form and returns a dictionary containing
the champion's passive, Q, W, E, and R ability names and descriptions
Parameters:
-----------
champion string
Example:
-----------
get_PQWER("Malphite"... | f0611f8f37e7d8620ca57203511b87c90429e283 | 74,986 |
def inv_mulaw_quantize(y, mu=255):
"""Inverse transformation of mu-law quantization.
Args:
y (ndarray): Input signal.
mu (int): Mu.
Returns:
ndarray: Unquantized signal.
"""
return inv_mulaw(inv_quantize(y, mu), mu) | 0f2fb3988b7f1cecce891a2499e9264151fee87d | 74,987 |
from typing import Tuple
def dice(count: int = 1) -> Tuple[int, ...]:
"""
Rolls N dice
Parameters:
count (int) : The number of dice to roll, default = 1
Returns:
tuple: The values of dice rolls
Each tuple element is a number between 1 and 6
"""
res = ()
for _ in range(int(co... | 98e554ea682f72d7cfde289cffd36b38332989ad | 74,988 |
def get_be_time(encoded_date):
"""
Returns a reversed list.
@param encoded_date: NetworkList encoded time value.
"""
# Divides the provided value into a four sized element.
time_units_hex_le = [encoded_date[inx:inx + 2] for inx in range(0, 16, 2)]
# Reverse the list and the bytes.
... | fe5aa25adb4590a606a5671557ac9876b7b07c5b | 74,989 |
def error(Y, X):
"""
Calculates mean squared error (MSE) of the reconstructed data (X) relative
to the original data (Y). In theory, this number should decrease as the
order of the markov process increases and/or the number of components
involved in the original projection (if used) increases.
... | 16e392f3ee4bece24ff736e47dcb7cae242a1997 | 74,990 |
def process_multi_page_menu(pages):
"""Processes a menu in the multi page format"""
date = get_date(pages[0])
lunch = get_meal(multi_page_classify, pages[1])
dinner = get_meal(multi_page_classify, pages[2])
return {"dinner": dinner, "lunch": lunch, "base_date": date} | 825808ee3d2ee3a7b07d83ffe12e9abf026325ec | 74,991 |
def valid_integer(variable, min_length=None, max_length=None):
"""Returns boolean whether variable is valid input or not"""
# check if integer against is_integer function
if not is_integer(variable):
return False
# if max_length is specified, checks if integer is longer than max_length
if ... | 338772336d28e22931815b7c3fe1b374720bb8d1 | 74,992 |
def noise_label_discovery(dve_out, noise_idx):
"""Noise label discovery rate metrics.
Args:
dve_out: data values
noise_idx: noise index
Returns:
output_perf: noise label discovery rate (per 5 percentiles)
"""
# Sorting
divide = 20 # Per 100/20 percentile
sort_idx = np.argsort(dve_out)
neg... | 12277819b997282b626ba480cb0d86886d61128f | 74,993 |
def regnetx_002(pretrained=False, **kwargs):
"""RegNetX-200MF"""
return _create_regnet('regnetx_002', pretrained, **kwargs) | 2b5c8961b82986c9a8ed38e33a202b906435b1ff | 74,995 |
from typing import Tuple
def _get_undistortion_shifts(
depth_image: np.ndarray, intrinsics: Tuple[float, ...],
distortion: Tuple[float, ...]) -> Tuple[np.ndarray, np.ndarray]:
"""Returns difference between using and not using distortion.
Args:
depth_image: Opencv Image.
intrinsics: [fx, fy, cx, c... | a01c42f0809df2dc1ded5fc4e7ef1048c47adba8 | 74,997 |
import types
def _package_mkdir_redhat_release_iso_root(releasever: str) -> types.TaskDict:
"""
Create the RedHat packages root directory on the ISO for a given release.
"""
return targets.Mkdir(
directory=constants.REPO_REDHAT_ROOT / releasever,
task_dep=["_package_mkdir_redhat_iso_ro... | 536cf40b1b76a369eed6ebd3f213b1b9612d5a6c | 74,998 |
def normalize_keys(data):
"""Convert keys to lowercase"""
return {k.lower(): v for k, v in data.items()} | b23e2aff374d9413a5c9a63db1fdd955ae7f24a6 | 74,999 |
def encrypt(data, key, authenticator_key):
"""
Use this function to encrypt data.
Two keys must be provided, one to guarantee confidentiality
and another to guarantee integrity.
:param data: The data to encrypt.
:type data: :class:`str`
:param key: The key to encrypt the data, in byte stri... | 575d0cd879cc8c65bb4fe0abc4928bc08e247418 | 75,000 |
def rfUnitary(theta, phi):
"""
Gives the unitary operator for an ideal microwave gate.
phi gives the rotation axis on the plane of the bloch sphere (RF drive phase)
theta is the rotation angle of the gate (pulse area)
rfUnitary(theta, phi) := expm(-1j * theta / 2 * \
(sigmaX() * cos(phi) + ... | 4e6883f0eff311deef0d7319a5a5733c928a48f7 | 75,001 |
def push(data, spec, **kwargs):
"""
The opposite of fetch, this is responsible for writing data to some
destination in a specified mode defined by ``spec``.
:param data: The data to push
:type data: opaque
:param spec: The output spec
:type spec: dict
"""
mode = _detect_mode(spec)
... | d80e90fc6989a186322cefbe1de2137a54bfb3b0 | 75,002 |
def accuracy(y_pred, y, tags):
"""
Returns the accuracy of a classifier
"""
o_id = tags.index("O") if "O" in tags else None
correct = ignore = 0
for i, tag_id in enumerate(y):
if y_pred[i] == y[i]:
if tag_id == o_id:
ignore += 1
else:
... | 950108d475220dc7e16e62b873c4a5d7dbff0e97 | 75,004 |
def extract_entities(texts, pos_tagger, chunk_tagger):
"""
Extract entities (named entities, like persons and organizations,\
and nouns) from arrays of tokens
:param texts: Array of tokens
:param pos_tagger: Part of Speech tagger
:param chunk_tagger: Chunk tagger
"""
nouns = ['NC', 'N... | 4a732e4b34270461a6e36ee0af9a2e2a7a9f38a5 | 75,005 |
def frac_year(hour, leap_year=False):
"""
This function calculates the fraction of the year.
Parameters
----------
hour : integer, float
The hour of the day. Could be a decimal value.
leap_year : boolean
Indicates if the year is a leap year. Default
is False.
Return... | fe66678278a2257e5b8fc34af042b5a72b29596f | 75,006 |
def circle_rating(contour, area_factor=0.9, radius_factor=0.8):
"""
Returns a rating of how close is the circle to being a circle
:param contour: the contour that its rating is calculated
:param area_factor: the factor (p-value) that separates an area ratio that is a circle and one that isn't
:para... | f534262e588009d80f75b2173b51365492840bd0 | 75,007 |
def _normalized_black_call_using_norm_cdf(x, s):
"""
b(x,s) = Φ(x/s+s/2)·exp(x/2) - Φ(x/s-s/2)·exp(-x/2)
= Φ(h+t)·exp(x/2) - Φ(h-t)·exp(-x/2)
with
h = x/s and t = s/2
:param x:
:type x: float
:param s:
:type s: float
:return:... | c30de5f0a10bef5a3322b0d2ce6830961f91f770 | 75,008 |
def find_direction(start, image, seglen):
"""
Parameters
----------
start :
image :
seglen :
Returns
-------
"""
n_angles = 20
angles = np.arange(n_angles) * np.pi * 2 / n_angles
detect_angles = angles
weighted_vector = np.zeros(2)
... | 698b8e5918a3e9d7933814a2c57670e983d75e40 | 75,009 |
def do_list(args):
"""
Handle the list command.
Current filters limited to --retired and --incomplete,
but more will hopefully be implemented in the near future.
"""
global machines
def filter_machine(machine):
"""
Check if machine matches the flags passed. (ie retired, owne... | a6180e21320a5f0df3d2afcca03d831b90f7e3e0 | 75,010 |
def get_user_answers_count(user_id):
"""Return total answers number for the user."""
user = get_object_or_404(User, pk=user_id)
if check_user_has_groups(user, 'admin'):
return get_admin_answers_count()
if check_user_has_groups(user, 'teacher'):
return get_teacher_answers_count(user_id)... | 2a2b9b2ff42de491f29ffe59f12c634e88b3ac96 | 75,012 |
def int_wrapper(string):
"""A helper function."""
if string.startswith('#$'):
return int(string[2:], base=16)
elif string.startswith('$'):
return int(string[1:], base=16)
return int(string, 0) | 909ed1ab0d3a2f6909ae5fb819e63a4658e7a521 | 75,013 |
def oo_flatten(data):
""" This filter plugin will flatten a list of lists
"""
if not isinstance(data, list):
raise errors.AnsibleFilterError("|failed expects to flatten a List")
return [item for sublist in data for item in sublist] | fc54e6ccdf74986e9a385dbe40cd1d9fa1612f92 | 75,014 |
def _fftn(
input_arr: np.ndarray | Array,
output_arr: np.ndarray | Array = None,
axes: tuple[int, ...] | None = None,
inplace: bool = False,
fast_math: bool = True,
*,
_inverse: bool = False,
_real_out=False,
) -> Array:
"""Perform fast Fourier transformation on `input_array`.
P... | ed91a553c1a9b46e5d30dfe1840500b39d2517fb | 75,015 |
def explore_node(_, uid):
"""Same as explore view but with shortened URL"""
if not models.Node.objects.filter(uid=uid).exists():
return redirect("openy:home")
return redirect("openy:explore", slug=models.Node.objects.get(uid=uid).slug) | 3724905555d1675dc2c3bb3cb2822c81fd6c5a6c | 75,016 |
def box_calc(size_xyz, pallet_xyz):
"""Calculates a list of points to store parts in a pallet"""
[size_x, size_y, size_z] = size_xyz
[pallet_x, pallet_y, pallet_z] = pallet_xyz
xyz_list = []
for h in range(int(pallet_z)):
for j in range(int(pallet_y)):
for i in range(int(pall... | 0ed2b14e117b1f66be67579136f0f25432367284 | 75,017 |
def get_builds(id):
"""return build details about an advisory"""
return get_json('%s/brew/list_files/%s.json' % (ET_SERVER, id)) | d637c68231dd506afa15d862a538f9fc0b3bac22 | 75,018 |
def average_country_temp(cities_data):
"""
Return a dictionary whose key:value pair is country name:its average temp. The size of the
returned dictionary must equal the number of countries represented.
"""
d = dict()
for country in country_list(cities_data):
t = []
for r in citie... | b78f224de4fc02ab1768558dee9416b147067be6 | 75,019 |
def get_mvdr_vector(atf_vector, noise_psd_matrix):
"""
Returns the MVDR beamforming vector.
:param atf_vector: Acoustic transfer function vector
with shape (..., bins, sensors)
:param noise_psd_matrix: Noise PSD matrix
with shape (bins, sensors, sensors)
:return: Set of beamforming ... | 7c75ce82e680b8ccf9e08d20d557cb19e3c22dc6 | 75,020 |
import pandas
def calculate_volumes_to_replace(trials_table: pandas.DataFrame) -> pandas.Series:
"""
Get exactly which volumes to replace with which values.
"""
volumes = dict()
for i in trials_table.index:
start = trials_table["trial_start"][i]
end = trials_table["trial_end"][i]
... | 8bff9653a716b15a9deea2510f206759c734d91d | 75,021 |
def markdown_filter(value):
"""Processes the given value as Markdown, optionally using a particular
Markdown style/config
Syntax::
{{ value|markdown }} {# uses the "default" style #}
{{ value|markdown:"mystyle" }}
Markdown "styles" are defined by the `MARKDOWN_DEUX_STYLES` ... | d092dbc8dd11c9261a58fb089db0587827589bd7 | 75,022 |
def load_word_embeddings(embedding_path, embedding_dimension, pad_token, unknown_token):
""" function used to load word embeddings """
# list of words
words = [pad_token, unknown_token]
# their indices
index_of_word = 2
# dictionary that maps: word -> index
word_to_index_glove = {pad_token: ... | e11e945eeb3f51c88d455c07cb172f1a3c16f8a7 | 75,023 |
def get_prauc(frame, y, yhat, pos=1, neg=0, res=0.01):
""" Calculates precision, recall, and f1 for a pandas dataframe of y and yhat values.
Args:
frame: Pandas dataframe of actual (y) and predicted (yhat) values.
y: Name of actual value column.
yhat: Name of predicted value column.
... | 91d1b8bb4def8be902a2a7f2f26bf5aa2e88e055 | 75,024 |
def create_http_headers(
context_stack=None, tracer=None, new_span_id=False,
):
"""
Generate the headers for a new zipkin span.
.. note::
If the method is not called from within a zipkin_trace context,
empty dict will be returned back.
:returns: dict containing (X-B3-TraceId, X-B3... | 845cec9425c88716c239def6685772502e245e29 | 75,026 |
def dEdt_sync(energy, B):
"""
Compute loss via synchrotron radiation.
From M. Longair, High Energy Astrophysics
Parameters
----------
- energy (quantity): energy array homogeneous to GeV
- B (quantity): magnetic field strength homogeneous to Gauss
Outputs
--------
- Energy loss... | 8572f9ec29a3b9d168db69e45d7da7c574c05cc9 | 75,027 |
def convolution(inp, outmaps, kernel,
pad=None, stride=None, dilation=None, group=1,
w_init=None, b_init=None,
base_axis=1, fix_parameters=False, rng=None, with_bias=True):
"""
N-D Convolution with a bias term.
For Dilated Convolution (a.k.a. Atrous Convolusi... | 1c655dc8fc892fd7cf64f2212e6b4dd2bbcf64ae | 75,028 |
def register_authorizer(instance, **options):
"""
registers a new authorizer or replaces the existing one.
if `replace=True` is provided. otherwise, it raises an error
on adding an authorizer which is already registered.
:param AbstractAuthorizerBase instance: authorizer to be registered.
... | a0d5ce60800a5bfbb4a73bfdbb116e40422ae4a2 | 75,029 |
def draw_labeled_videos(samples, output_dir, label_fields=None, config=None):
"""Renders annotated versions of the videos in the collection with the
specified label data overlaid to the given directory.
The filenames of the videos are maintained, unless a name conflict would
occur in ``output_dir``, in... | e47737b51a5356e8199f8217951dc9da55bb1cff | 75,030 |
def clamp(n: _N, minn: _N, maxn: _N) -> _N:
"""
Clamps a number between a minimum and maximum value.
:param n: Original value.
:param minn: Minimum allowed value.
:param maxn: Maximum allowed value.
:returns: Clamped value.
"""
if n > maxn:
return maxn
elif n < minn:
... | 753691ee0146eb86e2bcfa9360cdb604b0434e8e | 75,031 |
import json
import tqdm
def load_word_file(f_input):
"""
Get all words in files
:param string: input file
"""
file_words = {}
data_list = json.load(open(f_input, mode='r', encoding='utf-8'))
words = []
for dic in tqdm(data_list):
try:
postag = dic['postag']
... | 888aa9b973ae30ab9283c03ba15781269756875c | 75,032 |
from typing import Callable
def skip_unless(condition: bool, reason: str) -> Callable[[TV], TV]:
"""A test decorator which will skip the decorated test unless a condition is set
For example:
class MyTestCase(TestCase):
@skip_unless(HAS_FOO, "Cannot test without foo")
def test_foo(self):
... | 6a5085f378d8a2571a176e6842d98cb9aea53942 | 75,034 |
import torch
def predict3d(xy_hm, zy_hm, xz_hm):
"""
Predict normalized 3d skeleton joints
Args:
outs (list, list, list): output of the model
Returns:
torch tensor of normalized skeleton joints with shape (BATCH_SIZE, NUM_JOINTS, 3)
Note:
predi... | 31f53d27a3ef97d876697d908b049f9fce15bf7b | 75,036 |
def getMinute(date):
"""Extracts the minutes from a date, ranging from 0-59.
Args:
date (Date): The date to use.
Returns:
int: An integer that is representative of the extracted value.
"""
return date.minute | f4ef0c563028f4090b26642f36359c343c519ad6 | 75,037 |
import time
def poll_for_events(hc, stack_name, action=None, poll_period=5, marker=None):
"""Continuously poll events and logs for performed action on stack."""
if action:
stop_status = ('%s_FAILED' % action, '%s_COMPLETE' % action)
stop_check = lambda a: a in stop_status
else:
st... | 6cdd2ffa59487a5e83c7d438175667f38c4ba0a4 | 75,038 |
def coverage_test(hce_list, nhce_list, conservative=True):
"""
Run the coverage test on employees.
Note: This is assuming we calculate based on 1.410(b)(1)(b).
Source: https://www.law.cornell.edu/cfr/text/26/1.410(b)-2
"""
if conservative:
hce_benefit_percentage = (
len([hc... | d9ee09fdd5232cc280a1a7a1670633eb43235347 | 75,039 |
def ft_fwd(a):
"""Forward Fourier transform.
Parameters
----------
a : `numpy.ndarray`
ndarray of shape (m, n)
Returns
-------
`numpy.ndarray`
complex-valued FT of shape (m, n)
Notes
-----
this function makes those that use it clearer, replacing
ft_fwd(a)))... | 0386278bcee381b47b771866037cc3b31689cfe0 | 75,040 |
def function_intercept(intercepted_func, intercepting_func):
"""
Intercepts a method call and calls the supplied intercepting_func with the result of it's call and it's arguments
Example:
def get_event(result_of_real_event_get, *args, **kwargs):
# do work
return result_of_re... | 28cfa1e873500cc9ca87a9c07275683cf41a33ae | 75,041 |
import re
def remove_erhua(text):
"""
去除儿化音词中的儿:
他女儿在那边儿 -> 他女儿在那边
"""
new_str = ''
while re.search('儿', text):
a = re.search('儿', text).span()
remove_er_flag = 0
if ER_WHITELIST_PATTERN.search(text):
b = ER_WHITELIST_PATTERN.search(text).span()
... | 49e721a8269df2a521957898c64e662ba7bf470e | 75,042 |
def is_ref(prop):
"""
Returns True if prop is a reference.
"""
return list(prop.keys()) == ['$ref'] | 3c52ba784d3d490cf44a60d5d35b2251b640eeff | 75,043 |
def evaluate_min_distance_xy(pred_xyp, gt_xy, p_threshold):
"""
:param pred_xyp: distribution over xy at a given time lag, in m
assume sum p = 1
:param gt_xy: coordinates in m
:param p_threshold: minimum probability prediction to be considered
:return:
"""
if gt_xy.size == 0:
ret... | 888bd96d60248596dbaa34e6c0440bb702c63408 | 75,045 |
def get_models(ctx_cmip5, var, table, expts, nens):
"""
Get a list of all models for a given variable for each experiment and store them in a dictionary
:param ctx_cmip5: a esgf-pyclient context of all cmip5
:param var: variable to test
:param table: corresponding cmor_table for var... | 34f04c1d65c4c64e4f945a45c2f956477f6a40c5 | 75,046 |
from typing import List
import collections
def molecular_formula_from_symbols(symbols: List[str], order: str = "alphabetical") -> str:
"""
Returns the molecular formula for a list of symbols.
Parameters
----------
symbols: List[str]
List of chemical symbols
order: str, optional
... | 82142bcae734f89c46e9fce854fdf6de080d8fd7 | 75,047 |
def dump(widget, *a, **kw):
"""Dump a TTWidgets WIDGET, showing info about the parent Frame and all child
Label widgets used to represent the compound TTWidgets WIDGET.
See each TTWidget's custom dump method for details.
"""
try:
return widget.dump(*a, **kw)
except AttributeError:
... | cc5c316890317e80c737e98383a7c686b828d435 | 75,048 |
def indices_to_sparse(p, tag, type0, i0, type1, i1, sign = 0):
"""Auxiliary function for function sparse_from_indices()
The function deals with adressing a vector v of the monster
group representation in the form v[tag, i0, i1]. Here
tag, i0, and i1 refer to the index of a (possible negated)
comp... | a240992c4a030aef83495d87cf6d665511d2de76 | 75,049 |
def emission_counts(tokenlists, taglists):
""" Function to find emission counts for each word and their associated POS tag. It returns a dictionary
containing the corpus' emission counts for each token/tag pair. This function specifically caters to files
with the format of the Brown corpus. This fun... | cc1de55a14a906557f8d873bc7def47dcdc52732 | 75,050 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.