content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def load_jets(hdf5):
"""load_jets(hdf5) -> jets
Loads a list of Gabor jets from the given HDF5 file, which needs to be open for reading.
**Parameters**:
``hdf5`` : :py:class:`bob.io.base.HDF5File`
An HDF5 file open for reading
**Returns**:
``jets`` : [:py:class:`bob.ip.gabor.Jet`]
The l... | 59,400 |
def build_label_vector(label_dict_list, n_xgrids, n_ygrids, mean_lwh,
xlim=(0.0, 70.0), ylim=(-50.0,50.0), zlim=(-10.0,10.0)):
""" Build the ground-truth label vector
given a set of poses, classes, and
number of grids.
Input:
label_dict_list: list of lab... | 59,401 |
def test_version():
"""Test that the object returns a version"""
instance = solvate_step.Solvate()
result = instance.version
assert isinstance(result, str) and len(result) > 0 | 59,402 |
def get_all_admins_chat_ids():
"""
List all chat ids of admin
"""
session = Session()
admins_chat_ids = [admin.chat_id for admin in session.query(Admin)]
session.close()
return admins_chat_ids | 59,403 |
def decorator_with_args(decorator_to_enhance):
"""
This is decorator for decorator. It allows any decorator to get additional arguments
"""
def decorator_maker(*args, **kwargs):
def decorator_wrapper(func):
return decorator_to_enhance(func, *args, **kwargs)
return decorator_... | 59,404 |
def shutdown(tree):
"""Stop the tree."""
tree.interrupt() | 59,405 |
def get_k_model(Te0, alpha, ni_Al_profile, shot, Ew_fwhm=1300., delta_a=0.06, delta_h=0.01, ne=0.8, num_cores=16):
"""
"""
# Load threshold data from the supplied shot
MST_data = data.load_ME(shot, direction='horizontal')
MST_data = data.load_ME_horiz(MST_data)
Ec_map = MST_data['thresholds'][:,... | 59,406 |
def drop_by_activity(df: pd.DataFrame):
"""Drops non-active players from the dataframe. Active players are those
players who have at least one killmail per month that resulted from their
use of a combat-based Frigate-class ship type, for a minimum of 12 months
or more.
Examples
--------
Exa... | 59,407 |
def login(request, user):
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request.
"""
if user is None:
user = request.user
# TODO: It would be nice to support different login methods, like signed cookies.
user.last_login = ... | 59,408 |
def show_table_head():
"""
显示表头
:return:
"""
print("-" * 30)
print("姓名\t\t电话\t\t")
print("-" * 30) | 59,409 |
def login(userObj):
"""
If you are using the Auth module and want to track login times as part of the userObj, use this
to set the appropriate state of the user objects last_login field, can be used in conjunction with
``Mojo.Auth.Helpers.login_assistant()`` to round-off the login process::
fro... | 59,410 |
def test_create_test_instances_and_names(estimator_class):
"""Check that create_test_instances_and_names works."""
estimators, names = estimator_class.create_test_instances_and_names()
assert isinstance(estimators, list), (
"first return of create_test_instances_and_names must be a list, "
... | 59,411 |
def generate_intervals(nelements):
"""
Generates all possible permutations of lists that access elements from
boths ends of a list without accessing the middle, and one permutation
that accesses ALL elements of a list.
"""
intervals = list()
for i in range(0, nelements):
interval = l... | 59,412 |
def find_subtype(meta_dict):
"""Find subtype from dictionary of sequence metadata.
Args:
`meta_dict` (dict)
dictionary of metadata downloaded from genbank
Returns:
`subtype` (str)
RSV subtype as one letter string, 'A' or 'B'.
"""
subtype = ''
if ' A' in meta_... | 59,413 |
def multihop_sampling(src_nodes, sample_nums, neighbor_table):
"""根据源节点进行多阶采样
Arguments:
src_nodes {list, np.ndarray} -- 源节点id
sample_nums {list of int} -- 每一阶需要采样的个数
neighbor_table {dict} -- 节点到其邻居节点的映射
Returns:
[list of ndarray] -- 每一阶采样的结果
"""
sampling_re... | 59,414 |
def gen_random_series(
size: int,
dtype: str = "object",
na_ratio: float = 0.0,
str_max_len: int = 100,
random_state: Union[int, np.random.RandomState] = 0,
) -> pd.Series:
"""
Return a randomly generated Pandas Series.
Parameters
----------
size: int
The size of the gen... | 59,415 |
def cc_xls_ir_jit_wrapper(
name,
src,
jit_wrapper_args = {},
**kwargs):
"""Invokes the JIT wrapper generator and compiles the result as a cc_library.
The macro invokes the JIT wrapper generator on an IR source file. The
generated source files are the inputs to a cc_library w... | 59,416 |
def extract_gff3_fields(primer_info):
"""
The gff3 file is a format to annotate locations on a genome.
The gff3 annotations requires locations on the genome, this was not required for creating the primers.
This function computes these locations and prepares the data for the gff3 file
:param pri... | 59,417 |
def flip_label(target, ratio, pattern=0):
"""
Induce label noise by randomly corrupting labels
:param target: list or array of labels
:param ratio: float: noise ratio
:param pattern: flag to choose which type of noise.
0 or mod(pattern, #classes) == 0 = symmetric
int = asymme... | 59,418 |
def retrieve_stripe_checkout_session(subscription):
"""This function returns a Stripe Checkout Session object or raises an
error when the session does not exist or the API call has failed."""
stripe.api_key = settings.STRIPE_API_SECRET_KEY
return stripe.checkout.Session.retrieve(subscription.stripe_sess... | 59,419 |
def _create_agents(num_frames: int, num_agents: int, label: int = 1) -> List[List[Box3D]]:
"""
Generate dummy agent trajectories
:param num_frames: length of the trajectory to be generate
:param num_agents: number of agents to generate
:param label: agent type label. Typically, 1 == vehicles
:re... | 59,420 |
def get_ℓ_prior(points):
"""Calculates mean and sd for InverseGamma prior on lengthscale"""
distances = pdist(points[:, None])
distinct = distances != 0
ℓ_l = distances[distinct].min() if sum(distinct) > 0 else 0.1
ℓ_u = distances[distinct].max() if sum(distinct) > 0 else 1
ℓ_σ = max(0.1, (ℓ_u -... | 59,421 |
def parse_wars(content):
""" Second part of the main parser. Reads all relevant information about wars
from the savegame. Returns a list of all wars, as well as a dictionary about
the participants in each war."""
previous_wars = content.split("previous_war={")[0].split("active_war={")[1:] + content.split("previous_... | 59,422 |
def unique_fast(
seq: Sequence, *, ret_type: Type[Union[list, tuple]] = list
) -> Sequence:
"""Fastest order-preserving method for (hashable) uniques in Python >= 3.6.
Notes
-----
Values of seq must be hashable!
See Also
--------
`Uniquify List in Python 3.6 <https://www.peterbe.com/pl... | 59,423 |
def loadimg_from_id(ID, root_dir=test_dataset.root_dir):
"""load image from pre-defined id.
Args:
ID: List of ids of 5 items.
Return:
imgs: torch.tensor of shape (1, 5, 3, 224, 224)
"""
imgs = []
for id in ID:
if 'mean' in id:
img_path = os.path.... | 59,424 |
def verify_signed_url(url, salt=None):
"""
Check a signed URL is valid and unexpired.
"""
salt = salt or _DEFAULT_SALT
m = _SIGNED_URL_RE.match(url)
if not m:
return None
url = m.group(1)
signature = m.group(2)
expiry = int(m.group(3))
if expiry <= int(time.time()):
... | 59,425 |
def yices_type_is_function(tau):
"""Returns 1 if tau is a function type, 0 otherwise."""
return libyices.yices_type_is_function(tau) | 59,426 |
def kumaraswamy_sample(conc1, conc0, sample_shape):
"""
Sample from the Kumaraswamy distribution given the concentrations
:param conc1: torch tensor: the a concentration of the distribution
:param conc0: torch tensor: the b concentration of the distribution
:param batch_shape: scalar: the batch shape for the samp... | 59,427 |
def parse_atom_ids(input_list, mol):
"""
List of the form id,id,isotope,addHs
e.g. 1,2,104,True
:param input_list:
:param mol:
:return:
"""
spl_list = input_list.split(",")
bond_ids = []
atom_ids = []
bond_colours = {}
for i, data in enumerate(spl_list):
list_len ... | 59,428 |
def run_samplers(request_table, out_table, load_time = 5000, sample = 16, seed = None, requested_again = True):
"""
requested_again := if true, only items which are requested
again will be tracked.
"""
item_info = {}
item_sampler = []
for row in request_table:
time, item = row[:2]
... | 59,429 |
def cluster_hierarchically(active_sites):
"""
Cluster the given set of ActiveSite instances using a hierarchical algorithm. #
Calls to agglomerative clustering algorithm housed in another script
Input: a list of ActiveSite instances
O... | 59,430 |
def _is_container_running(duthost, container_name):
"""
Checks if the required container is running in DUT.
Args:
duthost (SonicHost): The target device.
container_name: the required container's name.
"""
try:
result = duthost.shell("docker inspect -f \{{\{{.State.Running\}}... | 59,431 |
def slow_closest_pair(cluster_list):
"""
Compute the distance between the closest pair of clusters in a list (slow)
Input: cluster_list is the list of clusters
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] have minimum dist... | 59,432 |
def is_retaincase(bunchdt, data, commdct, idfobject, fieldname):
"""test if case has to be retained for that field"""
thiscommdct = getfieldcomm(bunchdt, data, commdct, idfobject, fieldname)
return "retaincase" in thiscommdct | 59,433 |
def test_empty_spec(groups):
"""Test that an empty folder spec is valid."""
assert resolve_folder_spec('', groups) == [] | 59,434 |
def test_multiple_forks(scheduler: Scheduler) -> None:
"""
Ensure multiple handle forks are recorded.
"""
@task()
def task1(conn):
return conn
@task()
def main():
conn = DbHandle("conn", "data.db")
conn = task1(conn)
conn = task1(conn.fork("a").fork("b").for... | 59,435 |
def add_run_number(bids_suffix, run_no):
"""
Safely add run number to BIDS suffix
Handle prior existence of run-* in BIDS filename template from protocol translator
:param bids_suffix, str
:param run_no, int
:return: new_bids_suffix, str
"""
if "run-" in bids_suffix:
# Preserve... | 59,436 |
def logout():
"""Log user out."""
# forget any username
session.clear()
# redirect user to login form
return redirect(url_for("login")) | 59,437 |
def test_bulkRNASeq_STAGE01_paired(caplog, glds194_test_dir, glds194_sample_names):
""" Tests loader for state after demultiplexing for single end study """
caplog.set_level(0)
ds = load_BulkRNASeq_STAGE_01(
*load_BulkRNASeq_STAGE_00(
glds194_test_dir, dataSystem_name="GLDS-194", config... | 59,438 |
def worker_demand_path(args: list):
""" Worker function for the multi-processing system that will run the demand
limiting case of the Dynamic Solow model (k = kd) for a set of random
seeds. Each run will be saved as a pandas DataFrame using the pickle
module
Parameters
-----... | 59,439 |
def complement(clr):
""" Returns the color opposite on the color wheel.
The complementary color contrasts with the given color.
"""
if not isinstance(clr, Color):
clr = Color(clr)
return clr.rotate(180) | 59,440 |
def get_file_info(pipeline_context, filename):
"""Return a dictionary of CRDS information about `filename`."""
return S.get_file_info(pipeline_context, filename) | 59,441 |
def vcf2bedpe(caller, info, filter_, format_, vcf):
"""
Convert a VCF file into a BEDPE file.
A VCF argument is the path to the input VCF file.
"""
if isinstance(vcf, TextIOWrapper):
vcf_obj = viola.read_vcf(StringIO(vcf.read()), variant_caller=caller)
else:
vcf_obj = viola.read_vcf(vcf, ... | 59,442 |
def parse_colors(sequence):
"""Return escape codes from a color sequence."""
return ''.join(ESCAPE_CODES[n] for n in sequence.split(',') if n) | 59,443 |
def test_earnings():
"""Test module earnings.py by downloading
earnings.csv and testing shape of
extracted data has 4266 rows and 2 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = earnings(test_path)
try:
assert x_train.shape == (4266, 2)
except:
shutil.rmtree(test_path)
rai... | 59,444 |
def intersect(s1, s2):
"""
Returns the intersection of two slices (which must have the same step).
Parameters
----------
s1, s2 : slice
The slices to intersect.
Returns
-------
slice
"""
assert (s1.step is None and s2.step is None) or s1.step == s2.step, \
"Only i... | 59,445 |
def apply_hpso_parameters(o, hpso, hpso_pipe):
"""
Applies the parameters for the HPSO pipeline to the parameter container object o.
:param o: The supplied ParameterContainer object, to which the symbolic variables are appended (in-place)
:param hpso: The HPSO whose parameters we are applying
:para... | 59,446 |
def checkpoint_get_group_command(client: Client, identifier: str) -> CommandResults:
"""
Show existing group object using object name or uid.
Args:
client (Client): CheckPoint client.
identifier(str): uid or name.
"""
result = client.get_group(identifier)
printable_result = buil... | 59,447 |
def remove_duplicate_indices(data: pd.DataFrame, keep="first") -> pd.DataFrame:
"""Function that removes duplicate indices
Args:
data: The data frame for which duplicate indices need to be deleted
keep: Determines which duplicates (if any) to mark. See pandas.DataFrame.index.duplicated document... | 59,448 |
def rdkit_molecule(gra):
""" Convert a molecular graph to an RDKit molecule.
This is mainly useful for quick visualization with IPython, which can be
done as follows:
>>> from IPython.display import display
>>> display(rdkit_molecule(gra))
:param gra: the graph
:returns: the RDKit molecule... | 59,449 |
def get_data_source_output(id: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetDataSourceResult]:
"""
Resource Type definition for AWS::AppSync::DataSource
"""
... | 59,450 |
def test_list_mails_command_encoding(mocker, client):
"""Unit test
Given
- an email query
When
- calling list_mails
Then
- Validate that the queried value is properly url-encoded
"""
client = MsGraphClient(True, 'tenant', 'auth_token_url', 'enc_key', 'app_name', 'https://example.com'... | 59,451 |
def make_filename_template(**kwargs):
"""Generate a filename template snippet from the schema, based on specific
filters.
Parameters
----------
kwargs : dict
Keyword arguments used to filter the schema.
Example kwargs that may be used include: "suffixes", "datatypes",
"exten... | 59,452 |
def get_freq_group(W_MON): # real signature unknown; restored from __doc__
"""
Return frequency code group of given frequency str or offset.
Example
-------
>>> get_freq_group('W-MON')
4000
>>> get_freq_group('W-FRI')
4000
"""
pass | 59,453 |
def compute_entropy_bernoulli(logit: torch.Tensor):
""" Compute the entropy of the bernoulli distribution, i.e. H= - [p * log(p) + (1-p) * log(1-p)] """
p = torch.sigmoid(logit)
one_m_p = torch.sigmoid(-logit)
log_p = F.logsigmoid(logit)
log_one_m_p = F.logsigmoid(-logit)
entropy = - (p * log_p ... | 59,454 |
def test_inherit_constraints(model):
"""
Various tests for copying of constraint values between compound models and
their members.
There are two versions of this test: One where a compound model is created
from two model instances, and another where a compound model is created
from two model cl... | 59,455 |
def simple_context_manager(iterations=1000):
""" this could be a wrapper around a database """
def _gen():
for i in range(iterations):
yield str(i) + "\n"
time.sleep(0.001)
if i == iterations - 1:
print("reached the end")
try:
yield _gen
... | 59,456 |
def test_constructor_expanddim(data, series_name, frame_name, dtype):
"""Test DataSeries.to_frame()"""
ds = rs.DataSeries(data, name=series_name, dtype=dtype)
d = ds.to_frame(name=frame_name)
assert isinstance(d, rs.DataSet)
assert len(d.columns) == 1
assert isinstance(d.dtypes[0], type(ds.dtyp... | 59,457 |
def profile_ctx(profiling):
"""
Wrapper around to isolate responbability of profiling in a contextmanager
"""
if profiling:
pr = cProfile.Profile()
pr.enable()
yield
if profiling:
pr.disable()
pr.dump_stats(PROFILER_FILE_PATH) | 59,458 |
def domain_from_url(url):
"""Returns the website part of a given url
:param url: str the URL for which the website is needed
:returns: the website extracted from the url value
:rtype: str (or None)
"""
if url is None:
return None
try:
parsed = urlparse(url)
if parsed... | 59,459 |
def deDoc_run(dirname, sample_df, cutoff, deDoc_path):
"""
Input:
- dirname: ../Matrix_aligned/Sample_name/100k
- sample_df: chromosome pairs with sorted score
- cutoff: for choose the baseline of the prop in cumsum of the sorted score.
- deDoc_path: the path of deDoc.jar
Ret... | 59,460 |
def check_event_attr(logpath):
"""
Checks for existence of event attributes, given the path of event log.
Parameters:
logpath (str): Path of event log
Returns:
attr (List of str): List of event attributes
"""
log = importer.apply(logpath)
log_df = log_converter.apply(log, v... | 59,461 |
def is_word_guessed(word, guesses):
"""
This function will check if the user has guessed all of the letters in the word.
"""
# Loop through the word.
for letter in word:
# Check if the letter has been guessed.
if letter not in guesses:
# The user has not guessed the letter.
return False
# The user has ... | 59,462 |
async def test_proc_restart_not_verifying():
"""User not undergoing verification sent error."""
# Setup
db = MagicMock()
user = new_mock_user(0)
db.get_member_data.return_value = make_def_member_data()
# Call
await proc_restart(db, user)
# Ensure correct user queried.
db.get_member... | 59,463 |
def compile_command(contracts):
"""Compile cairo contracts to default output directory."""
# to do: automatically support subdirectories
if not os.path.exists(ABIS_DIRECTORY):
print(f"Creating {ABIS_DIRECTORY} to store compilation artifacts")
os.makedirs(ABIS_DIRECTORY, exist_ok=True)
... | 59,464 |
def verify():
"""
This function verify if the keypoints in from superpoint+superglue are correctly labelled by ground truth relative pose
"""
images_dir = os.path.join(args.dataset_dir, args.sequence)
images_info = make_images_info(
struct_filename=os.path.join(args.dataset_dir, 'struct_file... | 59,465 |
def solve(start, end, min_studios):
"""Solve an instance of the grid, given start and end gate locations.
min_studios is an integer specifying the minimum number of studio squares
that must be visited.
"""
# We may attempt the same gates multiple times. Memoize to improve speed.
memo_key = (start, end, min... | 59,466 |
def find_exe(arch='x86'):
"""Get the path to an exe launcher provided by this package.
The options for arch are currently 'x86' and 'x64'.
"""
if arch == 'x86':
return os.path.join(_pkg_dir, 'cli-32.exe')
elif arch == 'x64':
return os.path.join(_pkg_dir, 'cli-64.exe')
raise Val... | 59,467 |
def unpack_seven(inbytes):
"""
Reconstruct a number from the seven-bit representation used in
the SysEx message data.
Takes a bytes-like object, where each byte is seven bits of the number
(big-endian byte order)
Each byte must have its high bit zero, or else ValueError is raised.
"""
va... | 59,468 |
def clin_mut_found_fill_in_fus(summaryTable_):
""" fills in clin_mut_found_bool col: 1 if clin mut found, 0 if else
but for fusions """
for i in range(0,len(summaryTable_.index)):
currCell = summaryTable_['cell'][i]
currFus = summaryTable_['fusions_found'][i]
if not pd.isnull(currFus):
currFus = currFus.s... | 59,469 |
def list(state):
"""List all registered sites"""
table = AsciiTable([['Path', 'URL', 'Secure']])
sites = state.site.list()
if sites:
for s in sites:
table.table_data.append([
click.style(s.path, fg='bright_yellow') + (('\n => (Root) ' + s.documentRoot()) if s.root els... | 59,470 |
def test_case_insensitivity(forest_fires):
"""
Tests to ensure that the sql is case insensitive for table names
:return:
"""
my_table = query("select * from FOREST_fires")
ibis_table = forest_fires
assert_ibis_equal_show_diff(my_table, ibis_table) | 59,471 |
def h(node1, node2, l1, l2, *, g):
"""If node has 8 neighbors"""
g_n = g(node1)
path = node1.path
parent = next(path)
try:
parent = next(path)
except StopIteration:
pass
g_p = g(parent)
if g_p <= g_n:
w = l1
else:
w = l2
h_n = euclid(node1, node2)
... | 59,472 |
def logout_page():
"""Redirects user to homepage and cleans session"""
flask.session.clear()
clean_cache()
logging.debug(flask.request.remote_addr + ' logged out')
return flask.redirect(flask.url_for('home_page')) | 59,473 |
def nativestr(x):
"""Return the decoded binary string, or a string, depending on type."""
return x.decode("utf-8", "replace") if isinstance(x, bytes) else x | 59,474 |
def seperate(df, column, new_names, sep=".", remove=False):
"""Verb: split strings on a seperator.
Inverse of :func:`unite`
Parameters
----------
column : str or pd.Series
column to split on (Series.name is named in case of a series)
new_names : list
list of new column names
... | 59,475 |
def listdetail(filename,
itemtype,
name='',
tablefmt='simple',
header='default'):
"""List nodes and metadata in output file.
Parameters
----------
{filename}
{itemtype}
name : str
Optional specific name to print only that entry... | 59,476 |
def template_match_hashes(template_hashes, source_hashes, match_percent=0.6):
"""
Takes in array of template fingerprint hashes, and an array of hashes to search through. Looks through the search
array for the template, and registers a match so long as the percent of matches exceeds the provided match_perce... | 59,477 |
def unparse(tree: typed_ast.ast3.AST, *args, **kwargs) -> str:
"""Unparse AST based on typed_ast.ast3 with nodes as defined in horast.nodes into code."""
assert isinstance(tree, typed_ast.ast3.AST), type(tree)
stream = io.StringIO()
Unparser(tree, *args, file=stream, **kwargs)
return stream.getvalue... | 59,478 |
def Clean_price(post_price):
"""This function takes out the price range used by the website"""
if re.search('\-.*', post_price):
pos = re.search('\-.*', post_price).start()
return post_price[:pos]
else:
return post_price | 59,479 |
def add_zma_inp():
""" Add the zma input files using geo inputs
"""
cnf_managers = fs.iterate_managers(PFX, ['REACTION', 'THEORY', 'TRANSITION STATE'],
'CONFORMER')
for cnf_fs in cnf_managers:
if cnf_fs is not None:
print()
for... | 59,480 |
async def test_controlling_state_via_mqtt_rgbww_hex(hass, mqtt_mock, setup_tasmota):
"""Test state update via MQTT."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["rl"][0] = 2
config["lt_st"] = 5 # 5 channel light (RGBCW)
config["so"]["17"] = 0 # Hex color in state updates
mac = config["mac"... | 59,481 |
def breadthSearch(self, node, visitedNodes, visitedEdges):
"""
Algoritmo para realizar a busca em largura em um grafo.
Args:
node (int): nó de início da busca em largura.
visitedNodes (list): lista vazia a ser preenchida com os nós visitados.
visitedEdges (list): lista vazia a ser p... | 59,482 |
def synchronize_client(client):
"""
Synchronize all models as resources for a client.
:type client: django_keycloak.models.Client
"""
for app_config in apps.get_app_configs():
synchronize_resources(
client=client,
app_config=app_config
) | 59,483 |
def remove_duplicates(list1):
"""
Eliminate duplicates in a sorted list.
Returns a new sorted list with the same elements in list1, but
with no duplicates.
This function can be iterative.
"""
uniques = []
for dummy_idx in list1:
if dummy_idx not in uniques:
uniques... | 59,484 |
def extract_single_image(img_path, lab_path,
voxel_picker_class,
patch_picker_class,
cent_picker_class,
patch_size, scales,
n_voxels):
"""Sample and extract feature from an image.
Argume... | 59,485 |
def fitness_function(solution, answer):
"""fitness_function(solution, answer) Returns a fitness score of a solution compaired to the desired answer. This score is the absolute 'ascii' distance between characters."""
score =0
for i in range(len(answer)):
score += (abs(solution[i]-answer[i]))
retu... | 59,486 |
def rr_order_patterns(
signal1: "np.ndarray[np.int32]", signal2: "np.ndarray[np.int32]", m: int, tau: int
) -> float:
"""
Parameters
----------
signal1 :
signal2 :
m : int
Embedding dimension.
tau : int
Time delay parameter.
Notes
-----
* The results m... | 59,487 |
def adjust_cruise_no(cruise):
"""If shipc should be mapped we map cruise_no as well."""
if len(cruise) > 7:
return '_'.join((cruise[:4], cruise[4:8], cruise[8:]))
else:
return cruise | 59,488 |
def augment_genomes_json_download_file(fpath, h5, backup='.bak'):
"""Augment the genomes.json file in the download section with additional info
This function stores the ncbi taxonomy identifiers of internal nodes and adds
the number of ancestral genes to the internal nodes.
:param fpath: path to genom... | 59,489 |
def update_uas_class_admin(class_id=None,
comment=None,
default=None,
public_ip=None,
image_id=None,
priority_class_name=None,
namespace=None,
... | 59,490 |
def t1(name):
"""- change team 1's name"""
write(team1F, " ".join(name))
rprint(f"{main_colour}Team {t1_colour}1 {main_colour}Name: {arg_colour}"
f"{read(team1F)}") | 59,491 |
def parse_args():
"""Parse command line arguments.
"""
arg_parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
arg_parser.add_argument('-hca', '--http_cert', default=None,
help='The ca cert of external HTTP Server')
arg_parser... | 59,492 |
def test_batch_execution_of_gradient_tf(device, shots, mocker):
"""Test that the output of a parallelized execution of batch circuits to evaluate the
gradient is correct in comparison to default.qubit when using the tf interface."""
tf = pytest.importorskip("tensorflow", minversion="2.4")
qubits = 2
... | 59,493 |
def ref_array_angles(PALC_config, Ref_arr, gui_ref_array, \
gui_ref_start, gui_ref_step_stop, \
gui_ref_discrete_angles, gui_ref_userdef):
"""
Calculates the reference LSA tilt angles depending on user input. Called
by :any:`get_ref_array_angles` and :any:`get_value... | 59,494 |
def award_badge_to_user(db, badgename, username, hostdir=HOMEDIR + "awardedbadges/"):
"""awards a badge to a recipient, creating a publicly hosted json of the badge info (a badge assertion)
located at "http://HOMEIP/awardedbadges/"
the recipient will be a json with the user's email (hashed), type (email), h... | 59,495 |
def get_glconfig():
"""Returns a GLConfig to be used for OpenGL widgets initialisation."""
global __old_glconfig
if __old_glconfig == None:
# Query the OpenGL extension version.
# Configure OpenGL framebuffer.
# Try to get a double-buffered framebuffer configuration,
# if no... | 59,496 |
def newOrder(idProds):
"""
Creates a new order with the idProd
:return:
"""
product_ids = idProds.split(',')
order_id = uuid.uuid4()
order = agn['order_' + str(order_id)]
graph_message = Graph()
graph_message.add((order, RDF.type, Literal(OntologyConstants.ACTION_CREATE_ORDER)))
... | 59,497 |
def Demographic_Parity(pred_labels, true_labels, groups, priv_group=None):
"""
A fair algorithm would have an equal rate of positive outcomes :math:`(\\hat{Y}=1)` in privileged group :math:`(A=0)` and unprivileged groups :math:`(A=1)`.
:math: :math:`P(\\hat{Y} = 1|A=0) = P(\\hat{Y} = 1|A=1)`
:return:... | 59,498 |
def decode(k, key_length):
"""
Decodes a klv message
"""
key = k[:key_length]
val_length, ber_length = decode_ber(k[key_length:])
value = k[key_length + ber_length : key_length + ber_length + val_length]
return key, value | 59,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.