content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _create_entities(
device: hm_device.HmDevice,
device_address: str,
custom_entity_class: type,
device_enum: EntityDefinition,
device_def: dict[str, Any],
entity_def: dict[int, set[str]],
channel_no: int | None = None,
) -> list[hm_entity.BaseEntity]:
"""Create custom entities."""
... | 5,322,800 |
def TDF_ComparisonTool_SourceUnbound(*args):
"""
* Finds from <aRefDataSet> all the keys not bound into <aRelocationTable> and put them into <aDiffDataSet>. Returns True if the difference contains at least one key. (A key is a source object). <anOption> may take the following values: 1 : labels treatment only; 2... | 5,322,801 |
def sorted_qubits(qbs: Qubits) -> Qubits:
"""Return a sorted list of unique qubits in canonical order.
Qubits can be of different types, so we sort first by type (as a string),
then within types.
"""
return tuple(sorted(list(set(qbs)), key=lambda x: (str(type(x)), x))) | 5,322,802 |
def lu(a: np.ndarray,
permute_l: bool = False,
overwrite_a: bool = False,
check_finite: bool = True,
is_lapack_piv: bool = True):
"""
Compute pivoted LU decomposition of a matrix.
"""
if overwrite_a:
pivot, LU = _lu_internal(a,
permut... | 5,322,803 |
def compute_referendum_result_by_regions(referendum_and_areas):
"""Return a table with the absolute count for each region.
The return DataFrame should be indexed by `code_reg` and have columns:
['name_reg', 'Registered', 'Abstentions', 'Null', 'Choice A', 'Choice B']
"""
tempdf = referendum_and_are... | 5,322,804 |
def get_nvsmi_win():
"""Function that probes the nvsmi in windows
:return: the path of nvsmi or `None`
"""
logging.info("Detected System: Windows")
nvsmi_exe = nvsmi + ".exe"
for p in WIN_PATHS:
loc_path = os.path.join(p, nvsmi_exe)
if shutil.which(loc_path) is not None:
... | 5,322,805 |
def createZMIPSlabs(name, inputDir, outputDir):
"""Process all image files in immediate subdirectories of inputDir to
correspondingly prefixed images in outputDir. outputDir is
created if it doesn't already exist. The subdirectory structure
is not replicated.
See the documentation of createZMIPSl... | 5,322,806 |
def get_edfi_payloads(context, dbt_run_result, table_reference: str) -> List:
"""
Extract BigQUery table and return the
resulting JSON as a dict.
"""
df = context.resources.warehouse.download_table(table_reference)
df_json = df.to_json(orient="records", date_format="iso")
df_dict = json.loa... | 5,322,807 |
def deinterleaver(pseudo_rand_array: List[int], array: np.ndarray) -> np.ndarray:
"""Random permutations for deinterleaving an array according to a pseudo random sequence"""
dims = array.shape
flat_array = array.flatten()
matrix = np.zeros(array.size, int)
for index, position in enumerate(pseudo_ran... | 5,322,808 |
def add_rnn_encoder_arguments(group):
"""Define arguments for RNN encoder."""
group.add_argument(
"--elayers",
default=4,
type=int,
help="Number of encoder layers (for shared recognition part "
"in multi-speaker asr mode)",
)
group.add_argument(
"--eunits"... | 5,322,809 |
def sum_sample(attrfx='merge'):
"""Returns a mapper that computes the sum sample of a dataset.
Parameters
----------
attrfx : 'merge' or callable, optional
Callable that is used to determine the sample attributes of the computed
sum samples. By default this will be a string representation o... | 5,322,810 |
def karatsuba_512x512(w, ab, xy, t0, t1, t2, t3, t4, t5, t6):
""" w: 4 ymm reg. ab: 2 ymm reg. xy: 2 ymm reg. t*: 1 ymm reg """
a, b = ab[0], ab[1]
x, y = xy[0], xy[1]
aPb = t5
xPy = t6
p("vpxor %ymm{}, %ymm{}, %ymm{}".format(a, b, aPb))
p("vpxor %ymm{}, %ymm{}, %ymm{}".format(x, y, xPy))
... | 5,322,811 |
def match_profile_to_preset(profile_lookup, colour_preset_lookup):
"""Get a list of preset names that match the current profile colour scheme.
"""
match_list = []
for preset_name, preset_colours in colour_preset_lookup.iteritems():
match = True
for colour_name, colour_val in preset_colo... | 5,322,812 |
def jsonpify( data, callback ):
"""
Helper to support JSONP
"""
try:
output = json.dumps( data, sort_keys=True, indent=2 )
if callback:
output = '%s(%s)' % ( callback, output )
return output
except Exception as e:
message = 'exception jsonifying output, ``... | 5,322,813 |
def rnd_colors(
count, lightness=0.5, saturation=1.0, alpha=None,
init_dis=4.0, lr=0.95, ur=1.5,
rnd=None
) -> Iterator[Color]:
"""
Overview:
Generating random colors which are not similar.
:param count: Count of colors.
:param lightness: Lightness of the colors (in HLS ... | 5,322,814 |
def localize_gaspari_cohn(dist,c):
"""
Gaspari-Cohn correlation function
Arguments:
- z: Points to be evaluated
- c: Cutoff value
"""
# Initialize localization array
localization=np.zeros(dist.shape)
# Mask for mid-distance points
mid_mask=(dist<=2*c)
# c for mid-dist... | 5,322,815 |
def download_spectra(table, data_dir, save_raw=True, raw_dir=None):
"""
Downloads SDSS spectra
Parameters
----------
table : AstroPy.Table
Table with coordinates
data_dir : str
Specifies directory where the data is saved
save_raw : bool
Specifies whether the raw spec... | 5,322,816 |
def serialize_gs_channel(gs_channel, exclude_fields=None):
"""JSON serializer
Serializes the given groundstation channel.
:param gs_channel: The Ground Station channel object to be serialized
:param exclude_fields: List of fields to be excluded from the object
:return: JSON serialization
"""
... | 5,322,817 |
def get_is_valid_node_name(name):
"""get_is_valid_node_name(std::string name) -> bool"""
return _RMF.get_is_valid_node_name(name) | 5,322,818 |
def ranker(
sorted_iter: Iterator[Rank_Data], # 序列尾部
base: float,
same_rank_seq: List[Rank_Data], # 序列头
key: Callable[[Rank_Data], K_]
) -> Iterator[Tuple[float, Rank_Data]]:
"""根据给定的 base 值,在一个排好序的序列上输出等级值计算结果
>>> key0 = lambda x: x[0]
>>> rank_data_iter = iter([R... | 5,322,819 |
def split_multi_expr_clause(s):
"""
Transforms "abc, (123 + 1) * 2, f(a,b)"
into ["abc", "(123 + 1) * 2", "f(a,b)"]
"""
sin = list(s)
sep = [-1]
rb = 0 # ()
cb = 0 # {}
sb = 0 # []
for i in range(len(sin)):
c = sin[i]
if c == "(":
rb = rb + 1
... | 5,322,820 |
def load(experiment: Experiment, key: str) -> list:
"""Load kwarg from experiments.
Parameters
----------
experiment: Experiment.
Experiment meata-data.
key: str.
Key to load.
Returns
-------
data: list of data.
"""
save_dir = experiment.log_dir
values = [... | 5,322,821 |
def suffix(suffix, iterable):
"""Add suffix to each item of an iterable."""
for x in iterable:
yield '{x!s}{suffix!s}'.format(suffix=suffix, x=x) | 5,322,822 |
def setRCmatrix(m, p):
"""Random generate matrix ids to set zeros.
Parameters
----------
m : integer
Number of rows/columns of square matrix
p : float (0. < p < 1.0)
percent of entries in matrix that set to zero.
Returns
-------
rowsZeros, columnsZeros : Tuple
Rows and columns id of matr... | 5,322,823 |
def win_term():
"""
set the Windows console to understand the ANSI color codes
"""
from platform import system as platform_system
if platform_system() == "Windows":
import ctypes
kernel32 = ctypes.windll.kernel32
# https://docs.microsoft.com/en-us/windows/console/setconsol... | 5,322,824 |
def _two_qubit_accumulate_into_scratch(args: Dict[str, Any]):
"""Accumulates two qubit phase gates into the scratch shards."""
index0, index1 = args['indices']
half_turns = args['half_turns']
scratch = _scratch_shard(args)
projector = _one_projector(args, index0) * _one_projector(args, index1)
... | 5,322,825 |
def sections(parsed):
"""Calculates number of every type of section"""
num_small_sections = 0
num_medium_sections = 0
num_big_sections = 0
for fence in parsed.fences:
if not fence.isRemoval:
num_big_sections += (fence.length/12) // 8
if (fence.length/12) % 8 < 6 and (... | 5,322,826 |
def idn(sp):
""" Identity channel sp -> sp on space sp; it does nothing """
return Channel(np.eye(_prod(sp.shape)), sp, sp) | 5,322,827 |
def permutation_test(x1, x2, times=1000, sides=2, metrics="mean", seed=None):
"""
Permutation test: whether group x1 has equal [mean|median] as group x2
Parameters
----------
x1: array or list of int/float
samples for variable x1
x2: array or list of int/float
samples for variab... | 5,322,828 |
def build_tourism(image_set, args):
"""
image_set: whether to return train, val or test dataset
"""
all_imagepaths = sorted(Path(args.image_folder).glob("*.jpg"))
all_poses = np.load(args.c2w_path)
all_kinvs = np.load(args.kinv_path)
all_bounds = np.load(args.bound_path)
# first 20 imag... | 5,322,829 |
def find_package(app_name, version, revision):
"""Check for a specific package version"""
# NOTE: Originally this method also used 'pkg_type' (the 'builder'
# column in the 'packages' table) to filter; this may need to be
# re-added at some point.
pkg_def = find_package_definition(app_name)
i... | 5,322,830 |
def _group_by_internal_name(ports: List[WrapperPort]):
"""Group ports by their 'internal_name' attribute
return a list of (internal_name, group) where group is a list of ports
"""
ports.sort(key=lambda x: x.internal_name)
instances = [(name, list(group)) for name, group
in groupby(p... | 5,322,831 |
def export_books_from_db(directory_path):
"""
Exportar los libros de ingreso y gastos a partir de la información en la
base de datos. En caso que no se pase un directorio lo escribe en el directorio de salidas
con el nombre 'informe_periodos.txt'.
"""
if directory_path == '':
export_bo... | 5,322,832 |
def run_tests():
"""Run 'make test'"""
success = False
while not success:
try:
run(['make', 'test'], check=True)
except CalledProcessError as exc_info:
print("Failed tests: %s\n" % exc_info)
print("Fix the tests and ammend the release commit.")
... | 5,322,833 |
def homography_warp(patch, dst_H_src, dsize, points=None,
padding_mode='zeros'):
"""
.. note:: Functional API for :class:`torgeometry.HomographyWarper`
Warps patches by homographies.
Args:
patch (Tensor): The image or tensor to warp. Should be from source.
dst_homo_... | 5,322,834 |
def html2text(value):
"""
Uses html2text to convert HTML to text...
"""
return _html2text.html2text(value) | 5,322,835 |
def column_metadata(column, table_proxy, table_schema, chunks, exemplar_row=0):
"""
Infers column metadata for the purposes of creating dask arrays
that reference their contents.
Parameters
----------
column : string
Table column
table_proxy : string
CASA Table path
tabl... | 5,322,836 |
def generate_setup():
"""Used to initially populate the database with sample data"""
user1 = User(username="user", password=pbkdf2_sha256.hash("pass"))
user2 = User(username="user2", password=pbkdf2_sha256.hash("pass"))
user3 = User(username="user3", password=pbkdf2_sha256.hash("pass"))
feed_dt = d... | 5,322,837 |
def analyze(clf, data):
"""
Analyze how well a classifier performs on data.
Parameters
----------
clf : classifier object
data : dict
"""
# Get confusion matrix
from sklearn import metrics
predicted = clf.predict(data['test']['X'])
print("Confusion matrix:\n%s" %
m... | 5,322,838 |
def save_model_summary(model, path):
"""Saves model summary to a text file.
:param model: the model.
:param path: text file.
"""
with open(path, 'w') as f:
current_stdout = sys.stdout
sys.stdout = f
print(model.summary())
sys.stdout = current_stdout | 5,322,839 |
def plugin_loaded():
"""on plugin loaded"""
LOGGER.info("plugin loaded")
# update preference
update_settings()
@pipe
def initialize():
"""initialize server"""
try:
SERVICE.initialize(retry=False)
except (TimeoutError, errors.RequestAborted) as err:
... | 5,322,840 |
def GPS_VO_Merge_plot(T_v_dict, utm_dict):
""" Plot the VO and GPS trajectories.
The GPS trajectory is rotated and translated to the origin
in order to obtain a visual comparison between both trajectories."""
k = T_v_dict.keys() + utm_dict.keys()
k = [i for i in unique_everseen([i for i in k... | 5,322,841 |
def serialize_payload(payload):
"""Serialize a payload to a JSON string."""
return json.dumps(payload, default=_pack) | 5,322,842 |
def main():
"""Compare benchmarks for changes in a formatted report."""
args = parse_args(sys.argv[1:])
comparator = TestComparator(LogParser.results_from_file(args.old_file),
LogParser.results_from_file(args.new_file),
args.delta_threshold)
... | 5,322,843 |
def get_app_users(appname):
"""List users who has permissions to the specified app
.. todo::
* write tests for this API
* add example response
"""
app = _get_app(appname)
return app.list_users() | 5,322,844 |
def is_power(num, return_decomposition=False):
"""
Check if num is a perfect power in O(n^3) time, n=ceil(logN)
"""
b = 2
while (2 ** b) <= num:
a = 1
c = num
while (c - a) >= 2:
m = int((a + c) / 2)
if (m ** b) < (num + 1):
p = int(m ... | 5,322,845 |
def error(msg):
"""Log error message"""
cflog.error(msg) | 5,322,846 |
def train_rllib(submodule, flags):
"""Train policies using the PPO algorithm in RLlib."""
import ray
from ray import tune
class Args:
def __init__(self):
self.horizon = 400
self.algo = 'PPO'
self.randomize_vehicles = True
args = Args()
flow_params... | 5,322,847 |
def create_dataset(save_path, eco_path, happy_path):
"""
This function reads the various datasets we use to construct our dataset, cleans them
for missing values and bad characters, and saves the final dataset in a new file.
"""
### Import Global Ecological Footprint 2016 dataset ###
# link: https://www.kaggle.co... | 5,322,848 |
def choose_greatest():
"""Echo the largest of the two numbers given by the user to the program
Warning: this function was written quickly and needs proper error handling
"""
user_value_1 = input("What's your first number? ")
user_value_2 = input("What's your second number? ")
greatest_value = ... | 5,322,849 |
def validate_bucket_name(bucket_name):
"""
Validate bucket name
Bucket name must be compatible with DNS name (RFC 1123):
- Less than 63 characters
- Valid character set [a-z0-9-]
- Can not begin and end with "-"
Returns Trues if valid, False otherwise
"""
if len(bucket_name)... | 5,322,850 |
def format_gro_box(box):
""" Print a line corresponding to the box vector in accordance with .gro file format
@param[in] box Box NamedTuple
"""
if box.alpha == 90.0 and box.beta == 90.0 and box.gamma == 90.0:
return ' '.join(["% 13.9f" % (i/10) for i in [box.a, box.b, box.c]])
else:
... | 5,322,851 |
def bot_has_permissions(**perms: bool) -> AC:
"""Similar to :func:`.has_permissions` except checks if the bot itself has
the permissions listed.
This check raises a special exception, :exc:`.ApplicationBotMissingPermissions`
that is inherited from :exc:`.ApplicationCheckFailure`.
If this check is ... | 5,322,852 |
def get_ilsvrc_xception_trainner(config_file_path='./config/ilsvrc_2012_xception.yaml'):
"""
:param config_file_path:
:return:
"""
cfg = config_utils.get_config(config_file_path=config_file_path)
return base_trainner.BaseClsTrainner(cfg=cfg) | 5,322,853 |
def get_bpag(model: pd.DataFrame) -> tuple:
"""Calculate test statistics for heteroscedasticity
Parameters
----------
model : OLS Model
Model containing residual values.
Returns
-------
Test results from the Breusch-Pagan Test
"""
lm_stat, p_value, f_stat, fp_value = het_b... | 5,322,854 |
def name2link(name: str):
"""Used for hyperlink anchors"""
if not isinstance(name, str):
name = str(name)
return "-".join([s.lower() for s in name.split(" ")]) | 5,322,855 |
def window_rolling(origin_data, window_size):
"""Rolling data over 0-dim.
:param origin_data: ndarray of [n_records, ...]
:param window_size: window_size
:return: [n_records - window_size + 1, window_size, ...]
"""
n_records = len(origin_data)
if n_records < window_size:
return None
... | 5,322,856 |
def get_neighbors(grid, structure_num, proximity):
""" Given a grid of structures, returns the closest proximity neighbors to the given structure
params:
- Grid: 2D numpy array
- structure_num: int
- proximity: int
:returns
- A list of neighboring structures to the ... | 5,322,857 |
def test(url):
"""Test the 'formfill' extension stuff."""
execute_script('test_formfill.twill', initial_url=url) | 5,322,858 |
def vgg19_bn(pretrained=False, **kwargs):
"""VGG 19-layer model (configuration 'E') with batch normalization
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['E'], batch_norm=True)... | 5,322,859 |
def main():
"""Main function."""
config = open("/workspaces/DD2424-project/configs/alexnet_config.json")
dataset = Dataset(config)
ds_train = dataset.get_data("train")
config_alex = open("/workspaces/DD2424-project/configs/alexnet_config.json")
alex = AlexNet(config_alex)
alex.set_train_d... | 5,322,860 |
def init_ss_model() -> SentenceTransformer:
"""Load RoBERTa-base model."""
return SentenceTransformer(
"usc-isi/sbert-roberta-large-anli-mnli-snli", cache_folder=str(PRETRAINED_MODEL_DIR)
) | 5,322,861 |
def test_stolen_list_importer(per_test_postgres, tmpdir, db_user, mocked_config, monkeypatch):
"""Test stolen list import works with the security role created based on abstract role."""
files_to_zip = ['unittest_data/stolen_list/sample_stolen_list.csv']
zip_files_to_tmpdir(files_to_zip, tmpdir)
zipped_f... | 5,322,862 |
def _dassert_is_integration_branch(abs_dir: str) -> None:
"""
Ensure that name of the branch in `abs_dir` is an integration or lint one.
"""
_LOG.debug(hprint.to_str("abs_dir"))
branch_name = hgit.get_branch_name(dir_name=abs_dir)
hdbg.dassert_ne(branch_name, "master")
hdbg.dassert(
... | 5,322,863 |
def register_plot_prop(plot_prop_class):
"""
Registers a provided plot property class `plot_prop_class` for use in
*GuiPy*.
All plot properties must be registered with this function in order to be
used.
Parameters
----------
plot_prop_class : :class:`~guipy.plugins.figure.widgets.types... | 5,322,864 |
def flatten_dic(dic):
"""
Flatten dictionnary with nested keys into a single level : usable in a dataframe
Args:
dic -- a dictionnary
Returns:
out -- the flatenned dictionnary (df(out) is a Series)
"""
out = {}
def flatten(x, name=""):
"""
Rec... | 5,322,865 |
def policy_eval(policy, env, discount_factor=1.0, epsilon=0.00001):
"""
Evaluate a policy given an environment and a full description of the environment's dynamics.
Args:
policy: [S, A] shaped matrix representing the policy.
env: OpenAI env. env.P represents the transition probabilities... | 5,322,866 |
def split_data_target(element, device, logger=None):
"""Split elements in dataloader according to pre-defined rules."""
if not (isinstance(element, list) or isinstance(element, tuple)):
msg = (
"Invalid dataloader, please check if the input dataloder is valid."
)
if logger:
... | 5,322,867 |
def get_dataset_access_list(dataset: str, access_type: str) -> List[str]:
"""Get the comma-separated list of members of a dataset's {access_type} group."""
deploy_config = get_deploy_config()
membership_key = f"{dataset}-{access_type}-members-cache"
group_membership = deploy_config.read_dataset_config(d... | 5,322,868 |
def deploy_whitelist_to_constraints(
deploy_whitelist: DeployWhitelist,
) -> List[Constraint]:
"""Converts a whitelist of locations into marathon appropriate constraints
https://mesosphere.github.io/marathon/docs/constraints.html#like-operator
:param deploy_whitelist: List of lists of locations to whi... | 5,322,869 |
def _load_activity_data(engine: NeighborlyEngine, data: List[Dict[str, Any]]) -> None:
"""Process data related to defining activities"""
for activity in data:
register_activity(Activity(activity["name"], trait_names=activity["traits"])) | 5,322,870 |
def coerce_types(T1, T2):
"""Coerce types T1 and T2 to a common type.
Coercion is performed according to this table, where "N/A" means
that a TypeError exception is raised.
+----------+-----------+-----------+-----------+----------+
| | int | Fraction | Decimal | float |
+... | 5,322,871 |
def read_vecstim_protocol(protocol_name, protocol_definition, recordings, syn_locs):
"""Read Vecstim protocol from definitions.
Args:
protocol_name (str): name of the protocol
protocol_definition (dict): dict containing the protocol data
recordings (bluepyopt.ephys.recordings.CompRecord... | 5,322,872 |
def get_pair_elements(pair: str) -> Tuple[str, str, str]:
"""
Get a currency pair's base, quote, and trade base pair.
Eg. If the global trade base is 'USDT' and the pair is 'BTC-ETH', returns ('BTC', 'ETH', 'USDT-BTC').
Arguments:
pair: The currency pair eg. 'BTC-ETH'
Returns:
A... | 5,322,873 |
def create_app(**kwargs):
"""
Entry point to the Flask RESTful Server application.
"""
# Initialize the Flas-App
app: Flask = Flask(__name__, **kwargs)
# Load the config file
app.config.from_object('config.DevelopmentConfig')
# Initialize the API extensions
from . import extension... | 5,322,874 |
def GetCoastalDpaZones(kml_path=None):
"""Gets Coastal DPA zones.
Coastal DPA zones are Dynamic Protection Area monitored through the use of
ESC sensors.
Args:
kml_path: Optional path to the Coastal DPA KML. If unspecified, use the
default one from the `data/ntia/` folder.
Returns:
A dict of ... | 5,322,875 |
def dy4(vector, g, m1, m2, L1, L2):
"""
Abbreviations
M = m0 + m1
S = sin(y1 - y2)
C = cos(y1 - y2)
s1 = sin(y1)
s2 = sin(y2)
Equation
y4' = g*M*[s2 - s1*C] - S*[M * L1 * y3^2 + C * m2 * L2 * y4^2]
-------------------------------------------------------------
... | 5,322,876 |
def test_config_rpi4_fixed_pci_mmconfig_base(tmpdir):
""" Tests that rpi4_fixed_pci_mmconfig_base creates the expected configuration"""
os.chdir(tmpdir)
shutil.copytree(
Path(project_folder) / "rpi4_fixed_pci_mmconfig_base",
"rpi4_fixed_pci_mmconfig_base",
)
os.chdir("rpi4_fixed_pci... | 5,322,877 |
def test_sp_mp2_rohf_ae_error(mtd, opts, errmsg, nh2):
"""cfour/???/input.dat
#! single point MP2/qz2p on water
"""
nh2 = qcdb.set_molecule(nh2)
qcdb.set_options(opts)
with pytest.raises(qcng.exceptions.InputError) as e:
qcdb.gradient(mtd, molecule=nh2)
assert errmsg in str(e.valu... | 5,322,878 |
def sort_dict(od, d):
"""Sort parameters (same order as xsd:sequence)"""
if isinstance(od, dict):
ret = OrderedDict()
for k in od.keys():
v = d.get(k)
# don't append null tags!
if v is not None:
if isinstance(v, dict):
v = s... | 5,322,879 |
def _center_cmap(cmap, vmin, vmax, name="cmap_centered"):
"""
Center given colormap (ranging from vmin to vmax) at value 0.
Taken from MNE-Python v0.24, as it will be removed in MNE-Python v1.0.
Parameters
----------
cmap : matplotlib.colors.Colormap
The colormap to center around 0.
... | 5,322,880 |
def cli_predict(features_file, model_file):
"""Prediction CLI entry point."""
X_predict = data.load(features_file)
features_no_click_id = [c for c in X_predict.columns if c != 'click_id']
model = data.persist_load(model_file)
logging.info("Computing the predicted probabilities...")
y_predict = m... | 5,322,881 |
def port_number(worker_id):
"""A fixture that returns a different port for each parallel worker."""
i = 0
if worker_id != "master":
i = int("".join([c for c in worker_id if c.isdigit()]))
return PORTS[i] | 5,322,882 |
def get_loss_f(**kwargs_parse):
"""Return the loss function given the argparse arguments."""
return Loss(lamlSum=kwargs_parse["lamlSum"],
lamhSum=kwargs_parse["lamhSum"],
lamL2norm=kwargs_parse["lamL2norm"],
lamCMF=kwargs_parse["lamCMF"],
lamConv=k... | 5,322,883 |
def assert_greater_equal_v2(x, y, message=None, summarize=None, name=None):
"""Assert the condition `x >= y` holds element-wise.
This Op checks that `x[i] >= y[i]` holds for every pair of (possibly
broadcast) elements of `x` and `y`. If both `x` and `y` are empty, this is
trivially satisfied.
If `x` is not ... | 5,322,884 |
def pad_ends(
sequence, pad_left=True, left_pad_symbol="<s>", right_pad_symbol="</s>"
):
"""
Pad sentence ends with start- and end-of-sentence tokens
In speech recognition, it is important to predict the end of sentence
and use the start of sentence to condition predictions. Typically this
is d... | 5,322,885 |
def _create_checkpoint(weights_and_biases, global_step, model_dir):
"""Create checkpoint file with provided model weights.
Args:
weights_and_biases: Iterable of tuples of weight and bias values.
global_step: Initial global step to save in checkpoint.
model_dir: Directory into which checkpoint is saved.... | 5,322,886 |
def generate_png(dot_filename=None):
"""
$ dot -T png -o netpredictions.png firefox_fc/netpredictions.dot
"""
if dot_filename is not None:
png_filename = '{0}.png'.format(os.path.splitext(dot_filename)[0])
os.system('dot -Tpng -o {0} {1}'.format(png_filename, dot_filename)) | 5,322,887 |
def test_atomic_unsigned_short_enumeration_3_nistxml_sv_iv_atomic_unsigned_short_enumeration_4_1(mode, save_output, output_format):
"""
Type atomic/unsignedShort is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/unsignedShort/Schema+Instance/NISTSchema-SV-IV-atomic... | 5,322,888 |
def test_get_well_position_with_bottom_offset(
decoy: Decoy,
well_plate_def: LabwareDefinition,
standard_deck_def: DeckDefinitionV2,
labware_store: LabwareStore,
geometry_store: GeometryStore,
) -> None:
"""It should be able to get the position of a well top in a labware."""
labware_data = L... | 5,322,889 |
def client():
""" Create a client with authentication settings. """
cfg = get_config()
url = f"ldap://{cfg['SERVER']['hostname']}:{cfg['SERVER']['port']}"
client = LDAPClient(url)
client.set_credentials(
"SIMPLE", user=cfg["SIMPLEAUTH"]["user"], password=cfg["SIMPLEAUTH"]["password"]
)
... | 5,322,890 |
def _check_and_fire_deploy(job):
"""
Validates pre-conditions for deploy (hook status returned successfully)
and triggers deploy for enabled deployers.
:param job: Dictionary containing job parameters
:return: job or AsyncResult
"""
# Check and fires deploy
job_id = job['meta-info']['jo... | 5,322,891 |
def DownloadCompletePrinter(unused_response, unused_download):
"""Print information about a completed download."""
print('Download complete') | 5,322,892 |
def mark_errors_flipping(events):
"""
Marks error fractions
"""
single_errors = np.zeros(len(events) - 1)
double_errors = np.zeros(len(events) - 2)
for i in range(len(events) - 1):
# A single error is associated with a qubit error
if events[i] == events[i + 1]:
singl... | 5,322,893 |
def split_with_minimum_rt_distance(rts, min_rt_delta=0, random_state=None):
"""
Sample from a set ot retention times, so that the sampled rts have a
minimum rt differences.
:param rts:
:param min_rt_delta:
:param random_state:
:return:
"""
# if min_rt_delta == 0:
# return li... | 5,322,894 |
def create_proxy_model(name, model_mixins, base_model, attrs=None, module=None):
"""
Create a Django Proxy Model on the fly, to be used by any Cascade Plugin.
"""
from django.apps import apps
class Meta:
proxy = True
app_label = 'cmsplugin_cascade'
name = str(name + 'Model')
... | 5,322,895 |
def get_embed_video_model():
"""
Get the embed video model from the ``WAGTAILEMBEDVIDEOS_EMBEDVIDEO_MODEL`` setting.
Useful for developers making Wagtail plugins that need the embed video model.
Defaults to the standard :class:`~wagtail_embed_videos.models.EmbedVideo` model
if no custom model is def... | 5,322,896 |
def get_filetypes(key='type'):
"""Gets the list of possible filetypes from the filetype table
Parameters
----------
key : {'type', 'filetype_id'}, optional
Defaults to "type". Determines the format of the returned dict.
Returns
-------
dict
If `key` is "type", dict is of th... | 5,322,897 |
def check_templates_exist(pages):
"""Checks that all templates exist, raises FileNotFoundError if missing"""
for page in pages:
if "template" in page.page_vars:
template_path = os.path.join(".", "templates",
page.page_vars["template"])
if not os.pa... | 5,322,898 |
def make_dataloader(folder_names, data_path, batch_size, task, isTrain = False):
"""This function takes in a list of folders with images in them,
the root directory of these images, and a batchsize and turns them into a dataloader"""
# added flag isTrain - only augment/transform training set, not validation... | 5,322,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.