content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def generate_new_admin_class():
"""
we need to generate a new dashboard view for each `setup_admin` call.
"""
class MockDashboard(DashboardView):
pass
class MockAdmin(Admin):
dashboard_class = MockDashboard
return MockAdmin | 35,500 |
def visualize_warp(rgb, oflow):
"""TODO: add info."""
rgb = utils.to_numpy(rgb)
oflow = utils.to_numpy(oflow)
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
rgb = np.moveaxis(rgb, -3, -1)
rgb = rgb*std+mean
rgb = np.clip(rgb*255, 0, 255)
bgr = rgb[..., ::-1].astype(np.ui... | 35,501 |
def test_ok_none_charge_efficiency(schema: Type[BaseModel], data: Dict[str, Any]):
"""
Test that a charge efficiency is optional for a schema
"""
schema(charge_efficiency=None, **data) | 35,502 |
def for_default_graph(*args, **kwargs):
"""Creates a bookkeeper for the default graph.
Args:
*args: Arguments to pass into Bookkeeper's constructor.
**kwargs: Arguments to pass into Bookkeeper's constructor.
Returns:
A new Bookkeeper.
Raises:
ValueError: If args or kwargs are provided and the B... | 35,503 |
def check_paragraph(index: int, line: str, lines: list) -> bool:
"""Return True if line specified is a paragraph
"""
if index == 0:
return bool(line != "")
elif line != "" and lines[index - 1] == "":
return True
return False | 35,504 |
def most_similar(train_path, test_path, images_path, results_path, cuda=False):
"""
Nearest Neighbor Baseline: Img2Vec library (https://github.com/christiansafka/img2vec/) is used to obtain
image embeddings, extracted from ResNet-18. For each test image the cosine similarity with all the training images
... | 35,505 |
def pull_backgrounds() -> None:
"""Pull the shape generation backgrounds.
This function utilizes the ``BACKGROUNDS_URLS`` in
``hawk_eye.data_generation.generate_config.py``."""
for background_archive in config.BACKGROUNDS_URLS:
download_file(background_archive, config.ASSETS_DIR) | 35,506 |
def h2o_H2OFrame_tolower():
"""
Python API test: h2o.frame.H2OFrame.tolower()
"""
frame = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv"))
frame["C5"]= frame["C5"].tolower()
assert (frame["C5"]=='iris-setosa').sum() == 50, \
"h2o.H2OFrame.tolower() command is not wor... | 35,507 |
def remove_objects_without_content(page_spans, objects):
"""
Remove any objects (these can be rows, columns, supercells, etc.) that don't
have any text associated with them.
"""
for obj in objects[:]:
object_text, _ = extract_text_inside_bbox(page_spans, obj['bbox'])
if len(object_te... | 35,508 |
def find_packages(where='.', exclude=()):
"""Return a list all Python packages found within directory 'where'
'where' should be supplied as a "cross-platform" (i.e. URL-style) path; it
will be converted to the appropriate local path syntax. 'exclude' is a
sequence of package names to exclude; '*' can ... | 35,509 |
def ensure_downloaded(data_dir: PathLike, *datasets: str) -> None:
"""
Downloads the specified datasets (all available datasets if none specified)
into the data directory if they are not already present. This is useful in
situations where this package is used in an environment without Internet
acces... | 35,510 |
def _splitSerieIfRequired(serie, series):
""" _splitSerieIfRequired(serie, series)
Split the serie in multiple series if this is required.
The choice is based on examing the image position relative to
the previous image. If it differs too much, it is assumed
that there is a new dataset. This ca... | 35,511 |
def mask(node2sequence, edge2overlap, masking: str = "none"):
"""If any of the soft mask or hard mask are activated, mask
:param dict exon_dict: Dict of the shape exon_id: sequence.
:param dict overlap_dict: Dict of the shape (exon1, exon2): overlap between them.
:param str masking: Type of masking to ... | 35,512 |
def load_patch_for_test_one_subj(file_path, sub_i, patch_shape, over_lap=10,
modalities=['MR_DWI', 'MR_Flair', 'MR_T1', 'MR_T2'],
mask_sym='MR_MASK',
suffix='.nii.gz',
use_norm=True):
... | 35,513 |
def extract_el_from_group(group, el):
"""Extract an element group from a group.
:param group: list
:param el: element to be extracted
:return: group without the extracted element, the extracted element
"""
extracted_group = [x for x in group if x != el]
return [extracted_group] + [[el]] | 35,514 |
def scale_y(scale, axes="current", lines="all"):
"""
This function scales lines vertically.
You can specify a line index, such as lines=0 or lines=[1,2,4]
"""
if axes=="current": axes = _pylab.gca()
# get the lines from the plot
lines = axes.get_lines()
# loop over the lines and tri... | 35,515 |
def atualizar_pergunta_func(pergunta, titulo, pergunta_questao, resposta_1, resposta_2, resposta_3, resposta_4, resposta_certa, questao_dificuldade):
"""
Função para atualizar a pergunta
@param pergunta: A pergunta extraida do DB (objeto)
@param titulo: titulo extraido do form
@param pergunta_questa... | 35,516 |
def verify(pin, serial, udp):
"""Verify key is valid Nitrokey 'Start' or 'FIDO2' key."""
# Any longer and this needs to go in a submodule
print("Please press the button on your Nitrokey key")
try:
cert = pynitrokey.client.find(serial, udp=udp).make_credential(pin=pin)
except ValueError as e... | 35,517 |
def example_function_with_shape(a, b):
"""
Example function for unit checks
"""
result = a * b
return result | 35,518 |
def editAddressFile(path, address, property=""):
"""
Edits the address file.
"""
with open(path, "r") as file:
data = json.load(file)
testnets = [
'arbitrum-rinkeby',
'rinkeby'
]
if network.show_active() in testnets:
net = "testnet"
else:
net = "m... | 35,519 |
def write_comfeat(feat, lbl, fname):
"""Write combined TCN features
Args:
feat: combined feature, ndarray of shape (N_SAMPLES, DIM)
lbl: groundtruth label, ndarray of shape (N_SAMPLES, 1)
fname: path to the output filename
"""
mdict = {'A': feat, 'Y': lbl}
scipy.io.savemat(f... | 35,520 |
def p_statement_vardecl(p: yacc.YaccProduction):
"""STATEMENT : VARDECL SEMICOLON"""
p[0] = {'code': p[1]['code']} | 35,521 |
def fields(
builder: DataclassBuilder, *, required: bool = True, optional: bool = True
) -> "Mapping[str, Field[Any]]":
"""Get a dictionary of the given :class:`DataclassBuilder`'s fields.
.. note::
This is not a method of :class:`DataclassBuilder` in order to not
interfere with possible f... | 35,522 |
def read_csv(
filepath_or_buffer: Literal["/tmp/tmp0cdg5he1."],
names: List[Literal["amount", "name"]],
skiprows: int,
):
"""
usage.dask: 1
"""
... | 35,523 |
def main():
"""Combine N-Puzzle macros for different starting positions into a single file"""
results_dir = 'results/macros/npuzzle/'
filenames = glob.glob(results_dir+'macro-n15-*-results.pickle')
macros = OrderedDict()
for filename in filenames:
row = int(filename.split('/')[-1].split('-')... | 35,524 |
def test_export_format(sample_data) -> None:
"""
Test to ensure that the graph is being effectively exported as a dictionary
which is valid JSON.
:param sample_data: the sample data
:return: None
"""
# create an AuthorRank object
ar_graph = ar.Graph()
# fit to the data
ar_graph... | 35,525 |
def condon():
"""Testing whether or not the Condon approximation is appropriate."""
fig, ax = plt.subplots()
frequencies_all = []
intensities_all = []
csvfile = open('condon_analysis_linear_regression.csv', 'w')
csvwriter = csv.writer(csvfile)
csvwriter.writerow([
'# QM',
... | 35,526 |
def gemm(node: NodeWrapper,
params: Dict[str, np.ndarray],
xmap: Dict[str, XLayer]) -> List[XLayer]:
"""
ONNX Gemm to XLayer Dense (+ Scale) (+ BiasAdd) conversion function
Compute Y = alpha * A' * B' + beta * C
See https://github.com/onnx/onnx/blob/master/docs/Operators.md#Gemm
"... | 35,527 |
def check_response(game_id, response):
"""Check for correct response"""
if response["result"]["@c"] == "ultshared.rpc.UltSwitchServerException":
game = Game.query.filter(Game.game_id == game_id).first()
if "newHostName" in response["result"]:
print("new host: " + response["result"][... | 35,528 |
def extract_to_dst(src, dst):
"""extract addon src zip file to destination."""
copied_items = []
zip_file = path.basename(src)
zip_name, _ = path.splitext(zip_file)
cache_path = path.join(root_path, 'cache', zip_name)
with zipfile.ZipFile(src, 'r') as z:
# create folder and extract to ca... | 35,529 |
def get_signal_handler():
"""Get the singleton signal handler"""
if not len(_signal_handler_):
construct_signal_handler()
return _signal_handler_[-1] | 35,530 |
def post_rule(team_id):
"""Add a new rule.
.. :quickref: POST; Add a new rule.
**Example request**:
.. sourcecode:: http
POST /v1/teams/66859c4a-3e0a-4968-a5a4-4c3b8662acb7/rules HTTP/1.1
Host: example.com
Accept: application/json
{
"name": "Servers",
"descri... | 35,531 |
def intents(interface):
"""
Method to get an object that implements interface by just returning intents
for each method call.
:param interface: The interface for which to create a provider.
:returns: A class with method names equal to the method names of the
interface. Each method on this ... | 35,532 |
def _write_init_py(package_name: str) -> None:
"""
Dynamically write the __init__.py for the package using the chosen package.
:param chosen_package: mystery package name.
:type chosen_package: str
:rtype: None
"""
package_name = _fix_package_name(package_name)
init_py_path = pathlib.Pa... | 35,533 |
def model(X, Y, learning_rate=0.3, num_iterations=30000, print_cost=True, is_plot=True, lambd=0, keep_prob=1):
"""
实现一个三层的神经网络:LINEAR ->RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID
参数:
X - 输入的数据,维度为(2, 要训练/测试的数量)
Y - 标签,【0(蓝色) | 1(红色)】,维度为(1,对应的是输入的数据的标签)
learning_rate - 学习速率
... | 35,534 |
def load_phoenix_stars(logg_list=PHOENIX_LOGG, teff_list=PHOENIX_TEFF, zmet_list=PHOENIX_ZMET, add_carbon_star=True, file='bt-settl_t400-7000_g4.5.fits'):
"""
Load Phoenix stellar templates
"""
from collections import OrderedDict
try:
from urllib.request import urlretrieve
except:
... | 35,535 |
def write_ini(locStr_ini_file_path, locStr_ini):
"""
.. _write_ini :
Write the given string into the given INI file path.
Parameters
----------
locStr_ini_file_path : str
The file full path of the INI file. If the extension ".ini" is not included,
it would be adde... | 35,536 |
def save_model(model, out_dir):
"""
Save all model information in multiple files.
This is meant to be temporary until SBML output is functional.
:param model: Model to save
:type model: Model
:param out_dir: Directory to store files
:type out_dir: str
"""
import datetime
dt = da... | 35,537 |
def create_form(data, form_idx=0):
""" Creates PDB structure forms.
form_idx = 0 is apo; 1 - holo1; and 2 - holo2
Note: Only works for homodimers.
"""
# Make a deep copy of BioPandas object to make changes
data_out = deepcopy(data)
# If form_idx == 2 that's holo2 already
if ... | 35,538 |
def get_verbosity(parsed_arguments: Dict) -> int:
"""
Gets the verbosity level from parsed arguments.
Assumes parameter is being parsed similarly to:
```
parser.add_argument(f"-{verbosity_parser_configuration[VERBOSE_PARAMETER_KEY]}", action="count", default=0,
help="inc... | 35,539 |
def test_main_named_args():
"""
Ensure that named arguments are passed on properly to the flash() function.
"""
with mock.patch('uflash.flash') as mock_flash:
uflash.main(argv=['-r', 'baz.hex'])
mock_flash.assert_called_once_with(path_to_python=None,
... | 35,540 |
def finalize(c, push=False, branch='master'):
"""
Step 7: Finalize your changes. Merge them with the base branch and optionally push upstream.
:param push: git push your changes (Default: False)
:param branch: the base branch for your changes. (Default: master)
"""
init(c)
commit_num, bran... | 35,541 |
def update_versions_in_library_versions_kt(group_id, artifact_id, old_version):
"""Updates the versions in the LibrarVersions.kt file.
This will take the old_version and increment it to find the appropriate
new version.
Args:
group_id: group_id of the existing library
artifact_id: arti... | 35,542 |
def GetIdpCertificateAuthorityDataFlag():
"""Anthos auth token idp-certificate-authority-data flag, specifies the PEM-encoded certificate authority certificate for OIDC provider."""
return base.Argument(
'--idp-certificate-authority-data',
required=False,
help='PEM-encoded certificate authority ce... | 35,543 |
def MapBasinKeysToJunctions(DataDirectory,FilenamePrefix):
"""
Function to write a dict of basin keys vs junctions
Args:
DataDirectory (str): the data directory
fname_prefix (str): the name of the DEM
Returns:
A dictionary with the basin key as the key and the junction as the v... | 35,544 |
def _copy_file(src, dest):
""" Copies a file from src path to dest path
src: source path as string
dest: destination path as string
Uses ditto to perform copy; will silently overwrite dest if it exists
Raises exception if copy fails or either path is None """
if src is None or... | 35,545 |
def password_renew(_name: str, old_password: str, new_password: str):
"""パスワード変更"""
old_dat = old_password
new_dat = new_password
new_hs = sha256(new_dat.encode()).hexdigest() # sha256で暗号化
old_hs = sha256(old_dat.encode()).hexdigest() # sha256で暗号化
if User.select().where(User.name != _name):
... | 35,546 |
def fetch_abs(compare_res_fn: Callable[[res_arg_dict], List[BadResult]], paper_id: str) -> Tuple[Dict, List[BadResult]]:
"""Fetch an abs page."""
ng_url = ng_abs_base_url + paper_id
legacy_url = legacy_abs_base_url + paper_id
res_dict: res_arg_dict = {'ng_url': ng_url,
'le... | 35,547 |
def is_happy(number:int) -> bool:
"""Returns a bool that states wether a number is happy or not"""
results = []
result = thing(number)
results.append(result)
while results.count(result) < 2: # Checking if a number has shown up in the list of previous results again as that is
result = ... | 35,548 |
def self_play(n_iterations=10, ben_steps=1000, training_steps=int(1e4),
n_eval_episodes=100, **kwargs):
"""
Returns an agent that learns from playing against himself from random to
optimal play.
"""
agents = [RLAgent(**kwargs), RandomAgent()]
for _ in range(n_iterations):
benchmark(agents[... | 35,549 |
def auth(event, context):
"""
Return the plain text session key used to encrypt the CAN Data File
event dictionary input elements:
- CAN Conditioner Serial Number
- Encrypted data
Prerequisites:
The CAN Conditioner must be provisioned with a securely stored key tied to the
serial... | 35,550 |
def xpro_aws_settings(aws_settings):
"""Default xPRO test settings"""
aws_settings.XPRO_LEARNING_COURSE_BUCKET_NAME = (
"test-xpro-bucket"
) # impossible bucket name
return aws_settings | 35,551 |
def frames2files(arFrames, sTargetDir):
"""
Write array of frames to jpg files.
Keyword arguments:
arFrames -- np.array of shape: (number of frames, height, width, depth)
sTargetDir -- dir to hold jpg files
returns None
"""
os.makedirs(sTargetDir, exist_ok=True)
for nFrame in range(... | 35,552 |
def function_check(arg, result):
"""arg ↝ result : return"""
if result == TypeBuiltin():
return TypeBuiltin()
if arg == KindBuiltin() and result == KindBuiltin():
return KindBuiltin()
if arg == SortBuiltin() and result in (KindBuiltin(), SortBuiltin()):
return SortBuiltin()
r... | 35,553 |
def test_parameter_1_1():
"""
Feature: Check the names of parameters and the names of inputs of construct.
Description: If the name of the input of construct is same as the parameters, add suffix to the name of the input.
Expectation: No exception.
"""
class ParamNet(Cell):
def __init__(... | 35,554 |
def while_D():
""" *'s printed in the Shape of Capital D """
row =0
while row<9:
col =0
while col <6:
if col ==0 or row %8 == 0 and col!=5 or col ==5 and row %8 !=0:
print('*',end=' ')
else:
print(' ',end=' ')
col ... | 35,555 |
def frule_edit(request, frule_id):
""" FM模块编辑应用包下载规则 """
try:
frule = FRule.objects.filter(id=frule_id).first()
if not frule:
response = '<script>alert("Rule id not exist!");'
response += 'location.href=document.referrer;</script>'
return HttpResponse(response... | 35,556 |
def zip(args):
"""Combine 2 files with interleaved pages."""
filesandranges = iohelper.parse_ranges(args[:-1])
outputfilename = args[-1]
verbose = staplelib.OPTIONS.verbose
if not filesandranges or not outputfilename:
raise CommandError('Both input and output filenames are required.')
... | 35,557 |
def register_help(module: str, topic: str, contents: Union[str, callback_type]) -> None:
"""
Register a help article to a specific module, having a specific topic and contents.
If the contents is a callback, it will be called and awaited to get the help string.
"""
handler = HelpHandler(topic, modul... | 35,558 |
def load_preprocess_data(days_for_validation: int,
lag_variables: list,
random_validation: bool = False,
seed: int = None,
lag: int = 8,
reload: bool = True,
save_c... | 35,559 |
def extract_sha256_hash(hash):
"""Extrach SHA256 hash or return None
"""
prefix = 'sha256:'
if hash and hash.startswith(prefix):
return hash.replace(prefix, '')
return None | 35,560 |
def logout():
"""User logout"""
global bandwidth_object, qos_object
bandwidth_object = {}
qos_object = {}
success_login_form = None
return redirect(url_for('base_blueprint.login')) | 35,561 |
def draft_intro():
"""
Controller for presenting draft versions of document introductions.
"""
response.files.append(URL('static/js/codemirror/lib', 'codemirror.js'))
response.files.append(URL('static/js/codemirror/lib', 'codemirror.css'))
response.files.append(URL('static/js/codemirror/theme', ... | 35,562 |
def call_repeatedly(loop, interval, function, *args, **kwargs):
"""
Wrapper function to schedule function periodically
"""
# Schedule next call
loop.call_later(
interval, call_repeatedly, loop, interval, function,
*args, **kwargs,
)
# Call function
function(*args, **kwarg... | 35,563 |
def collect_shape_data(gtfs_dir):
"""Calculate the number of times a shape (line on a map) is travelled.
Appends some additional information about the route that the shape belongs to.
Args:
gtfs_dir: the directory where the GTFS file is extracted
Returns:
pandas.DataFrame: contains sha... | 35,564 |
def lick():
"""
Returns a string when a user says 'lick' (This is a joke command)
:return: A string
"""
return "*licks ice cream cone*" | 35,565 |
async def on_webhook_shutdown(dp):
"""Колбэк при выключении бота через вебхук"""
from . import db
from .bot import bot
from .logger import logger
await bot.delete_webhook()
db.close_connection()
logger.info("Работа бота завершена") | 35,566 |
def from_dict(obj, node_name='root'):
"""Converts a simple dictionary into an XML document.
Example:
.. code-block:: python
data = {
'test': {
'nodes': {
'node': [
'Testing',
'Another node'
... | 35,567 |
def scores_plot(values, start=0, ncomps=3,
classes=None, class_name=None,
dist_kws={}, scatter_kws={}):
"""
"""
ncomps = min(ncomps, values.shape[1])
if type(values) == pd.DataFrame:
values_ = values.iloc[:, start:(start + ncomps)].copy()
else:
valu... | 35,568 |
def parse_ascii(state: str, size: int) -> str:
"""
Args:
state: an ascii picture of a cube
size: the size of the cube
Returns:
a string of the cube state in ULFRBD order
"""
U = []
L = []
F = []
R = []
B = []
D = []
lines = []
for line in state.s... | 35,569 |
def _project_observation_params(access_token: str, project_id: int, observation_id: int):
"""Args:
access_token: An access token required for user authentication, as returned by :py:func:`.get_access_token()`
project_id: ID of project to add onto
observation_id: ID of observation to add
""" | 35,570 |
def _get_build_failure_reasons(build):
# type: (Build) -> List[str]
"""Return the names of all the FailureReasons associated with a build.
Args:
build (Build): The build to return reasons for.
Returns:
list: A sorted list of the distinct FailureReason.reason values associated with
... | 35,571 |
def parse_line(line: str):
"""
Parses single record from a log according to log_pattern.
If error occurs in parsing request_time, the log line is considered broken and function returns None.
If error occurs in parsing URL, while request_time is present,
the URL is marked as 'parse_failed' to all... | 35,572 |
def for_all_arglocs(*args):
"""
for_all_arglocs(vv, vloc, size, off=0) -> int
Compress larger argloc types and initiate the aloc visitor.
@param vv (C++: aloc_visitor_t &)
@param vloc (C++: argloc_t &)
@param size (C++: int)
@param off (C++: int)
"""
return _ida_typeinf.for_all_arglocs(*args... | 35,573 |
def set_settings_module():
"""
This function will choose a Django settings file to work with.
If you have a local file with settings, it will use that file.
But if not, stay calm: it will directly go with "settings.py".
"""
local_settings = Path(f"estudio/{LOCAL_SETTINGS}")
os.environ.setde... | 35,574 |
def fetch_project_check_perm(id, user, perm):
"""Fetches a project by id and check the permission.
Fetches a project by id and check whether the user has certain permission.
Args:
project_id:
The id of the project.
user:
A User instance.
perm:
... | 35,575 |
def toRoman(n):
""" Convert an integer to Roman numeral."""
if not (0 < n < 5000):
raise OutOfRangeError("number out of range (must be 1..4999)")
if int(n) != n:
raise NotIntegerError("decimals can not be converted")
result = ""
for numeral, integer in romanNumeralMap:
while... | 35,576 |
def imsave(addr,im):
"""
input a string of save address, an im array\n
save the image to the address
"""
import matplotlib.pyplot as plt
return plt.imsave(addr,im) | 35,577 |
def optimizer(args: 'Namespace'):
"""
Start an optimization from a YAML file
:param args: arguments coming from the CLI.
"""
from jina.optimizers import run_optimizer_cli
run_optimizer_cli(args) | 35,578 |
def test_imdb_test():
"""
Feature: Test IMDB Dataset.
Description: read data from test file.
Expectation: the data is processed successfully.
"""
logger.info("Test Case test")
# define parameters
repeat_count = 1
usage = "test"
# apply dataset operations
data1 = ds.IMDBDatase... | 35,579 |
def simulate_one(ticket: Ticket, strategy: Strategy, trials: int) -> float:
"""
:param ticket:
:return:
"""
diagnostics = False
workers = multiprocessing.cpu_count()
things = [(strategy, ticket) for x in range(0, trials)]
chunksize = int(len(things) / workers)
with multiprocessing... | 35,580 |
def copy_attr(f1, f2):
""" Copies the special packaging file attributes from f1 to f2.
"""
if f1._tags:
pattrs = [
tag
for tag in f1._tags
if not hasattr(f2, tag) and tag.startswith('PACKAGING_')
]
for attr in pattrs:
f2.Tag(attr, f1.Ge... | 35,581 |
def download_prostate():
"""Download prostate dataset."""
return _download_and_read('prostate.img') | 35,582 |
def create_json_instance(name, agts, vars, doms, cons, fileout=''):
""""
It assumes constraint tables are complete
"""
jagts = {}
jvars = {}
jcons = {}
for vid in vars:
v = vars[vid]
d = doms[v['dom']]
aid = v['agt']
jvars['v'+vid] = {
'value': No... | 35,583 |
def decBIPKey(encrypted_privK, passphrase, currency):
"""
Decrypt an encrypted Private key
Show the corresponding public address
"""
#using the currencies.json file, get the currency data
with open('currencies.json', 'r') as dataFile:
currencies = json.load(dataFile)
for cur in currencies:
if cur['currency']... | 35,584 |
def any_download(url: str, **kwargs):
"""
dowload a single html url
use module if matched, otherwise we use universal downloader
"""
m, url = url_to_module(url)
m.prefer_download(url) | 35,585 |
def plot_data(coordinate, box=[], plt_inst=None, **kwargs):
"""
Plot the coordinate with the "std box" around the curve
Args:
coordinate (float[]): 1D array of the coordinate to plot
box (float[]): 1D array of the box around the curve
plt_inst (pyplot): pyplot in... | 35,586 |
def test_parameter_wrapping_parameters():
"""Tests that ensure wrapping works with other parameters"""
var = 5
var = Parameter(var)
res = Parameter._wrap(var)
assert isinstance(res, Parameter)
assert res.x == var | 35,587 |
def read_config_file(config_file):
"""Read an YAML config file
:param config_file: [description]
:type config_file: [type]
"""
if os.path.isfile(config_file):
extension = os.path.splitext(config_file)[1]
try:
with open(config_file) as data_file:
if extens... | 35,588 |
def param_curve(t, R, r, d):
"""Coordinates of a hypotrochoid for parameters t, R, r and d"""
x = (R - r)*cos(t) + d*cos((R - r)/r*t)
y = (R - r)*sin(t) - d*sin((R - r)/r*t)
z = 3*sin(t)
return x, y, z | 35,589 |
def archive_link(link: Link, overwrite: bool=False, methods: Optional[Iterable[str]]=None, out_dir: Optional[Path]=None) -> Link:
"""download the DOM, PDF, and a screenshot into a folder named after the link's timestamp"""
# TODO: Remove when the input is changed to be a snapshot. Suboptimal approach.
from... | 35,590 |
def get_tests_dir(append_path=None):
"""
Args:
append_path: optional path to append to the tests dir path
Return:
The full path to the `tests` dir, so that the tests can be invoked from anywhere.
Optionally `append_path` is joined after the `tests` dir the former is provided.
"... | 35,591 |
def city():
"""The city function provide
the details of the city
Args:
city (str): name of the city
Returns:
None:
"""
city = "Aurangabad"
print("Welcome to the {0} city.".format(city))
maharashtra_info.mh(city) | 35,592 |
def say_my_name(first_name, last_name=""):
"""
Function that prints My name is <first name> <last name>.
Args:
first_name (string): the first name
last_name (string): the last name
"""
if type(first_name) is not str:
raise TypeError("first_name must be a string")
if type... | 35,593 |
def monthly_sales_splash() -> None:
"""Display monthly sales splash."""
print('Monthly Sales Program\n')
display_options() | 35,594 |
def create_collection(metadata_url: str = METADATA_URL,
thumbnail_url: str = THUMBNAIL_URL) -> pystac.Collection:
"""Create a STAC Collection using AAFC Land Use metadata
Args:
metadata_url (str, optional): Metadata json provided by AAFC
Returns:
pystac.Collection: py... | 35,595 |
def close_socket_cleanly(sock: socket.socket) -> None:
"""
Ensures that the connection to a client is closed cleanly without errors and with no data loss.
Use this instead of the .close() method.
"""
# The code is based on this blog post:
# https://blog.netherlabs.nl/articles/2009/01/18/the-ult... | 35,596 |
def deploy(account, timeout=TIMEOUT_DEPLOY):
"""
deploys contract, waits for receipt, returns address
"""
before = time.time()
_, abi, contract_bin = load_contract(file_abi=FILE_CONTRACT_ABI, file_bin=FILE_CONTRACT_BIN)
storage_contract = w3.eth.contract(abi=abi, bytecode=contract_bin)
contr... | 35,597 |
def test_root_route(client):
"""Test root route."""
response = client.get('/')
assert b'Hello, World!' in response.data | 35,598 |
def calculate_average_crossing_per_month_and_measure(num_of_months, list_with_agg_values):
"""Calculates the average crossings per month and per measure.
Args:
num_of_months: the number of months based on the
frequency of each measure, saved as
a dict or a ... | 35,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.