content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_get_zone_backend_ids(shared_zone_test_context):
"""
Test that you can get possible backend ids for zones
"""
client = shared_zone_test_context.ok_vinyldns_client
response = client.get_backend_ids(status=200)
assert_that(response, has_item(u'func-test-backend')) | 5,315,800 |
def test_models_edx_ui_problem_save_with_valid_statement(statement):
"""Tests that a `problem_save` browser statement has the expected `event_type` and
`name`.
"""
assert statement.event_type == "problem_save"
assert statement.name == "problem_save" | 5,315,801 |
def auto_scaling(setup_trainer_and_train, config, num_iters=2):
"""
Auto-scale the number of envs and batch size to maximize GPU utilization.
param num_iters: number of iterations to use when performing auto-scaling.
"""
def launch_process(func, args):
"""
Run a Python function on a... | 5,315,802 |
def eta_sat_Vargaftik_and_Yargin_Table():
"""Dynamic viscosity of saturated Li vapor
Returns
-------
array
Array of temperature and dynamic viscosity data
References
----------
Vargaftik, N B, and V S Yargin.
Ch 7.4: Thermal Conductivity and Viscosity of the Gaseous Phase.
... | 5,315,803 |
def do_cmd(gargs, args, _):
"""List LNSs in the discovery service database."""
# if args.project_id:
# url = '/api/v1/projects/%s/lnss' % args.project_id
# else:
# url = '/api/v1/lnsd/lnss'
if args.lns_euid:
url = "/api/v1/lnsd/lnss/" + args.lns_euid
_, entry = command.con... | 5,315,804 |
def getColumn(data, colN):
""" Return the column colN (counted starting from 0) in the data. """
return transpose(data)[colN] | 5,315,805 |
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)
now = arrow.utcnow... | 5,315,806 |
def file_compare_files_sum(filelist1,filelist2,filetype='blankspace'):
"""
This is built on file_add_data_files to compare and plot the two list of files by checking if their respective summing is equal.
Notes
-----
Now only the 1Darray is allowed to contained in each file
"""
outarr1 = fil... | 5,315,807 |
def toluene_material_stream():
"""
Create a homogeneous material_stream model
"""
class material_stream(MaterialStream):
def __init__(self, name, description, pp = pp_toluene):
super().__init__(name, description, property_package=pp())
self.mdot.setValue(100.)
... | 5,315,808 |
def wilight_to_opp_position(value):
"""Convert wilight position 1..255 to opp.format 0..100."""
return min(100, round((value * 100) / 255)) | 5,315,809 |
def bload(address, offset, commands):
"""
Хелпер для генерации инструкций для загрузки значения
из heap memory по заданному адресу с заданным смещением
"""
commands.add(Load, address)\
.add(Load, offset)\
.add(Add)\
.add(BLoad, 0) | 5,315,810 |
def create_gh_repos(git_repo_names, gh_access_token):
"""Create new Git repos on Github."""
gh = Github(gh_access_token)
gh_user = gh.get_user()
for git_repo_name in git_repo_names:
gh_repo = gh_user.create_repo(git_repo_name, private=True)
my_print(f"Created Github repo: {gh_repo.full_... | 5,315,811 |
def has_staged_uncommitted():
"""
Return a boolean indicating whether the repository has staged, but
uncommitted changes
"""
try:
sh.git('diff', '--cached', '--exit-code')
return False
except sh.ErrorReturnCode_1:
return True | 5,315,812 |
async def on_ready():
"""Fires when the bot goes online"""
# We use this so that this event only fires after the bot is ready
await bot.wait_until_ready()
# We try to play a sound to let the user know that the bot is online
# If the sound playing fails we just ignore it
try:
playsound("... | 5,315,813 |
def get_transition_matrix(exp, group_name, bnames):
"""Gets a markov transition matrix for a given FixedCourtshipExperiment
and list of behavioral states.
Parameters
----------
exp : FixedCourtshipExperiment
group_name : string
Name of group to get transition matrix for.
... | 5,315,814 |
def get_task_link(task_id, task_df):
"""Get the link from the PYBOSSA task."""
try:
task = task_df.loc[int(task_id)]
except KeyError:
return None
return task['info']['link'] | 5,315,815 |
def hchart(request):
"""Renders the about page."""
assert isinstance(request, HttpRequest)
return render(
request,
'research/bar.html',
{
'title':'Chart',
'message':'Highcharts Based',
'year':datetime.now().year,
'hchart_url':'bar',
... | 5,315,816 |
def get_async_configs():
"""Retrieve async configurations for all functions and versions in a region"""
page_iterator = PAGINATOR.paginate(**OPERATION_PARAMETERS)
for page in page_iterator:
functions = page['Functions']
for function in functions:
try:
response = L... | 5,315,817 |
def partwise_function(function: str, parts: List[Tuple[str, str]], add_zero_otherwise: bool = True) -> str:
"""
Returns a string representing the definition a part-wise mathematical function.
**Parameters**
- `function`: str
The name of the function.
- `parts`: list
Each element ... | 5,315,818 |
def pytest_addoption(parser):
"""
pytest hook that is used to make values from the pytest.ini available to all
test
"""
parser.addini(
"rmse",
"Min RMSE score for a model to past post-train test",
)
parser.addini(
"inference_time",
"Max inference time for the ... | 5,315,819 |
def coprime(a, b):
"""0 is coprime only with 1"""
return gcd(a, b) in (0, 1) | 5,315,820 |
def user_picture1(request):
"""A view that is vulnerable to malicious file access."""
filename = request.GET.get('p')
# BAD: This could read any file on the file system
data = open(filename, 'rb').read()
return HttpResponse(data) | 5,315,821 |
def random_array():
"""
089
Create an array which will store a list of integers. Generate five random numbers and store them in
the array. Display the array (showing each item on a separate line).
"""
import random
rand_array, counter = array("i"), 5
while counter:
rand_array.app... | 5,315,822 |
def load_seq_ids(fname):
"""Load sequence of IDs from txt file."""
ids = []
with open(fname, "r") as f:
for line in f:
ids.append(int(line.strip()))
ids = np.asarray(ids)
return ids | 5,315,823 |
def create_app(config):
"""Initialize the core application."""
app = Flask(__name__, instance_relative_config=False)
app.config.from_object(config)
db.init_app(app)
with app.app_context():
# Include our Routes
from . import routes
# Register Blueprints
# Call facto... | 5,315,824 |
def test_private_std_petal_width(example_private_table: PrivateTable):
"""check private std implementation using Petal Width in iris dataset."""
noisy_std = example_private_table.std('Petal Width', PrivacyBudget(10000.))
check_absolute_error(noisy_std, 0.7631607417008414, 1.)
del noisy_std | 5,315,825 |
async def download(set):
""" .gsetf komutu dizini belirtmenizi sağlar. """
await set.edit("İşleniyor ...")
input_str = set.pattern_match.group(1)
if input_str:
parent_id = input_str
await set.edit(
"Özel Klasör ID'si başarıyla ayarlandı. Sonraki uploadlar şuraya uploadlanacak... | 5,315,826 |
def write(img, degree, file_name):
"""
write file
"""
height, width, _ = img.shape
mat = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)
affine_img = cv2.warpAffine(img, mat, (width, height))
cv2.imwrite(TARGET_PATH+file_name+".jpg", affine_img) | 5,315,827 |
def is_valid_maze(maze):
"""Returns True if the maze is valid, False otherwise."""
# Asserts each constraint and returns False if any are not met.
if not constraint_0(maze):
return(False)
if not constraint_1(maze):
return(False)
if not constraint_2(maze):
return(False... | 5,315,828 |
def spectral_dimension_ui(i):
"""Return a list of widgets whose entries are used in evaluating the dimension
coordinates along the i^th dimension. The widgets includes number of points (count),
spectral width, and reference offset.
Args:
i: An integer with the dimension index.
"""
# cou... | 5,315,829 |
def get_params(filename=None, **kwargs):
"""Return all the parameters, retrieved following this order of priority:
* parameters specified as keyword arguments in this function,
* parameters specified in the .PRM file given in `filename`,
* default parameters.
"""
# Extract sample_rate ... | 5,315,830 |
def read_restrictions_file(file):
"""
<Purpose>
Reads in the contents of a restrictions file.
<Arguments>
file: name/path of the file to open
<Returns>
A list, where each element is a line in the file
"""
# Get the file object, read mode with universal newlines
fileo = open(file,"rU"... | 5,315,831 |
def argsToParams(args):
"""
"""
if args.explanation_computer == ExplanationComputer.MUS.name:
params = MUSParams()
elif args.explanation_computer == ExplanationComputer.OUS_INCREMENTAL_NAIVE.name:
params = OusIncrNaiveParams()
elif args.explanation_computer == ExplanationComputer.OUS... | 5,315,832 |
def autodiscover():
"""
Goes and imports the permissions submodule of every app in INSTALLED_APPS
to make sure the permission set classes are registered correctly.
"""
global LOADING
if LOADING:
return
LOADING = True
from django.utils.module_loading import autodiscover_modules
... | 5,315,833 |
def randiwishart(sigma, df):
""" Generate an inverse Wishart random matrix in the form consistent with randiwishart.m
:param sigma: covariance matrix (n x n)
:param df: degrees of freedom. Must be greater than n (dimension of sigma)
:type sigma: np.ndarray
:type df: int
:return: sqrtinvx
... | 5,315,834 |
def download(date_array, tag='', inst_id='', data_path=None, user=None,
password=None, file_type='hdf5'):
"""Downloads data from Madrigal.
Parameters
----------
date_array : array-like
list of datetimes to download data for. The sequence of dates need not
be contiguous.
... | 5,315,835 |
def save_heuristic_net(net, path):
"""
Saves a heuristic net to the specified path.
:param net: the heuristic net
:param path: the path
"""
log.info('saving heuristic net %s to path %s', net, path)
hn_vis.save(net, path) | 5,315,836 |
def get_pred_metrics(key_filepath, pred_filepath, average="macro"):
""" Gets F1 value out a key and predicted csv files
Files must be formated as
name,target
name1,1
name2,3
...
name948,2
name949,2
"""
key = pd.read_csv(key_filepath)
pred = pd.read_csv(pred_filepath)
asse... | 5,315,837 |
def guess_email_class(email: EmailMessage) -> str :
"""
:param email:
:return:
"""
for part in email.walk():
if part.get_content_type() == 'text/calendar':
return 'IPM.Appointment'
else:
return 'IPM.Note' | 5,315,838 |
def slice_generator(image_file, out_dir, new_size=None):
"""
Image generator.
creates slices of a given size for an image and saves them
to disk, to use for c3d.
image_filename: Filename of the image.
out_dir: output directory.
Returns the paths of each of the saved slices.
"""
# f... | 5,315,839 |
def synctree(a, b):
"""
Copy new and updated files from a to b.
:param a: The seed directory
:param b: The destination directory
:return: `True` if files were copied, `False` otherwise
"""
def sync(cmp):
for name in cmp.left_only + cmp.diff_files:
a_path = str(Path(cmp.... | 5,315,840 |
def main():
"""Hoo.
Wat.
"""
if len(argv) > 1:
raise app.UsageError("Too many command-line arguments.")
x = (
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
)
y = [
1,
2,
[
3,
],
]
z = ... | 5,315,841 |
def parse(source, output):
"""Parse skb tbody table to .csv which can be used to inport to MMEX."""
with open('category_mapping.yaml', 'r') as stream:
category_mapping = yaml.load(stream)
with open(source, 'r') as fp:
with open(output, 'w', newline='') as csvfile:
csv_writer = cs... | 5,315,842 |
def fqn(o):
"""Returns the fully qualified class name of an object or a class
:param o: object or class
:return: class name
"""
parts = []
if isinstance(o, (str, bytes)):
return o
if not hasattr(o, '__module__'):
raise ValueError('Invalid argument `%s`' % o)
parts.append... | 5,315,843 |
def get_lane_boundaries_surface(
world: carla.World, # pylint: disable=no-member
pixels_per_meter: int = 5,
scale: float = 1.0,
margin: int = 150,
) -> pygame.Surface:
"""Generates a `PyGame` surface of a CARLA town lane boundaries.
Heavily inspired by the official CARLA `no_rendering_mode.py` exa... | 5,315,844 |
def batch_dq_prod_vector(dqs, V):
"""Apply transforms represented by a dual quaternions to vectors.
Parameters
----------
dqs : array-like, shape (..., 8)
Unit dual quaternions
V : array-like, shape (..., 3)
3d vectors
Returns
-------
W : array, shape (3,)
3d v... | 5,315,845 |
def handle_mpd_load(bot, ievent):
""" arguments: <playlist> - load playlist. """
handle_mpd_playlist_manipulation(bot, ievent, 'load') | 5,315,846 |
def uniescape(text: str) -> str:
"""
Escapes all non-ASCII printable characters with JavaScript Unicode escapes.
"""
def escape(match):
character = match.group(0)
assert len(character) == 1
code_point = ord(character)
assert code_point <= 0xFFFF
return f"\\u{code... | 5,315,847 |
def test_process_5():
"""
makes sure the conf score doesn't get changed
:return:
"""
from scipy.special import betainc
a = 0 # pseudocount
b = 0 # pseudocount
cov_margin = 0.01
total_coverage = 100
dp4 = '99,0,1,0'
fraction = 0.01
# confidence = 1 - betainc(G, A, cov_mar... | 5,315,848 |
def aggregate_collate_fn(insts) -> Dict[str, List[List[Union[int, str, List[int]]]]]:
"""aggregate the instance to the max seq length in batch
Args:
insts: list of sample
Returns:
"""
subtree_spans, children_spans, snts = [], [], []
for inst in insts:
subtree_spans.append(inst['... | 5,315,849 |
def encode_extended(values, value_range):
"""Encode data using Google's "extended" encoding for the most granularity."""
return "".join(num2chars(v, value_range) for v in values) | 5,315,850 |
def init_tf(FLAGS):
"""
Set global options for TensorFlow
"""
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
tf.config.experimental.set_visible_devices(gpus[hvd.local_rank()], 'GPU')
if hvd.size() > 1:
memory_limit_mb = FLAGS.tf_gpu_memory_limit_gb * 1024
... | 5,315,851 |
def main(argv=None):
"""
The main function of this script. Converts JSON to XML based on the arguments provided.
:param argv: List[str] Arguments to parse (default sys.argv)
:return: int
"""
#Parse arguments
parser = argparse.ArgumentParser(description='Converts JSON to XML.')
parser.add_argument('-t', '--inde... | 5,315,852 |
def part_b(puzzle_input, workers=5, offset=60):
"""
Calculate the answer for part_b.
Args:
puzzle_input (list): Formatted as the provided input from the website.
Returns:
string: The answer for part_b.
"""
deps = parse_deps(puzzle_input)
finished = []
queue = []
pro... | 5,315,853 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up a National Weather Service entry."""
latitude = entry.data[CONF_LATITUDE]
longitude = entry.data[CONF_LONGITUDE]
api_key = entry.data[CONF_API_KEY]
station = entry.data[CONF_STATION]
client_session = async_get_clien... | 5,315,854 |
def write_cache_time(f, t):
"""Write a cache time.
:param f: File-like object to write to
:param t: Time to write (as int, float or tuple with secs and nsecs)
"""
if isinstance(t, int):
t = (t, 0)
elif isinstance(t, float):
(secs, nsecs) = divmod(t, 1.0)
t = (int(secs), ... | 5,315,855 |
def cov_hvus(data1,data2,label):
"""
Estimate the covariance of hvus between two classifiers/features based on graph theory
Parameters
----------
data1 : array-like of shape (n_samples,)
samples' value from classifier1
data2 : array-like of shape (n_samples,)
samples' value ... | 5,315,856 |
def clean(s):
"""
remove symbols and lowercase
"""
regex = re.compile('\W+')
s = regex.sub(' ', s).strip()
return s.lower() | 5,315,857 |
def trueifset(xeval, typematch=False):
"""return True if @xeval is set, otherwise False"""
if typematch:
if not (xeval is False or xeval is None): return True
else: return False
else:
if xeval: return True
else: return False | 5,315,858 |
def _generate_dash_manifest(encoding, output, output_path):
# type: (Encoding, Output, str) -> DashManifestDefault
"""
Creates a DASH default manifest that automatically includes all representations configured in
the encoding.
<p>API endpoint:
https://bitmovin.com/docs/encoding/api-reference/se... | 5,315,859 |
def shipping():
"""The webapp's page for viewing the shipping status of work orders.
This allows the employee to review existing work orders and see if they are ready to ship or not."""
# if the current user is not authenticated, redirect the user to the logged out index page
if not current_user.is_authenticated:
... | 5,315,860 |
def get_file_content(file: str) -> str:
"""
Get file content.
"""
try:
with open(file, 'r') as f:
content = f.read()
return content
except IOError as e:
print(e)
print('Exiting...')
exit(1) | 5,315,861 |
def test_read_and_convert_10x_example(anndata_from_10x_sample):
"""Test that a full 10x CSV table can be imported without errors.
To this end, only the fixture needs to be loaded.
"""
assert anndata_from_10x_sample.shape[0] > 0 | 5,315,862 |
def test_x_format():
"""
Check if format "Pandas" or "Numpy" are still valids and not others.
"""
myclass_fitted = SameSizeKmeans(n_clusters=2)
myclass_fitted.fit(X=pd.DataFrame({'x': [0, 1, 2, 3, 4, 5, 6]}))
assert myclass_fitted._n_samples == 7
myclass_fitted.fit(X=np.array([[1, 2], [2, ... | 5,315,863 |
def simplify_name_to_string(input_name):
"""
``simplify_name_to_string`` simplifies a templated C++ name with default arguments and returns a string
:param input_name: String or qualified name to be simplified
:type input_name: Union[str, QualifiedName]
:return: simplified name (or original name if simplifier fai... | 5,315,864 |
def _normalize_index(index, axis_size):
"""Normalizes an index value in the range [-N, N) to the range [0, N)."""
return lax.select(
lax.lt(index, _constant_like(index, 0)),
lax.add(index, _constant_like(index, axis_size)),
index) | 5,315,865 |
def show_databases(host, user, passwd):
"""
Prints report on all the databases
@param host : host name
@type host : str
@param user : user name
@type user : str
@param passwd : user's password
@type passwd : str
@return: printed report all the tables in each database.
"""
dbs = get_database... | 5,315,866 |
def test_ntp_service(Service):
""" Ensure the NTP service is both enabled and running
Args:
Service - Module used to determine service status
"""
ntp = Service("ntp")
assert ntp.is_enabled
assert ntp.is_running | 5,315,867 |
def english_to_french(english_text):
#write the code here
"""class docstring
code to translate english text to french"""
translation = language_translator.translate(
text = english_text, model_id = "en-fr"
).get_result()
french_text = translation["translations"][0]["translation"]
... | 5,315,868 |
def test_radial_velocity3():
""" Put a central at (9, 9, 9) in a box of length 10.
Place all satellites at the point (11, 11, 9), moving in the direction (-1, -1, 0),
i.e., in the negative radial direction away from the (stationary) central.
Verify that we recover the correct radial velocity after apply... | 5,315,869 |
def get_sampling_distribution(samples):
"""
Get the sampling distribution of all samples of a population.
Parameter: a list of lists containing all possibile samples of a distribution.
Returns: sampling distribution, which is the list of means of all samples given.
"""
sampling_distrib... | 5,315,870 |
def compute_loss3D(embeddings, labels, device, temperature=0.7):
"""
embeddings: a B, C, D, H, W array
lables: B, 1 array
device: torch.device instance, either cuda or cpu
"""
# all of them are 3d embeddings, I again need to separate
# them and then do the dot product things.
... | 5,315,871 |
def grad_polynomial_bases(X, N):
"""
Compute the gradients of the monomial bases.
Parameters
----------
X : ndarray
contains the points to evaluate the monomials
N : int
the maximum degree of the monomial basis
Returns
-------
dB : ndarray
contains the grad... | 5,315,872 |
def test_job_metadata_api(per_test_flask_app, per_test_postgres, request, api_version, mocked_config,
monkeypatch):
"""Test job_metadata API call works with the security role created based on abstract role."""
# Run dirbs-classify to generate some metadata
runner = CliRunner()
... | 5,315,873 |
def hor1f(x, z, offset=1):
"""
BROKEN: Haven't quite figured this one out
Calculate the horizon pixel for all x,z
This mimics the algorthim from Dozier 1981 and the
hor1f.c from IPW
Works backwards from the end but looks forwards for
the horizon
xrange stops one index before [stop]
... | 5,315,874 |
def make_multi_class_binomial_deviance(n_class, alpha=2., beta=0.5, cy=25., sim='cosine'):
""" Builder for the Binomial Deviance loss function. Ref:
https://papers.nips.cc/paper/6464-learning-deep-embeddings-with-histogram-loss.pdf
Note that the batch must be built using M exclusive classes and N images pe... | 5,315,875 |
def json_to_odict(json_series):
"""
Load a JSON series into OrderedDict
"""
import json
from collections import OrderedDict
odict = json.loads(js, object_pairs_hook=OrderedDict)
return odict | 5,315,876 |
def test_run_setup():
""" Test the setup script
"""
# Remove .setup if needed
sfiles = glob.glob('*.setups')
for sfile in sfiles:
os.remove(sfile)
#
droot = data_path('b')
pargs = Setup.parse_args(['-r', droot, '-s', 'shane_kast_blue', '-c=all',
'--e... | 5,315,877 |
def sectors_performance(
apikey: str, limit: int = DEFAULT_LIMIT
) -> typing.List[typing.Dict]:
"""
Query FMP /sectors_performance/ API
:param apikey: Your API key.
:param limit: Number of rows to return
:return: A list of dictionaries.
"""
path = f"sectors-performance"
query_vars =... | 5,315,878 |
def _prepTrends(rawReport, startDt, numFiles, countMonth, granularity):
"""
Helper function which reformats data into list of lists with correct data
types. If anything is empty or has incorrect data, then an empty list is
returned.
"""
#load each rawReport into separate list
reportData = []
for i in range(numF... | 5,315,879 |
def drift(ips, tau):
"""Drift operator.
"""
if ips.include_pn_corrections:
return drift_pn(ips, tau)
return drift_n(ips, tau) | 5,315,880 |
def F1Score4(pred, groundtruth):
"""
# N A O P
# Normal AF Other Noisy Total
#Normal Nn Na No Np ∑N
# AF An Aa Ao Ap ∑A
#Other On Oa Oo Op ∑O
#Noisy Pn Pa Po Pp ∑P
#Total ∑n ∑a ∑o ∑p
"""
pred_len = len(pred)
re_table =np.zeros([4,4])
for i in range(pred_... | 5,315,881 |
def get_point_pixel_values(
coords,
start_date: datetime = date.today() - timedelta(days=365),
end_date: datetime = date.today(),
ascending: bool = True,
orbit_number: object = None,
scale: int = 20,
n_jobs: int = 1,
verbose: int = 0,
):
"""Given a coordinate tuple and a list of date... | 5,315,882 |
def any(x: Union[ivy.Array, ivy.NativeArray],
axis: Optional[Union[int, Tuple[int], List[int]]] = None,
keepdims: bool = False)\
-> ivy.Array:
"""
Tests whether any input array element evaluates to ``True`` along a specified axis.
.. note::
Positive infinity, negative infinit... | 5,315,883 |
def stash(keychain, source, destination, treasure, location):
"""
Encrypt and stash file.
\f
:param keychain: Object containing key and spice
:type keychain: :class:`narrenschiff.chest.Keychain`
:param source: Source filepath for encryption
:type source: ``str``
:param destination: Dest... | 5,315,884 |
def _filter_in_wet_days(da: DataArray, dry_day_value: float):
"""
Turns non wet days to NaN.
dry_day_value may be Nan or 0.
"""
precip = convert_units_to(da, "mm/d")
return precip.where(precip > 1, dry_day_value) | 5,315,885 |
def codemirror_field_css_assets(*args):
"""
Tag to render CodeMirror CSS assets needed for all given fields.
Example:
::
{% load djangocodemirror_tags %}
{% codemirror_field_css_assets form.myfield1 form.myfield2 %}
"""
manifesto = CodemirrorAssetTagRender()
manifesto.r... | 5,315,886 |
def request(method, url, **kwargs):
"""
Wrapper around :func:`treq.request` with some added arguments
and validation.
:param str method:
The HTTP method to use when making the request.
:param str url:
The url this request will be made to.
:type data: str, list, tuple, set, dic... | 5,315,887 |
def for_stmt(target, iter_, body, orelse, local_writes):
"""Functional form of a for statement."""
if tf.is_tensor(iter_):
local_writes = [
var for var in local_writes if not py_defaults.is_undefined(var.val)
]
n = _tf_len(iter_)
def for_test(i, *_):
return i < n
def for_body(i... | 5,315,888 |
def is_running():
"""Return if the main global loop is running."""
global __loop__
return __loop__ is not None and __loop__.is_running() | 5,315,889 |
def build_web_site(resources, site_class=None):
"""Build a Twisted web Site instance for a specified dictionary of
resources.
:param dict resources:
Dictionary of path -> resource class mappings to create the site from.
:type site_class: Sub-class of Twisted's Site
:param site_class:
... | 5,315,890 |
async def test_site_cannot_connect(hass, requests_mock, legacy_patchable_time):
"""Test we handle cannot connect error."""
requests_mock.get("/public/data/val/wxfcs/all/json/sitelist/", text="")
requests_mock.get("/public/data/val/wxfcs/all/json/354107?res=3hourly", text="")
entry = MockConfigEntry(do... | 5,315,891 |
def CheckExpectedOutput(output, expected):
"""Assert that expected content appears in the output.
Arguments:
output: Output from a tool to be searched for matches
expected: An iterable which contains regular expressions, a match for
each of which must appear in 'output'
Returns the nu... | 5,315,892 |
def vector_sum(vectors):
""" sums all corresponding elements """
return reduce(vector_add, vectors) | 5,315,893 |
async def get_all_consent_documents(environment, access_token, deployment_id):
"""
Function: [get_all_consent_documents]
:param environment: The CARP [environment].
:param access_token: The [access_token].
:param deployment_id: The [deployment_id].
:return: Lists all consents documents by [deplo... | 5,315,894 |
def convert_to_time_series(dataset, sequence_len, input_dim, output_dim):
"""
Function to convert a sequential `dataset` into time series data
:param dataset: 1-D List containing sequential data
:param sequence_len: Number of time steps in each instance
:param input_dim: Dimension of input at each t... | 5,315,895 |
def get_ip_reputation_score(classification: str) -> Tuple[int, str]:
"""Get DBot score and human readable of score.
:type classification: ``str``
:param classification: classification of ip provided from GreyNoise.
:return: tuple of dbot score and it's readable form.
:rtype: ``tuple``
"""
... | 5,315,896 |
def _cv_input_text(cfg):
"""Configure validation helper for input box (voluptuous)."""
minimum = cfg.get(CONF_MIN)
maximum = cfg.get(CONF_MAX)
if minimum > maximum:
raise vol.Invalid('Max len ({}) is not greater than min len ({})'
.format(minimum, maximum))
state = ... | 5,315,897 |
def eyediagram (signal, samplesPerSymbol, totalSamples, Tsymb, ax):
"""
"""
t = np.linspace(-1,1,2*samplesPerSymbol)
for i in range(0,totalSamples-2*samplesPerSymbol+1,2*samplesPerSymbol):
plt.plot(t,signal[i:i+2*samplesPerSymbol],'b')
ax.set_title("eyediagram",fontsize=7)
ax.set_xlabel("Time [sec]",fontsiz... | 5,315,898 |
def map_values(e):
"""
:rtype: Column
"""
return col(MapValues(ensure_column(e))) | 5,315,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.