content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 |
import os
import re
def scrape_md_file(md_path):
"""
Yield the Python scripts and URLs in the md_file in path.
Parameters
----------
md_path : str
path to md file to scrape
Returns
-------
python_examples : List[str]
The list of Python scripts included in the pro... | afac5538a469dafb06dfd2df40a28be5284b61be | 14,102 |
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 |
import os
import glob
import shutil
def copy_files(extension, source, target=None):
"""Copy matching files from source to target.
Scan the ``source`` folder and copy any file that end with
the given ``extension`` to the ``target`` folder.
Both ``source`` and ``target`` are expected to be either a ``... | 5b6ae6a908448487206612e7686e573c266bc287 | 14,119 |
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 |
from typing import Optional
import os
import logging
import sys
def load_mat(path: str, mat: str, fid: str, size: Optional[int] = None, overwrite: Optional[bool] = False, loop: Optional[int] = 0) -> np.ndarray:
"""Get the raw data for one individual file.
If the file does not exist in the specified path then... | 2824a3c6b40db2b7f47e4d33d92da5dc27dc702b | 14,121 |
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 |
from typing import Optional
from typing import Dict
from typing import Any
import pathlib
import os
import tomli
def parse_toml(path_string: Optional[str]) -> Dict[str, Any]:
"""Parse toml"""
if not path_string:
path = pathlib.Path(os.getcwd())
else:
path = pathlib.Path(path_string)
to... | 7adffb1dd2bd73c0fa6c2ef85d9a5e80582b95a8 | 14,133 |
def mtxv(m1, vin):
"""
Multiplies the transpose of a 3x3 matrix
on the left with a vector on the right.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxv_c.html
:param m1: 3x3 double precision matrix.
:type m1: 3x3-Element Array of floats
:param vin: 3-dimensional double precisi... | 5602f4c399983b10e0d701b53026ceabc2af35cd | 14,134 |
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 optimize_concrete_function(
concrete_function: function.ConcreteFunction,
strip_control_dependencies: bool) -> wrap_function.WrappedFunction:
"""Returns optimized function with same signature as `concrete_function`."""
wrapped_fn = wrap_function.WrappedFunction(
concrete_function.graph,
vari... | 3176b544dd6fc2305a0e66a9da0cc25d7dc11658 | 14,136 |
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 |
import os
def fixture_path(relapath=''):
""":return: absolute path into the fixture directory
:param relapath: relative path into the fixtures directory, or ''
to obtain the fixture directory itself"""
return os.path.join(os.path.dirname(__file__), 'fixtures', relapath) | 4630d61c08c52570a9cb15522bd10cea5f82dbbd | 14,157 |
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 |
import os
def find_vcs_root(location="", dirs=(".git", ".hg", ".svn"), default=None) -> str:
"""Return current repository root directory."""
if not location:
location = os.getcwd()
prev, location = None, os.path.abspath(location)
while prev != location:
if any(os.path.isdir(os.path.joi... | bb8c7525085a46bcb8822e7fcd1b9d1875b819b0 | 14,166 |
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 |
def errorString(node, error):
"""
Format error messages for node errors returned by checkLinkoStructure.
inputs:
node - the node for the error.
error - a (backset, foreset) tuple, where backset is the set of
missing backlinks and foreset is the set of missing forelinks.
returns: string
... | df87b7838ed84fe4e6b95002357f616c96d04ad0 | 14,182 |
def deep_update(target, source):
"""
Deep merge two dicts
"""
if isinstance(source, dict):
for key, item in source.items():
if key in target:
target[key] = deep_update(target[key], item)
else:
target[key] = source[key]
return target | 5db0c6fa31f3d4408a359d90dbf6e50dfdc12cdc | 14,183 |
import hashlib
def md5_hash_file(path):
"""
Return a md5 hashdigest for a file or None if path could not be read.
"""
hasher = hashlib.md5()
try:
with open(path, 'rb') as afile:
buf = afile.read()
hasher.update(buf)
return hasher.hexdigest()
except I... | 514cafcffa0ae56d54f43508ece642d25b4be442 | 14,184 |
def Constant(value):
"""
Produce an object suitable for use as a source in the 'connect' function that
evaluates to the given 'value'
:param value: Constant value to provide to a connected target
:return: Output instance port of an instance of a Block that produces the given constant when evaluated... | 1763d657e3396286516e6669e57b7ee297463b14 | 14,185 |
def _Backward3a_T_Ps(P, s):
"""Backward equation for region 3a, T=f(P,s)
Parameters
----------
P : float
Pressure [MPa]
s : float
Specific entropy [kJ/kgK]
Returns
-------
T : float
Temperature [K]
References
----------
IAPWS, Revised Supplementary ... | cb0b9b55106cf771e95505c00043e5772faaef40 | 14,186 |
import re
def expandvars(s):
"""Expand environment variables of form %var%.
Unknown variables are left unchanged.
"""
global _env_rx
if '%' not in s:
return s
if _env_rx is None:
_env_rx = re.compile(r'%([^|<>=^%]+)%')
return _env_rx.sub(_substenv, s) | ede7861831ea9d9e74422eb3a92a13ba4d1937f2 | 14,187 |
def make_map_counts(events, ref_geom, pointing, offset_max):
"""Build a WcsNDMap (space - energy) with events from an EventList.
The energy of the events is used for the non-spatial axis.
Parameters
----------
events : `~gammapy.data.EventList`
Event list
ref_geom : `~gammapy.maps.WcsG... | 7a22340c8f3909d6ca559361290a4608a0321de1 | 14,188 |
def stats_aggregate():
""" RESTful CRUD Controller """
return crud_controller() | 4a8439139257f39e0d2a34b576e9a9bd98cded5c | 14,189 |
def format_dB(num):
"""
Returns a human readable string of dB. The value is divided
by 10 to get first decimal digit
"""
num /= 10
return f'{num:3.1f} {"dB"}' | 13d6313834333ee2ea432cf08470b6ce1efe1ad6 | 14,190 |
def _check_index_dtype(k):
"""
Check the dtype of the index.
Parameters
----------
k: slice or array_like
Index into an array
Examples
--------
>>> _check_index_dtype(0)
dtype('int64')
>>> _check_index_dtype(np.datetime64(0, 'ms'))
dtype('<M8[ms]')
>>> _check_in... | f9f7bac24f7ceba57978d7e1aed7c4e052c79f35 | 14,191 |
def _wrapper_for_precessing_snr(args):
"""Wrapper function for _precessing_snr for a pool of workers
Parameters
----------
args: tuple
All args passed to _precessing_snr
"""
return _precessing_snr(*args) | 4d64d7e658ecfeed6206abd0827f37805c3ecd0c | 14,192 |
def readpcr(path):
"""
Only for multipattern formats.
"""
with open(path) as file:
lines = file.readlines()
# Strip comments
lines = [line for line in lines if not line.startswith("!")]
pcr = {} # main dictionary
line = 0 # line reference
##### start read
# pcr name... | b3f612752b064de5f8ac77b6d5d77baf9aff3400 | 14,193 |
import logging
def put_file_store(store_name, store, block_on_existing=None, user=None): # noqa: E501
"""Create/update store
# noqa: E501
:param store_name: Name of the store
:type store_name: str
:param store: Store information
:type store: dict | bytes
:rtype: FileStore
"""
... | 2e799c7fc2f394c925562c8600b83a1149586ad2 | 14,194 |
from typing import Dict
from typing import Set
from typing import Tuple
def assign_sections(region_table: RegionTable, sections: Dict[str, int]):
"""Assign memory sections.
This is a packing problem and therefore reasonably complex.
A simplistic algorithm is used here which may not always be optimal if u... | 6ad4af4c67be9e9d07a4464bfc1d3c529a5afd4b | 14,195 |
def humanize_arrow_date( date ):
"""
Date is internal UTC ISO format string.
Output should be "today", "yesterday", "in 5 days", etc.
Arrow will try to humanize down to the minute, so we
need to catch 'today' as a special case.
"""
try:
then = arrow.get(date).to('local')
now... | 511e5f7a85a5906d78ed9b252076b1f0e8ea02d9 | 14,196 |
def getCourseTeeHoles(request, courseId, courseTeeId):
"""
Getter function for list of courses and tees
"""
resultList = list(Tee.objects.filter(course_tee_id=courseTeeId).values('id', 'yardage', 'par', 'handicap', 'hole__id', 'hole__name', 'hole__number'))
return JsonResponse({'data' : resultList}) | 7abac65449503d2309cf8cae49b7e555488333f9 | 14,197 |
import tarfile
from pathlib import Path
import tqdm
import logging
def simulate(SNOwGLoBESdir, tarball_path, detector_input="all", verbose=False):
"""Takes as input the neutrino flux files and configures and runs the supernova script inside SNOwGLoBES, which outputs calculated event rates expected for a given (se... | fad0b3e54f1b3908f4efef6cc5ae0729756e14c9 | 14,198 |
import argparse
def args():
"""
Argument Parsing Handler:
-m <path_to_keras> :
Path to keras model
-o <model_output> :
Path to directory that will store pb model
"""
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--path_to_keras", type=str,
h... | 6d2ccb8c871af5e4c9616690c80b566c49424130 | 14,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.