content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def make_pkg(pkgname, context):
"""Create a new extension package.
:param pkgname: Name of the package to create.
:param context: Mapping with keys that match the placeholders in the
templates.
:return: True if package creation succeeded or a tuple with False and an
e... | 36,800 |
def _save_custom_objects(path, custom_objects):
"""
Save custom objects dictionary to a cloudpickle file so a model can be easily loaded later.
:param path: An absolute path that points to the data directory within /path/to/model.
:param custom_objects: Keras ``custom_objects`` is a dictionary mapping
... | 36,801 |
def view_explorer_node(node_hash: str):
"""Build and send an induction query around the given node."""
node = manager.get_node_by_hash_or_404(node_hash)
query = manager.build_query_from_node(node)
return redirect_to_view_explorer_query(query) | 36,802 |
def shells_main():
"""The function pointed to by `bscan-shells` in console_scripts."""
sys.exit(cli_shells_main()) | 36,803 |
def encode_into_any_base(number, base, encoded_num):
"""Encode number into any base 2-36. Can be fractional or whole.
Parameters:
number: float -- integer representation of number (in base 10)
base: int -- base to convert to
encoded_num: str -- representation (so far) of number in base
... | 36,804 |
def handle_forbidden(error: Forbidden) -> Response:
"""Render the base 403 error page."""
return respond(error.description, status=HTTPStatus.FORBIDDEN) | 36,805 |
async def test_form_import_invalid_auth(hass):
"""Test we handle invalid auth on import."""
with patch(
"homeassistant.components.kodi.config_flow.Kodi.ping",
side_effect=InvalidAuthError,
), patch(
"homeassistant.components.kodi.config_flow.get_kodi_connection",
return_value... | 36,806 |
def getval(l, b, map='sfd', size=None, order=1):
"""Return SFD at the Galactic coordinates l, b.
Example usage:
h, w = 1000, 4000
b, l = numpy.mgrid[0:h,0:w]
l = 180.-(l+0.5) / float(w) * 360.
b = 90. - (b+0.5) / float(h) * 180.
ebv = dust.getval(l, b)
imshow(ebv, aspect='auto', norm=ma... | 36,807 |
def format_timedelta(tdelta):
"""Return the timedelta as a 'HH:mm:ss' string."""
total_seconds = int(tdelta.total_seconds())
hours, remainder = divmod(total_seconds, 60*60)
minutes, seconds = divmod(remainder, 60)
return "{0:02d}:{1:02d}:{2:02d}".format(hours, minutes, seconds) | 36,808 |
def test_add_with_set_input_extend():
"""Input is a set, not a string key with an extend."""
context = Context({
'arbset': {1, 2},
'add': {
'set': PyString('arbset'),
'addMe': 3
}})
add.run_step(context)
context['add']['addMe'] = [4, 5]
context['add'... | 36,809 |
def video_data_to_df(videos_entries, save_csv):
"""
Creating a dataframe from the video data stored as tuples
:param videos_entries: (list) list of tuples containing topics, subtopics, videos and durations
:param save_csv: (boolean) condition to specify if the df is saved locally as a csv file
:ret... | 36,810 |
def create_mysql_entitySet(username, databaseName):
""" Create a new entity set in the databaseName """
password = get_password(username)
entitySetName = request.json['entitySetName']
attributes = request.json['attributes']
addToSchema(request.get_json(),"mysql")
pks = []
sql = "CREATE TABLE... | 36,811 |
def test_symmetry_with_laue_group_override(dials_data, tmpdir):
"""Simple test to check that dials.symmetry, with overridden laue group, completes"""
result = procrunner.run(
[
"dials.symmetry",
"laue_group=P121",
"change_of_basis_op=-b,-a,-c",
dials_data... | 36,812 |
def m6(X, Y, Xp, Yp, alpha=1.0, prev='ident', post='ident', **kwargs):
"""Computes a matrix with the values of applying the kernel
:math:`m_4` between each pair of elements in :math:`X` and :math:`Y`.
Args:
X: Numpy matrix.
Y: Numpy matrix.
Xp: Numpy matrix with the probabilities of... | 36,813 |
def serve_communications_and_statuses(erpnext_support_user, erpnext_support_issues, bench_site):
"""
returns a dict of support issue communications and statuses
response = {
"issue_name_1": {
"communications": [],
"status": "status",
"last_sync_on": "last_sync_on"
},
"issue_name_2": {
"com... | 36,814 |
def answer_view(answerid):
"""route to view a specific answer"""
return jsonify({"answer":"Your updated answer: {} ".format(user_answers[answerid])}) | 36,815 |
def jwk_factory(acct_priv_key_path: str) -> _JWKBase:
"""generate jwk object according private key file"""
with open(acct_priv_key_path, 'rb') as f:
acct_priv = serialization.load_pem_private_key(
data=f.read(),
password=None,
backend=default_backend()
)
... | 36,816 |
def execute(
scan_definition: str | Path,
df: DataFrame,
*,
soda_server_client: SodaServerClient | None = None,
) -> ScanResult:
"""
Execute a scan on a data frame.
Parameters
----------
scan_definition : Union[str, Path]
The path to a scan file or the content of a scan file... | 36,817 |
def select_best_model(scouseobject):
"""
Selects the best model out of those fitted - that with the smallest aic
value
Parameters
----------
scouseobject : Instance of the scousepy class
"""
for key in scouseobject.indiv_dict.keys():
spectrum = scouseobject.indiv_dict[key]... | 36,818 |
def jaccard_similarity(emb1: np.ndarray, emb2: np.ndarray) -> float:
""" 计算特征向量的Jaccard系数
:param emb1: shape = [feature,]
:param emb2: shape = [feature,]
:return: Jaccard 系数
"""
up = np.double(np.bitwise_and((emb1 != emb2), np.bitwise_or(emb1 != 0, emb2 != 0)).sum())
down = np.double(np.bit... | 36,819 |
def check_job_order_correct(filename):
"""
1 -> 2 -> 3 ->
-> 4 ->
5 -> 6
"""
precedence_rules = [[1, 2],
[2, 3],
[1, 4],
[5, 6],
[3, 6],
... | 36,820 |
def test_list_nmtoken_max_length_nistxml_sv_iv_list_nmtoken_max_length_1_2(mode, save_output, output_format):
"""
Type list/NMTOKEN is restricted by facet maxLength with value 5.
"""
assert_bindings(
schema="nistData/list/NMTOKEN/Schema+Instance/NISTSchema-SV-IV-list-NMTOKEN-maxLength-1.xsd",
... | 36,821 |
def _share_secret_int_indices(s_i: int, n: int, t: int) -> Tuple[Dict[int, int], List[PointG1]]:
""" Computes n shares of a given secret such that at least t + 1 shares are required for recovery
of the secret. Additionally returns the commitents to the coefficient of the polynom
used to verify the ... | 36,822 |
def auto_type(key, redis=None, default=None, o=True):
"""Returns datatype instance"""
if redis is None:
redis = config.redis
key = compress_key(key)
if redis.exists(key):
datatype = redis.type(key)
if datatype == 'string':
test_string = RedisString(key, redis=red... | 36,823 |
def get_user_data_dir(app_name=DEFAULT_APP_NAME, auto_create=True) -> Path:
"""
Get platform specific data folder
"""
return _get_user_dir(
app_name=app_name,
xdg_env_var='XDG_DATA_HOME', win_env_var='APPDATA',
fallback='~/.local/share', win_fallback='~\\AppData\\Roaming', macos_... | 36,824 |
def unlink(annotation):
"""
Unlinks *annotation* from its neighbors in a doubly-linked list.
:param annotation: The annotation to unlink.
:type annotation: :class:`~gatenlphiltlab.Annotation`
"""
# if surrounded
if annotation.previous and annotation.next:
annotation.previous.next = ... | 36,825 |
def parse_evidence(
fixed_labels=None,
evidence_files=None,
molecules=None,
evidence_score_field=None,
return_raw_csv_data=False,
unimod_file_list=None,
):
"""
Reads in the evidence file and returns the final formatted fixed labels,
the evidence lookup, which is passed to the isotopo... | 36,826 |
def large_plants(plants):
"""
This function compares the values assigned to the key <"Max height"> to the average among all
the values assigned to <"Max height"> using the <avg_height()> function.
Parameters:
plants (list): list of dictionaries representing plants and their characteristics.
... | 36,827 |
def calculateDominantFrequency(signal, fs, fMin = 0, fMax = None, applyWindow = True,
fftZeroPaddingFactor = 1
):
"""
calculates the dominant frequency of the given signal
@param signal input signal
@param fs sampling frequency
@param fMin the minimum frequency [Hz] that should be considered
@param fMax the ma... | 36,828 |
def check_title(file_path):
"""
return 'has title' if found
no title, None, if not found
file_path is full path with file name and extension
"""
#print('is text file: ', tool.is_utf8_text_file(file_path))
if tool.is_utf8_text_file(file_path):
with open(file_path, 'r') as f:
... | 36,829 |
def permute_adjacency_twin(t1,t2) -> Tuple[torch.Tensor,torch.Tensor]:
"""
Makes a permutation of two adjacency matrices together. Equivalent to a renaming of the nodes.
Supposes shape (n,n)
"""
n,_ = t1.shape
perm = torch.randperm(n)
return t1[perm,:][:,perm],t2[perm,:][:,perm] | 36,830 |
def rad_extract(eventfiles,center,radius_function,return_cols=['PULSE_PHASE'],cuts=None,apply_GTI=True,theta_cut=66.4,zenith_cut=105,return_indices=False):
""" Extract events with a radial cut.
Return specified columns and perform additional boolean cuts.
Return is in form of a dictionary whose k... | 36,831 |
def save_collate_preds(collate_preds, collate_true):
"""Save the predictions of the slides to a csv when in eval mode.
"""
print(len(collate_preds) == len(collate_true))
print('Writing collate predictions to collate_preds.csv')
with open('collate_preds.csv', 'w') as f:
f.write('slide_ids, g... | 36,832 |
def _create_pdf(image_dir: str, output_dir: str, pdf_name: str) -> None:
"""Combine all downloaded images into a single PDF
Args:
image_dir (str): Directory containing the image files
output_dir (str): Directory where the output PDF should be saved
pdf_name (str): What to name the PDF
... | 36,833 |
def goggles():
"""
This function illustrates two glasses the bondage of goggles.
"""
# Outer glasses
right_outer_glasses = GOval(100, 100, x=415, y=180)
right_outer_glasses.filled = True
right_outer_glasses.fill_color = 'silver'
window.add(right_outer_glasses)
left_outer_glasses = G... | 36,834 |
def strtobool(value):
"""Cast a string to a bool."""
if value is None:
return None
if type(value) is bool:
return value
return distutils.util.strtobool(value) | 36,835 |
def init_lstm(input_lstm):
"""
Initialize lstm
"""
for ind in range(0, input_lstm.num_layers):
weight = eval('input_lstm.weight_ih_l'+str(ind))
bias = np.sqrt(6.0 / (weight.size(0)/4 + weight.size(1)))
nn.init.uniform(weight, -bias, bias)
weight = eval('input_lstm... | 36,836 |
def list_to_exp(str_list, term_padding_exp=r'\b', compile=True):
"""
Returns a regular expression (compiled or not) that will catch any of the strings of the str_list.
Each string of the str_list will be surrounded by term_padding_exp (default r'\b' forces full word matches).
Note: Also orders the strin... | 36,837 |
def prepare_ddp_loader(loader: DataLoader, num_processes: int, process_index: int) -> DataLoader:
"""
Transfers loader to distributed mode. Experimental feature.
Args:
loader: pytorch dataloder
num_processes (:obj:`int`, `optional`, defaults to 1):
The number of processes runnin... | 36,838 |
def __validate_exchange(value: str) -> str:
"""
Check to see if passed string is in the list of possible Exchanges.
:param value: Exchange name.
:return: Passed value or No Return
"""
valid_values = EXCHANGE_VALUES
if value in valid_values:
return value
else:
logging.erro... | 36,839 |
def main(content, title="", classes=[]):
"""Generate a 'Material for MkDocs' admonition.
"""
md = markdown.markdown(content)
return '<div class="admonition {0}">\n'.format(" ".join(classes)) + \
' <p class="admonition-title">{0}</p>\n'.format(title) + \
' <p>{0}</p>\n'.format... | 36,840 |
def get_bprop_matrix_set_diag(self):
"""Generate bprop for MatrixSetDiag"""
get_dtype = P.DType()
def bprop(x, y, z, out, dout):
input_shape = F.shape(x)
batch_shape = input_shape[:-2]
matrix_shape = input_shape[-2:]
diag_shape = batch_shape + (_get_min(matrix_shape),)
... | 36,841 |
def fake_sph_grid_ds(hsml_factor=1.0):
"""Returns an in-memory SPH dataset useful for testing
This dataset should have 27 particles with the particles arranged uniformly
on a 3D grid. The bottom left corner is (0.5,0.5,0.5) and the top right
corner is (2.5,2.5,2.5). All particles will have non-overlapp... | 36,842 |
def jobdict(program, jobname):
"""Usage: jobname
Print the jobdict for the named job.
"""
print(jobname)
for key, value in program.disco.jobpack(jobname).jobdict.items():
print("\t{0}\t{1}".format(key, value)) | 36,843 |
def test_custom_exception() -> None:
"""User-defined exception."""
class CustomError(Exception):
"""A custom exception."""
try:
raise CustomError("expr", "msg")
except CustomError as ce:
assert ce.args == ("expr", "msg") | 36,844 |
def ffplay_video(source: str, x: int = None, y: int = None, video_size: str = None,
pixel_format: str = None, fs: bool = False, an: bool = False,
vn: bool = False, sn: bool = False, f: str = None, s: str = None,
sync: str = None, ss: float = None, t: float = None, vf: ... | 36,845 |
async def _async_get_image_sessions(device: Device) -> dict[str, ImageSession]:
"""Return image events for the device."""
events = await device.event_media_manager.async_image_sessions()
return {e.event_token: e for e in events} | 36,846 |
def make_element_weight_parser(weight_column):
""" Parameterize with the column - this allows us
to generate data from different analysis result types.
"""
def parse_element_weight(csv_row):
name = csv_row[0]
weight = float(csv_row[weight_column]) # Assert not zero?
return name, weight
return parse_element... | 36,847 |
async def aio_aws_client(
service_name: str, *args, **kwargs
) -> aiobotocore.client.AioBaseClient:
"""
Yield an asyncio AWS client with an option to provide a client-specific config; this is a
thin wrapper on ``aiobotocore.session.get_session().create_client()`` and the additional
kwargs as passed ... | 36,848 |
def test_multiple_words(sro, syllabics):
"""
Test transcoding multiple words. The test inputs here can be trivially
converted back-and-forth.
"""
assert sro2syllabics(sro) == syllabics
assert syllabics2sro(syllabics) == sro | 36,849 |
def jitterer(out, z):
"""This function jitters the x axis
1: matrix of layer activations of the form:
2. which layer number to do
outputs a transposed matrix of no of neurons rows and no of data columns"""
Jx=np.ones(out[z].T.shape)
for i in range(out[z].T.shape[0]):
'this is the number... | 36,850 |
def deconstruct_full_path(filename: str) -> Tuple[str, str]:
"""
Returns a tuple with the parent folder of the file and the file's name.
Parameters
----------
filename : str
The path (with filename) that will be deconstructed.
Returns
-------
Tuple[str, str]
A tuple... | 36,851 |
def bbx_to_world(cords, vehicle):
"""
Convert bounding box coordinate at vehicle reference to world reference.
Parameters
----------
cords : np.ndarray
Bounding box coordinates with 8 vertices, shape (8, 4)
vehicle : opencda object
Opencda ObstacleVehicle.
Returns
-----... | 36,852 |
def load_data():
""" Loading data and padding """
training_set, testing_set = imdb.load_data(num_words = 10000)
x_train, y_train = training_set
x_test, y_test = testing_set
x_train_padded = sequence.pad_sequences(x_train, maxlen = 100)
x_test_padded = sequence.pad_sequences(x_test, maxlen = 100)... | 36,853 |
def poor_joke_validator(joke):
"""Responds with a 'HAHA' which means the user's wish wasn't grantedor else says 'Granted' """
pass | 36,854 |
def rotate_to_calibrated_axis(
data: np.ndarray, ref_val_0: complex, ref_val_1: complex
) -> np.ndarray:
"""
Rotates, normalizes and offsets complex valued data based on calibration points.
Parameters
----------
data
An array of complex valued data points.
ref_val_0
The refe... | 36,855 |
def filter_graph_data(df: pd.DataFrame, x_col: str, x_range: Optional[Tuple[int, int]], file_cols: List[str],
file_tuple: FileTuple) -> Optional[pd.DataFrame]:
"""
Filter data relevant for the graph from the dataframe.
:param df: The dataframe to filter
:param x_col: Name of the c... | 36,856 |
def test_srx_to_srp(sraweb_connection):
"""Test if srx is converted to srp correctly"""
df = sraweb_connection.srx_to_srp("SRX663254")
assert list(df["study_accession"]) == ["SRP044932"] | 36,857 |
def test_list_unsigned_short_max_length_3_nistxml_sv_iv_list_unsigned_short_max_length_4_1(mode, save_output, output_format):
"""
Type list/unsignedShort is restricted by facet maxLength with value 8.
"""
assert_bindings(
schema="nistData/list/unsignedShort/Schema+Instance/NISTSchema-SV-IV-list-... | 36,858 |
def get_question_summary_from_model(question_summary_model):
"""Returns a domain object for an Oppia question summary given a
question summary model.
Args:
question_summary_model: QuestionSummaryModel. The QuestionSummary model
object to fetch corresponding QuestionSummary domain object... | 36,859 |
async def test_full_recurring_schedule(event_loop: AbstractEventLoop) -> None:
"""Test full recurring SwitcherV2Schedule object."""
schedule = SwitcherV2Schedule(
event_loop, 0, [unhexlify(DUMMY_FULL_RECCURING_SCHEDULE_DATA)]
)
await wait([schedule.init_future])
assert schedule.sch... | 36,860 |
def processLine(line):
"""Process a single line of input, returning a single line of output as a string.
Input on stdin is
<input path>\t<output fmt>\t<aligner>\t<fiducials>\t<output parameters>
where:
- <input path> is a local path of the input image to align (not a url),
- <output fmt>... | 36,861 |
def main() -> None:
"""Extends index.yaml file."""
with open(INDEX_YAML_PATH, 'r', encoding='utf-8') as f:
index_yaml_dict = yaml.safe_load(f)
with open(WEB_INF_INDEX_YAML_PATH, 'r', encoding='utf-8') as f:
web_inf_index_yaml_dict = yaml.safe_load(f)
if web_inf_index_yaml_dict['indexes'... | 36,862 |
def refraction(alt_degrees, temperature_C, pressure_mbar):
"""Given an observed altitude, return how much the image is refracted.
Zero refraction is returned both for objects very near the zenith,
as well as for objects more than one degree below the horizon.
"""
r = 0.016667 / tan((alt_degrees + ... | 36,863 |
def reduce_mem_usage(df):
"""
iterate through all the columns of a dataframe and modify the data type to reduce memory usage.
"""
start_mem = df.memory_usage().sum() / 1024**2
logger.info('Memory usage of dataframe is {:.2f} MB'.format(start_mem))
for col in df.columns:
col... | 36,864 |
def retry_pattern():
"""Retry pattern decorator used when connecting to snowflake
"""
return backoff.on_exception(backoff.expo,
snowflake.connector.errors.OperationalError,
max_tries=5,
on_backoff=log_backoff_att... | 36,865 |
def get_vrf_route_targets(
device, address_family, rt_type, vrf=None, route_distinguisher=None
):
""" Get route target value from a device
Args:
address_family ('str'): address family value
rt_type ('str'): route target type
ex.) rt_type = 'import' OR
... | 36,866 |
async def create(ctx, name, *, message):
"""Creates a B* tag with your code"""
# try:
createTag(ctx.author, name, message)
await ctx.send(f"Tag `{name}` created!")
# except:
# await ctx.send("Tag creation failed") | 36,867 |
def test_order_asc():
"""order works with asc"""
col = Column("foo", str).asc()
expr = Order(col)
assert str(expr) == "| order by\n\tfoo asc" | 36,868 |
def privGetElevationLocs(locs, dataProvider, dataProviderArgs):
"""
FIXME
"""
try:
dataProvider = dataProvider.lower()
except:
pass
# NOTE: Neither mapquest, pgRouting, nor OSRM are supported.
# FIXME -- None is not allowed
if (elevDataProviderDictionary[dataProvider] == 'ors-online'):
locsWithA... | 36,869 |
def _format_field(value, parts, conv, spec, want_bytes=False):
"""Format a replacement field."""
for k, part, _ in parts:
if k:
if part.isdigit():
value = value[int(part)]
else:
value = value[part]
else:
value = getattr(value, p... | 36,870 |
def set_powerups(*args, **kwargs): # real signature unknown
""" Sets a player's powerups. """
pass | 36,871 |
def mixed_string_list_one_valid():
"""Return mixed strings."""
return _MIXED_STRING_LISTS_ONE_VALID_ | 36,872 |
def generate_project(project):
"""for generating a format project"""
directory = os.getcwd()
template_dir = TEMPLATES_PATH
# error if
if not re.search(r'^[A-Z]\w*$', project):
print 'Error: Project names must begin with a capital letter. \
\nand contain only letters, numbers an... | 36,873 |
def test_retry_connect():
"""Test retry_connect.""" | 36,874 |
def deployments_update(deployment_name, new_name, default_version, yaml_file, quiet):
"""
Update a deployment.
If you only want to update the name of the deployment or the default deployment version,
use the options `<new_name>` and `<default_version>`.
If you want to update the deployment input/ou... | 36,875 |
def log_mlflow(gv, args):
"""Log data into MLFlow."""
import mlflow
mlflow.log_params(vars(args))
gv.keep("train_loss", "test_loss", "correct") >> mlflow.log_metrics | 36,876 |
def make_parser():
"""Create the argument parser, derived from the general scripts parser."""
parser = get_parser(
__doc__,
('A file containing a list of files/file paths to be read. These '
'should be nxml or txt files.')
)
parser.add_argument(
dest='output_name',
... | 36,877 |
def script_names():
"""Returns the sequence of example script names."""
result = [str(pathlib.Path(s).with_suffix('.py')) for s in _stem_names()]
return result | 36,878 |
def service_event_log(
simulated_log: alarms.Manager, active_log_events: mcu_pb.ActiveLogEvents,
simulated_log_receiver: lists.ReceiveSynchronizer[mcu_pb.LogEvent]
) -> None:
"""Output outstanding events."""
result = simulated_log.output()
if result is None:
return
simulated_log_receive... | 36,879 |
def test_convert_output_type_nornir(runner):
"""
Test that the motherstarter convert outputs nornir
files to the correct location.
Args:
runner: The runner which simulates command-line
inputs, replicating an end user.
Returns:
N/A
Raises:
N/A
"""
# Assi... | 36,880 |
def lovasz_grad(gt_sorted):
"""
Computes gradient of the Lovasz extension w.r.t sorted errors
See Alg. 1 in paper
"""
p = len(gt_sorted)
gts = gt_sorted.sum()
intersection = gts - gt_sorted.float().cumsum(0)
union = gts + (1 - gt_sorted).float().cumsum(0)
jaccard = 1. - intersection ... | 36,881 |
def expand_image(_img, block, stride, deform=True):
"""
Args:
_img: numpy array
block: size of the blocks required
stride: step size
Returns: array of blocks
"""
if deform:
_img=_img.astype('float32')
ims_Z=np.zeros([_img.shape[0],block[1],block[0]... | 36,882 |
def hubstatus_cli(hub, eater_name, color):
"""
A dumpling eater.
Connects to nd-hub (the dumpling hub) and continually prints summary status
information from any SystemStatusChef dumplings. This is a system
monitoring dumpling eater which can be used to keep an eye on nd-hub.
"""
global PRI... | 36,883 |
def test_convert_fueltypes_sectors_ktoe_gwh():
"""Testing function
"""
in_value = {'enduse': {'sector': np.zeros((2))}}
in_value['enduse']['sector'][0] = 10
in_value['enduse']['sector'][1] = 20
expected = {'enduse': {'sector': np.zeros((2))}}
expected['enduse']['sector'][0] = 10 * 11.630000... | 36,884 |
def disabled(reason='No reason given'):
"""Decorator that disables a command."""
# pylint:disable=missing-docstring,unused-argument
def actual_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
raise DisabledCommandException('This command is disabled: %s' % reason)
... | 36,885 |
def get_tensor_model_parallel_group():
"""Get the tensor model parallel group the caller rank belongs to."""
assert _TENSOR_MODEL_PARALLEL_GROUP is not None, \
'intra_layer_model parallel group is not initialized'
return _TENSOR_MODEL_PARALLEL_GROUP | 36,886 |
async def test_form_errors_get_info(hass, error):
"""Test we handle errors."""
exc, base_error = error
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"aioshelly.get_info", side_effect=exc,
):
resul... | 36,887 |
def normalize(data):
"""Normalizes the values of incoming data
Args:
data (dict): Dictionary of response data
Returns:
dict
"""
normalized_data = {}
for key in data:
value = str(data[key])
key = key.lower()
# Strip all fields and reduce multiple space... | 36,888 |
def five_fold(data_set):
"""[summary]
Args:
data_set (List of Sample objects): The Samples to be partitioned
Returns:
fold: where fold is list of len n in n-fold of (train,test) where train and test are lists of Samples
"""
partition_index = int( len(data_set) / 5 )
s = 0
fol... | 36,889 |
def test(n=10):
""" Demo multiplication of two square matrices of given dimension 'n' """
print('Making two random square matrices of dimension',n,'...')
m1 = MatrixFactory.makeRandom(n, n)
m2 = MatrixFactory.makeRandom(n, n)
print(m1)
print(m2)
m3 = m1*m2
print(m3) | 36,890 |
def train(p_number, params, shared_net, optimizer, frames, episodes, steps=20):
"""Train function used for Multiprocessing"""
################### train function ######################
torch.manual_seed(params.seed + p_number)
env = create_atari(params)
env.unwrapped.seed(params.seed + p_number)
... | 36,891 |
async def listen_and_arbitrate(isTest, backend):
"""Listens for bounties & vote reveals to establish ground truth"""
if not check_address(address):
# Always exit. Unusable with a bad address
fatal_error(True, "Invalid address %s" % address, 7)
scheduler = SchedulerQueue()
scanner = back... | 36,892 |
def _query_trembl(accessions: List[str], format: str) -> str:
"""Searches TrEMBL server for UniProt entries based on accession.
The server to use is set as an environment variable 'TREMBL_SERVER'.
Normally this would be the internal TrEMBL server which contains the most
up-to-date version of the databa... | 36,893 |
def simple_broken_app_client() -> FlaskClient:
"""Create client for demo Flask app that fails internally."""
handle_spec = HandleSpec(
failing_func,
'/fail'
)
app = create_app([handle_spec])
client = app.test_client()
yield client | 36,894 |
def get_english_info(content_section):
"""
The english source section can have multiple publishers and volume counts. The criteria is that
the publisher with the largest volume count is most likely the one we want so sort the lines in
the section and grab data from the first line.
"""
english_s... | 36,895 |
def test_format_error_message():
"""
Test ``format_error_message``.
"""
assert format_error_message([]) == ""
response = {
"version": "0.6",
"reqId": "0",
"status": "error",
"errors": [
{
"reason": "invalid_query",
"message"... | 36,896 |
def load_factual_vec(fname, vocab, k):
"""
Loads 300x1 word vecs from FACTBANK compiled word embeddings
"""
word_vecs = {}
with open(fname, "rb") as f:
header = f.readline()
vocab_size, layer1_size = map(int, header.split())
binary_len = numpy.dtype('float32').itemsize * la... | 36,897 |
def vaccine(date):
"""
Auxiliary function.
Download data about vaccination in Cantabria from the Ministry of Health, Consumer Affairs and Social Welfare.
https://www.mscbs.gob.es
Args:
date(str): Date in format %Y%m%d
Returns: DataFrame with vaccination data from first day (2021... | 36,898 |
def cache(f):
"""A decorator to cache results for a given function call.
Note: The caching is only done on the first argument, usually "self".
"""
ret = {}
def _Wrapper(*args, **kwargs):
self = args[0]
if self not in ret:
ret[self] = f(*args, **kwargs)
return ret... | 36,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.