content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def prompt_and_delete(path, no_input=False):
"""
Ask user if it's okay to delete the previously-downloaded file/directory.
If yes, delete it. If no, checks to see if the old version should be
reused. If yes, it's reused; otherwise, Cookiecutter exits.
:param path: Previously downloaded zipfile.
... | 53,600 |
def continuous_ob(orderbooks):
"""
Creates a continuous orderbook timeseries data, for all orderbooks included as input. i.e. all timestamps
that one orderbook has and the other dont, in the latter repeates the information of the former, with
this, the output will deliver two historical orderbooks with ... | 53,601 |
def test_calculate_class_2_individuals_best_response_upper_and_lower_bounds():
"""
Tests that when both the lower and upper bound of the routing function have
the same sign, then the output is either 0 (when positive) and 1 (when
negative).
"""
assert (
calculate_class_2_individuals_best... | 53,602 |
def aStarSearch(problem, heuristic=nullHeuristic):
"""Search the node that has the lowest combined cost and heuristic first."""
"*** YOUR CODE HERE ***"
from util import PriorityQueue # i use PriorityQueue to store the frontier
frontier = PriorityQueue() # initialize frontier
explored =... | 53,603 |
def test_getH_interfaces3():
"""self-consistent test of different possibilities for computing the field"""
mag = (22, -33, 44)
dim = (3, 2, 3)
src = magpy.magnet.Cuboid(mag, dim)
src.move(np.linspace((0.1, 0.2, 0.3), (1, 2, 3), 10), start=-1)
poso = [[(-1, -2, -3)] * 2] * 2
sens = magpy.Sen... | 53,604 |
def ffmpeg_decode(file_name, sr, mono=True):
"""Reads an audio file and returns its data. If `mono` is
set to true, the returned audio data are monophonic.
:param file_name: The file name of the audio file.
:type file_name: str
:param sr: The sample rate of the audio file, optional.
:type sr: i... | 53,605 |
def split_irregular_date_list(date_list):
"""
Takes a list of dates and groups it into blocks of continuous dates.
It returns the begin and end of those blocks
eg. A list with continuous dates from januari to march and september to october will be split into two lists
Parameters
----------
... | 53,606 |
def validate(args, fid_stat, gen_net: nn.Module, writer_dict=None):
"""
Compute both IS and FID (torch).
:param args:
:param fid_stat:
:param gen_net:
:param writer_dict:
:return:
"""
# eval mode
gen_net = gen_net.eval()
eval_iter = args.num_eval_imgs // args.eval_batch_size... | 53,607 |
def SR_setRaw(self: CPointer, raw_data: np.ndarray, nx: int, ny: int, nz: int) -> None:
"""Set raw data to reconstruct.""" | 53,608 |
def transform_observation(attribute, data):
""" place to hook any transforms on te data """
output = data
if (attribute == 'observation_time'):
output = data[16:]
return output | 53,609 |
def batch_handler(repo, request):
"""Handle batch requests."""
req = {}
try:
req = json.loads(request)
except json.JSONDecodeError:
return create_response(status_code=400)
operation = req['operation']
objects = req['objects']
res_objects = []
for obj in objects:
... | 53,610 |
def smooth_lattice_point(ratio=0.1, prevent_dent=True):
"""
選択されたラティスポイントのスムース
"""
# 選択されているラティスポイント
selected_lattice_points = [x for x in pm.selected(flatten=True) if type(x) == pm.LatticePoint]
if not selected_lattice_points:
return
# ラティスオブジェクト
lattice = nu.... | 53,611 |
def cos_angular_separation_tf(y_true, y_pred):
"""
Compute the angular separation in radians
between two pointing direction given with lat-long
Parameters
----------
lat1: 1d `numpy.ndarray` , latitude of the first pointing direction
long1: 1d `numpy.ndarray` longitude of the first po... | 53,612 |
def on_data_handler(msg):
"""Callback associated with ps_diagnostic_trace_msg types on the PolySync
bus
"""
#######
# Disable the COUNT logic to iterate a full logfile
global COUNT
COUNT += 1
if COUNT > 3:
sys.exit(0)
######
# ignore any logged messages that don't make... | 53,613 |
def all_stocks():
"""
#查询当前所有正常上市交易的股票列表
:return:
"""
data = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date')
# d = data["symbol"].values
# random.shuffle(d)
return data["symbol"].values | 53,614 |
def get_dependent_databases(demand_dict):
"""Demand can be activitiy ids or tuple keys."""
db_labels = [
x[0] if isinstance(x, tuple) else get_activity(x)["database"]
for x in demand_dict
]
return set.union(*[Database(label).find_graph_dependents() for label in db_labels]) | 53,615 |
def build_action_observations(
observations: Sequence[data.Observation]
) -> Sequence[data.ActionObservation]:
"""Given observations, creates the actions associated with them.
Args:
observations: a sequence of Observation objects capturing a PanoContext, a
heading, and the object the observer fixated... | 53,616 |
def handle_write_config_request(config_request):
"""Set piaware-config setting
Expected config_request format:
{
"request": piaware_config_write
"request_payload" : {"rtlsdr-gain": 20, "wireless-network": "no"}
}
request_payload must be a dictionary of key/v... | 53,617 |
def check_matching_file_versions(up_scripts: list[Script],
down_scripts: list[Script]) -> None:
"""Make sure each up script has a down script and vice versa.
Assumes both lists are sorted.
"""
for up, down in zip(up_scripts, down_scripts):
if up.file_version != ... | 53,618 |
def nanallclose(x, y, rtol=1.0e-5, atol=1.0e-8):
"""Numpy allclose function which allows NaN
Args:
* x, y: Either scalars or numpy arrays
Returns:
* True or False
Note:
Returns True if all non-nan elements pass.
"""
xn = numpy.isnan(x)
yn = numpy.isnan(y)
if n... | 53,619 |
def get_current_data(cfg):
"""Reads the output file to see what are the contents of the arrays and the version control string
Returns a dictionary with:
'etag' -- Etag of the source file used to render the file. As stored in the version control string
'date' -- Date of the source file used to render the file. As ... | 53,620 |
def vgg13_bn(pretrained=False, requires_grad=False, **kwargs):
"""VGG 13-layer model (configuration "B") with batch normalization
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['... | 53,621 |
def get_shape_label():
"""Get shape of the labels in Thyroid dataset"""
return (None,) | 53,622 |
def pick_random_question(df_questions, topic_id):
"""Randomly pick a question for a given topic
Random choice uses 1/box as weight
Parameters
----------
df_questions: DataFrame
DataFrame containing questions
columns = ['ID_question', 'ID_topic', 'label', 'link', 'box']
topic_id... | 53,623 |
def graph_results_3(a, b):
"""
Plots the
:param results_dict: holds voltages and magnetization percentages
:return: None
"""
a = a - a[0]
g = Graph(a, b)
g.set_labels("Light Lumen vs. Relative Angle between 3 Polarizers, With fit.", "Relative Angle", "Lumen")
g.set_errors(a/50, b/50)... | 53,624 |
def CTDensityPixel_getGray():
"""CTDensityPixel_getGray() -> vpl::img::tDensityPixel"""
return _Core.CTDensityPixel_getGray() | 53,625 |
def bfm2Mesh(bfm_info, image_shape=default_init_image_shape):
"""
generate mesh data from 3DMM (bfm2009) parameters
:param bfm_info:
:param image_shape:
:return: mesh data
"""
[image_h, image_w, channel] = image_shape
pose_para = bfm_info['Pose_Para'].T.astype(np.float32)
shape_para ... | 53,626 |
def watch():
"""Renerate documentation when it changes.
Requires watchdog (pip install watchdog)
"""
index = Path(os.getcwd(), 'doc', 'html', 'index.html')
gen()
print('\n' + str(index))
subprocess.call(['watchmedo', 'shell-command', '--patterns=*.rst;*.py', '--ignore-pattern=_build/*', '-... | 53,627 |
def script_write(filename, script):
"""Write a script to a file.
Proper execute permissions will be set.
:param ``str`` filename:
File to write to.
:param ``iterable|unicode`` script:
Unicode string or iterable.
"""
if isinstance(script, six.string_types):
# If the scri... | 53,628 |
def query_rest_server(ts1, ts2, data_url, idstr, nbins):
"""get xml from restful interface for the requested channels
with a single request
inputs:
t1, t2 are start/stop time in ms
data_url is url w/out args
idstr is all channel ids as '&id='.join(id for id in oflds)
... | 53,629 |
def _merge_css_item(item):
"""Transform argument into a list with a single string value."""
if isinstance(item, (list, tuple)):
return _merge_css_list(*item)
item = f"{item}" if item else ""
return [item] | 53,630 |
def get_iscsi_auth_groups(client):
"""Display current authentication group configuration.
Returns:
List of current authentication group configuration.
"""
return client.call('get_iscsi_auth_groups') | 53,631 |
def list():
""" Return list of all available books. """
return jsonify({'books': [x for x in os.listdir(BOOK_PATH)
if not x.startswith('.')]}) | 53,632 |
def main_ds9():
"""Run main function."""
# galaxy numbers to open in ds9
nums = [1, 14, 31, 33, 38, 40, 41, 44, 46, 52, 54,
56, 59, 69, 73, 76, 79, 80, 81, 85, 90, 92, 95]
# print magnitude difference
# /Users/poudel/jedisim/simdatabase/galaxies/f606w_gal195.fits
f606 = '/Users/poud... | 53,633 |
def line_in_file(path, regex, replace, backup=None):
"""If 'regex' exists in the file specified by path, then replace it with
the value in 'replace'. Else append 'replace' to the end of the file. This
facilitates simplified changing of a parameter to a desired value if it
already exists in the file or a... | 53,634 |
def arguments():
"""
parsing command line arguments
"""
parser = argparse.ArgumentParser(description="Summarize columns in given file.")
parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Print debug info.")
parser.add_argument("-f", "--file", action="store", dest="fi... | 53,635 |
def _filter_returned_ops(fn):
"""Filtering out any ops returned by function.
Args:
fn: a function
Returns:
A tuple of (
Wrapped function that returns `None` in place of any ops,
dict that maps the index in the flat output structure to the returned op
)
"""
returned_ops = {}
def wr... | 53,636 |
def output_info (cutoff, cluster, gram_p, gram_n, archaea, location, score,location_p, location_n, location_a, assign_flag, outfile):
"""
open_file = open(outfile, "w")
title = "sample\tdiagnosis\tmode\tseqID\ttype\tnumber"
open_file.write(title + "\n")
for sample in sorted(gram_p.keys()):
mymode = "Gram+"
my... | 53,637 |
def test_file_upload_local(
db, clients, tmp_uploads_local, file_field, data_review
):
"""
Test validation report/results file uploads
"""
vrs = data_review.validation_resultset
file_field = getattr(vrs, file_field)
file_field.save(f"foo.ext", ContentFile("foo"))
assert vrs.study.bucket ... | 53,638 |
def test_amendment_staff_missing_account_200(session, client, jwt):
"""Assert that an amendment statement request with a staff jwt and no account ID returns a 200 status."""
# setup
json_data = copy.deepcopy(SAMPLE_JSON)
json_data['baseDebtor']['businessName'] = 'TEST BUS 2 DEBTOR'
json_data['baseRe... | 53,639 |
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
print('The most common month is: ', df['month'].mode()[0])
# display the most common day o... | 53,640 |
def subclass_of(*args):
"""
This type validation function can be used in two modes:
* providing two arguments (c, ref_type), it returns `True` if issubclass(c, ref_type) and raises a IsWrongType
error if not. If ref_type is a set of types, any match with one of the included types will do
* provid... | 53,641 |
async def radio_monitor_alert_transport() -> None:
"""Run the radio monitor alert loop."""
# Wait for system to initialize
await asyncio.sleep(15)
while True:
try:
log.debug("Checking for monitored units' radio activity.")
if (
radio_monitor_alert_messages... | 53,642 |
def info() -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""
Get input and output schemas
:return: OpenAPI specifications. Each specification is assigned as (input / output)
"""
input_sample = [
{
'name': "a",
'type': "string",
'required': True,
... | 53,643 |
def region_growing_lab_hsv(I, max_dist, min_pixels=1, smoothing=0):
"""Performs region growing on an color image in HSV space.
Parameters
----------
I : ndarray of float32
3D array representing the image
max_dist : float
maximum hsv distance to add a neighbou... | 53,644 |
def wolf_mass(sigma, Re):
"""
Wolf mass estimator from Wolf+ 2010
Args:
sigma :
1D line of sight velocity dispersion in km/s
Re :
2D radius enclosing half the stellar mass in pc
Returns: estimate of the dynamical mass within the half light radius in Msun
... | 53,645 |
async def delete_pokemon(id: int):
"""
## Deletes a Pokemon by ID.
Path Parameters
---------------
Pokemon ID.
Body Parameters
---------------
None
Returns
-------
None
"""
if not await PokemonRepository.exists(id=id):
# Non-existent Pokemon, ... | 53,646 |
def anagrams_in_list(word, list_of_words):
"""Given a word (str) and list of words (list or tuple, a list is returned
with the valid anagrams of the word in the list of words
Args:
- word (str): The word that you want to test
- list_of_words (list or tuple): The list of words that you want ... | 53,647 |
def use_pebble(func):
"""Creates an config with pebble as the CA, and returns the pebble process"""
def pebble_wrapper(tmpdir, pebble, opt_username, opt_password, opt_lb):
os.environ["REQUESTS_CA_BUNDLE"] = os.path.abspath(
"tests/functional/pebble/pebble.minica.pem"
)
old_d... | 53,648 |
def oavol(x, y, z, v, xx, yy, zz, pmap=None, weight=10, nx=2, ny=2,
verbose=False):
"""
Objective analysis interpolation for 3D fields
Parameters
----------
x: array [2-D]
x-values of source data
y: array [2-D]
y-values of source data
z: array [3-D]
z-value... | 53,649 |
def create_study(
name: str,
description: str,
run_ids: List[int],
alias: Optional[str],
benchmark_suite: Optional[int],
) -> OpenMLStudy:
"""
Creates an OpenML study (collection of data, tasks, flows, setups and run),
where the runs are the main entity (collection consists of runs and a... | 53,650 |
def nats_to_params(nat1, nat2, nat3, nat4):
"""
natural parameters to distribution parameters
"""
alpha = nat1 + (1./2)
nu = -2 * nat4
mu = nat3 / nu
beta = - nat2 - (nu * (mu**2) / 2)
return alpha, beta, mu, nu | 53,651 |
def depth_type_order(order):
"""Create a function which constrains paragraphs depths to a particular
type sequence. For example, we know a priori what regtext and
interpretation markers' order should be. Adding this constrain speeds up
solution finding."""
order = list(order) # defensive copy
... | 53,652 |
async def test_scope_existence(tmpdir, request, role, response):
"""Test checking of scopes provided in role definitions"""
kwargs = {'load_roles': [role]}
ssl_enabled = getattr(request.module, "ssl_enabled", False)
if ssl_enabled:
kwargs['internal_certs_location'] = str(tmpdir)
hub = MockHu... | 53,653 |
def euclidean(a: Dict, b: Dict)->float:
"""Return the euclidean distance beetween the given dictionaries.
Parameters
----------------------------
a: Dict,
First dictionary to consider.
b: Dict,
Second dictionary to consider.
Returns
----------------------------
Return t... | 53,654 |
def get_system_category():
"""获取文档分类"""
systems = ComponentSystem.objects.all()
doc_category = {}
for system in systems:
if not system.has_display_doc:
continue
system_doc_category = system.doc_category
doc_category.setdefault(system_doc_category.id, {
'na... | 53,655 |
def _serialize_graph(ops):
"""
Serializes a graph and returns the actual protobuf python object (rather than serialized
byte string as done by `serialize_graph`).
"""
assert isinstance(ops, Iterable), "Ops passed into `serialize_graph` must be an iterable"
ops = Op.all_op_references(ops)
pb... | 53,656 |
def single_cell_variables(model_name, dat, let):
"""
Single cell variable of model_name.
1: head, 2:temp, 3:conc, 4:kz, 5:lz, 6:por (inside mem)
11: head, 12:temp, 13:conc, 14:kz, 15:lz, 16:por (not inside mem)
"""
output_path = rm.make_output_dirs(model_name, dat, let)[0]
enkf_inpu... | 53,657 |
def add_signature(db, df):
"""Adds `signature` from database `db` to dataframe `df`."""
events = df["event_no"]
with sqlite3.connect(db) as con:
query = (
"select event_no, pid, interaction_type from truth where event_no in %s"
% str(tuple(events))
)
data = (
... | 53,658 |
def delete_folder(path):
"""
Deletes a folder
"""
basePath = pathlib.Path(path)
if not basePath.exists():
print("Sequestrum: Folder already deleted!")
return
try:
if basePath.is_symlink():
basePath.unlink()
else:
shutil.rmtree(basePa... | 53,659 |
def test_get_user_command__bad_response(mocker):
"""
Given:
- A ServiceNow IAM client object
- A user-profile argument that contains an email of a non-existing user in ServiceNow
When:
- Calling function get_user_command
- A bad response (500) is returned from ServiceNow's AP... | 53,660 |
def docs(obj):
"""Open the online documentation in a web browser."""
browser.open(config.documentation_url()) | 53,661 |
def getLLVMVersion(llvmProgram):
"""executes the program with --version and extracts the LLVM version string"""
versionString = getVersion(llvmProgram)
printLLVMVersion = re.search(r'(clang |LLVM )?(version )?((\d)\.\d)(\.\d)?', versionString, re.IGNORECASE)
if printLLVMVersion is None:
return N... | 53,662 |
def init_with(app):
"""Initialize extensions and funcions with the FLask"""
on_production_env = app.config.get('FLASK_ENV') == 'production'
exts.db.init_app(app)
exts.talisman.init_app(app,
force_https=on_production_env,
force_https_permanent=on_production_env,
conte... | 53,663 |
def box2patch(image_dir, detection_result):
"""
Clip and get bbox patch, also normalize
"""
img = Image.open(os.path.join(image_dir, detection_result['name']))
# for normalization
mean=(0.485, 0.456, 0.406)
std=(0.229, 0.224, 0.225)
transform = T.Compose([T.ToTensor(), T.Normalize(mean=m... | 53,664 |
def lambert(disk):
"""Converts coordinates on the disk to spherical coordinates, using
the Lambert azimuthal equal-area projection.
Args:
disk: Array of shape [..., 2] representing points on the disk.
Returns:
phi, theta: Spherical coordinates
>>> phi, theta = lambert(_TEST_DISK_R... | 53,665 |
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Flair Rooms."""
flair = hass.data[DOMAIN]
rooms = []
for room in flair.rooms():
rooms.append(FlairRoom(room))
async_add_entities(rooms) | 53,666 |
def nuke_pg_server():
"""Server is DNS resolved to service name of PG SQL-container"""
q1 = f"drop database if exists {TESTING_DB};"
q2 = f"create database {TESTING_DB};"
conn:connection = psycopg2.connect(host=PG_HOST, dbname=PG_DB, user=PG_UID, password=PG_PWD, port=5432)
conn.autocommit = True
... | 53,667 |
def splitFile(fileName, splitSize):
"""
split big file
"""
pass | 53,668 |
def mandel_geom(params, x, etc = []):
"""
This function computes a transit shape using equations provided by Mandel & Agol (2002).
Parameters
----------
midpt: Center of eclipse
width: Eclipse duration from contacts 1 to 4
rp_rs: Planet-star radius ratio
b: Impact parameter
flux... | 53,669 |
def test_average_pooling_feature_map_fprop_weight():
"""
Test that AveragePoolingFeatureMap really does what we think it does
on a forward pass.
"""
apfmap = AveragePoolingFeatureMap((2, 2), (4, 4))
apfmap.biases[:] = 0.
apfmap.weights[:] = 4.4
inp = np.arange(1,17).reshape((4,4))
o... | 53,670 |
def test_enqueue_adds_data_to_tail_and_points_to_prev(test_queues):
"""Test enqueue adds to the tail and point to prev tail."""
test_queues[1].enqueue(2)
assert test_queues[1]._container.tail.prev.data is 3 | 53,671 |
def parse_args():
"""
Parse out testing arguments.
"""
_, fname = os.path.split(__file__)
usage = "cat data | python %s" % fname
parser = ArgumentParser(usage=usage)
parser.add_argument("-m", "--center", dest="m", required=True,
type=float, help="control chart center... | 53,672 |
def from_columns(mapping, fp):
"""
Write columns to the open file opbject ``fp`` in XPT-format.
The mapping should be of column names to equal-length sequences.
Column labels are restricted to 40 characters. The XPT format also
requires a separate column "name" that is restricted to 8
characte... | 53,673 |
def find_unused_relay_number(event_number, organizer_number) -> Optional[str]:
"""Find a relay number that isn't currently used by an existing chatroom
connection."""
# TODO: Should probably be a join, but its unlikely this list will
# get big enough in the near future to be an issue.
used_rela... | 53,674 |
def list_random_circuits_onelen(opLabels, length, count, seed=None):
"""
Create a list of random operation sequences of a given length.
Parameters
----------
opLabels : tuple
tuple of operation labels to include in operation sequences.
length : int
the operation sequence length... | 53,675 |
def _url_post_delete(sender, instance, *args, **kwargs):
""" Clear cache on delete """
if conf.USE_CACHE:
cache.delete(instance.token) | 53,676 |
def simulate_lambda(drlambda, date, zone):
"""
TODO: do we assume that the lambda is for the peak period only: 4-7pm
how do we do this on the backend?
assume date is in YYYY-MM-DD
"""
print(xsg.get_zones(sites[0]))
start = pendulum.parse(date, tz='US/Pacific')
end = start.add(hours=... | 53,677 |
def main(description, project_id, day, month, year, hours, minutes,
source_bucket, sink_bucket):
"""Create a transfer from the Google Cloud Storage Standard class to the
Nearline Storage class."""
credentials = GoogleCredentials.get_application_default()
storagetransfer = discovery.build(
... | 53,678 |
def get_number_of_pictures(directions,cutOff,referenceAtom):
"""
Finding the amount of copies
of the original SuperCell
.---------------------------.
/ \ \
/ \ \
/ \ ... | 53,679 |
def _create_extension_feed_items(client, customer_id, campaign_resource_name):
"""Helper method that creates extension feed items.
Args:
client: a GoogleAdsClient instance.
customer_id: a str Google Ads customer ID, that the extension feed items
will be created for.
campaign... | 53,680 |
def rgb2hsv(img):
""" Use matplotlib to convert rgb to hsv (TA allowed) """
return (rgb_to_hsv(img.astype(np.float32) / 255.) * 255).astype(np.uint8) | 53,681 |
def get_territory_options_formatted():
"""
Formats list of territory options per Dash dropdown standards.
Example of returned data structure:
{'country': [{'label': 'Algeria', 'value': 'Algeria'}, {'label': 'Angola', 'value': 'Angola'}], 'state': [{'label': 'Alberta, Canada', 'value': 'Alberta, Canada'}... | 53,682 |
def _get_resources(rtype='resources'):
""" resource types from state summary include: resources, used_resources
offered_resources, reserved_resources, unreserved_resources
The default is resources.
:param rtype: the type of resources to return
:type rtype: str
:param role: the name of the role... | 53,683 |
def feature_name_to_placeholder(feature_name, params):
"""
Get a placeholder for the given feature.
Args:
- feature_name: name of the feature (<string>).
Returns:
Return as a tensor tf.placeholder.
"""
feature_type, shape = (
DATASETS_METADATA[feature_name].dtype,
... | 53,684 |
def split_words(value: str) -> List[str]:
"""Split a string on words and known delimiters"""
# We can't guess words if there is no capital letter
if any(c.isupper() for c in value):
value = " ".join(re.split("([A-Z]?[a-z]+)", value))
return re.findall(rf"[^{DELIMITERS}]+", value) | 53,685 |
def test_getChannelByName_invalid_name():
"""Get a channel by the name but one that is not present."""
anode = Node('foo', 'bar')
channel1 = Channel(index=1, role=1)
channel1.settings.modem_config = 3
channel1.settings.psk = b'\x01'
channel2 = Channel(index=2, role=2)
channel2.settings.psk... | 53,686 |
def setup(app: sphinx.application.Sphinx) -> Dict[str, Any]:
"""Entry point for sphinx theming."""
app.require_sphinx("3.0")
app.add_config_value(
"pygments_dark_style", default="native", rebuild="env", types=[str]
)
app.add_html_theme("furo", str(THEME_PATH))
app.connect("html-page-c... | 53,687 |
def before_askingfor_turn_to_givingto(actor, x, y, ctxt) :
"""Turns the AskingFor into a AskingTo(...,GivingTo(...))."""
raise DoInstead(AskingTo(actor, x, GivingTo(x, y, actor)), suppress_message=True) | 53,688 |
def ldns_key_set_pubkey_owner(*args):
"""LDNS buffer."""
return _ldns.ldns_key_set_pubkey_owner(*args) | 53,689 |
def graph(ich, no_stereo=False):
""" inchi => graph
"""
return automol.convert.inchi.graph(ich, no_stereo=no_stereo) | 53,690 |
def det_cat_fct_accum(contab, pred, obs):
"""Accumulate the frequency of "yes" and "no" forecasts and observations
in the contingency table.
Parameters
----------
contab: dict
A contingency table object initialized with
pysteps.verification.detcatscores.det_cat_fct_init.
pred: array... | 53,691 |
def get_rancher_services_list():
"""
:return: array of all system services
"""
service_list = []
stacks = get_request(
RANCHER_API_URL + RANCHER_API_STACKS_LIST_ENDPOINTS + '?system=false',
True
)
for stack in stacks['data']:
services = get_request(
RANCH... | 53,692 |
def test_init_deviance(capsys):
"""Test init exceptions"""
import pykern.pkdebug as d
output = six.StringIO()
d.init(control=r'(regex is missing closing parent', output=output)
out, err = capsys.readouterr()
assert not d._have_control, \
'When control re.compile fails, _printer is not se... | 53,693 |
async def test_set_target_temperature_low_high_with_templates(hass, mqtt_mock, caplog):
"""Test setting of temperature high/low templates."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["climate"]["temperature_low_state_topic"] = "temperature-state"
config["climate"]["temperature_high_state_topic"] = ... | 53,694 |
def check_peak(data: List[DataPoint]) -> bool:
"""
This is a function to check the condition of a simple peak of signal y in index i
:param data:
:return:
"""
if len(data) < 3:
return False
midpoint = int(len(data) / 2)
test_value = data[0]
for i in data[1:midpoint + 1]:
... | 53,695 |
def load_subtensor(g, labels, seeds, input_nodes, device):
"""
Copys features and labels of a set of nodes onto GPU.
"""
batch_inputs = g.ndata['feat'][input_nodes].to(device)
batch_labels = labels[seeds].to(device)
return batch_inputs, batch_labels | 53,696 |
def node_index_at_link_ends(shape):
"""Array of nodes at each end of links."""
node_ids = np.arange(np.prod(shape))
node_ids.shape = shape
return (node_at_link_tail(node_ids), node_at_link_head(node_ids)) | 53,697 |
def get_symbol_list(number_of_symbols):
""" Returns a list of sympy expression, each being an identity of a variable. To be used for input layer."""
return sympy.symbols(['x_{}'.format(i + 1) for i in range(number_of_symbols)], real=True) | 53,698 |
def test_config_with_bogus_class():
"""Test the configuration while trying to load a bogus class."""
cfg = Config.load("""
id: cbc_binary_toolkit
version: 0.0.1
database:
_provider: not_exist_package.NotExist
is_test: "True"
""")
with pytest.raises(ImportError):
StateMana... | 53,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.