content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def convert_string(inpt):
"""Return string value from input lit_input
>>> convert_string(1)
'1'
"""
if PY2:
return str(inpt).decode()
else:
return str(inpt) | 5,338,800 |
def get_ipc_kernel(imdark, tint, boxsize=5, nchans=4, bg_remove=True,
hotcut=[5000,50000], calc_ppc=False,
same_scan_direction=False, reverse_scan_direction=False):
""" Derive IPC/PPC Convolution Kernels
Find the IPC and PPC kernels used to convolve detector pixel data... | 5,338,801 |
def magma_finalize():
"""
Finalize MAGMA.
"""
status = _libmagma.magma_finalize()
magmaCheckStatus(status) | 5,338,802 |
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['cache'] = 86400
desc['description'] = """This plot presents the trailing X number of days
temperature or precipitation departure from long term average. You can
express th... | 5,338,803 |
def SpringH(z,m,k):
""" with shapes (bs,2nd)"""
D = z.shape[-1] # of ODE dims, 2*num_particles*space_dim
q = z[:,:D//2].reshape(*m.shape,-1)
p = z[:,D//2:].reshape(*m.shape,-1)
return EuclideanK(p,m) + SpringV(q,k) | 5,338,804 |
def write_sushi_input_files(lhafile):
""" Add SusHi-related blocks to LHA file """
outfiles = {}
for higgsname, higgstype in {'H': 12, 'A': 21}.iteritems():
lha = LHA(lhafile)
sushi = Block('SUSHI', comment='SusHi specific')
sushi.add(Entry([1, 2], commen... | 5,338,805 |
def test_fetch_market_trade_data_dataframe():
"""Tests downloading of market and trade/order data from dataframe
"""
from tcapy.data.databasesource import DatabaseSourceCSV
### Get market data
market_loader = Mediator.get_tca_market_trade_loader()
market_data_store = DatabaseSourceCSV(market_... | 5,338,806 |
def pytest_collection(session): # pylint: disable=unused-argument
"""Monkey patch lru_cache, before any module imports occur."""
# Gotta hold on to this before we patch it away
old_lru_cache = functools.lru_cache
@wraps(functools.lru_cache)
def lru_cache_wrapper(*args, **kwargs):
"""Wrap ... | 5,338,807 |
def __graph_laplacian(mtx):
""" Compute the Laplacian of the matrix.
.. math::
"""
L = np.diag(np.sum(mtx, 0)) - mtx
return L | 5,338,808 |
def moon_illumination(phase: float) -> float:
"""Calculate the percentage of the moon that is illuminated.
Currently this value increases approximately linearly in time from new moon
to full, and then linearly back down until the next new moon.
Args:
phase: float
The phase angle of... | 5,338,809 |
def integ_test(gateway_host=None, test_host=None, destroy_vm="True"):
"""
Run the integration tests. This defaults to running on local vagrant
machines, but can also be pointed to an arbitrary host (e.g. amazon) by
passing "address:port" as arguments
gateway_host: The ssh address string of the mach... | 5,338,810 |
def convex_hull_mask_iou(points_uv, im_shape, gt_hull_mask):
"""Computes masks by calculating a convex hull from points. Creates two masks (if possible),
one for the estimated foreground pixels and one for the estimated background pixels.
Args:
points_uv: (2, N) Points in u, v coordinates
i... | 5,338,811 |
def remove_dataset_from_disk(interval_list_dataset, version=None, dest_path=CACHE_PATH):
"""
Remove the full-seq dataset from the disk.
Parameters:
interval_list_dataset (str or Path): Either a path or a name of dataset included in this package.
version (int)... | 5,338,812 |
def run(text, base_dir, debug_filename, symbols = set()):
"""Rudimentary resolver for the following preprocessor commands:
// #include <some-file>
(no check for cyclic includes!)
// #ifdef | #if <symbol>
// <contents>
// [ #elif
// <alt-contents> ]*
// [ #else
// <alt-contents> ]
// #endi... | 5,338,813 |
def load_callback(module: ModuleType, event: Event) -> Callable[..., Awaitable[None]]:
"""
Load the callback function from the handler module
"""
callback = getattr(module, "handler")
if not inspect.iscoroutinefunction(callback):
raise TypeError(
f"expected 'coroutine function' f... | 5,338,814 |
def read_config_key(fname='', existing_dict=None, delim=None):
"""
Read a configuration key.
"""
# Check file existence
if os.path.isfile(fname) is False:
logger.error("I tried to read key "+fname+" but it does not exist.")
return(existing_dict)
logger.info("Reading: "+fname)
... | 5,338,815 |
def animeuser_auto_logical_delete():
"""一定の日数以上生き残ってしまったAnimeUserを論理削除します"""
logical_divide_day: str = os.getenv("LOGICAL_DIVIDE_DAY", default="3")
logical_divide_day_int: int = int(logical_divide_day)
divide_datetime: datetime.datetime = datetime.datetime.now() - datetime.timedelta(
days=logic... | 5,338,816 |
def start_app() -> None:
"""Start Experiment Registry."""
bcipy_gui = app(sys.argv)
ex = ExperimentRegistry(
title='Experiment Registry',
height=700,
width=600,
background_color='black')
sys.exit(bcipy_gui.exec_()) | 5,338,817 |
def launch_lambdas(total_count, lambda_arn, lambda_args, dlq_arn, cubes_arn, downsample_queue_url, receipt_handle):
"""Launch lambdas to process all of the target cubes to downsample
Launches an initial set of lambdas and monitors the cubes SQS queue to
understand the current status. If the count in the qu... | 5,338,818 |
def send_result_mail(adress, link):
"""Create and send a mail with the download link to adress."""
# parse adress
if "," in adress:
splitchar = ","
elif ";" in adress:
splitchar = ";"
else:
splitchar = " "
toadress = adress.split(splitchar)
toadress = [i.strip() for i... | 5,338,819 |
def examples(conf, concept, positives, vocab, neg_count=None):
"""
Builds positive and negative examples.
"""
if neg_count is None:
neg_count = conf.getint('sample','neg_count')
while True:
for (chosen_idx, idces), e_token_indices in positives:
if len(chosen_idx... | 5,338,820 |
def molmer_sorensen(theta, N=None, targets=[0, 1]):
"""
Quantum object of a Mølmer–Sørensen gate.
Parameters
----------
theta: float
The duration of the interaction pulse.
N: int
Number of qubits in the system.
target: int
The indices of the target qubits.
Retur... | 5,338,821 |
def verify_path(path):
"""check if the project path is correct"""
if not os.path.exists(path) or not os.path.isdir(path):
error('Path specified for project creation does not exist or is not a directory') | 5,338,822 |
def get_pixel_dist(pixel, red, green, blue):
"""
Returns the color distance between pixel and mean RGB value
Input:
pixel (Pixel): pixel with RGB values to be compared
red (int): average red value across all images
green (int): average green value across all images
blue (int... | 5,338,823 |
def test_capture_log(allured_testdir, logging):
"""
>>> import logging
>>> import pytest
>>> import allure
>>> logger = logging.getLogger(__name__)
>>> @pytest.fixture
... def fixture(request):
... logger.info("Start fixture")
... def finalizer():
... logger.inf... | 5,338,824 |
def list_children_shapes(node, all_hierarchy=True, full_path=True):
"""
Returns a list of children shapes of the given node
:param node:
:param all_hierarchy:
:param full_path:
:return:
"""
raise NotImplementedError() | 5,338,825 |
def structure_pmu(array: np.ndarray) -> np.ndarray:
"""Helper function to convert 4 column array into structured array
representing 4-momenta of particles.
Parameters
----------
array : numpy ndarray of floats, with shape (num particles, 4)
The 4-momenta of the particles, arranged in co... | 5,338,826 |
def _log_from_checkpoint(args):
"""Infer logging directory from checkpoint file."""
int_dir, checkpoint_name = os.path.split(args.checkpoint)
logdir = os.path.dirname(int_dir)
checkpoint_num = int(checkpoint_name.split('_')[1])
_log_args(logdir, args, modified_iter=checkpoint_num)
return logdir,... | 5,338,827 |
def url_query_parameter(url, parameter, default=None, keep_blank_values=0):
"""Return the value of a url parameter, given the url and parameter name
General case:
>>> import w3lib.url
>>> w3lib.url.url_query_parameter("product.html?id=200&foo=bar", "id")
'200'
>>>
Return a default value i... | 5,338,828 |
def read_ground_stations_extended(filename_ground_stations_extended):
"""
Reads ground stations from the input file.
:param filename_ground_stations_extended: Filename of ground stations basic (typically /path/to/ground_stations.txt)
:return: List of ground stations
"""
ground_stations_extende... | 5,338,829 |
def _stdin_yaml_arg():
"""
@return: iterator for next set of service args on stdin. Iterator returns a list of args for each call.
@rtype: iterator
"""
import yaml
import select
loaded = None
poll = select.poll()
poll.register(sys.stdin, select.POLLIN)
try:
arg = 'x'
... | 5,338,830 |
def main():
"""
Converts characters to uppercase,
then output the complementary sequence through the newly created function (build_complement())
"""
dna = input('Please give me a DNA strand and I\'ll find the complement: ')
# Converts characters to uppercase
dna = dna.upper
ans = build_c... | 5,338,831 |
def quiet_py4j():
"""Suppress spark logging for the test context."""
logger = logging.getLogger('py4j')
logger.setLevel(logging.WARN) | 5,338,832 |
def send_email(destination, code):
"""
Send the validation email.
"""
if 'CLOUD' not in os.environ:
# If the application is running locally, use config.ini anf if not, set environment variables
config = configparser.ConfigParser()
config.read_file(open('config.ini'))
# S... | 5,338,833 |
def shortPrescID():
"""Create R2 (short format) Prescription ID
Build the prescription ID and add the required checkdigit.
Checkdigit is selected from the PRESCRIPTION_CHECKDIGIT_VALUES constant
"""
_PRESC_CHECKDIGIT_VALUES = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+'
hexString = str(uuid.uuid1()).... | 5,338,834 |
def rmse(predictions, verbose=True):
"""Compute RMSE (Root Mean Squared Error).
.. math::
\\text{RMSE} = \\sqrt{\\frac{1}{|\\hat{R}|} \\sum_{\\hat{r}_{ui} \in
\\hat{R}}(r_{ui} - \\hat{r}_{ui})^2}.
Args:
predictions (:obj:`list` of :obj:`Prediction\
<surprise.prediction_... | 5,338,835 |
def test_cbv_proxyidmixin_should_succeed(quantity: int, client) -> None:
"""Tests if CBVs using ProxydMixin can retrieve objects correctly"""
int_persons = baker.make("appmock.PersonIntegerPK", _quantity=quantity)
uuid_persons = baker.make("appmock.PersonUUIDPK", _quantity=quantity)
for person in int_... | 5,338,836 |
def join_csvs(column,
csvs_in,
csv_out,
encoding_in='utf-8',
encoding_out='utf-8'):
"""Outer join a comma-delimited list of csvs on a given column.
Common encodings include: utf-8, cp1252.
"""
dfs = [read_csv(csv_in, encoding_in) for csv_in in csv... | 5,338,837 |
def get_module_docstring(path):
"""get a .py file docstring, without actually executing the file"""
with open(path) as f:
return ast.get_docstring(ast.parse(f.read())) | 5,338,838 |
def get_authenticate_kwargs(oauth_credentials=None, http_=None):
"""Returns a dictionary with keyword arguments for use with discovery
Prioritizes oauth_credentials or a http client provided by the user
If none provided, falls back to default credentials provided by google's command line
utilities. If ... | 5,338,839 |
def marginal_expectation(distribution: Tensor, axes: AxesLike, integrals: Union[Callable, Sequence[Callable]],
*args, **kwargs):
"""
Computes expectations along the ``axes`` according to ``integrals`` independently.
``args`` and ``kwargs`` are passed to ``integral`` as additional ... | 5,338,840 |
def get_transforms(size=128, mobilenet=False):
"""
Gets all the torchvision transforms we will be applying to the dataset.
"""
# These are the transformations that we will do to our dataset
# For X transforms, let's do some of the usual suspects and convert to tensor.
# Don't forget to normalize... | 5,338,841 |
def transform(f, a, b, c, d):
"""
Transform a given function linearly.
If f(t) is the original function, and a, b, c, and d are the parameters in
order, then the return value is the function
F(t) = af(cx + d) + b
"""
return lambda x: a * f(c * x + d) + b | 5,338,842 |
def delete_rules(request):
"""
Deletes the rules with the given primary key.
"""
if request.method == 'POST':
rules_id = strip_tags(request.POST['post_id'])
post = HouseRules.objects.get(pk=rules_id)
post.filepath.delete() # Delete actual file
post.delete()
return re... | 5,338,843 |
def display_word(word, secret_word, word_to_guess):
"""Function to edit the word to display and the word to guess (word to display
is the test word with its colored letter and the word to guess is the word
with spaces in it, for each missing letter).
Args:
word (str): the input word
secr... | 5,338,844 |
def test_append_new_event(init_context):
"""
Append new event
"""
pc = init_context
pc.append_event("test", Arguments("test", a=1))
pc.append_event("test1", Arguments("test1", a=2))
pc.append_event("test2", Arguments("test2", a=3))
e1 = pc.event_queue.get()
e2 = pc.event_... | 5,338,845 |
def fixPythonImportPath():
"""
Add main.py's folder to Python's import paths.
We need this because by default Macros and UNO components can only import files located in `pythonpath` folder,
which must be in extension's root folder. This requires extra configuration in IDE and project structure becomes
... | 5,338,846 |
def plot_imfs(signal, time_samples, imfs, fignum=None):
"""Visualize decomposed signals.
:param signal: Analyzed signal
:param time_samples: time instants
:param imfs: intrinsic mode functions of the signal
:param fignum: (optional) number of the figure to display
:type signal: array-like
:... | 5,338,847 |
def get_config_cache(course_pk: 'int') -> dict:
"""Cacheからコンフィグを取得する.存在しない場合,新たにキャッシュを生成して格納後,コンフィグを返す."""
cache_key = f"course-config-{course_pk}"
cached_config = cache.get(cache_key, None)
if cached_config is None:
config = Config.objects.filter(course_id=course_pk).first()
cached_conf... | 5,338,848 |
def log_command(func):
"""
Logging decorator for logging bot commands and info
"""
def log_command(*args, **kwargs):
slack, command, event = args
user = slack.user_info(event["user"])
log_line = 'USER: %s | CHANNEL ID: %s | COMMAND: %s | TEXT: %s'
command_info = log_line ... | 5,338,849 |
def expand_home_folder(path):
"""Checks if path starts with ~ and expands it to the actual
home folder."""
if path.startswith("~"):
return os.environ.get('HOME') + path[1:]
return path | 5,338,850 |
def calc_stats(scores_summ, curr_lines, curr_idx, CI=0.95, ext_test=None,
stats="mean", shuffle=False):
"""
calc_stats(scores_summ, curr_lines, curr_idx)
Calculates statistics on scores from runs with specific analysis criteria
and records them in the summary scores dataframe.
... | 5,338,851 |
def report_date_time() -> str:
"""Return the report date requested as query parameter."""
report_date_string = dict(bottle.request.query).get("report_date")
return str(report_date_string).replace("Z", "+00:00") if report_date_string else iso_timestamp() | 5,338,852 |
def assign_colour_label_data(catl):
"""
Assign colour label to data
Parameters
----------
catl: pandas Dataframe
Data catalog
Returns
---------
catl: pandas Dataframe
Data catalog with colour label assigned as new column
"""
logmstar_arr = catl.logmstar.values... | 5,338,853 |
def get_policy(arn):
"""Get info about a policy."""
client = get_client("iam")
response = client.get_policy(PolicyArn=arn)
return response | 5,338,854 |
def get_file_xml(filename):
"""
:param filename: the filename, without the .xml suffix, in the tests/xml directory
:return: returns the specified file's xml
"""
file = os.path.join(XML_DIR, filename + '.xml')
with open(file, 'r') as f:
xml = f.read()
return xml | 5,338,855 |
def _write_roadways(roadway_feature_class, condition):
"""Writes roadway feature class to STAMINA syntax
Arguments:
roads_feature_class {String} -- Path to feature class
condition {String} -- Existing, NoBuild, or Build. Determines fields to use from geospatial template
Returns:
... | 5,338,856 |
def detect_backends() -> tuple:
"""
Registers all available backends and returns them.
This includes only backends for which the minimal requirements are fulfilled.
Returns:
`tuple` of `phi.math.backend.Backend`
"""
try:
from .tf import TF_BACKEND
except ImportError:
... | 5,338,857 |
def WriteMobileRankings(IncludedTitles, TxtFile, TitleMin = DefaultTitleMin, SortedBy = DefaultSort, SortedByTie = DefaultSortTie, LinesBetween = DefaultLines):
"""Writes a TxtFile for the titles in IncludedTitles, in a mobile friendly format.
IncludedTitles: a list of string(s) in Titles; the Title(s) whose rankin... | 5,338,858 |
def mix_audio(word_path=None,
bg_path=None,
word_vol=1.0,
bg_vol=1.0,
sample_time=1.0,
sample_rate=16000):
"""
Read in a wav file and background noise file. Resample and adjust volume as
necessary.
"""
# If no w... | 5,338,859 |
def analytical_pulse_width(ekev):
"""
Estimate analytical_pulse_width (FWHM) from radiation energy (assumes symmetrical beam)
:param ekev: radiation energy [keV]
:return sig: Radiation pulse width (FWHM) [m]
"""
sig = np.log((7.4e03/ekev))*6
return sig/1e6 | 5,338,860 |
def progress_timeout(progress_bar):
"""
Update the progress of the timer on a timeout tick.
Parameters
----------
progress_bar : ProgressBar
The UI progress bar object
Returns
-------
bool
True if continuing timer, False if done.
"""
global time_remaining, time... | 5,338,861 |
def socket_file(module_name):
"""
Get the absolute path to the socket file for the named module.
"""
module_name = realname(module_name)
return join(sockets_directory(), module_name + '.sock') | 5,338,862 |
def test_create_kernel(tmpdir):
"""Creates a new directory '3-kernel' and all its input files."""
dirname = '3-kernel'
d = tmpdir.join(dirname)
expected_dir = os.path.join(fixtures_dir, dirname)
bgw.create_kernel(config, tmpdir.realpath())
with open(os.path.join(expected_dir, 'kernel.inp.expec... | 5,338,863 |
def create_notification_entry(testcase_id, user_email):
"""Create a entry log for sent notification."""
notification = data_types.Notification()
notification.testcase_id = testcase_id
notification.user_email = user_email
notification.put() | 5,338,864 |
def postBuild(id: str):
"""Register a new build.
Args:
id: Identifier of Repository for which build is to be registered.
Returns:
build_id: Identifier of Build created.
"""
return register_builds(
id, request.headers["X-Project-Access-Token"], request.json
) | 5,338,865 |
def submit(g_nocaptcha_response_value, secret_key, remoteip):
"""
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_response_field -- The value of recaptcha_response_field
from the form
secret_key -- your reCAPTCHA private key
remoteip -- the u... | 5,338,866 |
def boundary(shape, n_size, n):
""" Shape boundaries & their neighborhoods
@param shape 2D_bool_numpy_array: True if pixel in shape
@return {index: neighborhood}
index: 2D_int_tuple = index of neighborhood center in shape
neighborhood: 2D_bool_numpy_array of size n_size
Boundaries are s... | 5,338,867 |
def centered_mols(self, labels, return_trans=False):
"""
Return the molecules translated at the origin with a corresponding cell
Parameters
----------
labels : int or list of ints
The labels of the atoms to select
print_centro : bool
Print the translation vector which was detect... | 5,338,868 |
def binary_accuracy(output: torch.Tensor, target: torch.Tensor) -> float:
"""Computes the accuracy for binary classification"""
with torch.no_grad():
batch_size = target.size(0)
pred = (output >= 0.5).float().t().view(-1)
correct = pred.eq(target.view(-1)).float().sum()
correct.m... | 5,338,869 |
def arp(ipaddress):
"""Clear IP ARP table"""
if ipaddress is not None:
command = 'sudo ip -4 neigh show {}'.format(ipaddress)
(out, err) = run_command(command, return_output=True)
if not err and 'dev' in out:
outputList = out.split()
dev = outputList[outputList.in... | 5,338,870 |
def prepare_config(config):
"""
Prepares a dictionary to be stored as a json.
Converts all numpy arrays to regular arrays
Args:
config: The config with numpy arrays
Returns:
The numpy free config
"""
c = {}
for key, value in config.items():
if isinstance(value, n... | 5,338,871 |
def load_config(path='config.json'):
"""
Loads configruation from config.json file.
Returns station mac address, interval, and units for data request
"""
# Open config JSON
with open(path) as f:
# Load JSON file to dictionary
config = json.load(f)
# Return mac a... | 5,338,872 |
def log_px_z(pred_logits, outcome):
"""
Returns Bernoulli log probability.
:param pred_logits: logits for outcome 1
:param outcome: datapoint
:return: log Bernoulli probability of outcome given logits in pred_logits
"""
pred = pred_logits.view(pred_logits.size(0), -1)
y = outcome.view(... | 5,338,873 |
def test_one_epoch(sess, ops, data_input):
""" ops: dict mapping from string to tf ops """
is_training = False
loss_sum = 0
num_batches = data_input.num_test // BATCH_SIZE
acc_a_sum = [0] * 5
acc_s_sum = [0] * 5
preds = []
labels_total = []
acc_a = [0] * 5
acc_s = [0] * 5
f... | 5,338,874 |
def main():
""" Main function for handling user arguments
"""
parser = argparse.ArgumentParser(description='Check windows hashdumps against http://cracker.offensive-security.com')
parser.add_argument('priority_code', help='Priority code provided by PWK course console')
parser.add_argument('hash_dump... | 5,338,875 |
def stderr_redirector(stream: typing.BinaryIO):
"""A context manager that redirects Python stderr and C stderr to the given binary I/O stream."""
def _redirect_stderr(to_fd):
"""Redirect stderr to the given file descriptor."""
# Flush the C-level buffer stderr
libc.fflush(c_stderr)
... | 5,338,876 |
def _sort_rows(matrix, num_rows):
"""Sort matrix rows by the last column.
Args:
matrix: a matrix of values (row,col).
num_rows: (int) number of sorted rows to return from the matrix.
Returns:
Tensor (num_rows, col) of the sorted matrix top K rows.
"""
tmatrix = tf.transpose(a=matrix, perm=... | 5,338,877 |
def partial_at(func, indices, *args):
"""Partial function application for arguments at given indices."""
@functools.wraps(func)
def wrapper(*fargs, **fkwargs):
nargs = len(args) + len(fargs)
iargs = iter(args)
ifargs = iter(fargs)
posargs = (next((ifargs, iargs)[i in indice... | 5,338,878 |
def try_load_module(module_name):
"""
Import a module by name, print the version info and file name.
Return None on failure.
"""
try:
import importlib
mod = importlib.import_module(module_name)
print green("%s %s:" % (module_name, mod.__version__)), mod.__file__
retur... | 5,338,879 |
def test_VaultFile_load(
testcase, vault_yaml, password, server_schema, exp_data, exp_encrypted):
"""
Test function for VaultFile._load_vault_file()
"""
with TempDirectory() as tmp_dir:
# Create the vault file
filename = 'tmp_vault.yml'
filepath = os.path.join(tmp_dir.p... | 5,338,880 |
def project_image(request, uid):
"""
GET request : return project image
PUT request : change project image
"""
project = Project.objects.filter(uid=uid).first()
imgpath = project.image.path if project.image else get_thumbnail()
if request.method == "PUT":
file_object = request.data.... | 5,338,881 |
def validate(prefix: str, identifier: str) -> Optional[bool]:
"""Validate the identifier against the prefix's pattern, if it exists.
:param prefix: The prefix in the CURIE
:param identifier: The identifier in the CURIE
:return: Whether this identifier passes validation, after normalization
>>> val... | 5,338,882 |
def test_correct_config():
"""Test whether config parser properly parses configuration file"""
flexmock(builtins, open=StringIO(correct_config))
res_key, res_secret = twitter.parse_configuration("some_path")
assert res_key == key
assert res_secret == secret | 5,338,883 |
def laplacian_positional_encoding(g, pos_enc_dim):
"""
Graph positional encoding v/ Laplacian eigenvectors
"""
# Laplacian
A = g.adjacency_matrix_scipy(return_edge_ids=False).astype(float)
N = sp.diags(dgl.backend.asnumpy(g.in_degrees()).clip(1) ** -0.5, dtype=float)
L = sp.eye(g.number... | 5,338,884 |
async def replace_chain():
""" replaces the current chain with the most recent and longest chain """
blockchain.replace_chain()
blockchain.is_chain_valid(chain=blockchain.chain)
return{'message': 'chain has been updated and is valid',
'longest chain': blockchain.chain} | 5,338,885 |
def ucb(bufferx,
objective_weights,
regression_models,
param_space,
scalarization_method,
objective_limits,
iteration_number,
model_type,
classification_model=None,
number_of_cpus=0):
"""
Multi-objective ucb acquisition function as detailed... | 5,338,886 |
def np_array_to_binary_vector(np_arr):
""" Converts a NumPy array to the RDKit ExplicitBitVector type. """
binary_vector = DataStructs.ExplicitBitVect(len(np_arr))
binary_vector.SetBitsFromList(np.where(np_arr)[0].tolist())
return binary_vector | 5,338,887 |
def augment_features(data, feature_augmentation):
"""
Augment features for a given data matrix.
:param data: Data matrix.
:param feature_augmentation: Function applied to augment the features.
:return: Augmented data matrix.
"""
if data is not None and feature_augmentation is not None:
... | 5,338,888 |
def _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None):
""" Helper function for _get_data that handles empty lists. """
fields = get_field_list(fields, schema)
return {'cols': _get_cols(fields, schema), 'rows': []}, 0 | 5,338,889 |
def setup(bot: Monty) -> None:
"""Load the TokenRemover cog."""
bot.add_cog(TokenRemover(bot)) | 5,338,890 |
def copy_keys_except(dic, *keys):
"""Return a copy of the dict without the specified items.
"""
ret = dic.copy()
for key in keys:
try:
del ret[key]
except KeyError:
pass
return ret | 5,338,891 |
def get_params(img, scale, ratio):
"""Get parameters for ``crop`` for a random sized crop.
Args:
img (PIL Image): Image to be cropped.
scale (tuple): range of size of the origin size cropped
ratio (tuple): range of aspect ratio of the origin aspect ratio cropped
Returns:
tu... | 5,338,892 |
async def start_time() -> Any:
"""
Returns the contest start time.
"""
return schemas.Timestamp(timestamp=settings.EVENT_START_TIME) | 5,338,893 |
def reshape(v, shape):
"""Implement `reshape`."""
return np.reshape(v, shape) | 5,338,894 |
def generate_html_from_module(module):
"""
Extracts a module documentations from a module object into a HTML string
uses a pre-written builtins list in order to exclude built in functions
:param module: Module object type to extract documentation from
:return: String representation of an HTML file
... | 5,338,895 |
def _phi(r, order):
"""Coordinate-wise nonlinearity used to define the order of the
interpolation.
See https://en.wikipedia.org/wiki/Polyharmonic_spline for the definition.
Args:
r: input op
order: interpolation order
Returns:
phi_k evaluated coordinate-wise on r, for k = r
... | 5,338,896 |
def updated_topology_description(topology_description, server_description):
"""Return an updated copy of a TopologyDescription.
:Parameters:
- `topology_description`: the current TopologyDescription
- `server_description`: a new ServerDescription that resulted from
a hello call
Called ... | 5,338,897 |
def test_success(database):
""" Testing valid program activity name for the corresponding TAS/TAFS as defined in Section 82 of OMB Circular
A-11.
"""
populate_publish_status(database)
af_1 = AwardFinancialFactory(row_number=1, agency_identifier='test', submission_id=1, main_account_code='test... | 5,338,898 |
def get_absolute_filepath(filepath: str) -> str:
"""Returns absolute filepath of the file/folder from the given `filepath` (along with the extension, if any)"""
absolute_filepath = os.path.realpath(path=filepath)
return absolute_filepath | 5,338,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.