content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def load_memmap(filename: str, mode: str = 'r') -> Tuple[Any, Tuple, int]:
""" Load a memory mapped file created by the function save_memmap
Args:
filename: str
path of the file to be loaded
mode: str
One of 'r', 'r+', 'w+'. How to interact with files
Returns:
... | 5,304,700 |
def im_list_to_blob(ims):
"""Convert a list of images into a network input."""
max_shape = np.array([im.shape for im in ims]).max(axis=0)
num_images = len(ims)
blob = np.zeros((num_images, max_shape[0], max_shape[1], max_shape[2]),
dtype=ims[0].dtype)
for i in xrange(num_ima... | 5,304,701 |
def get_bitmasks(enumid):
""" Return list of bitmasks used in enum. """
bmasks = []
bid = idc.get_first_bmask(enumid)
while bid != idaapi.BADADDR:
bmasks.append(bid)
bid = idc.get_next_bmask(enumid, bid)
return bmasks | 5,304,702 |
def get_discrete_physical_eigenvalues_and_amplitudes(lamdas, amps, re_lower):
"""Find and print only physical eigenvalues.
Eigenvalue :math:`\lambda` is called nonnegative here
if :math:`\Re \lambda >=` -`re_lower` and :math:`\Im \lambda >= 0`.
Parameters
----------
lamdas : ndarray
Ar... | 5,304,703 |
def label_sequence( df, seqID, label, complete=False ):
"""Gets the sequence of a ``label``.
Depends on label data for the ``seqID``.
Adds a new column to the data container:
=========================== ====================================================
New Column Data Conten... | 5,304,704 |
def configure_modules(app, modules):
"""load modules that want to be used"""
for module, url_prefix in modules:
app.register_blueprint(module, url_prefix=url_prefix) | 5,304,705 |
def MSF_config(BIM):
"""
Rules to identify a HAZUS MSF configuration based on BIM data
Parameters
----------
BIM: dictionary
Information about the building characteristics.
Returns
-------
config: str
A string that identifies a specific configration within this buidling... | 5,304,706 |
def test_set_cancelled_apple_receipt(
api_client, apple_receipt_client, user_factory
):
"""
If a user sends a PUT request with a valid Apple receipt but the
subscription has been cancelled by Apple's customer support, the
upload should be rejected.
"""
expires = timezone.now().replace(micros... | 5,304,707 |
def _cleanup_past_qinit(input_directory):
"""
Removes past qinit files.
:param input_directory:
:return:
"""
past_init_flow_files = glob(os.path.join(input_directory, 'Qinit_*.csv'))
for past_init_flow_file in past_init_flow_files:
try:
os.remove(past_init_flow_file)
... | 5,304,708 |
def get_bond(mol, bond_idx):
"""
Get oebond object
Parameters
----------
mol : oemol
Molecule to extract bond from
bond_idx : tuple of ints
tuple of map indices of atoms in bond
Returns
-------
bond: oebond
"""
atoms = [mol.GetAtom(oechem.OEHasMapIdx(i)) for... | 5,304,709 |
def find_pyfiles() -> typing.Iterator[pathlib.Path]:
"""Return an iterator of the files to format."""
return itertools.chain(
pathlib.Path("../gdbmongo").rglob("*.py"),
pathlib.Path("../gdbmongo").rglob("*.pyi"),
pathlib.Path("../stubs").rglob("*.pyi"),
pathlib.Path("../tests").r... | 5,304,710 |
def compare_angle(attr_a, attr_b=0, operation=0):
"""Create math_CompareAngle-node to get boolean of logical comparison between given attrs.
Args:
attr_a (NcNode or NcAttrs or string): Maya node attribute.
attr_b (NcNode or NcAttrs or float): Maya node attribute.
operation (NcNode or Nc... | 5,304,711 |
def _power_off(ssh_obj, driver_info):
"""Power OFF this node.
:param ssh_obj: paramiko.SSHClient, an active ssh connection.
:param driver_info: information for accessing the node.
:returns: one of ironic.common.states POWER_OFF or ERROR.
"""
current_pstate = _get_power_status(ssh_obj, driver_i... | 5,304,712 |
def train_valid_test_generator():
"""Loading mnist dataset from tensorflow.keras and scaling the pixels between 0 to 1
Args:
NA
Returns:
nd array: Train, Test and Validation datasets
"""
mnist = tf.keras.datasets.mnist
(x_train_full, y_train_full), (x_test,y_test)= mnist.load_dat... | 5,304,713 |
def main() -> None:
""" The entry point """
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--create", metavar = "FOLDER", help = "Create the index", type=str)
arg_parser.add_argument("--search", metavar = "TERM", help = "Search a term")
args = arg_parser.parse_args()
if args.... | 5,304,714 |
def merge_args(args, cloud_args):
"""merge_args"""
args_dict = vars(args)
if isinstance(cloud_args, dict):
for key in cloud_args.keys():
val = cloud_args[key]
if key in args_dict and val:
arg_type = type(args_dict[key])
if arg_type is not type(... | 5,304,715 |
def java_path():
"""
get the java path using JAVA_HOME if set
"""
if os.environ.get('JAVA_HOME') == None:
return "java"
else:
return os.path.join(os.environ.get('JAVA_HOME'), "bin", "java") | 5,304,716 |
def test_give_xp_to_pokemon(client_log, pokemon_factory):
"""Authenticated user can give XP to an existing pokermon"""
pokemon = pokemon_factory(level=1, experience=40)
payload = {
"amount": 150,
}
res = client_log.post(
reverse("api:pokemon-give-xp", args=[pokemon.id]),
pay... | 5,304,717 |
def has_permission(obj, actor, codename, roles=None):
"""Checks whether the passed actor has passed permission for passed object.
**Parameters:**
obj
The object for which the permission should be checked.
codename
The permission's codename which should be checked.
request
... | 5,304,718 |
def create_df_with_errors(all_dfs):
"""
used in run_bias_experiments.py, only for mt5.
all_dfs : a list of paths to .csvs for various seeds
returns a final dataframe that includes statistical significance
"""
size = str(all_dfs[0])[28:34].strip('_')
lang = str(all_dfs[0])[34:37].strip('_')
... | 5,304,719 |
def fontDeclaration(fontString, fontSize, fh):
""" Defines the font for the labels. """
# fh.write(('/MainFont\n'
# ' /' + fontString + ' findfont '
# + str(fontSize) + ' scalefont def\n'))
# fh.write('MainFont setfont\n')
fh.write('/' + fontString + ' findfont ' + str(fontSi... | 5,304,720 |
def OD2RGB(OD):
"""Convert optical density back to RGB"""
return 255 * np.exp(-OD) | 5,304,721 |
def test_imag_self_energy_freq_points(si_pbesol):
"""Imaginary part of self energy spectrum of Si.
* specified frquency points
"""
si_pbesol.mesh_numbers = [9, 9, 9]
si_pbesol.init_phph_interaction()
_fpoints, _gammas = si_pbesol.run_imag_self_energy(
si_pbesol.grid.grg2bzg[[1, 103]],
... | 5,304,722 |
def get_caqi_no2_1h(no2_max_1h: float) -> float:
"""
Calculates NO2 (max in 1h) CAQI Europe
:param no2_max_1h: NO2 (max in 1h), ppm
:return: NO2 CAQI Europe
"""
cp = __round_down(no2_max_1h * 1000)
return __get_aqi_general_formula(cp, EU_NO2_1H, EU_CAQI) | 5,304,723 |
def run_R(file_name):
"""
This method will run R file
"""
os.system(f"Rscript {file_name}") | 5,304,724 |
def visibility_define(config):
"""Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string)."""
hide = '__attribute__((visibility("hidden")))'
if config.check_gcc_function_attribute(hide, 'hideme'):
return hide
else:
return '' | 5,304,725 |
def retrying_perform(curl):
"""
Perform a curl request, retrying in case of connection errors,
We want to be able to resend the request if the current connection
is unusable due to econnreset (e.g. because a proxy or a load balancer
has just killed a keep-alive connection).
:param curl: Curl o... | 5,304,726 |
def batch_iterator(fname, stop_at=None, verbose=True):
"""
Iterates over all items of a sequence stored in batches in a pickle,
or alternatively only up to the n-th element.
Examples
--------
>>> safe_dump([1, 2], 'TEST', append=True)
>>> safe_dump([3, 4], 'TEST', append=True)
>>> for i in batch_iterator('TES... | 5,304,727 |
def get_best_path(digraph, start, end, path, max_buildings, best_dist,
best_path):
"""
Finds the shortest path between buildings subject to constraints.
Parameters:
digraph: instance of Digraph or one of its subclasses
The graph on which to carry out the search
... | 5,304,728 |
def get_callbacks(data_path, sess_id, config, bot_config_file):
"""
Get a list of callbacks to use for training.
"""
# Get config values
mode = config['mode']
tb_logdir = config['tb_logdir']
save_best_only = config['save_best_only']
use_earlystopping = config['use_earlystopping']
es... | 5,304,729 |
def calculate_num_points_in_solution(solution):
"""Calculates the number of data points in the given solution."""
return sum(len(points) for points in solution.values()) | 5,304,730 |
def _create_dataset(
mesh: salvus.mesh.unstructured_mesh.UnstructuredMesh,
mask: np.ndarray,
parameters: List[str],
coords: str,
):
"""
Create an xarray dataset with relevant information from mesh
:param mesh: Salvus UnstructuredMesh object
:type mesh: salvus.mesh.unstructured_mesh.Unst... | 5,304,731 |
def binarize_labels(labels):
"""
Change the labels to binary
:param labels: np array of digit labels
:return:
"""
labels = np.where(labels == 0, labels, 1)
return labels | 5,304,732 |
def test_validate_default_config():
"""Test if default configuration works with configuration dataclasses."""
try:
FaddrConfig(**DEFAULT_CONFIG)
except ValidationError as err:
pytest.fail(err) | 5,304,733 |
def match_datasets(base_dataset, dataset_tomatch):
"""" Match two datasets defined on different grid.
Given a base dataset and a dataset to be matched, find for each point in
the dataset to mathc the closest cell in the base dataset and return its
index.
Parameters
----------
base_dataset:... | 5,304,734 |
def check_db_version(install_path, db_file):
"""
Check if db exists and is up to date.
If it doesn't exist create it. If it's out of date update it.
"""
from alembic.script import ScriptDirectory
from alembic.config import Config
import sqlite3
import flask_migrate
mig_dir = os.pat... | 5,304,735 |
def rest_invalid_arguments_error_handler(exception: Exception) -> Tuple[Dict, int]:
"""Handle invalid arguments errors.
:param exception: Python Exception
:return: tuple with response and status code
"""
logger.warning(traceback.format_exc())
details = str(exception)
return {'message': 'Inv... | 5,304,736 |
def render(template_name, context, doc_file):
"""
Xuất nội dung và lưu tập tin
:param template_name:
:param context:
:param doc_file:
:return:
"""
file_path = f'{doc_file}.docx'
doc = DocxTemplate(template_name)
doc.render(context)
doc.save(file_path)
print(f'Saved file ... | 5,304,737 |
def _capabilities_semantic_checks(caps_dict):
""" Early check of capabilities """
# Get supported capabilities
valid_data = {}
for key in caps_dict:
if key in CAPABILITIES['backend']:
valid_data[key] = caps_dict[key]
continue
for svc in constants.SB_CEPH_SVCS_SUP... | 5,304,738 |
def generate_spirals(n_samples=100, noise=1e-4, **kwargs):
"""Creates a *spirals* dataset of `n_samples` data points.
:param n_samples: number of data points in the generated dataset
:type n_samples: int
:param noise: standard deviation of noise magnitude added to each data point
:type noise: float... | 5,304,739 |
def register_feature(fn, name=""):
"""
Decorator that can be used to register a feature.
:param function fn: The function to register.
:param str name: Optional string with the name of the function
as it should be registered. If not provided the name of the
function is used.
"""
... | 5,304,740 |
def apply_rotation_on_vector(q, v):
"""q is the quaternion describing the rotation to apply, v is the vector on
which to apply the rotation"""
quaternion_v = transform_vector_to_quaternion(v)
transposed_q = conjugate_quaternion(q)
r = quaternion_product(quaternion_product(q, quaternion_v), transpo... | 5,304,741 |
def brain():
"""Brain operations."""
pass | 5,304,742 |
def get_polygon_speed(polygon_name):
"""Returns speed unit within a polygon."""
result = re.search(r"\(([0-9.]+)\)", polygon_name)
return float(result.group(1)) if result else None | 5,304,743 |
def pt_in_ploy(poly, x, y):
""" 判断 点(x,y) 是否 在 poly 最大和最小坐标之外,粗略 判断点是否在图形之内 """
n = len(poly)
if n < 3:
return False
xmax = xmin = poly[0]['x']
ymax = ymin = poly[0]['y']
for i in range(1, n):
if poly[i]['x'] > xmax:
xmax = poly[i]['x']
elif poly[i]['x'] < x... | 5,304,744 |
async def indexer_get_merkle_proof(request: web.Request) -> web.Response:
"""
Optional endpoint if running an indexer.
Give the client access to arbitrary merkle proofs from any running indexer.
"""
# TODO(1.4.0) This should be monetised with a free quota.
query_params: dict[str, str] = {}
... | 5,304,745 |
def random_node_presence(t_windows, rep, plac, dur):
"""
Generate the occurrence and the presence of a node given occurrence_law(occurrence_param)
and presence_law(presence_param).
:param t_windows: Time window of the Stream Graph
:param rep: Number of segmented nodes
:param plac: Emplacement o... | 5,304,746 |
def db_gen():
"""
Generate synthetic database for regression
:return:
"""
x_random = np.random.random((100, 1)) * 5
print(x_random.shape)
x_train = np.hstack((x_random, np.ones_like(x_random)))
print(x_train.shape)
y_train = x_train.dot([[0.4], [3]])
print(y_train.shape)
y_t... | 5,304,747 |
def action_details(request, test_id, action_id):
"""
Generate HTML page with detail data about test action
**Template:**
:template:`test_report/action_details.html`
"""
action_aggregate_data = list(
TestActionAggregateData.objects.annotate(
test_name=F('test__name')).filte... | 5,304,748 |
def batch_hard_triplet_loss(labels, embeddings, k, margin=0, margin_type='soft'):
"""Build the triplet loss over a batch of embeddings.
For each anchor, we get the hardest positive and hardest negative to form a triplet.
Args:
labels: labels of the batch, of size (batch_size,)
embeddings: ... | 5,304,749 |
def rebin(x: VariableLike, dim: str, bins: _cpp.Variable) -> VariableLike:
"""
Rebin a dimension of a data array or dataset.
The input must contain bin edges for the given dimension `dim`.
:param x: Data to rebin.
:param dim: Dimension to rebin over.
:param bins: New bin edges.
:raises: If... | 5,304,750 |
async def run(
filename: str,
command: str,
verbose: bool = False,
options: Sequence[str] | None = None,
) -> None:
"""
Run autoflake on file at filename.
Return True on success.
"""
if not options:
options = []
temp_directory: str | None = None
try:
temp_di... | 5,304,751 |
def stop():
"""
Print exit message and turn off the UnicornPHAT
"""
print("\nExiting program.")
unicornhat.off() | 5,304,752 |
def resource_path(relative_path):
""" Return absolute path for provided relative item based on location
of program.
"""
# If compiled with pyinstaller then sys._MEIPASS points to the location
# of the bundle. Otherwise path of python script is used.
base_path = getattr(sys, '_MEIPASS', str(Path... | 5,304,753 |
def scalar_div(x: Number, y: Number) -> Number:
"""Implement `scalar_div`."""
_assert_scalar(x, y)
if isinstance(x, (float, np.floating)):
return x / y
else:
return int(x / y) | 5,304,754 |
def _set_default_voltage_ratio(
voltage_ratio: float, subcategory_id: int, type_id: int
) -> float:
"""Set the default voltage ratio for semiconductors.
:param voltage_ratio: the current voltage ratio.
:param subcategory_id: the subcategory ID of the semiconductor with missing
defaults.
:pa... | 5,304,755 |
def add(args, vault):
"""Run this module
:returns: None
"""
vault.secret.add(args.engine, args.vaultpath, json.loads(args.data)) | 5,304,756 |
def PureMultiHeadedAttention(x, params, n_heads=8, dropout=0.0, mode='train',
**kwargs):
"""Pure transformer-style multi-headed attention.
Args:
x: inputs (q, k, v, mask)
params: parameters (none)
n_heads: int: number of attention heads
dropout: float: dropout rate
... | 5,304,757 |
def flatten_factory(flatten_children, is_internal):
"""
Adaptor for single_filter_proc to accept multiple elements
"""
return single_to_multiple(functools.partial(single_filter_proc, should_filter))
return single_to_multiple(functools.partial(single_flatten_proc, flatten_children, is_internal)) | 5,304,758 |
def parse_sentence(obj: Dict) -> BioCSentence:
"""Deserialize a dict obj to a BioCSentence object"""
sentence = BioCSentence()
sentence.offset = obj['offset']
sentence.infons = obj['infons']
sentence.text = obj['text']
for annotation in obj['annotations']:
sentence.add_annotation(... | 5,304,759 |
def _test_for_licensing(esh_machine, identity):
"""
Used to determine whether or not an instance should launch
Returns True OR raise Exception with reason for failure
"""
try:
core_machine = ProviderMachine.objects.get(
instance_source__identifier=esh_machine.id,
inst... | 5,304,760 |
def numba_find_phys(x, y, bdyx, bdyy):
"""
Computes whether the points x, y are inside of the polygon defined by the
x-coordinates bdyx and the y-coordinates bdyy
The polgon is assumed not to be closed (the last point is not replicated)
"""
inside = np.zeros(x.shape, dtype=bool)
vecPointInPa... | 5,304,761 |
def _get_session_client_inject_error_and_call_handler(
handler_name: str,
error_name: str = None,
) -> ProgressEvent:
"""Inject a given botocore client error and call a given handler"""
if error_name:
side_effect = botocore.exceptions.ClientError(
error_response={
... | 5,304,762 |
def stream_text(text, chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming text.
Returns a buffered generator which encodes a string as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
text : str
The data bytes to stream
chunk_size : int
The maximu... | 5,304,763 |
def mergesort(lst: Union[list, LinkedList, DoublyLinkedList],
key: Callable[[Any], Any] = (lambda x: x)) -> None:
"""
Return a sorted list of the items in lst
using the merge sort algorithm.
This algorithm is heavily based off 'Approach 2' by Krikti,
https://www.geeksforgeeks.org/in-p... | 5,304,764 |
def put_number(image, num):
"""アイコンサイズの画像imageの上に
numの値を表示する。
"""
image = image.convert_alpha()
s = str(num)
if len(s) == 1:
font = cw.cwpy.rsrc.fonts["statusimg1"]
elif len(s) == 2:
font = cw.cwpy.rsrc.fonts["statusimg2"]
else:
font = cw.cwpy.rsrc.font... | 5,304,765 |
def generate_sequences(fuzzing_requests, checkers, fuzzing_jobs=1):
""" Implements core restler algorithm.
@param fuzzing_requests: The collection of requests that will be fuzzed
@type fuzzing_requests: FuzzingRequestCollection
@param checkers: The list of checkers to apply
@type checkers: list[C... | 5,304,766 |
def linechart():
"""Fake endpoint."""
return json.dumps({
"line1": [1, 4, 3, 10, 12, 14, 18, 10],
"line2": [1, 2, 10, 20, 30, 6, 10, 12, 18, 2],
"line3": rr_list(),
}) | 5,304,767 |
def calc_intensityAsFktOfRadius_test():
""" based on: calc_intensityAsFktOfRadius_versusRuShan
- the aim is to get a pattern at 90 degrees and almost no area of the mirror
"""
event = Mie(silent = True)
# event.set_r(1.00)
event.set_wavelength(.405)
event.set_n(1.52)
event.set_nang(... | 5,304,768 |
def calculate_conf_matrix_cont(tree,test_X,test_Y,features_Y):
"""
This function calculates confusion matrix using a given tree
for a given data with continious attribute values
It uses given tree with given test_X to create prediction and
compares them with the ground truth labels ... | 5,304,769 |
def server_static(filename):
"""定义/assets/下的静态(css,js,图片)资源路径"""
return static_file(filename, root='./images') | 5,304,770 |
def p_declaration_stmt(t):
"""
declaration_stmt : R_DECLARE global_variable_declaration
"""
t[0] = t[2]
repGrammar.append(t.slice) | 5,304,771 |
def build_execution_summary(execution_timestamp, execution_id,
ml_framework_build_label, execution_label,
platform_name, system_name, output_gcs_url,
benchmark_result, env_vars, flags, harness_info,
site_pack... | 5,304,772 |
def retrieve_one(loc_id):
"""
Return one record from the collection matching given ID
:param loc_id: record ID for localization data
:return: matching data object
"""
query = Geolocation.query.filter(Geolocation.visible == 1).filter(
Geolocation.id == loc_id).one_or_none()... | 5,304,773 |
def get_seed(seed):
"""Returns the local seeds an operation should use given an op-specific seed.
See @{tf.get_seed} for more details. This wrapper adds support for the case
where `seed` may be a tensor.
Args:
seed: An integer or a @{tf.int64} scalar tensor.
Returns:
A tuple of two @{tf.i... | 5,304,774 |
def setup(app):
""" Extension registration hook.
"""
app.add_directive('naclcode', NaclCodeDirective)
app.add_builder(DevsiteBuilder)
# "Production mode" for local testing vs. on-server documentation.
app.add_config_value('devsite_production_mode', default='1', rebuild='html') | 5,304,775 |
def _SendInsertRequest(client, resources, url_map_ref, url_map):
"""Sends a URL map insert request and waits for the operation to finish.
Args:
client: The API client.
resources: The resource parser.
url_map_ref: The URL map reference.
url_map: The URL map to insert.
Returns:
The operation r... | 5,304,776 |
def convert_types(rows: Iterable[List[Any]], types: Any) -> List[Any]:
"""
Generator converting input data to values with supplied list of funcs.
Args:
rows: Iterable - to process records from.
types: List of functions to convert the data.
Returns:
A list containing converted va... | 5,304,777 |
def make_request_with_cancellation_test(
test_name: str,
reactor: MemoryReactorClock,
site: Site,
method: str,
path: str,
content: Union[bytes, str, JsonDict] = b"",
) -> FakeChannel:
"""Performs a request repeatedly, disconnecting at successive `await`s, until
one completes.
Fails ... | 5,304,778 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_utilities package"""
reload_params = {"package": u"fn_utilities",
"incident_fields": [],
"action_fields": [u"excel_named_range", u"excel_range", u"extract_file_path", u"parallel_timers", u"utilit... | 5,304,779 |
def random_reset_mutation(random, candidate, args):
"""Return the mutants produced by randomly choosing new values.
This function performs random-reset mutation. It assumes that
candidate solutions are composed of discrete values. This function
makes use of the bounder function as specified in the EC'... | 5,304,780 |
def plot_lines_and_violins(
all_version_stats: Dict[str, VersionStats], # {version: version_stats}
all_resource_type_stats: Dict[
str, ResourceTypeStats
], # {resource_type: resource_type_stats}
) -> go.Figure:
"""
Plots 2 subfigures in 1 column
top row: a (version, n_shapes) line per ... | 5,304,781 |
def get_ipv6_addrs(ip, count):
"""
Get N IPv6 addresses in a subnet.
Args:
subnet (str): IPv6 subnet, e.g., '2001::1/64'
number_of_ip (int): Number of IP addresses to get
Return:
Return n IPv6 addresses in this subnet in a list.
"""
subnet = str(IPNetwork(ip).network) + "... | 5,304,782 |
def main(cfg: DictConfig) -> None:
"""Converts .CSV files into tokenized PyTorch tensors"""
logger = logging.getLogger(__name__)
logger.info("Tokenize tweets")
c = cfg.build_features
assert (
c.split_train + c.split_test + c.split_eval == 1
), "The split train:{c.split_train} test:{c.spl... | 5,304,783 |
def true_positive_rate(prediction: np.ndarray, ground_truth: np.ndarray) -> float:
"""A.k.a. recall or sensitivity. From the actual positives, how many did I classify as positive?"""
tp = true_positives(prediction, ground_truth)
fn = false_negatives(prediction, ground_truth)
return tp / (tp + fn) | 5,304,784 |
def command_dump(opts):
"""Unpack some or all of the contents of a .zs file.
Usage:
zs dump <zs_file>
zs dump [--start=START] [--stop=STOP] [--prefix=PREFIX]
[--terminator=TERMINATOR | --length-prefixed=TYPE]
[-j PARALLELISM]
[-o FILE]
[--] <zs_file>
zs dump --help
Ar... | 5,304,785 |
def is_same_data(data1, data2, precision=10**-5):
"""
Compare two data to be the same.
:param data1: given data1
:type data1: list
:param data2: given data2
:type data2: list
:param precision: comparing precision
:type precision: float
:return: True if they are the same
"""
... | 5,304,786 |
def get_highest_score(league_id):
"""
Gets the highest score of the week
:param league_id: Int league_id
:return: List [score, team_name]
"""
week = get_current_week()
scoreboards = get_league_scoreboards(league_id, week)
max_score = [0, None]
for matchup_id in scoreboards:
... | 5,304,787 |
def on_connect(client, userdata, flags, rc):
"""Called when script has successfully connected to the given MQTT Broker."""
print("ISS RGB LED subscriber connected.")
logging.info("ISS RGB LED subscriber connected with result code "+str(rc))
client.subscribe(MQTT_STATUS_TOPIC) | 5,304,788 |
def qrs_amplitude_sqi():
""" """
return | 5,304,789 |
def normalise_name(raw_name):
"""
Normalise the name to be used in python package allowable names.
conforms to PEP-423 package naming conventions
:param raw_name: raw string
:return: normalised string
"""
return re.sub(r"[-_. ]+", "_", raw_name).lower() | 5,304,790 |
def webhooks_settings():
"""
Shows the settings page
"""
with get_db() as DB:
c = DB.cursor()
results = c.execute(
"""
SELECT
id,
type,
endpointUrl,
authorizationHeader,
enabled
FROM webhooks
... | 5,304,791 |
def build_parameters(integration_config: dict, instance_config: dict) -> dict:
"""Gets configurations and building the parameters to context
Args:
integration_config: The integration's configuration
instance_config: The instance's config
Returns:
A dictionary of parameters to check... | 5,304,792 |
def decodeall(b):
"""Decode all CBOR items present in an iterable of bytes.
In addition to regular decode errors, raises CBORDecodeError if the
entirety of the passed buffer does not fully decode to complete CBOR
values. This includes failure to decode any value, incomplete collection
types, incomp... | 5,304,793 |
def ensemble_architecture(result):
"""Extracts the ensemble architecture from evaluation results."""
architecture = result["architecture/adanet/ensembles"]
# The architecture is a serialized Summary proto for TensorBoard.
summary_proto = tf.summary.Summary.FromString(architecture)
return summary_pr... | 5,304,794 |
def average_nifti_list(input_path_list):
"""Averages NIfTIs given as a list of image file paths, into the space of the first. Returns the average NIfTI (does not save).
Images must be the same shape.
"""
return divide(add_nifti_list(input_path_list), np.float(len(input_path_list)))
# ... | 5,304,795 |
def copy():
"""copy message from source to destination
use this to transfer file input to database, or from a database to another
database.
"""
class CopyProcessorSettings(ProcessorSettings):
model_definition: str = Field("", title="optional model definition file")
settings = CopyProc... | 5,304,796 |
def transform_inv(T):
"""
Calculates the inverse of the input homogeneous transformation.
This method is more efficient than using C{numpy.linalg.inv}, given
the special properties of the homogeneous transformations.
@type T: array, shape (4,4)
@param T: The input homogeneous transformation
@rtype: array... | 5,304,797 |
def pandas_to_etable(df):
"""
returns a pyet.eTable constructed from given pandas DataFrame
"""
pt = eTable()
pt.Rows = len(df.index)
for cn in df.columns:
dc = df.loc[:, cn].values
pt.AddCol(dc, cn)
return pt | 5,304,798 |
def db_details_without_password(db_connection_id):
"""
To generate a dictionary for data base details.
Args:
db_connection_id(int):data base connection id.
Returns:
Returns a dictionary containing data base details for a particular
data base connection id.
"""
db_deta... | 5,304,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.