content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def find_2020(inputs,num_combinations = 2):
"""
accepts an interable as input and returns the product of the first two numbers in the
iterable that sum to 2020
"""
for vals in itertools.permutations(inputs,num_combinations):
if sum(vals) == 2020:
yield np.prod(vals) | 5,341,500 |
def test_compare_build():
"""Build version must not be use in precedence."""
# https://semver.org/#spec-item-10
assert Version(1, 0, 0, None, "build1") == Version(1, 0, 0)
assert Version(1, 0, 0, None, "build1") == Version(1, 0, 0, None, "build2") | 5,341,501 |
def feedback(olsys,H=1):
"""Calculate the closed-loop transfer function
olsys
cltf = --------------
1+H*olsys
where olsys is the transfer function of the open loop
system (Gc*Gp) and H is the transfer function in the feedback
loop (H=1 for unity feedback)."""
... | 5,341,502 |
def get_sigma_grid(
init_sigma: float = 1.0, factor: int = 2, n_grid_points: int = 20
) -> List[float]:
"""Get a standard parameter grid for the cross validation strategy.
Parameters
----------
init_sigma : float, default=1.0
The initial sigma to use to populate the grid points.
... | 5,341,503 |
def parse_csv(value_column):
"""Parses a CSV file based on the provided column types."""
columns = tf.decode_csv(value_column, record_defaults=DEFAULTS)
features = dict(zip(ALL_COLUMNS, columns))
label = features.pop(LABEL_COLUMN)
classes = tf.cast(label, tf.int32) - 1
return features, classes | 5,341,504 |
def on_over_limit():
""" This is called when the rate limit is reached """
return jsonify(status='error', error=[_('Whoa, calm down and wait a bit before posting again.')]) | 5,341,505 |
def comment(strng,indent=''):
"""return an input string, commented out"""
template = indent + '# %s'
lines = [template % s for s in strng.splitlines(True)]
return ''.join(lines) | 5,341,506 |
def square(number):
"""
Calculates how many grains were on each square
:param number:
:return:
"""
if number <= 0 or not number or number > 64:
raise ValueError(ERROR)
return 2**(number - 1) | 5,341,507 |
def get_doc(name=None, filename=None, url=None, parsed=True, start=0, end=None,
localfile=None, params=None, cookies=None, **kwargs):
"""
Retrieve an IDE file from either a file or URL.
Note: `name`, `filename`, and `url` are mutually exclusive arguments.
One and only one must be specified.... | 5,341,508 |
def naginator(parser, xml_parent, data):
"""yaml: naginator
Automatically reschedule a build after a build failure
Requires the Jenkins :jenkins-wiki:`Naginator Plugin <Naginator+Plugin>`.
:arg bool rerun-unstable-builds: Rerun build for unstable builds as well
as failures (default False)
:... | 5,341,509 |
def health_check() -> ControllerResponse:
"""
Retrieve the current health of service integrations.
Returns
-------
dict
Response content.
int
HTTP status code.
dict
Response headers.
"""
status = {}
for name, obj in _getServices():
logger.info('Ge... | 5,341,510 |
def GeoSim(hss_0, pow_law_exp, lat1, lon1, lat2, lon2):
""" In order to make the Similarity adimensional I have to add a scale to the game.
This scale is hss, i.e. the scale after which the similairty is damped by a factor 2.
:param pow_law_exp: is the exponent of the power law
"""
# @TODO: measure... | 5,341,511 |
def _get_script():
"""Get path to the image sequence script"""
try:
from openpype.scripts import publish_filesequence
except Exception:
raise RuntimeError("Expected module 'publish_deadline'"
"to be available")
module_path = publish_filesequence.__file__
i... | 5,341,512 |
def main():
"""Main"""
try:
config.load_kube_config()
except FileNotFoundError:
config.load_incluster_config()
core_v1_client = client.CoreV1Api()
k8s_client = client.ApiClient()
# ConfigMap
deploy_config_map(core_v1_client)
# CSI Pods
deploy_csi_pods(core_v1_clien... | 5,341,513 |
def residual_unit(data, nchw_inshape, num_filter, stride, dim_match, name, bottle_neck=True,
workspace=256, memonger=False, conv_layout='NCHW', batchnorm_layout='NCHW',
verbose=False, cudnn_bn_off=False, bn_eps=2e-5, bn_mom=0.9, conv_algo=-1,
fuse_bn_relu=False, fus... | 5,341,514 |
def dwa_control(x, config, goal, ob):
"""
Dynamic Window Approach control
"""
dw = calc_dynamic_window(x, config)
u, trajectory = calc_final_input(x, dw, config, goal, ob)
return u, trajectory | 5,341,515 |
def detect_meteors(rf_dir, id_dir, noise_dir, output_dir,
t0=None, t1=None, rxch='zenith-l', txch='tx-h'):
"""Function to detect and summarize meteor head echoes.
Arguments
---------
rf_dir : string or list
RF data directory or directories.
id_dir : string
ID c... | 5,341,516 |
def GetCoverageDirectory(fuzzer):
"""Get a coverage report directory for a fuzzer
Args:
fuzzer: The fuzzer to get the coverage report directory for.
Returns:
The location of the coverage report directory for the |fuzzer|.
"""
relative_path = os.path.join(COVERAGE_REPORT_DIRECTORY_NAME, fuzzer)
ret... | 5,341,517 |
def decompress_bytes(inp_bytes: bytes, verbose=False) -> bytearray:
"""
Main function to decompress input bytes by extracting the Huffman map
and using the map to replace the encoded sequences with the original
characters.
:param inp_bytes: Input data to be compressed
:param verbose: set to Tru... | 5,341,518 |
def test_init():
""" Config initialization works as expected """
inst = _config.Config.from_file(fixture('config1.schema'))
assert inst.tables == [
('Yo', 'Yo'),
('some', 'table'),
('somethingElse', 'somethingElse'),
('y', 'x.y'),
('a', 'b.c'),
]
assert inst.s... | 5,341,519 |
def filter_nans(data,
threshold = 3,
threshold_type = "data"):
"""
=================================================================================================
filter_nans(data, threshold, threshold_type)
This function is meant to filter out the nan values from... | 5,341,520 |
def configure_template_filters(app):
"""Configures the template filters."""
filters = {}
filters['format_date'] = format_date
filters['time_since'] = time_since
filters['is_online'] = is_online
filters['crop_title'] = crop_title
filters['forum_is_unread'] = forum_is_unread
filters['topi... | 5,341,521 |
def edit_seq2seq_config(config, frameworks=FULL_FRAMEWORKS, no_attn=False):
"""Rotate frameworks and optionally remove attention."""
configs = []
for fw in frameworks:
c = deepcopy(config)
c['backend'] = fw
configs.append(c)
if not no_attn:
new_configs = []
# Run ... | 5,341,522 |
def get_bioportal_prefix(prefix: str) -> Optional[str]:
"""Get the Bioportal prefix if available."""
return _get_mapped_prefix(prefix, "bioportal") | 5,341,523 |
def _obtain_rapt(request, access_token, requested_scopes):
"""Given an http request method and reauth access token, get rapt token.
Args:
request (google.auth.transport.Request): A callable used to make
HTTP requests.
access_token (str): reauth access token
requested_scopes ... | 5,341,524 |
def argunique(items, key=None):
"""
Returns indices corresponding to the first instance of each unique item.
Args:
items (Sequence[VT]): indexable collection of items
key (Callable[[VT], Any], default=None): custom normalization function.
If specified returns items where ``key(... | 5,341,525 |
def promote_cvals(*vals):
"""
Promote Python values into the most general dshape containing
all of them. Only defined over simple CType instances.
>>> promote_vals(1,2.)
dshape("float64")
>>> promote_vals(1,2,3j)
dshape("complex128")
"""
promoted = np.result_type(*vals)
datasha... | 5,341,526 |
def setup_logging(
color: bool, verbose: bool = False, add_timestamp: bool = False
) -> None: # pragma: no cover
"""Setup logging.
Args:
color (bool): If true, the output will be colored using
colorlog. Otherwise, it will be plaintext.
"""
root_logger = logging.getLogger()
... | 5,341,527 |
def load_directory_metadata(directory_path, return_copy=True):
"""
Get stored metadata for files in path. This currently only stores bookmarks.
If no metadata is available, return an empty dictionary.
This is a hidden file in the directory which stores metadata for all files
in the directory, as w... | 5,341,528 |
def download_all():
"""Download all files in the DATA_HUB"""
for name in DATA_HUB:
download(name) | 5,341,529 |
def _traverse_tree_and_group_all_objects_by_oclass(root_obj, result=None):
"""Traverses the tree once and groups all objects by oclass
:param root_obj: The root object where to start the traversion
:type root_obj: CUDS
:param result: The current results of the recursion, defaults to None
:type resu... | 5,341,530 |
def check_measurement(m_info, filters):
"""
Determine whether a given measurement should be included based on the
filters.
Inputs:
m_info - A dictionary containing the configuration parameters for an
individual measurement.
filters - A dictionary containing a set of configur... | 5,341,531 |
def audiosegment2wav(data: AudioSegment):
"""
pydub.AudioSegment格式转为音频信号wav。
:param data:
:return:
"""
wav = np.array(data.get_array_of_samples()) / _int16_max
return wav | 5,341,532 |
def embargo(cand_times, test_times, embargo_table):
"""
"Embargo" observations from the training set.
Args:
cand_times(Series): times of candidates to be the "embargoed set"
index: t0(start time)
value: t1(end time)
test_times(Series): times of the test set
... | 5,341,533 |
def mkdirp(directory):
"""
利用python库来做到shell中的 ``mkdir -p``
好处是不用 ``os.system()``,避免了fork进程造成的资源浪费。
:param directory: 路径
"""
if not os.path.isdir(directory):
os.makedirs(directory) | 5,341,534 |
def test_can_parse_and_serialize_frozen_attrs_class():
"""Parse and serialize a frozen attrs class."""
processor = xml.user_object('book', _FrozenBook, [
xml.string('title'),
xml.string('author'),
])
value = _FrozenBook(
title='The Three Body Problem',
author='Liu Cixin'... | 5,341,535 |
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the WiZ Light platform from config_flow."""
# Assign configuration variables.
wiz_data = hass.data[DOMAIN][entry.entry_id]
wizbulb = WizBulbEntity(wiz_data.bulb, entry.data.get(CONF_NAME), wiz_data.scenes)
# Add devices with def... | 5,341,536 |
def handle_uploaded_file(file, filename):
"""
Обработка файла csv спарсенного с online.edu.ru
"""
if not os.path.exists('upload/'):
os.mkdir('upload/')
path = 'upload/' + filename
with open(path, 'wb+') as destination:
for chunk in file.chunks():
destination.write(c... | 5,341,537 |
async def check_account():
"""
A check that checks if the user has an account and if not creates one for them.
"""
async def check(ctx) -> bool:
conn = get_db()
cur = conn.cursor()
cur.execute("SELECT * FROM economy WHERE user_id = ?", (ctx.author.id,))
if cur.fetchone() ... | 5,341,538 |
def run_send_feedback(args):
"""
Do a semd-feedback call to the Seldon API
Parameters
----------
args
Command line args
"""
contract = json.load(open(args.contract, "r"))
contract = unfold_contract(contract)
sc = get_seldon_client(args)
if args.grpc:
transport = ... | 5,341,539 |
def mtf_image_transformer_base_cifar():
"""Data parallel CIFAR parameters."""
hparams = mtf_image_transformer_base()
hparams.mesh_shape = "batch:8"
hparams.layout = "batch:batch"
hparams.learning_rate_decay_steps = 13600 # one epoch
hparams.batch_size = 32
hparams.num_heads = 4
hparams.num_decoder_laye... | 5,341,540 |
def edc_t(path):
"""EPICA Dome C Ice Core 800KYr Temperature Estimates
Temperature record, using Deuterium as a proxy, from the EPICA (European
Project for Ice Coring in Antarctica) Dome C ice core covering 0 to 800
kyr BP.
A data frame with 5788 observations on the following 5 variables.
`Bag`
Bag... | 5,341,541 |
def init_group_prams(net):
"""Initialize group_prams."""
decayed_params = []
no_decayed_params = []
for param in net.trainable_params():
if 'beta' not in param.name and 'gamma' not in param.name and 'bias' not in param.name:
decayed_params.append(param)
else:
no_d... | 5,341,542 |
def nni_differences_parameters(nni=None, rpeaks=None):
"""Computes basic statistical parameters from a series of successive NN interval differences (mean, min, max, standard deviation).
Parameters
----------
nni : array
NN intervals in [ms] or [s].
rpeaks : array
R-peak times in [ms] or [s].
Returns (biospp... | 5,341,543 |
def contextualize_model(model, cell_line, genes):
"""Contextualize model at the level of a PySB model."""
# Here we just make a PysbAssembler to be able
# to apply set_context on the model being passed in
model.name = cell_line
cell_line_ccle = cell_line + '_SKIN'
pa = PysbAssembler()
pa.mod... | 5,341,544 |
def _quaternionInverse(quat):
""" Inverses a list of quaternions
"""
quat_ = np.empty((quat.shape[0],4))
# For every quaternion
for i in range(quat.shape[0]):
mag = quat[i,0]**2 + quat[i,1]**2 + quat[i,2]**2 + quat[i,3]**2
quat_[i,0] = -quat[i,0]/mag
quat_[i,1] = -quat[i,1]... | 5,341,545 |
def load_dataset(files: list[str]) -> Union[list[int], list[list[list[int]]]]:
"""load the images and labels of the test dataset
Args:
files (list[str]): list of files path for images and label dataset
Returns:
Union[list[int], list[list[list[int]]]]: list of labels and list of int matrixes
"""
... | 5,341,546 |
def get_minion_node_ips(boot_conf, hb_conf):
"""
Returns a list of IPs for all master nodes
:param boot_conf: the snaps-boot configuration dict
:param hb_conf: the adrenaline configuration dict
:return: a list of IP addresses
"""
return __get_node_ips(boot_conf, hb_conf, 'minions') | 5,341,547 |
def _normalize_sql(sql, maxlen=150):
"""Collapse whitespace and middle-truncate if needed."""
out = ' '.join(sql.split())
if len(out) > maxlen:
i = int(maxlen / 2 - 4)
out = (out[0:i] +
' . . . ' +
out[-i:None])
return out | 5,341,548 |
def utt_non_punct_dialog(dialog: Dict):
"""
Used by: book_skill
"""
dialog = utils.get_last_n_turns(dialog)
dialog = utils.remove_clarification_turns_from_dialog(dialog)
return [{"dialogs": [dialog]}] | 5,341,549 |
def griddata_easy(xx, yy, data, xi=None, yi=None, dx=None, dy=None, nx=10, ny=10, method='nearest', fill_value=None):
"""
Generate a girdded data from scattered data z=f(x, y)
... Wrapper of scipy.interplate.riddata
Parameters
----------
xx: nd array-like
x-coordinate of scattered data
... | 5,341,550 |
def emit_cover(ctx, go_toolchain,
source = None,
mode = None,
importpath = ""):
"""See go/toolchains.rst#cover for full documentation."""
if source == None: fail("source is a required parameter")
if mode == None: fail("mode is a required parameter")
if not importpat... | 5,341,551 |
async def test_binary_sensor_update_mount_type_garage(
hass: HomeAssistant, ufp: MockUFPFixture, sensor_all: Sensor
):
"""Test binary_sensor motion entity."""
await init_entry(hass, ufp, [sensor_all])
assert_entity_counts(hass, Platform.BINARY_SENSOR, 10, 10)
_, entity_id = ids_from_device_descrip... | 5,341,552 |
def shortdate(date=None):
"""turn (timestamp, tzoff) tuple into iso 8631 date."""
return datestr(date, format='%Y-%m-%d') | 5,341,553 |
def default_fram( object_to_serialize):
"""
Python json api custom serializer function for FRAM Warehouse API
per:'Specializing JSON object encoding', https://simplejson.readthedocs.org
>>> import simplejson as json
>>> json.dumps({'Without':[1,'a',datetime(1999, 1, 1),'Serializer']})
Trac... | 5,341,554 |
def read_random_stack_for_multiple_pickles(all_spectra, all_sequence, num_spectra, stack_size):
"""TODO(nh2tran): docstring."""
print("read_random_stack_for_multiple_pickles()")
random_idx = random.sample(xrange(num_spectra[-1]), min(stack_size, num_spectra[-1]))
random_locations = []
f_idx = np.array(num_s... | 5,341,555 |
def reset_fields_to_default():
"""reset datamodel to default : core fields and default custom fields"""
self.application.coll_model.remove({ "field_class" : "custom" })
create_generic_custom_fields() | 5,341,556 |
def test_user_create_command(gsuite_client, mocker):
"""
Scenario: gsuite-user-create should works if valid arguments are provided.
Given:
- Command args.
When:
- Calling gsuite-user-create command with the arguments provided.
Then:
- Ensure CommandResult entry should be as expected.
... | 5,341,557 |
def perfect_pattern(dict_class_counts, distinct_classes, pattern, supporting_items, results_dir):
"""
Performs checking whether the pattern is perfect and a common class can be found directly without constructing the
relative class hierarchy.
:param dict_class_counts: the count of each distinct class c... | 5,341,558 |
def _benchmark_grep(filename, pattern):
"""Benchmarks grep.
Args:
- filename: The name of the file to be searched.
- pattern: The pattern we are searching for in the file.
"""
time_taken = timeit(setup=BENCHMARK_SETUP, number=SINGLE_STRING_TESTS,
stmt='subprocess.call(%s)' %... | 5,341,559 |
def inotify_test(
test_paths: dict[str, pathlib.Path], tmp_path: pathlib.Path
) -> InotifyTest:
"""Generate a pre-configured test instance of `inotify_simple.INotify`.
Parameters
----------
test_paths: dict[str, pathlib.Path]
The test fixture that generates test files based on configuration... | 5,341,560 |
async def mock_pyatag_sleep():
"""Mock out pyatag sleeps."""
asyncio_sleep = asyncio.sleep
async def sleep(duration, loop=None):
await asyncio_sleep(0)
with patch("pyatag.gateway.asyncio.sleep", new=sleep):
yield | 5,341,561 |
def set_system_bios( context, settings, system_id = None ):
"""
Finds a system matching the given ID and sets the BIOS settings
Args:
context: The Redfish client object with an open session
settings: The settings to apply to the system
system_id: The system to locate; if None, perfo... | 5,341,562 |
def ucs():
"""show unicode categories with 10 example values"""
print(A.print(ex=CAT)) | 5,341,563 |
def create() -> UserSecurityModel:
"""
Creates a new instance of the USM
"""
return UserSecurityModel() | 5,341,564 |
def clDice(v_p, v_l):
"""[this function computes the cldice metric]
Args:
v_p ([bool]): [predicted image]
v_l ([bool]): [ground truth image]
Returns:
[float]: [cldice metric]
"""
if len(v_p.shape)==2:
tprec = cl_score(v_p,skeletonize(v_l))
tsens = cl_score(v... | 5,341,565 |
def validate_regex(regex_str):
"""
Checks if a given string is valid regex
:param str regex_str: a suspicios string that may or may not be valid regex
:rtype: bool
:return: True if valid regex was give, False in case of TypeError or re.error
"""
# another of those super basic function where... | 5,341,566 |
def main():
"""
Initialize as global variable the settings as found in the config file and the command-line arguments.
"""
global done_list
global CONFIG_FILE
done_list = []
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
parser.add_argument("titles", type=str, nargs='*',
... | 5,341,567 |
def add_host_ages(
input_metadata_file,
host_id_list,
host_birthday_list,
float_years,
output_metadata_file,
) -> None:
"""Add host age in years on to a metadata file.
The column added will be named "host_age_years" if --float-years isn't
set, and "host_age" if --float-years *is* ... | 5,341,568 |
def load_stats_from_file(date):
"""
Load stats data from a stat file.
Params:
date -- a `datetime` instance.
"""
file_path = _build_stats_file_path(date)
if not isfile(file_path):
raise IOError # This will be FileNotFoundError in Python3.
with open(file_path, 'r') as fin:
... | 5,341,569 |
def one_permutation(index):
""""
save the interaction score on one permutation dataset to NN_idx
"""
name = 'NN_' + str(index)
## Generate permutation datasets with main effects NN model
phenotype_y_perm = permutation_data_generation(BRRR, x_train, phenotype_y, gene_size)
phenotype_y_... | 5,341,570 |
def null_gt_null(left, right):
""":yaql:operator >
Returns false. This function is called when left and right are null.
:signature: left > right
:arg left: left operand
:argType left: null
:arg right: right operand
:argType right: null
:returnType: boolean
.. code:
yaql> ... | 5,341,571 |
def read_header(file):
""" Read the information in an OpenFOAM file header.
Parameters
----------
file : str
Name (path) of OpenFOAM file.
Returns
-------
info : dictionary
The information in the file header.
"""
with open(file, 'r') as f:
content = f.read()... | 5,341,572 |
def set_object_show_name(object, show=True):
""" Display the name of an object.
Parameters:
object (obj): Object to display name.
show (bool): True or False.
Returns:
None
"""
object.show_name = show | 5,341,573 |
def write_batch_preds_to_csv(predictions, csv_fpath: Path) -> None:
"""print batch preds to csv"""
raise NotImplementedError(f"Not implemented for type {predictions}") | 5,341,574 |
def point_from_b58(b):
"""Return b58 decoded P."""
x, y = [int_from_b58(t) for t in b.split(",")]
return ECC.EccPoint(x=x, y=y, curve=CURVE) | 5,341,575 |
def _cp_embeds_into(cp1, cp2):
"""Check that any state in ComplexPattern2 is matched in ComplexPattern1.
"""
# Check that any state in cp2 is matched in cp1
# If the thing we're matching to is just a monomer pattern, that makes
# things easier--we just need to find the corresponding monomer pattern
... | 5,341,576 |
def get_tags_for_message(khoros_object, msg_id):
"""This function retrieves the tags for a given message.
.. versionadded:: 2.8.0
:param khoros_object: The core :py:class:`khoros.Khoros` object
:type khoros_object: class[khoros.Khoros]
:param msg_id: The Message ID for the message from which to re... | 5,341,577 |
def _build_hierarchical_histogram_computation(
lower_bound: float, upper_bound: float, num_bins: int,
aggregation_factory: factory.UnweightedAggregationFactory):
"""Utility function creating tff computation given the parameters and factory.
Args:
lower_bound: A `float` specifying the lower bound of the... | 5,341,578 |
def test_fst_sta_start_session_no_add_params(dev, apdev, test_params):
"""FST STA start session - no add params"""
fst_start_session(apdev, test_params, bad_param_session_add_no_params,
False) | 5,341,579 |
def detect_intent_texts(project_id, session_id, language_code):
"""Returns the result of detect intent with texts as inputs.
Using the same `session_id` between requests allows continuation
of the conversation."""
import dialogflow_v2 as dialogflow
session_client = dialogflow.SessionsClient()
s... | 5,341,580 |
def check_endpoint(func):
"""Check available endpoint."""
@wraps(func)
def wrapper(*args, **kwargs):
sig = inspect.signature(func)
args_value = sig.bind(*args, **kwargs)
endpoint = args_value.arguments["endpoint"]
if endpoint not in AVAILABLE_ENDPOINTS:
raise Cl... | 5,341,581 |
def read_sql_one(id):
"""
This function responds to a request for api/reviews/{id}
with one matching review from reviews
:param id: id of the review
:return: review matching the id
"""
response = Response.query.filter_by(id=id).one_or_none()
if response is not None:
# serial... | 5,341,582 |
def ds_to_numpy(ds: Dataset) -> Tuple[np.ndarray, np.ndarray]:
"""Transform torch dataset to numpy arrays
Parameters
----------
ds : Dataset
COVID dataset
Returns
-------
Tuple[np.ndarray, np.ndarray]
Flattened images + labels
"""
imgs = []
labels = []
for ... | 5,341,583 |
def _b64(b):
"""Helper function base64 encode for jose spec."""
return base64.urlsafe_b64encode(b).decode('utf8').replace("=", "") | 5,341,584 |
def load_from_arff(filename, label_count, label_location="end",
input_feature_type='float', encode_nominal=True, load_sparse=False,
return_attribute_definitions=False):
"""Method for loading ARFF files as numpy array
Parameters
----------
filename : str
path... | 5,341,585 |
def gapfill_to_ensemble(model, iterations=1, universal=None, lower_bound=0.05,
penalties=None, exchange_reactions=False,
demand_reactions=False, integer_threshold=1e-6):
"""
Performs gapfilling on model, pulling reactions from universal.
Any existing constraints on base_mod... | 5,341,586 |
def reparameterize(mu, logvar, n_samples=1):
"""Reparameterization trick.
Args:
mu (torch.Tensor): Mean.
logvar (torch.Tensor): Logarithm of variation.
n_samples (int): The number of samples.
Returns:
torch.Tensor: Samples drawn from the given Gaussian distribution.
... | 5,341,587 |
def rotationMatrixFromNormals(v0,v1,tol=1e-20):
"""
Performs the minimum number of rotations to define a rotation from the direction indicated by the vector n0 to the direction indicated by n1.
The axis of rotation is n0 x n1
https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula
... | 5,341,588 |
def test_temporal():
"""
Show that the kronecker product of a spherical harmonic
covariance and a temporal covariance projected into
flux space is just the elementwise product of the
spherical harmonic covariance projected into flux
space and the temporal covariance.
"""
np.random.seed(... | 5,341,589 |
def test_original(ssf_app):
"""Test an unmodified call, without function calls."""
original = open_url('/', application=ssf_app)
assert (original.SimpleGrid.SimpleGrid.shape == (2, 3)) | 5,341,590 |
def P_to_array(P: NestedDicts) -> np.array:
""" Converts a transition matrix in nested dictionary format to a numpy array.
P is usually given as starting state -> action -> ending state w/ data, we reorder this to
action -> starting state -> ending state -> transition probability.
"""
# Action, Sta... | 5,341,591 |
def write_dataframe(df, fileName):
"""write_dataframe
Writes a DataFrame into a .csv file.
Input:
df -- the DataFrame to write
fileName -- the name of the file (will be saved in ./data/)
"""
path = dataPath + fileName
df.to_csv(path) | 5,341,592 |
def get_available_smc_versions():
"""
Return list of available SMC versions. SMC versioning is done by
d70/smc:v6.1.2. Version returned is after the colon.
"""
return [repotag for image in get_images(filter='d70/smc')
for repotag in image.get('RepoTags')] | 5,341,593 |
def pprint(obj, cols=4, columnwise=True, gap=4):
"""
Print the given list in evenly-spaced columns.
Parameters
----------
obj : list
The list to be printed.
cols : int
The number of columns in which the list should be printed.
columnwise : bool, default=True
If True,... | 5,341,594 |
def boolean_fn2(a, b, c):
""" Return the truth value of (a ∧ b) ∨ (-a ∧ -b) """
return a and b or not a and not b | 5,341,595 |
def get_ica_gds_configuration() -> libgds.Configuration:
"""
Get the configuration object for ica wes
:return:
"""
from utils.ica_base import get_configuration
return get_configuration(libgds.Configuration) | 5,341,596 |
def retry_load_images(image_paths, retry=10, backend="pytorch"):
"""
This function is to load images with support of retrying for failed load.
Args:
image_paths (list): paths of images needed to be loaded.
retry (int, optional): maximum time of loading retrying. Defaults to 10.
back... | 5,341,597 |
def b2p(exts):
"""Convert two points of a polygon into its bounding box.
(Rectangular polygon parallel with axes.)
"""
p0x = exts[0][0]
p0y = exts[0][1]
p0 = str(p0x) + ' ' + str(p0y) + ' ' + '0.0'
p1x = exts[0][2]
p1y = exts[0][3]
p1 = str(p1x) + ' ' + str(p1y) + ' ' + '0.0'
pb... | 5,341,598 |
def unix_to_human_time(utime, alt_format=0):
"""convert Unix time to Human readable time"""
try:
fraction = utime - int(utime)
except OverflowError as err:
t = 'Unix time %s too long to convert, substituting 0' % utime
# TODO log this time issue
print('NEED TO LOG THIS TIME I... | 5,341,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.