content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def read_cesar_out(cesar_line):
"""Return ref and query sequence."""
cesar_content = cesar_line.split("\n")
# del cesar_content[0]
fractions = parts(cesar_content, 4)
cesar_fractions = []
for fraction in fractions:
if len(fraction) == 1:
continue
ref_seq = fraction[1]... | fb1a1a66647fb6d3e6fec1b27d26836067c6b023 | 14,070 |
def aa_i2c_slave_write_stats (aardvark):
"""usage: int return = aa_i2c_slave_write_stats(Aardvark aardvark)"""
if not AA_LIBRARY_LOADED: return AA_INCOMPATIBLE_LIBRARY
# Call API function
return api.py_aa_i2c_slave_write_stats(aardvark) | 87e64465b1bc79c7ab48e39274e39cab17f74755 | 14,071 |
import json
def get_aliases_user(request):
"""
Returns all the Aliases
API_ENDPOINT:api/v1/aliases
----------
payload
{
"email":"[email protected]"
}
"""
alias_array = []
payload = {}
print("came to get_aliases_user()")
data_received = json.loads(request.body)
email = dat... | 2501fa15bafc2214585bd1e7d568a9a685725020 | 14,072 |
def _sorted_attributes(features, attrs, attribute):
"""
When the list of attributes is a dictionary, use the
sort key parameter to order the feature attributes.
evaluate it as a function and return it. If it's not
in the right format, attrs isn't a dict then returns
None.
"""
sort_key =... | 473c3d30c4fde5f00932adfb50c4d34c08324d54 | 14,073 |
def ldensity_laplace_uniform_dist(prob_laplace, location, scale, low, high,
val):
"""
A mixture of a Laplace and a uniform distribution
"""
return np.log((prob_laplace * np.exp(-np.abs(val - location) / scale) / (2 * scale))
+ ((1 - prob_laplace) / (hi... | b069b2de4c2da3c69245b6a5507b61e918d5bb76 | 14,075 |
def readConfirmInput():
"""asks user for confirmation
Returns:
bool: True if user confirms, False if doesn't
"""
try:
result = readUserInput("(y/n): ") # UnrecognisedSelectionException
return 'y' in result[0].lower() # IndexError
except (UnrecognisedSelectionExcept... | 007fe5e0002711db7cd0bcb1869dcbef9c667213 | 14,076 |
def linkElectron(inLep, inLepIdx, lepCollection, genPartCollection):
"""process input Electron, find lineage within gen particles
pass "find" as inLepIdx of particle to trigger finding within the method"""
linkChain = []
lepIdx = -1
if inLepIdx == "find":
for Idx, lep in enumerate(lepCollec... | 87747414f5e086f16a455dbc732f86ddcb0db630 | 14,077 |
def status():
"""Determines whether or not if CrowdStrike Falcon is loaded.
:return: A Boolean on whether or not crowdstrike is loaded.
:rtype: bool
.. code-block:: bash
salt '*' crowdstrike.status
"""
if not __salt__['crowdstrike.system_extension']():
# if we should be using... | e9bdbce3e290967b95d58ddf75c2054e06542043 | 14,078 |
def sparse_search(arr, s):
""" 10.5 Sparse Search: Given a sorted array of strings that is interspersed
with empty strings, write a method to find the location of a given string.
EXAMPLE:
Input: find "ball" in {"at", "", "", "" , "ball", "", "", "car", "" , "" , "dad", ""}
Output: 4
"""
def ... | 605a56c518539117a83382c9e73d37d5e56b535f | 14,079 |
import uuid
def uuid_pk():
"""
Generate uuid1 and cut it to 12.
UUID default size is 32 chars.
"""
return uuid.uuid1().hex[:12] | 9efb12a6e72b02adcd4a64ca721ceab8c688055a | 14,080 |
def infected_symptomatic_00x80():
"""
Real Name: b'Infected symptomatic 00x80'
Original Eqn: b'Infected symptomatic 00+Infected symptomatic 80'
Units: b'person'
Limits: (None, None)
Type: component
b''
"""
return infected_symptomatic_00() + infected_symptomatic_80() | 0a3500659fad466c92fcd3d073003094c56efe9d | 14,081 |
def stencilCompare(firstElem, secondElem):
"""
stencilCompare(const std::pair< int, FP_PRECISION > &firstElem, const std::pair< int,
FP_PRECISION > &secondElem) -> bool
Comparitor for sorting k-nearest stencil std::pair objects
"""
return _openmoc.stencilCompare(firstElem, secondElem) | 3eda1a57e521134e77ba55ae38771f151699fdfd | 14,082 |
import random
def bisect_profiles_wrapper(decider, good, bad, perform_check=True):
"""Wrapper for recursive profile bisection."""
# Validate good and bad profiles are such, otherwise bisection reports noise
# Note that while decider is a random mock, these assertions may fail.
if perform_check:
if decide... | 8fbe2f018c7dfb7fdeb71dd5080993a9773a41d7 | 14,083 |
import typing
def rolling_median_with_nan_forward_fill(vector: typing.List[float], window_length: int) -> typing.List[float]:
"""Computes a rolling median of a vector of floats and returns the results. NaNs will be forward filled."""
forward_fill(vector)
return rolling_median_no_nan(vector, window_length) | 708cd1f6371846ea3b7acb4d7b59a7a61f85de7c | 14,084 |
from typing import Optional
from typing import Dict
def Subprocess(
identifier: Optional[str] = None, variables: Optional[Dict] = None,
env: Optional[Dict] = None, volume: Optional[str] = None
) -> Dict:
"""Get base configuration for a subprocess worker with the given optional
arguments.
Paramete... | 97a90179c91ec862c6008e12ae6c12368ec301c5 | 14,086 |
def get_var(name):
"""
Returns the value of a settings variable.
The full name is CONTROLLED_VOCABULARY_ + name.
First look into django settings.
If not found there, use the value defined in this file.
"""
full_name = "CONTROLLED_VOCABULARY_" + name
ret = globals().get(full_name, None)
... | 3c7b5507a387917b9639510023948571160b5973 | 14,087 |
def get_schema_from_dataset_url_carbon(dataset_url,
key=None,
secret=None,
endpoint=None,
proxy=None,
proxy_port=None,
... | 2c562e39232dfbe1ac7359d0c88bd2a1efa5a334 | 14,088 |
import time
def get_all_metrics(model, epoch, val_x, val_y, start_time, loss_fn):
"""每个epoch结束后在发展集上预测,得到一些指标
:param model: tf.keras.Model, epoch训练后的模型
:param epoch: int, 轮数
:param val_x: tf.data.Dataset, 发展集的输入, 和val_y一样的sample_size
:param val_y: tf.data.Dataset, 发展集的标签
:param start_time: ti... | 24025cbdcc702ca32c5887f1ec2ccf424d492e69 | 14,089 |
def get_labels(decode_steps: DecodeSteps) -> LabelsDict:
"""Returns labels dict given DecodeSteps."""
return {
"target_action_types": decode_steps.action_types,
"target_action_ids": decode_steps.action_ids,
} | 66047e41b3d173e53b676a60e48647e3862aac16 | 14,090 |
def get_body_barycentric_posvel(body, time, ephemeris=None):
"""Calculate the barycentric position and velocity of a solar system body.
Parameters
----------
body : str or other
The solar system body for which to calculate positions. Can also be a
kernel specifier (list of 2-tuples) if... | 41be03294a5cd21163afae9650f556fc64257110 | 14,091 |
def recurDraw(num, data):
"""
Purpose: to draw polygons
Parameters: num - indicator of what layer the program is on, data - instance
of the Data class
Returns: data - instance of the data class
Calls: recurDraw - itself, Data - data processing class, toDraw - drawing
intermediary function
... | d94d2f250396b6acfcf02306fd78b180f070aa92 | 14,092 |
def cont4():
"""
Two clusters, namely <cont1> (5 contours) and <cont3> 4 contours).
The enclosing contours of the clusters have a different value.
Contains 3 minima.
"""
cont_min = [
cncc(5, (6.00, 3.00), 0.2, (1, 1)),
cncc(2, (7.00, 4.00), 0.1, (4, 1), rmin=0.15),
cncc(2... | c83cb48c3bc257dcf1ead50312d186464acdd57d | 14,093 |
def predict(test_data, qrnn, add_noise = False):
"""
predict the posterior mean and median
"""
if add_noise:
x_noise = test_data.add_noise(test_data.x, test_data.index)
x = (x_noise - test_data.mean)/test_data.std
y_prior = x_noise
y = test_data.y_noise
y... | d45e843d529babb99baa160ad976c0c9753da42d | 14,094 |
def handle_login_GET():
"""
Displays the index (the login page).
"""
if request.args.get('next'):
url_kwargs = dict(next=request.args.get('next'))
else:
url_kwargs = {}
try:
weblab_api.api.check_user_session()
except SessionNotFoundError:
pass # Expected beha... | f496519518b5d3b8a71ff4a8e60be2a2fe2110f3 | 14,095 |
import copy
def get_role_actions():
"""Returns the possible role to actions items in the application.
Returns:
dict(str, list(str)). A dict presenting key as role and values as list
of actions corresponding to the given role.
"""
return copy.deepcopy(_ROLE_ACTIONS) | 79b53e4003b1dc9264d9210f03395ce32d737c1e | 14,096 |
import json
def jsons_str_tuple_to_jsons_tuple(ctx, param, value):
"""
Converts json str into python map
"""
if value is None:
return []
else:
return [json.loads(a) for a in value] | 8b6f03650d566d74b0400868f12b59c2fa37bc3e | 14,097 |
def voucher_and_partial_matches_with_coupons(voucher_and_partial_matches):
"""
Returns a voucher with partial matching CourseRuns and valid coupons
"""
context = voucher_and_partial_matches
products = [
ProductFactory(content_object=course_run)
for course_run in context.partial_match... | 4f9e5732b0f3863504dec2aeef1309c0c24abc77 | 14,100 |
import batman
def one_transit(t=np.linspace(0,27,19440),
per=1., rp=0.1, t0=1., a=15., inc=87., ecc=0.,
w=90., limb_dark ='nonlinear', u=[0.5,0.1,0.1,-0.1]):
"""
~Simulates a one-sector long TESS light curve with injected planet transits per input parameters.~
Requires: ba... | 4bb9a59e307cdab7554c10ae952279588c47bd94 | 14,101 |
def activate(request: Request) -> dict:
"""View to activate user after clicking email link.
:param request: Pyramid request.
:return: Context to be used by the renderer.
"""
code = request.matchdict.get('code', None)
registration_service = get_registration_service(request)
return registrati... | ccc543ff740d3c7ebbe7e0404c0ef6a7fc310866 | 14,103 |
def _create_eval_metrics_fn(
dataset_name, is_regression_task
):
"""Creates a function that computes task-relevant metrics.
Args:
dataset_name: TFDS name of dataset.
is_regression_task: If true, includes Spearman's rank correlation
coefficient computation in metric function; otherwise, defaults t... | 732baaf729739d7150f09185233efaa873045605 | 14,104 |
def brighter(rgb):
"""
Make the color (rgb-tuple) a tad brighter.
"""
_rgb = tuple([ int(np.sqrt(a/255) * 255) for a in rgb ])
return _rgb | f1d6ba4deea3896ce6754d622913b7f2d2af91e4 | 14,105 |
def delete_workspace_config(namespace, workspace, cnamespace, config):
"""Delete method configuration in workspace.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
mnamespace (str): Method namespace
method (str): Method name
Swagger... | e86106fc6eabc0f1ae703e31abe3283e9df3e31b | 14,106 |
import math
def test_filled_transparent_graphs_2():
""" Two functions with transparend grid over them """
coordinate_system = cartesius.CoordinateSystem()
coordinate_system.add(
charts.Function(
math.sin,
start = -4,
end = 5,
... | 9cc51358b2e92a869ea318ac8d18f3b9ea988012 | 14,107 |
def get_shader_code(name):
""" Returns the shader as a string """
fname = op.join( op.dirname(__file__), name )
if op.exists( fname ):
with open(fname) as f:
return f.read() | bdd21d6c36b5e71608d48ecdce32adb79bb58428 | 14,108 |
import torch
def compute_translation_error(pred_pose, gt_pose, reduction="mean"):
"""
Computes the error (meters) in translation components of pose prediction.
Inputs:
pred_pose - (bs, 3) --- (x, y, theta)
gt_pose - (bs, 3) --- (x, y, theta)
Note: x, y must be in meters.
"""
... | e1e0863c37a3c42e3081d5b21f529172315ccb66 | 14,109 |
def get_base_snippet_action_menu_items(model):
"""
Retrieve the global list of menu items for the snippet action menu,
which may then be customised on a per-request basis
"""
menu_items = [
SaveMenuItem(order=0),
DeleteMenuItem(order=10),
]
for hook in hooks.get_hooks('regis... | d741097c3e75764578e3f1aa6cc33cb194a40b42 | 14,110 |
def assign_file(package, source):
"""Initializes package output class.
Parameters
----------
package : :obj:`str`
Name of the package that generated the trajectory file.
source : :obj:`str`
Path to the trajectory file.
Returns
-------
The class corresponding to the ... | 70f01dc69ef87738fd87b6c321787d7159a85e3a | 14,111 |
import logging
def _magpie_register_services_with_db_session(services_dict, db_session, push_to_phoenix=False,
force_update=False, update_getcapabilities_permissions=False):
# type: (ServicesSettings, Session, bool, bool, bool) -> bool
"""
Registration procedu... | b2f96f213f1ab84e7be56788a1b4dad6d93dbe16 | 14,112 |
def journal(client):
"""
Fetch journal entries which reference a member.
"""
client.require_auth()
with (yield from nwdb.connection()) as conn:
cursor = yield from conn.cursor()
yield from cursor.execute("""
select A.tx_id, A.wallet_id, A.debit, A.credit, B.currency_id, C.nar... | 06eada531634f25ba076114b3858eae0a75b1807 | 14,113 |
def triplet_to_rrggbb(rgbtuple):
"""Converts a (red, green, blue) tuple to #rrggbb."""
hexname = _tripdict.get(rgbtuple)
if hexname is None:
hexname = '#%02x%02x%02x' % rgbtuple
_tripdict[rgbtuple] = hexname
return hexname | 9ba66d9aadb8385726178b32d69e14adfe380229 | 14,114 |
import math
def stab_cholesky(M):
""" A numerically stable version of the Cholesky decomposition.
Used in the GLE implementation. Since many of the matrices used in this
algorithm have very large and very small numbers in at once, to handle a
wide range of frequencies, a naive algorithm can end up having... | 73f2989bb77513090b8ccbcf99b5f31a3aab9115 | 14,115 |
from datetime import datetime
import json
def prodNeventsTrend(request):
"""
The view presents historical trend of nevents in different states for various processing types
Default time window - 1 week
"""
valid, response= initRequest(request)
defaultdays = 7
equery = {}
if 'days' in r... | 55b7fcbf352e98b01ce4146ff5b5984c86c435d3 | 14,116 |
def create_storage_policy_zios(session, cloud_name, zios_id, policy_name, drive_type, drive_quantity,
policy_type_id, description=None, return_type=None, **kwargs):
"""
Creates a new policy to ZIOS.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.... | 16cec8686df1fb634064e75478364285dcfc3c1d | 14,117 |
def format_tooltips(G, **kwargs):
""" Annotate G, format tooltips.
"""
# node data = [(n, {...}), ...]
node_data = {}
if isinstance(G, nx.Graph):
node_data = G.nodes(True)
elif 'nodes' in G:
node_data = [(d["id"], d) for d in G['nodes']]
# unique ids
member_uids = np.sor... | cfbfc3012dffce017110288847f3bcefa4612645 | 14,118 |
def add_centroid_frags(fragList, atmList):
"""Add centroid to each fragment."""
for frag in fragList:
atoms = [atmList[i] for i in frag['ids']]
frag['cx'], frag['cy'], frag['cz'] = centroid_atmList(atoms)
return fragList | 1f050fcf0b60a7bb62d6d5be844b9a895e91fc7f | 14,120 |
def _apply_sobel(img_matrix):
"""
Input: img_matrix(height, width) with type float32
Convolves the image with sobel mask and returns the magnitude
"""
dx = sobel(img_matrix, 1)
dy = sobel(img_matrix, 0)
grad_mag = np.hypot(dx, dy) # Calculates sqrt(dx^2 + dy^2)
grad_mag *= 255 ... | 5c297cf822e1d5cba092070ecb52f57b1dbe720b | 14,122 |
def isDeleted(doc_ref):
"""
Checks if document is logically deleted, i.e. has a deleted timestamp.
Returns: boolean
"""
return exists(doc_ref) and 'ts_deleted' in get_doc(doc_ref) | 0c7357357edfc645c771acbe40730cb4668fe13e | 14,123 |
from typing import Optional
def sys_wait_for_event(
mask: int, k: Optional[Key], m: Optional[Mouse], flush: bool
) -> int:
"""Wait for an event then return.
If flush is True then the buffer will be cleared before waiting. Otherwise
each available event will be returned in the order they're recieved.
... | 4c0ba8f8b49f0f0dc837739afb46f667785b8a8c | 14,124 |
def get_test():
"""
Return test data.
"""
context = {}
context['test'] = 'this is a test message'
return flask.jsonify(**context) | 01f99a070a61414461d9a407574591f715ca5c63 | 14,125 |
def num_poisson_events(rate, period, rng=None):
"""
Returns the number of events that have occurred in a Poisson
process of ``rate`` over ``period``.
"""
if rng is None:
rng = GLOBAL_RNG
events = 0
while period > 0:
time_to_next = rng.expovariate(1.0/rate)
if time_to_... | 0f2378040bcf6193507bd15cb01c9e753e5c5235 | 14,126 |
import fnmatch
def findmatch(members,classprefix):
"""Find match for class member."""
lst = [n for (n,c) in members]
return fnmatch.filter(lst,classprefix) | 05038eb4796161f4cc64674248473c01fd4b13aa | 14,127 |
def is_narcissistic(number):
"""Must return True if number is narcissistic"""
return sum([pow(int(x), len(str(number))) for x in str(number)]) == number | b94486d4df52b7108a1c431286e7e86c799abf58 | 14,128 |
def Plot1DFields(r,h,phi_n_bar,g_s,g_b):
"""
Generates a nice plot of the 1D fields with 2 axes and a legend.
Note: The sizing works well in a jupyter notebook
but probably should be adjusted for a paper.
"""
fig,ax1 = plt.subplots(figsize=(6.7,4))
fig.subplots_adjust(right=0.8)
ax2 = a... | 3e48dc6745e49ca36a2d9d1ade8b684ac24c3c25 | 14,129 |
def get_yesterday():
"""
:return:
"""
return _get_passed_one_day_from_now(days=1).date() | 99201bd9cde9fdf442d17a6f1c285523e3b867cc | 14,130 |
def classroom_mc():
"""
Corresponds to the 2nd line of Table 4 in https://doi.org/10.1101/2021.10.14.21264988
"""
concentration_mc = mc.ConcentrationModel(
room=models.Room(volume=160, inside_temp=models.PiecewiseConstant((0., 24.), (293,)), humidity=0.3),
ventilation=models.MultipleVent... | c272bc1de9b5b76eb55aa5b8d6dfbe42d2c95e66 | 14,131 |
import linecache
import ast
def smart_eval(stmt, _globals, _locals, filename=None, *, ast_transformer=None):
"""
Automatically exec/eval stmt.
Returns the result if eval, or NoResult if it was an exec. Or raises if
the stmt is a syntax error or raises an exception. If stmt is multiple
statements ... | d314e1a2f5536304f302ca7c79875a894275b171 | 14,132 |
def cmip_recipe_basics(func):
"""A decorator for starting a cmip recipe
"""
def parse_and_run(*args, **kwargs):
set_verbose(_logger, kwargs.get('verbose'))
opts = parse_recipe_options(kwargs.get('options'), add_cmip_collection_args_to_parser)
# Recipe is run.
returnval = func... | 3411b68180d878802379a413524f9a3db185a654 | 14,135 |
def serialize_cupcake(cupcake):
"""Serialize a cupcake SQLAlchemy obj to dictionary."""
return {
"id": cupcake.id,
"flavor": cupcake.flavor,
"size": cupcake.size,
"rating": cupcake.rating,
"image": cupcake.image,
} | 35fa140cf8b6527984002e28be1f102ee6c71a1b | 14,137 |
def compute_accuracy(labels, logits):
"""Compute accuracy for a single batch of data, given the precomputed logits
and expected labels. The returned accuracy is normalized by the batch size.
"""
current_batch_size = tf.cast(labels.shape[0], tf.float32)
# logits is the percent chance; this gives the category... | 2e53fc01053a5caafa2cdd976715dd31d3d43b0f | 14,138 |
import torch
def get_data(generic_iterator):
"""Code to get minibatch from data iterator
Inputs:
- generic_iterator; iterator for dataset
Outputs:
- data; minibatch of data from iterator
"""
data = next(generic_iterator)
if torch.cuda.is_available():
data = data.cuda()
r... | 364151694fb452279691986f5533e182a8b905f3 | 14,139 |
from re import T
def aug_transform(crop, base_transform, cfg, extra_t=[]):
""" augmentation transform generated from config """
return T.Compose(
[
T.RandomApply(
[T.ColorJitter(cfg.cj0, cfg.cj1, cfg.cj2, cfg.cj3)], p=cfg.cj_p
),
T.RandomGrayscale(p=... | 4d8ac62e4ad550f563d9adb237db8853a0c7d36a | 14,140 |
def _check_definition_contains_or(definition_dict, key, values):
"""need docstring"""
out = False
for value in values:
if (np.array(list(definition_dict[key])) == value).any():
out = True
break
return out | bb15bdbe50476ea46425be20e0c35229352ba03f | 14,141 |
def concurrent_map(func, data):
"""
Similar to the bultin function map(). But spawn a thread for each argument
and apply `func` concurrently.
Note: unlike map(), we cannot take an iterable argument. `data` should be an
indexable sequence.
WARNING : this function doesn't limit the number of thr... | d88c66af120f9a4408bf6e1d61c08f2fdcf81acd | 14,142 |
def star_hexagon(xy, radius=5, **kwargs):
"""
|\
c | \ b
|__\
a
"""
x,y = xy
r = radius
a = 1/4*r
b = a*2
c = a*3**(1/2)
return plt.Polygon(xy=(
(x, y-2*c), (x+a, y-c), (x+a+b, y-c),
(x+b, y), (x+a+b, y+c), (x+a, y+c),
(x, y+2*c),... | 62f09f26e98723764d03a678634cbb00f051e105 | 14,143 |
def calibrate(leveled_arcs, sat_biases, stn_biases):
"""
???
"""
calibrated_arcs = []
for arc in leveled_arcs:
if arc.sat[0] == 'G':
sat_bias = sat_biases['GPS'][int(arc.sat[1:])][0] * NS_TO_TECU
stn_bias = stn_biases['GPS'][arc.stn.upper()][0] * NS_TO_TECU
el... | 63065e0000ebaa48b71d3f9ed9814277b6bf63ed | 14,144 |
def negSamplingCostAndGradient(predicted, target, outputVectors, dataset, K=10):
"""
Implements the negative sampling cost function and gradients for word2vec
:param predicted: ndarray, the predicted (center) word vector(v_c)
:param target: integer, the index of the target word
:param outputVectors... | 4e1fbf082d97b1a4c7b5b5f9ee722c54fc993712 | 14,145 |
from datetime import datetime
import pytz
def isotime(timestamp):
"""ISO 8601 formatted date in UTC from unix timestamp"""
return datetime.fromtimestamp(timestamp, pytz.utc).isoformat() | f6a922d75a186e26f158edc585691e31bf430b01 | 14,146 |
def initializeSeam():
"""
This function defines the seams of a baseball. It is
based, in large extant, on the work from
http://www.darenscotwilson.com/spec/bbseam/bbseam.html
"""
n = 109 #number of points were calculating on the seam line
alpha = np.linspace(0,np.pi*2,n)
x = np.zeros(len... | 43c7e968ecd98595c46e679676f23cbb07d28bb3 | 14,147 |
def check_model_consistency(model, grounding_dict, pos_labels):
"""Check that serialized model is consistent with associated json files.
"""
groundings = {grounding for grounding_map in grounding_dict.values()
for grounding in grounding_map.values()}
model_labels = set(model.estimator.... | b5d1beda0be5ceccec158839c61c1d79349596ef | 14,148 |
def get_submission_info(tile_grid, collections, tile_indices,
period_start, period_end, period_freq):
""" Return information about tracked order submissions
"""
return {
'submitted': dt.datetime.today().isoformat(),
'collections': collections,
'tile_grid': til... | 990740ef15760fd5514598772d496db47a436786 | 14,149 |
def load_obj(path):
"""Load an object from a Python file.
path is relative to the data dir. The file is executed and the obj
local is returned.
"""
localdict = {}
with open(_DATADIR / path) as file:
exec(file.read(), localdict, localdict)
return localdict['obj'] | 8c44141e58d0aa1402f6d5244857fbe3d07ddc84 | 14,150 |
def dp_policy_evaluation(env, pi, v=None, gamma=1, tol=1e-3, iter_max=100,
verbose=True):
"""Evaluates state-value function by performing iterative policy evaluation
via Bellman expectation equation (in-place)
Based on Sutton/Barto, Reinforcement Learning, 2nd ed. p. 75
Args:
env: Envi... | e920f48f6b37f9815b077b18e02b0403b78f2ce7 | 14,151 |
def gpst2utc(tgps, leaps_=-18):
""" calculate UTC-time from gps-time """
tutc = timeadd(tgps, leaps_)
return tutc | a1bf6aa583ae1827cce572f809831b3396bdd91b | 14,152 |
def create_shell(username, session_id, key):
"""Instantiates a CapturingSocket and SwiftShell and hooks them up.
After you call this, the returned CapturingSocket should capture all
IPython display messages.
"""
socket = CapturingSocket()
session = Session(username=username, session=session... | 13af90ea2497211c75d66fbff334ee95ede678b8 | 14,153 |
def _get_index_sort_str(env, name):
"""
Returns a string by which an object with the given name shall be sorted in
indices.
"""
ignored_prefixes = env.config.cmake_index_common_prefix
for prefix in ignored_prefixes:
if name.startswith(prefix) and name != prefix:
return n... | cdf7a509ef8f49ff15cac779e37f0bc5ab98c613 | 14,154 |
from datetime import datetime
def utcnow():
"""Gets current time.
:returns: current time from utc
:rtype: :py:obj:`datetime.datetime`
"""
return datetime.datetime.utcnow() | a85b4e28b0cbc087f3c0bb641e896958ea267c3f | 14,155 |
def elem2full(elem: str) -> str:
"""Retrieves full element name for short element name."""
for element_name, element_ids, element_short in PERIODIC_TABLE:
if elem == element_short:
print(element_name)
return element_name
else:
raise ValueError(f"Index {elem} does not ... | 2c78531dc21722cc504182abec469eabdfeec862 | 14,156 |
def create_random_totp_secret(secret_length: int = 72) -> bytes:
"""
Generate a random TOTP secret
:param int secret_length: How long should the secret be?
:rtype: bytes
:returns: A random secret
"""
random = SystemRandom()
return bytes(random.getrandbits(8) for _ in range(secret_length... | 6ecaf035212e5e4e2d8e71856c05ea15407fdb19 | 14,158 |
def _get_roles_can_update(community_id):
"""Get the full list of roles that current identity can update."""
return _filter_roles("members_update", {"user", "group"}, community_id) | 7701cc425a83212dbd5ffd039a629b06a17fcb83 | 14,159 |
def register_external_compiler(op_name, fexternal=None, level=10):
"""Register the external compiler for an op.
Parameters
----------
op_name : str
The name of the operator.
fexternal : function (attrs: Attrs, args: List[Expr], compiler: str)
-> new_expr: Expr
The fun... | 0d41fce383407af3d8a60d1886950424b89ee18b | 14,160 |
def kl_divergence_from_logits_bm(logits_a, logits_b):
"""Gets KL divergence from logits parameterizing categorical distributions.
Args:
logits_a: A tensor of logits parameterizing the first distribution.
logits_b: A tensor of logits parameterizing the second distribution.
Returns:
... | 8078fcbd4c4c58bed888ba5b45e99783799bde42 | 14,161 |
import logging
def if_stopped_or_playing(speaker, action, args, soco_function, use_local_speaker_list):
"""Perform the action only if the speaker is currently in the desired playback state"""
state = speaker.get_current_transport_info()["current_transport_state"]
logging.info(
"Condition: '{}': Sp... | 7daa5bd040e6753ce1e39807071e0911a8dd3182 | 14,162 |
def compute_src_graph(hive_holder, common_table):
""" computes just the src part of the full version graph.
Side effect: updates requirements of blocks to actually point to real dep versions
"""
graph = BlockVersionGraph()
versions = hive_holder.versions
graph.add_nodes(versions.itervalues())
... | 55d150e583e93c0d5b25490543738f79ba23fe64 | 14,163 |
def get_uv(seed=0, nrm=False, vector=False):
"""Dataset with random univariate data
Parameters
----------
seed : None | int
Seed the numpy random state before generating random data.
nrm : bool
Add a nested random-effects variable (default False).
vector : bool
Add a 3d ... | 1394ae09705aa01f9309399ab8f1b7fcff04e010 | 14,164 |
from typing import Iterable
def private_names_for(cls, names):
"""
Returns:
Iterable of private names using privateNameFor()"""
if not isinstance(names, Iterable):
raise TypeError('names must be an interable')
return (private_name_for(item, cls) for item in names) | 606afdcfd8eed1e288df71a79f50a37037d84139 | 14,165 |
def invert_trimat(A, lower=False, right_inv=False, return_logdet=False, return_inv=False):
"""Inversion of triangular matrices.
Returns lambda function f that multiplies the inverse of A times a vector.
Args:
A: Triangular matrix.
lower: if True A is lower triangular, else A is upper triangu... | ad449fe1718136e64a6896e74fbb8ee7a3cefcec | 14,167 |
def category_input_field_delete(request, structure_slug,
category_slug, module_id,
field_id, structure):
"""
Deletes a field from a category input module
:type structure_slug: String
:type category_slug: String
:type module_id: Integer... | f5319ea5b992529e7b8d484b1dc6c0be621f9955 | 14,168 |
def cat_to_num(att_df):
"""
Changes categorical variables in a dataframe to numerical
"""
att_df_encode = att_df.copy(deep=True)
for att in att_df_encode.columns:
if att_df_encode[att].dtype != float:
att_df_encode[att] = pd.Categorical(att_df_encode[att])
att_df_enco... | dbd57022ddd99d8ea4936da45d8c2cbe09078b81 | 14,169 |
async def handle_get(request):
"""Handle GET request, can be display at http://localhost:8080"""
text = (f'Server is running at {request.url}.\n'
f'Try `curl -X POST --data "text=test" {request.url}example`\n')
return web.Response(text=text) | 2398870ab6479d8db3517b89e0177cab674156b0 | 14,170 |
def values_target(size: tuple, value: float, cuda: False) -> Variable:
""" returns tensor filled with value of given size """
result = Variable(full(size=size, fill_value=value))
if cuda:
result = result.cuda()
return result | be9db2c08fbac00e1f8d10b859da8422e7331901 | 14,171 |
def get_new_perpendicular_point_with_custom_distance_to_every_line_segment(
line_segments: np.ndarray, distance_from_the_line: np.ndarray
):
"""
:param line_segments: array of shape [number_of_line_segments, 2, 2]
:param distance_from_the_line: how far the new point to create from the reference
:ret... | 3ebb94b9fa4b7f28e655a3e9a4fe93ec40276dff | 14,172 |
import requests
def tmdb_find_movie(movie: str, tmdb_api_token: str):
"""
Search the tmdb api for movies by title
Args:
movie (str): the title of a movie
tmdb_api_token (str): your tmdb v3 api token
Returns:
dict
"""
url = 'https://api.themoviedb.org/3/search/movie?'
... | ea676fbb91f451b20ce4cd2f7258240ace3925b3 | 14,173 |
def is_missing_artifact_error(err: WandbError):
"""
Check if a specific W&B error is caused by a 404 on the artifact we're looking for.
"""
# This is brittle, but at least we have a test for it.
return "does not contain artifact" in err.message | 023bdab0b3a2914272a1087a5c42ba81ec064548 | 14,174 |
def create_reforecast_valid_times(start_year=2000):
"""Inits from year 2000 to 2019 for the same days as in 2020."""
reforecasts_inits = []
inits_2020 = create_forecast_valid_times().forecast_time.to_index()
for year in range(start_year, reforecast_end_year + 1):
# dates_year = pd.date_range(sta... | 0ea34549aef8b8b4551534560ab29c9580f9f1ca | 14,175 |
def _checkerror(fulloutput):
"""
Function to check the full output for known strings and plausible fixes to the error.
Future: add items to `edict` where the key is a unique string contained in the offending
output, and the data is the reccomended solution to resolve the problem
"""
edict = {'mu... | 5312beff6f998d197a3822e04e60d47716520f50 | 14,176 |
def create_pre_process_block(net, ref_layer_name, means, scales=None):
"""
Generates the pre-process block for the IR XML
Args:
net: root XML element
ref_layer_name: name of the layer where it is referenced to
means: tuple of values
scales: tuple of values
Returns:
... | 54013ec9d06cf7eff9b0af18d1655a5455a894be | 14,177 |
def GetSystemFaultsFromState(state, spot_wrapper):
"""Maps system fault data from robot state proto to ROS SystemFaultState message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
SystemFaultState message
"""
system_fault_state_msg = SystemFaultStat... | cda2d0bbe3ee3ca02724828d9f0f882695c3e0b0 | 14,178 |
def findAnEven(L):
"""
:Assumes L is a list of integers:
:Returns the first even number in L:
:Raises ValueError if L does not contain an even number:
"""
for num in L:
if num % 2 == 0:
return num
raise ValueError | 93f7854bd376d52df40b23d21bfde784db124106 | 14,179 |
def get_points(wire):
"""
get all points (including starting point), where the wire bends
>>> get_points(["R75","D30","R83","U83","L12","D49","R71","U7","L72"])
[((0, 0), (75, 0)), ((75, 0), (75, -30)), ((75, -30), (158, -30)), ((158, -30), (158, 53)), ((158, 53), (146, 53)), ((146, 53), (146, 4)), ((14... | 8f0e7bad7500b8113d6ce601c6f2af472192774f | 14,180 |
def getcutscheckerboard(rho):
"""
:param rho:
:return: cell centers and values along horizontal, vertical, diag cut
"""
ny, nx = rho.shape
assert nx == ny
n = ny
horizontal = rho[6 * n // 7, :]
vertical = rho[:, n // 7]
if np.abs(horizontal[0]) < 1e-15:
horizontal = hor... | 31d95160d1b34b50e616a346e04d5b6567886677 | 14,181 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.