content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def opensearch_plugin(request):
"""Render an OpenSearch Plugin."""
host = "%s://%s" % ("https" if request.is_secure() else "http", request.get_host())
# Use `render_to_response` here instead of `render` because `render`
# includes the request in the context of the response. Requests
# often include... | 5df7e8a8bb89ff5e83b51f1bc4b634db9dea6930 | 7,685 |
from datetime import datetime
def serialize_time(output_value: datetime.time) -> str:
""" Serializes an internal value to include in a response. """
return output_value.isoformat() | 81fc648eaf27efc47531f9895a9523aa5f012cf6 | 7,686 |
def decode_binary(state_int):
"""
Decode binary representation into the list view
:param state_int: integer representing the field
:return: list of GAME_COLS lists
"""
assert isinstance(state_int, int)
bits = int_to_bits(state_int, bits=GAME_COLS*GAME_ROWS + GAME_COLS*BITS_IN_LEN)
res = ... | a2dd5462031eeb82d9e3b59565d41b2b06e8e2d8 | 7,688 |
def clean_features(vgsales):
"""
This function cleans up some of the dataset's features. The dataset is
quite messy as many values are missing from both categorical and numerical
features. Many of these features are difficult to impute in a reasonable
manner.
<class 'pandas.core.frame.DataFrame... | ffcae20af436d4012381c4933c841c3689fbbca0 | 7,689 |
def get_object(proposition):
"""[75]
Returns the object of a given proposition
"""
return proposition[2][0] | dc9d5fe007bb66ee92cddd964bb29b897a561c8c | 7,690 |
import hmac
def __verify_hmac(data: bytes, ohmac: bytes, key: bytes) -> bool:
"""
This function verifies that a provided HMAC matches a computed HMAC for
the data given a key.
Args:
data: the data to HMAC and verify
ohmac: the original HMAC, normally appended to the data
key: ... | 6381bb70e35cccafdb3dcafc2428ca5ca850364a | 7,691 |
def create_block_option_from_template(text: str, value: str):
"""Helper function which generates the option block for modals / views"""
return {"text": {"type": "plain_text", "text": str(text), "emoji": True}, "value": str(value)} | 23f0cf455e659eddeca0b4eda732995feeac6341 | 7,692 |
from typing import Any
import json
def get_token_payload(token: str) -> Any:
"""Extract the payload from the token.
Args:
token (str):
A JWT token containing the session_id and other data.
Returns:
dict
"""
decoded = json.loads(_base64_decode(token.split('.')[0]))
... | 1b9b03f8e9db6940cc44725025c1ed2ccf751e89 | 7,693 |
import torch
def create_mock_target(number_of_nodes, number_of_classes):
"""
Creating a mock target vector.
"""
return torch.LongTensor([np.random.randint(0, number_of_classes-1) for node in range(number_of_nodes)]) | e226d9e7d1944b0736952d5952e8ef3438a1e54b | 7,694 |
def initFindAndFit(parameters):
"""
Initialize and return a SplinerFISTAFinderFitter object.
"""
# Create spline object.
spline_fn = splineToPSF.loadSpline(parameters.getAttr("spline"))
# Create peak finder.
finder = SplinerFISTAPeakFinder(parameters = parameters,
... | 6f045b664157437fb33ab3804b84fe1c7d1deb4e | 7,695 |
def UpdateDatabase(asset, images, status):
"""Update the database entries of the given asset with the given data."""
return {'asset': asset} | 1d7d42355410be7481e706e47d7810755974dadc | 7,696 |
def get_max_word_length(days: dict, keys: list) -> int:
"""
Находит длину самого длинного слова.
"""
max_word_len = 0
for key in keys:
if days.get(key):
for _, data in days.get(key).items():
value = data.split(" ")
for word in value:
... | 8a98c7384839f10fdfa713c535b3bf7765416b4c | 7,697 |
def rateCBuf(co2: float, par: float, params: dict,
rates: dict, states: dict) -> float:
"""
Rate of increase of carbohydrates in the buffer
During the light period, carbohydrates produced by
photosynthesis are stored in the buffer and, whenever
carbohydrates are available in the buffer... | 33a6c5fcc6d9d1a0641d197dffa1ee5fd6afd038 | 7,698 |
import hashlib
import json
def get_config_tag(config):
"""Get configuration tag.
Whenever configuration changes making the intermediate representation
incompatible the tag value will change as well.
"""
# Configuration attributes that affect representation value
config_attributes = dict(fram... | 2cab6e9473822d0176e878114ceb3fda94d1e0f7 | 7,699 |
def ctf_to_pickle(trace_directory: str, target: Pickler) -> int:
"""
Load CTF trace, convert events, and dump to a pickle file.
:param trace_directory: the trace directory
:param target: the target file to write to
:return: the number of events written
"""
ctf_events = get_trace_ctf_events(... | e317be9d5577c8f85e02945d9ae95e63be9e76ef | 7,700 |
def list_lines(lines):
"""Returns the list of trimmed lines.
@param lines Multi-line string
"""
return list(filter(None, (x.strip() for x in lines.splitlines()))) | 293610d17e1fe8a27ab6bb5c35a349059e0179f3 | 7,701 |
def carbon_offset_cost(kWh):
"""
Donation to Cool Earth (in USD) needed to offset carbon emssions.
"""
return KG_CO2_PER_KWH * USD_PER_KG_CO2 * kWh | 6bbb9cfd3c058d4148fe3286defe75ade0fddb62 | 7,703 |
from typing import List
from typing import Tuple
from typing import Union
import time
def run(
duration: int, runtime_mode: str, connection_mode: str
) -> List[Tuple[str, Union[int, float]]]:
"""Test memory usage."""
# pylint: disable=import-outside-toplevel,unused-import
# import manually due to some... | 677bdb5cb73cfc4ccc38d813bf875d506905512e | 7,704 |
def tf_fermion_massmatrix(t_A3, t_potential, tc_masses_factor):
"""Computes the spin-1/2 mass matrix from the A3-tensor."""
# The extra factor 2.0 relative to https://arxiv.org/abs/1906.00207
# makes the fermion masses align with the way particle states are
# grouped into SUSY multiplets in appendix (B.2) of:
... | 934c606fd55f93bdfa91a1e4d23fb7b6b5df8703 | 7,705 |
def filter_nsa_catalog_to_approximate_sky_area(nsa, bricks, visualise=False):
"""
DECALS is only in a well-defined portion of sky (which depends on the data release version). Filter the NSA catalog
so that it only includes galaxies in that approximate area. This saves time matching later.
Args:
... | 3f961cab16a58e7323f1f0730497beaf15f5db18 | 7,706 |
from typing import Dict
from typing import Union
from typing import List
from typing import Optional
from typing import Any
from typing import Tuple
def apply_variants(variants: Dict[Union[str, List[str]], int], parameters: Optional[Dict[Any, Any]] = None, variant=DEFAULT_VARIANT_VARIANTS) -> Tuple[PetriNet, Marking,... | 13a2466c1c7921fe5f6ccbf4fe819e2ac19ee87f | 7,707 |
def query_update(request: HttpRequest, **kwargs: str) -> str:
"""Update the query string with new values."""
updated = request.GET.copy()
for key, value in kwargs.items():
updated[key] = value
return updated.urlencode() | 43d60853f53fec4e696c2c6010b6e3b3db0da389 | 7,708 |
def get_user_info(user_id):
""" Fetches User Info Based On User ID
:param user_id:
:return: user
"""
user = session.query(User).filter_by(id=user_id).one_or_none()
return user | e1134f9305bd6df1b650bc3362c0e85f6dc10ccf | 7,709 |
def gatk_version(request) -> GATKVersion:
"""Given a version number, return a GATKVersion."""
return GATKVersion(request.param) | ec05d5f34f45454bb7c0b8c562851c3691d01ace | 7,710 |
def load_objs(name_obj_dat, sim, obj_ids, auto_sleep=True):
"""
- name_obj_dat: List[(str, List[
transformation as a 4x4 list of lists of floats,
int representing the motion type
])
"""
static_obj_ids = []
for i, (name, obj_dat) in enumerate(name_obj_dat):
if len(obj_id... | 899670f7ff63ef124dd51575ff59560b27b6e974 | 7,711 |
def get_mod_metadata(module: Module):
"""
Get descriptions for produced dependencies.
"""
meta = {}
has_meta = hasattr(module, 'prod_meta')
for prod in module.produces:
prod = prod.replace('?', '').replace('!', '')
if not has_meta:
meta[prod] = '<no descritption>'
... | b0000c555cc22f5d81f31241bc3eaa3aee7d99ad | 7,712 |
def register_module():
"""Registers this module in the registry."""
dashboard.dashboard.DashboardRegistry.add_analytics_section(
dashboard.analytics.QuestionScoreHandler)
global_handlers = []
for path, handler_class in mapreduce_main.create_handlers_map():
# The mapreduce and pipeline ... | 7e711f6e67e7a9bcd118dc304bd99073b25a8049 | 7,713 |
import warnings
def theta_b(wlen, d, n=1):
"""return the Bragg angle, $\theta_{B}$, (deg) for a given wavelength
(\AA$^{-1}$) and d-spacing (\AA)"""
if not (d == 0):
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
_thb = np.rad2deg(n... | 89080b455744bab1e94aa47eb53a3a2935985d32 | 7,714 |
def replace_newlines(s, replacement=' / ', newlines=(u"\n", u"\r")):
"""
Used by the status message display on the buddy list to replace newline
characters.
"""
# turn all carraige returns to newlines
for newline in newlines[1:]:
s = s.replace(newline, newlines[0])
# while there are... | d7b42ad67a3732c1ecac5bbfd7b9920b0215aa13 | 7,715 |
def default_bucket_name():
"""Obtain the default Google Storage bucket name for this application.
Returns:
A string that is the name of the default bucket.
"""
return files._default_gs_bucket_name() | 01cad1b881217849ff55af6f1b67da624b584810 | 7,717 |
def LineGaussSeidel_i(Uo, Beta):
"""Return the numerical solution of dependent variable in the model eq.
This routine uses the Line-Gauss Seidel method along constant i
direction (parallel to y-axis)
to obtain the solution of the Poisson's equation.
Call signature:
LineGaussSeidel_i(Uo, B... | 2fd2fda54169bc0f1e686781b26823a8f1a29b49 | 7,718 |
def add_padding_to_grid(
component,
grid_size=127,
x=10,
y=10,
bottom_padding=5,
layers=[pp.LAYER.PADDING],
suffix="p",
):
""" returns component width a padding layer on each side
matches a minimum size
"""
c = pp.Component(name=f"{component.name}_{suffix}")
c << componen... | 5f886f7f5cec874eda10675580954ad46cbb2200 | 7,719 |
def _find_role(oneandone_conn, role):
"""
Given a name, validates that the role exists
whether it is a proper ID or a name.
Returns the role if one was found, else None.
"""
for _role in oneandone_conn.list_roles(per_page=1000):
if role in (_role['id'], _role['name']):
return... | b8e2e93b13c9595e40dd61b2e9bbda1f89f23cca | 7,720 |
def created_median_mask(disparity_map, valid_depth_mask, rect=None):
"""生成掩模,使得矩形中不想要的区域的掩模值为0,想要的区域的掩模值为1"""
if rect is not None:
x, y, w, h = rect
disparity_map = disparity_map[y:y + h, x:x + w]
valid_depth_mask = valid_depth_mask[y:y + h, x:x + w]
# 获得中位数
median = np.median(di... | e57a990d250564c4e8d2b59aa27522115c9791e2 | 7,722 |
import torch
def l2_loss(pred_traj, pred_traj_gt, mode='sum'):
"""
Input:
- pred_traj: Tensor of shape (seq_len, batch, 2). Predicted trajectory.
- pred_traj_gt: Tensor of shape (seq_len, batch, 2). Groud truth
predictions.
- mode: Can be one of sum, average, raw
Output:
- loss: l2 los... | f9e98e30d4299c79a93de6905c65dcb23da65ac1 | 7,723 |
import requests
import re
def api_wowlight_version_check(version: str) -> bool:
"""
Checks incoming wow-lite wallet version, returns False when the version is too old and needs to be upgraded.
:param version:
:return: bool
"""
url = "https://raw.githubusercontent.com/wownero/wow-lite-wallet/ma... | 470f8580df357c206b595c1145e04e33fd897058 | 7,725 |
import math
def fruit_growth(jth: int, last_24_canopy_t):
"""
Equations 9.38
fruit_growth_rate_j = POTENTIAL_FRUIT_DRY_WEIGHT*math.exp(-math.exp(-curve_steepness*(days_after_fruit_set - fruit_development_time)))
Returns: fruit growth rate [mg {CH2O} fruit^-1 d^-1]
"""
fruit_development_rate = ... | 78d1ee0e9ea8d364b6282466fb9ee27dc9cbb602 | 7,726 |
from typing import Callable
def _pickled_cache_s(filepath: str) -> Callable[[Callable], Callable]:
"""Store the last result of the function call
in a pickled file (string version)
Args:
filepath (str): The path of the file to read/write
Returns:
Callable[[Callable], Callable]: function decorator.
... | b95703fc90275ba06d3816b442d07b14e4854eaf | 7,727 |
from datetime import datetime
def home(request):
"""Index page view
:param request: HTTP request
:return: index page render
"""
today = datetime.date.today()
return render(request, 'taskbuster/index.html',
{'today': today, 'now': now()}) | cccfa91a728ce4f5dd482bbbd9418ec94f102844 | 7,728 |
from typing import Tuple
from typing import Iterable
def get_trials_for_drug(
drug: Tuple[str, str], *, client: Neo4jClient
) -> Iterable[Node]:
"""Return the trials for the given drug.
Parameters
----------
client :
The Neo4j client.
drug :
The drug to query.
Returns
... | 64641e52468d46a3b4071d58cbdbff3167ff3fa6 | 7,729 |
from typing import List
import torch
def convert_features_to_dataset(all_features: List[InputFeaturesTC],
dataset_type: str = 'pytorch'
) -> TensorDataset:
"""Converts a list of features into a dataset.
Args:
all_features (:obj:`list` of... | 88e892effbc60569d35d8f14e1a8032837d409e0 | 7,730 |
import requests
from bs4 import BeautifulSoup
def soup_from_name(username):
""" Grabs bs4 object from html page """
# html_source = urlopen('https://www.instagram.com/'+ str(username) + '/')
url = 'https://www.instagram.com/'+ str(username) + '/'
headers = {"User-Agent" : "Mozilla/5.0 (Macintosh; Inte... | 442c6e9fa036fef59b82246462bf0e992384fd15 | 7,731 |
def SectionMenu(rating_key, title=None, base_title=None, section_title=None, ignore_options=True,
section_items_key="all"):
"""
displays the contents of a section
:param section_items_key:
:param rating_key:
:param title:
:param base_title:
:param section_title:
:param ig... | 3ba91e054de81c4d8eb32d2feaeb9ab99125683e | 7,732 |
def round_floats_for_json(obj, ndigits=2, key_ndigits=None):
"""
Tries to round all floats in obj in order to reduce json size.
ndigits is the default number of digits to round to,
key_ndigits allows you to override this for specific dictionary keys,
though there is no concept of nested keys.
It... | 8143a3a063e45b6a501ca2de6f1bb5dd1b64e843 | 7,733 |
def read_shared(function_name, verb, request, local_variables=None):
"""all the shared code for each of thse read functions"""
command = function_name.split('_')[1] # assumes fn name is query_<command>
command_args, verb_args = create_filters(function_name, command, request,
... | c60feac9c16cfcd2d503032826aedced20d2959d | 7,734 |
def construct_SN_default_rows(timestamps, ants, nif, gain=1.0):
""" Construct list of ants dicts for each
timestamp with REAL, IMAG, WEIGHT = gains
"""
default_nif = [gain] * nif
rows = []
for ts in timestamps:
rows += [{'TIME': [ts],
'TIME INTERVAL': [0.1],
... | b81e45d2d5299042b3332a2386a0fd4d2d6d59d7 | 7,736 |
import aiohttp
async def test_disable(aresponses):
"""Test disabling AdGuard Home query log."""
async def response_handler(request):
data = await request.json()
assert data == {"enabled": False, "interval": 1}
return aresponses.Response(status=200)
aresponses.add(
"exampl... | a9c211d5bf9a0c2842ae835215718f4f81430c69 | 7,737 |
def kron_diag(*lts):
"""Compute diagonal of a KroneckerProductLazyTensor from the diagonals of the constituiting tensors"""
lead_diag = lts[0].diag()
if len(lts) == 1: # base case:
return lead_diag
trail_diag = kron_diag(*lts[1:])
diag = lead_diag.unsqueeze(-2) * trail_diag.unsqueeze(-1)
... | d57bb679dede93ababb2d164cfc85132acef60db | 7,739 |
import time
def makeBundleObj(config_fname, getPackage, getPackageLength):
"""Given a description of a thandy bundle in config_fname,
return a new unsigned bundle object. getPackage must be a function
returning a package object for every package the bundle requires
when given the package's ... | 4579cab99a2e1f7f52bc49bfd12c001aee06de21 | 7,740 |
import re
def find_English_term(term: list) -> tuple:
"""
Find the English and numbers from a term list
and remove the English and numbers from the term
:param term: the term list
:return term: the term removed the English and numbers
:return Eng_terms: the removed English
"""
temp_ter... | 69507970eb226d2379bb11e121bc224b1ce741ad | 7,741 |
def add_target_variable(df: pd.DataFrame) -> pd.DataFrame:
"""Add column with the target variable to the given dataframe."""
return df.assign(y=df.rent + df.admin_fee) | 236f16bab38d36625173640d5223f9fed48f34fe | 7,743 |
def get_address_from_public_key(public_key):
""" Get bytes from public key object and call method that expect bytes
:param public_key: Public key object
:param public_key: ec.EllipticCurvePublicKey
:return: address in bytes
:rtype: bytes
"""
public_key_bytes = get_public_ke... | 775701261e07b9153807d9b5ae08f02050ecc51e | 7,744 |
import re
import math
def read_ORIGEN_gamma_spectrum(output_filename, cooling_time_string):
"""
Function for reading a gamma spectrum from an ORIGEN output file.
"""
#Too long text may cause problems, so check for it.
if len(cooling_time_string) >= 10:
print("The cooling time could no... | 1e722bea88e9947f7c297a07bb4f0c5cb5ec4419 | 7,745 |
def process_cases(list_):
"""Process cases and determine whether group flag or empty line."""
# Get information
is_empty = (len(list_) == 0)
if not is_empty:
is_group = list_[0].isupper()
is_comment = list_[0][0] == '#'
else:
is_group = False
is_comment = False
... | 5a0dda6873417cfcd813efe30b64c9e0a71b9b11 | 7,746 |
def updateNestedDicts(d1, d2):
"""Updates two dictionaries, assuming they have the same entries"""
finalDict = createDictionary()
for key in d1:
#print(key)
newDict = updateDicts(d1[key], d2[key])
finalDict[key] = newDict
return finalDict | 29fa5218cb4bca67f8e358aebf742025dd541789 | 7,747 |
def page_not_found(e):
"""error handler for page not found"""
flash(e.description, 'danger')
return render_template('main/404.html'), 404 | a64941bca6bd9e90d35286e3d2474c2841ecb112 | 7,748 |
def get_cifar10_raw_data():
"""
Gets raw CIFAR10 data from http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz.
Returns:
X_train: CIFAR10 train data in numpy array with shape (50000, 32, 32, 3).
Y_train: CIFAR10 train labels in numpy array with shape (50000, ).
X_test: CIFAR10 test data in numpy a... | 1606c8aa00729a6fb9dca8fbd5663e78d5c93503 | 7,749 |
from typing import OrderedDict
def MovieMaker(images, dpath, site, scheck, coords, bandlist, datelist, bands):
""" Function to build the movie """
failed = 0
while failed <2:
spath = dpath + "UoL/FIREFLIES/VideoExports/%s" % coords["name"]
# for bands in bandcombo:
print("\n starting %s at:" % bands, ... | 3daba6917329e1be8d58c36bfe709488db34d430 | 7,751 |
def TypeUrlToMessage(type_url):
"""Returns a message instance corresponding to a given type URL."""
if not type_url.startswith(TYPE_URL_PREFIX):
raise ValueError("Type URL has to start with a prefix %s: %s" %
(TYPE_URL_PREFIX, type_url))
full_name = type_url[len(TYPE_URL_PREFIX):]
try... | 03727fd60bdebed6b47768f2ec489c68b0a8a45b | 7,752 |
def encode_sentence(tokenized_sentence, max_word_len):
"""
Encode sentence as one-hot tensor of shape [None, MAX_WORD_LENGTH,
CHARSET_SIZE].
"""
encoded_sentence = []
sentence_len = len(tokenized_sentence)
for word in tokenized_sentence:
# Encode every word as matrix of shape [MAX_WO... | 77cadac1b4d29976883cc4d8f7540992b997c381 | 7,753 |
def footnote_ref(key, index):
"""Renders a footnote
:returns: list of `urwid Text markup <http://urwid.org/manual/displayattributes.html#text-markup>`_
tuples.
"""
return render_no_change(key) | 52182e90a73f2b0fb4499b919b3ebf71b562dcbf | 7,754 |
def mconcat(*args):
"""
Apply monoidal concat operation in arguments.
This function infers the monoid from value, hence it requires at least
one argument to operate.
"""
values = args[0] if len(args) == 1 else args
instance = semigroup[type(values[0])]
return instance(*values) | 0c939ab0da77843b96c11dcf523557351a602a65 | 7,755 |
def parallelMeasurements(filename='CCD204_05325-03-02_Hopkinson_EPER_data_200kHz_one-output-mode_1.6e10-50MeV.txt',
datafolder='/Users/sammy/EUCLID/CTItesting/data/', gain1=1.17, limit=105, returnScale=False):
"""
:param filename:
:param datafolder:
:param gain1:
:param lim... | e40dedd715d76a52729c218623a90b53123f4c27 | 7,756 |
from typing import Union
def get_all_urls(the_json: str) -> list:
"""
Extract all URLs and title from Bookmark files
Args:
the_json (str): All Bookmarks read from file
Returns:
list(tuble): List of tublle with Bookmarks url and title
"""
def extract_data(data: dict):
... | 3a76a42fd303e603709c7703fbe877bb47a64a5f | 7,758 |
from typing import Callable
from typing import Iterable
def _goertzel(
block_size: int,
sample_rate: float,
freq: float
) -> Callable[[Iterable[float]], float]:
"""
Goertzel algorithm info:
https://www.ti.com/lit/an/spra066/spra066.pdf
"""
k = round(block_size * (freq / sample_rate))
... | 4e9a039435ccc63cfa1506730c89c915f8cc14c4 | 7,759 |
def rotate_xyz(x,y,z,angles=None,inverse=False):
""" Rotate a set of vectors pointing in the direction x,y,z
angles is a list of longitude and latitude angles to rotate by.
First the longitude rotation is applied (about z axis), then the
latitude angle (about y axis).
"""
if angles==None:
... | 803668619f1ad46f0a48db88f2aba05800f85487 | 7,760 |
def indented_open(Filename, Indentation = 3):
"""Opens a file but indents all the lines in it. In fact, a temporary
file is created with all lines of the original file indented. The filehandle
returned points to the temporary file."""
IndentString = " " * Indentation
try:
fh = open... | 26ba2213c5e9c8fd7932c92f4a162e68e642a01e | 7,761 |
def gan_loss(
gan_model: tfgan.GANModel,
generator_loss_fn=tfgan.losses.modified_generator_loss,
discriminator_loss_fn=tfgan.losses.modified_discriminator_loss,
gradient_penalty_weight=None,
gradient_penalty_epsilon=1e-10,
gradient_penalty_target=1.0,
feature_matc... | dfa1639e049737f943a70ea1d5dcdfe9463b0102 | 7,762 |
def list_subjects():
"""
List all subjects
"""
check_admin()
subjects = Subject.query.all()
return render_template('admin/subjects/subjects.html', subjects=subjects, title="Subjects") | aef910bbae3d25a573b23646ca849a2b790be680 | 7,763 |
async def async_setup(opp, config):
"""Set up the Tibber component."""
opp.data[DATA_OPP_CONFIG] = config
if DOMAIN not in config:
return True
opp.async_create_task(
opp.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
... | 4186491c248d862186a93954ed47e301c4526aea | 7,764 |
def beautifyValue(v):
"""
Converts an object to a better version for printing, in particular:
- if the object converts to float, then its float value is used
- if the object can be rounded to int, then the int value is preferred
Parameters
----------
v : object
the object to ... | aa0a8881989cbfde7a7b5f506c4f45b844df0753 | 7,765 |
def english_to_french(english_text):
""" A function written using ibm api to translate from english to french"""
translation = LT.translate(text=english_text, model_id='en-fr').get_result()
french_text = translation['translations'][0]['translation']
return french_text | 0f93fe02f8f0898b0d62c6ce4880b9eae4303459 | 7,766 |
def get_responsibilities():
"""Returns a list of the rooms in the approvers responsibility."""
email = get_jwt_identity()
# Checks if the reader is an approver
approver = Approver.query.filter_by(email=email).first()
if not approver:
return bad_request("This user does not have the approver role!")
room_list =... | 22ca15c30c5dc5bf5c528e2e19b96af8ab8f2d53 | 7,767 |
import datasets
def get_test_loader(dataset):
"""
Get test dataloader of source domain or target domain
:return: dataloader
"""
if dataset == 'MNIST':
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Lambda(lambda x: x.repeat(3, 1, 1)),
... | 52e1570a7911bf9234e76c27b2156b1a7f358164 | 7,768 |
def push(
message,
user: str = None,
api_token: str = None,
device: str = None,
title: str = None,
url: str = None,
url_title: str = None,
priority: str = None,
timestamp: str = None,
sound: str = None,
) -> typing.Union[http.client.HTTPResponse, typing.BinaryIO]:
"""Pushes t... | 3166be0bae5d21313cecaedf2fa8cf11c7bab0c5 | 7,770 |
def add_init_or_construct(template, variable_slot, new_data, scope, add_location=-1):
"""Add init or construct statement."""
if isinstance(new_data, list):
template[variable_slot][scope].extend(new_data)
return template
if add_location < 0:
template[variable_slot][scope].append(new_d... | 125bc4e34dff837372dbbdc70c69a08a1e83e176 | 7,772 |
def im2col_indices(x, field_height, field_width, padding=1, stride=1):
""" An implementation of im2col based on some fancy indexing """
# Zero-pad the input
p = padding
x_padded = np.pad(x, ((0, 0), (0, 0), (p, p), (p, p)), mode='constant')
k, i, j = get_im2col_indices(x.shape, field_height, field_width, padd... | b2f3f24b3a03ea70efbf5f41cbbfd61fe2bf8cbd | 7,773 |
def nms_1d(src, win_size, file_duration):
"""1D Non maximum suppression
src: vector of length N
"""
pos = []
src_cnt = 0
max_ind = 0
ii = 0
ee = 0
width = src.shape[0]-1
while ii <= width:
if max_ind < (ii - win_size):
max_ind = ii - win_size
ee ... | 70f2e15ce4044095d74d02fd87e779a2d3b206c2 | 7,775 |
import torch
def tensor_text_to_canvas(image, text=None, col=8, scale=False):
"""
:param image: Tensor / numpy in shape of (N, C, H, W)
:param text: [str, ] * N
:param col:
:return: uint8 numpy of (H, W, C), in scale [0, 255]
"""
if scale:
image = image / 2 + 0.5
if torch.is_te... | 5c37d9b3e72d5df14d71fa88aff429081c1f5469 | 7,776 |
import six
def is_sequence(input):
"""Return a bool indicating whether input is a sequence.
Parameters
----------
input
The input object.
Returns
-------
bool
``True`` if input is a sequence otherwise ``False``.
"""
return (isinstance(input, six.collections_abc.S... | 1b11275843adaf32618a09d77ec6053039085b54 | 7,777 |
def auto_prefetch_relationship(name, prepare_related_queryset=noop, to_attr=None):
"""
Given the name of a relationship, return a prepare function which introspects the
relationship to discover its type and generates the correct set of
`select_related` and `include_fields` calls to apply to efficiently ... | baac4ed7215c89311badb22bafe8365fd7be2263 | 7,779 |
def no_conjugate_member(magic_flag):
"""should not raise E1101 on something.conjugate"""
if magic_flag:
something = 1.0
else:
something = 1.0j
if isinstance(something, float):
return something
return something.conjugate() | 5e32d31aa907ac9de2bd153bbe61354207262409 | 7,780 |
def sub_ntt(f_ntt, g_ntt):
"""Substraction of two polynomials (NTT representation)."""
return sub_zq(f_ntt, g_ntt) | b2e538a00bb4b46e52258080ad9007358c82bc71 | 7,781 |
def is_pareto_efficient(costs):
"""
Find the pareto-efficient points given an array of costs.
Parameters
----------
costs : np.ndarray
Array of shape (n_points, n_costs).
Returns
-------
is_efficient_maek : np.ndarray (dtype:bool)
Array of which elements in costs are ... | c7564cab171b833b84bf16a24242666f05022eb2 | 7,782 |
def merge_dict(base, delta, merge_lists=False, skip_empty=False,
no_dupes=True, new_only=False):
"""
Recursively merges two dictionaries
including dictionaries within dictionaries.
Args:
base: Target for merge
delta: Dictionary to merge into base
... | 74b9d29a3137826319f10dbf6f86e65015c53659 | 7,783 |
def redirect_or_error(opt, key, override=''):
"""
Tests if a redirect URL is available and redirects, or raises a
MissingRequiredSetting exception.
"""
r = (override or opt)
if r:
return redirect(r)
raise MissingRequiredSetting('%s.%s' % (
options.KEY_DATA_DICT, key)) | 2dbe71b8332b79c242108cc133fc51bf195fac8a | 7,784 |
def stdev(df):
"""Calculate standard deviation of a dataframe."""
return np.std(df['rate'] - df['w1_rate']) | 8f7d49548dac617855c9232af6aed7ec04e9b64c | 7,785 |
def add_to_cart(listing_id):
"""Adds listing to cart with specified quantity"""
listing = Listing.query.filter_by(id=listing_id, available=True).first()
if not listing:
abort(404)
if not request.json:
abort(400)
if ('quantity' not in request.json or
type(request.json['qua... | ee21468f432374c81f4fe8aada92a6ff757d8d38 | 7,786 |
def get_zip_code_prefixes(df_geolocation : pd.DataFrame) -> pd.DataFrame:
"""
Gets the first three and four first digits of zip codes.
"""
df = df_geolocation.copy()
df['geolocation_zip_code_prefix_1_digits'] = df['geolocation_zip_code_prefix'].str[0:1]
df['geolocation_zip_code_prefix_2_digits'... | 8ba9ae223ba76871363b6c3ed452f157b8a848b0 | 7,787 |
def elina_scalar_infty(scalar):
"""
Return -1 if an ElinaScalar is -infinity, 0 if it is finite and 1 if it is +infinity.
Parameters
-----------
scalar : ElinaScalarPtr
Pointer to the ElinaScalar that needs to be tested for infinity.
Returns
-------
result : c_int
... | 73d5dd7e552e94ce11f739386f225c3b2dbad741 | 7,788 |
import math
def get_target_grid(return_type, **kwargs):
"""
Function: get polar or cartasian coordinates of targets
Inputs:
- return_type: str. "cart" for cartasian coordinates; "polar" for polar coordinates.
- kwargs: additional params.
- rel_points: dictionary. relative length for target positions and heel p... | d69bd81912502d0dde04fce0dc4a57201810f9df | 7,790 |
from datetime import datetime
def s2_filename_to_md(filename):
"""
This function converts the S2 filename into a small dict of metadata
:param filename:
:return: dict
"""
basename = system.basename(filename)
metadata = dict()
splits = basename.split("_")
if len(splits) < 4:
... | 86c40009f915fd250091a68d52f79f5701f64270 | 7,791 |
from typing import Optional
def get_rest_api(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRestApiResult:
"""
Resource Type definition for AWS::ApiGateway::RestApi
"""
__args__ = dict()
__args__['id'] = id
if opts is None:
opts =... | 86edad14cb2ccd8b5da5316db8ac9b66a25dbddd | 7,793 |
def regroup_if_changed(group, op_list, name=None):
"""Creates a new group for op_list if it has changed.
Args:
group: The current group. It is returned if op_list is unchanged.
op_list: The list of operations to check.
name: The name to use if a new group is created.
Returns:
Either group or a ne... | f6a811e34ac79d2563906c4971fa23b7316a0976 | 7,795 |
def spike_train_order_profile(*args, **kwargs):
""" Computes the spike train order profile :math:`E(t)` of the given
spike trains. Returns the profile as a DiscreteFunction object.
Valid call structures::
spike_train_order_profile(st1, st2) # returns the bi-variate profile
spike_train_or... | ab57e5de52c0064ad691501d131e66ed5b230093 | 7,796 |
def home():
"""Home page."""
form = LoginForm(request.form)
with open("POSCAR", "r") as samplefile:
sample_input = samplefile.read()
inputs = InputForm()
current_app.logger.info("Hello from the home page!")
# Handle logging in
if request.method == "POST":
if form.validate_on... | 0494bc54040677d6ae09992280afe8922141a93a | 7,797 |
def isUniqueSeq(objlist):
"""Check that list contains items only once"""
return len(set(objlist)) == len(objlist) | 4522c43967615dd54e261a229b05c742676c7f99 | 7,798 |
import torch
def compute_kld(confidences: torch.Tensor, reduction="mean") -> torch.Tensor:
"""
Args:
confidences (Tensor): a tensor of shape [N, M, K] of predicted confidences from ensembles.
reduction (str): specifies the reduction to apply to the output.
- none: no reduction will... | 4fb57a18fdfae56dc04a2502c4cd21590bc31c93 | 7,799 |
def get_crypto_quote(symbol, info=None):
"""Gets information about a crypto including low price, high price, and open price
:param symbol: The crypto ticker.
:type symbol: str
:param info: Will filter the results to have a list of the values that correspond to key that matches info.
:type info: Opt... | db10e7493ef6e98ad0876d30357c6b5be8269776 | 7,800 |
def data_split(*args, **kwargs):
"""A function to split a dataset into train, test, and optionally
validation datasets.
**Arguments**
- ***args** : arbitrary _numpy.ndarray_ datasets
- An arbitrary number of datasets, each required to have
the same number of elements, as numpy arrays.... | e2ad6e52d2868020cc0bcb960533348a1f93ed31 | 7,802 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.