content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_oneof_io_formats_deserialize_as_mapping():
"""
Evaluates ``oneOf`` deserialization for inputs/outputs CWL definition specified as key-mapping of objects.
Should work simultaneously with the listing variation using the same deserializer.
.. seealso::
- :func:`test_cwl_deploy_io_deseria... | 41,100 |
def visit_children_first(graph_head, visitor):
"""
:type graph_head: DecisionGraphNode
:param visitor: Visitor
:return:
"""
todo = deque()
todo.append(graph_head)
todo_set = {graph_head}
results = {}
while len(todo) != 0:
node = todo.pop()
todo_set.remove(node)... | 41,101 |
def random_transform(x, seed=None):
"""Randomly augment a single image tensor.
# Arguments
x: 3D tensor, single image.
seed: random seed.
# Returns
A randomly transformed version of the input (same shape).
"""
np.random.seed(seed)
img_row_axis = 0
img_col_axis = 1
... | 41,102 |
def process_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
if argv is None:
argv = sys.argv[1:]
# initialize the parser object, replace the description
parser = argparse.ArgumentParser(
... | 41,103 |
def global_avg_pooling_forward(z):
"""
全局平均池化前向过程
:param z: 卷积层矩阵,形状(N,C,H,W),N为batch_size,C为通道数
:return:
"""
return np.mean(np.mean(z, axis=-1), axis=-1) | 41,104 |
def test_api_base_url_with_ip_port(hass):
"""Test setting api url."""
result = yield from async_setup_component(hass, 'http', {
'http': {
'base_url': '1.1.1.1:8124'
}
})
assert result
assert hass.config.api.base_url == 'http://1.1.1.1:8124' | 41,105 |
def s3_download_specific_or_default(s3: boto3.resources, bucket: str, plan: str, branch: str,
hostname: str, port: int, username: str,
default_branch: str = DEVELOP_BRANCH) -> None:
"""
Downloads build artifact for specific plan and branch ... | 41,106 |
def find_local_term(match_text: SearchText, service: OntologyService) -> Optional[ConditionMatchingSuggestion]:
"""
Note that local search is pretty dumb, uses SearchText which already simplifies a bunch of words
Code looks through local database, erring of false positives, then uses search_text_to_suggesti... | 41,107 |
def label_encoder(adata):
"""
Encode labels of Annotated `adata` matrix using sklearn.preprocessing.LabelEncoder class.
Parameters
----------
adata: `~anndata.AnnData`
Annotated data matrix.
Returns
-------
labels: numpy nd-array
Array of encoded labels
"""
le = ... | 41,108 |
def put_method_response(restApiId=None, resourceId=None, httpMethod=None, statusCode=None, responseParameters=None, responseModels=None):
"""
Adds a MethodResponse to an existing Method resource.
See also: AWS API Documentation
Exceptions
:example: response = client.put_method_response(
... | 41,109 |
def is_plus_or_minus(token_type: TokenType) -> bool:
"""Check if token is a plus or minus."""
return is_plus(token_type) or is_minus(token_type) | 41,110 |
def gen_data(test_size=TEST_SIZE, channels=CHANNELS,
width=WIDTH, height=HEIGHT,
mmean=0, vmean=1, channel_last=False, fc_output=False):
"""
Generate random data to pass through the layer
NOTE:
- The generated data should not be normal, so that the layer can try to
... | 41,111 |
def test_cookiecutter_template_cleanup(change_dir_main_fixtures, mocker):
"""Verify temporary folder for zip unpacking dropped."""
mocker.patch('tempfile.mkdtemp', return_value='fake-tmp', autospec=True)
mocker.patch(
'tackle.utils.prompts.prompt_and_delete',
return_value=True,
auto... | 41,112 |
def plot_r2_pvalues(
model: mofa_model,
factors: Union[int, List[int], str, List[str]] = None,
n_iter: int = 100,
groups_df: pd.DataFrame = None,
group_label: str = None,
view=0,
fdr: bool = True,
cmap="binary_r",
**kwargs,
):
"""
Plot R2 values for the model
Parameters
... | 41,113 |
def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None,
pred_labels=None, title=None, normalize=False,
hide_zeros=False, x_tick_rotation=0, ax=None,
figsize=None, cmap='Blues', title_fontsize="large",
... | 41,114 |
def dump(value, fp, *custom_encoders):
"""
Serialize `value` to BINN format and saves bytes to stream `fp`
"""
BINNEncoder(fp, *custom_encoders).encode(value) | 41,115 |
def backup_program(past_moves, steps):
"""
:return:
"""
last_entry = -1
while node_info[steps][0] is False and node_info[steps][1] is False and node_info[steps][2] is False:
print("-----INSIDE THE BACKUP LOOP-------")
print("This is the past moves list:", past_moves)
print("... | 41,116 |
def _check_lfs_hook(client, paths):
"""Pull the specified paths from external storage."""
return client.check_requires_tracking(*paths) | 41,117 |
def update():
"""
Processes update, fetching data from the router and writing to the database
Returns:
None:
"""
_logger.info("Writing update")
write_update(parse_update(fetch_router_data())) | 41,118 |
def write_categories_table():
"""Write the categories to the database.
Because the database does not ship with the categories, this function writes the categories in.
This is accessed via the <siteURL>/initial_setup link.
"""
# Delete the contents of the lists of programs and categories... | 41,119 |
def parse_args():
"""Parse the input argument of the program"""
parser = argparse.ArgumentParser(
description='Process FAQ template files to create the FAQ.')
parser.add_argument('-i', '--input', required=True, metavar='I', nargs='+',
help='FAQ files parsed')
parser.add_... | 41,120 |
def name_to_zamid(name):
"""Converts a nuclide's name into the nuclide's z-a-m id.
Parameters
----------
name: str
Name of a nuclide
"""
dic = d.nuc_name_dic
elt_name = name.split('-')[0]
na = int(name.split('-')[1].replace('*',''))
if '*' in name:
state = 1
... | 41,121 |
def sample_category(name):
"""Create and return a sample category"""
return models.Category.objects.create(name=name) | 41,122 |
def GetAllRunningAUProcess():
"""Get all the ongoing AU processes' pids from tracking logs.
This func only checks the tracking logs generated in latest several hours,
which is for avoiding the case that 'there's a running process whose id is
as the same as a previous AU process'.
Returns:
A list of back... | 41,123 |
def get_installed_app_locale_path(appname):
"""
Load the app given by appname and return its locale folder path, if it exists.
Note that the module is imported to determine its location.
"""
try:
m = importlib.import_module(appname)
module_path = os.path.dirname(m.__file__)
... | 41,124 |
def file_share_exists(ctx, filesvc, share_name):
"""
Checks if a File Share already exists
:rtype: `azure.storage.file.models.Share` or `None`
:returns: Azure File Share object if the File Share
exists or None if it does not
"""
ctx.logger.debug('Checking if File Share "{0}" exists'... | 41,125 |
def visual_fft_phase(fft, title='fft_phase'):
"""
:param fft:
:param title:
:return:
"""
# centralize
central_f = np.fft.fftshift(fft)
real_f = np.real(central_f)
imag_f = np.imag(central_f)
phase_f = np.arctan2(imag_f, real_f)
# convert scale to (0, 255)
min = np.min(ph... | 41,126 |
def test_patch_account_with_data_well_formatted_returning_200_status_code(client, session, auth):
"""
GIVEN a Flask application
WHEN the '/account' URL is requested (PATCH)
THEN check the response is valid
"""
user = create_user(session)
tokens = create_tokens(user.username)
endpoint = ... | 41,127 |
def plan_add(request):
"""
测试计划添加
:param request:
:return:
"""
user_id = request.session.get('user_id', '')
if not get_user(user_id):
request.session['login_from'] = '/base/plan/'
return HttpResponseRedirect('/login/')
else:
if request.method == 'POST':
... | 41,128 |
def visualizar_imagen(imagen: list) -> None:
""" Muestra la imagen recibida
Parámetros:
imagen (list) Matriz (M,N,3) con la imagen a visualizar.
"""
plt.imshow(imagen)
plt.show() | 41,129 |
def get_dftd3_energy(ipt):
""" Grimme's D3 correction to energy """
fxyz, func, iabc = ipt
sabc = ' -abc' if iabc else ''
cmd = "dftd3 %s -func %s -bj%s | grep Edisp | awk '{print $NF}'"%(fxyz,func,sabc)
#print(cmd) #; sys.exit(2)
e = eval(os.popen(cmd).read().strip())
return e | 41,130 |
def get_state_vect_cols(prefix=''):
"""Get the column names of the state vector components with the
provided `prefix`.
:param prefix: The prefix that is used in front of the state vector
components in the column names, examples are `physics_pred` and
`physics_err` or none
:type prefix: ... | 41,131 |
def set_df_index(typingctx, df_t, index_t=None):
"""used in very limited cases like distributed to_csv() to create a new
dataframe with index
"""
# TODO: make inplace when dfs are full objects
def codegen(context, builder, signature, args):
in_df_arg = args[0]
index = args[1]
... | 41,132 |
def parse_options(options=None, api=False):
"""
Parse given option string
:param options:
:type options:
:param api
:type api: boolean
:return:
:rtype:
"""
if isinstance(options, six.string_types):
args = shlex.split(options)
options = vars(argument_parser.parse_... | 41,133 |
def data_for_column(column: dict, kwargs: dict, size: int) -> list:
"""Generates data for schema column
:param dict column: Column definition
:param dict kwargs: Faker keyword arguments
:param int size: Number of rows
:return: List of random data for a column
:rtype: list
"""
data = []... | 41,134 |
def peak_bin(peaks, i):
"""Return the (bin) index of the ith largest peak. Peaks is a list of tuples (i, x[i])
of peak indices i and values x[i], sorted in decreasing order by peak value."""
if len(peaks) > i:
return peaks[i][0]
else:
return np.nan | 41,135 |
def fetch_all(path, params=None, client=default_client):
"""
Args:
path (str): The path for which we want to retrieve all entries.
Returns:
list: All entries stored in database for a given model. You can add a
filter to the model name like this: "tasks?project_id=project-id"
"""... | 41,136 |
def plotter(fdict):
""" Go """
pgconn = get_dbconn('coop')
cursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor)
ctx = get_autoplot_context(fdict, get_description())
station = ctx['station']
table = "alldata_%s" % (station[:2],)
nt = NetworkTable("%sCLIMATE" % (station[:2],))
... | 41,137 |
def link_library_dynamic(hs, dep_info, object_files, my_pkg_id):
"""Link a dynamic library for the package using given object files.
Returns:
File: Produced dynamic library.
"""
dynamic_library = hs.actions.declare_file(
"lib{0}-ghc{1}.{2}".format(
pkg_id.library_name(hs, my_pkg_id),
hs.too... | 41,138 |
def save_mvgcca_latents_space(X, W, model, path, prefix, epochs):
"""Saves the list containing the common latent space Z and all the views latent space Z_m.
- X : [np.array(n x d1),...,np.array(n x dM)] multivews features ; n number of instances; dm dimension of views m ; M number of views
... | 41,139 |
def _CreateXMLFile(comment, parent_node_string, nodes, output_dir, filename):
"""Creates XML file for given type of XML nodes.
This function also creates a |parent_node_string| tag as the parent node, e.g.
<histograms> or <histogram_suffixes_list>, that wraps all the |nodes| in the
output XML.
Args:
com... | 41,140 |
def test_kafka_origin_csv_record_header_missmatch(sdc_builder, sdc_executor, cluster):
"""Write csv messages into Kafka and confirm that Kafka successfully reads them.
Test delimited data format with 2 records, the first one containing an extra, unexpected column.
We verify that the first one is sent to er... | 41,141 |
def TDC_sampling(in_channels, mode='downsampling'):
"""
wrapper_function: -> TIC_sampling
[B, in_channels, T, F] => [B, in_channels, T, F//2 or F*2]
in_channels: number of input channels
"""
return TIC_sampling(in_channels, mode) | 41,142 |
def bmxbm(s, t, batch_first=True):
"""
Batched matrix and batched matrix multiplication.
"""
if batch_first:
equation = "aij,ajk->aik"
else:
equation = "ija,jka->ika"
return tf.einsum(equation, s, t) | 41,143 |
def get_all_semantic_case_ids():
"""Get iterator over test sorted IDs of all cases in the SBML semantic
suite"""
pattern = re.compile(r'\d{5}')
return sorted(str(x.name) for x in SBML_SEMANTIC_CASES_DIR.iterdir()
if pattern.match(x.name)) | 41,144 |
def generate_points(n=500, min_=0, max_=1):
"""
Generate a list of n points.
Parameters
----------
n : int
min_ : float
max_ : float
Returns
-------
list
List of length n with tuples (x, y) where x is in [min_, max_] and
y is either 0 or 1.
"""
assert ma... | 41,145 |
def gce(nvf):
"""
Write the necessary code for launch the VNF using GCE
:param nvf:
:return: vagrantfile code
"""
element = Template(u'''\
config.vm.box = "{{image}}"
config.vm.provider :google do |google, override|
google.google_project_id = {{google_project_id}}
google.google_client_email = {... | 41,146 |
def filter_unique(iterable, container=None, key=None, add=None):
"""
Yield unique items from an iterable, omitting duplicates.
By default, to provide uniqueness, it puts the generated items into a
set created as a local variable. It only yields items which are not
already present in the local set.
... | 41,147 |
def test_restarted_node_catches_up_config_ledger_txns(looper,
some_config_txns_done,
txnPoolNodeSet,
sdk_wallet_client,
... | 41,148 |
def test_cloud_shell():
"""Cloud Shell environment: only MSI_ENDPOINT set"""
access_token = "AccessToken"
url = "http://localhost:42/token"
token_json = json.dumps({"access_token": access_token, "expires_on": int(time.time() + 3600)})
httpretty.register_uri(httpretty.POST, url, body=token_json, co... | 41,149 |
def build_covid_report_detailed(directory='pdf_reports', destination='mobility_report.csv', report_type='regions'):
"""
Build report in CSV format
directory - path of downloaded pdfs
destination - destination file of report
report_type: 'regions', 'US'
"""
if os.path.isfile('codes.csv'):
... | 41,150 |
def save_pretrained_models(
model: nn.Module,
config: DictConfig,
path: str,
) -> DictConfig:
"""
Save the pretrained models and configs to local to make future loading not dependent on Internet access.
By loading local checkpoints, Huggingface doesn't need to download pretrained che... | 41,151 |
def get_ethpm_birth_block(
w3: Web3, from_block: int, to_block: int, target_timestamp: int
) -> int:
"""
Returns the closest block found before the target_timestamp
"""
version_release_date = datetime.fromtimestamp(target_timestamp)
while from_block < to_block:
mid = BlockNumber((from_b... | 41,152 |
def test_190806(prodtest):
"""Test that we can limit verification to tags."""
params = {
"wfo": "DMX",
"begints": "2012-06-20T12:00Z",
"endts": "2012-06-30T12:00Z",
"hailsize": 1.0,
}
res = client.get("/cow.json", params=params)
cow = res.json()
assert cow["stats... | 41,153 |
def Line(p0, p1=None, c="r", alpha=1, lw=1, dotted=False, res=None):
"""
Build the line segment between points `p0` and `p1`.
If `p0` is a list of points returns the line connecting them.
A 2D set of coords can also be passed as p0=[x..], p1=[y..].
:param c: color name, number, or list of [R,G,B] c... | 41,154 |
def date_dd(dataset, source):
"""Display 3 blocks: 1. image of the patent, 2. choice block, 3. text block for date. 2 is
artifical and should be ignored"""
def get_stream():
# Load the directory of images and add options to each task
stream = Images(source)
for eg in stream:
... | 41,155 |
def sort(array=[12,4,5,6,7,3,1,15]):
"""Sort the array by using quicksort."""
less = []
equal = []
greater = []
if len(array) > 1:
pivot = array[0]
for x in array:
if x < pivot:
less.append(x)
elif x == pivot:
equal.append(x)
... | 41,156 |
def _derive_country_JP(place):
"""Derive Japanese place names."""
derived = []
if _JP_FU_SUFFIX.search(place.asciiname):
bare = _JP_FU_SUFFIX.sub("", place.asciiname)
derived += [bare, bare + " prefecture", bare + " pref"]
elif _JP_KEN_SUFFIX.search(place.asciiname):
bare = _JP_K... | 41,157 |
def definitions(prefix: str, identifier: Optional[str], force: bool):
"""Page through the identifiers and definitions of entities in the given namespace."""
id_to_definition = get_id_definition_mapping(prefix, force=force)
if identifier is None:
_help_page_mapping(id_to_definition)
else:
... | 41,158 |
async def remove_completed_game(player_id: str, game_id: str) -> Optional[dict]:
"""
Updates the player's current games by removing a game from it.
:param player_id: the object id of the player
:param game_id: the object id of the game
:return: an awaitable resolving to the updated document, or No... | 41,159 |
def triangulate_dlt(Ps, ys):
"""Triangulate 3D position between two 2D correspondances using the direct
linear transformation (DLT) method.
If any 2D correspondance is missing (i.e. NaN), returns triangulated
position as NaN value as well.
TODO: Normalize input data (see HZ, p104. "4.4 Transformat... | 41,160 |
def is_multioutput(y):
"""Whether the target y is multi-output (or multi-index)"""
return hasattr(y, "shape") and y.ndim == 2 and y.shape[1] > 1 | 41,161 |
def read_all(db: Session):
""" Get all dimensions.
:param db:
:return: List[QuestionModel]
"""
question = db.query(QuestionModel).all()
return question | 41,162 |
def test_orientation_point_plane_containing_origin():
"""Test the orientation_point_plane_containing_origin function.
This test takes the first two vectors of an orthogonal orientation matrix to
describe the plane which contains the origin. Afterwards, several
factors are multiplied with the normal vec... | 41,163 |
def on_connect(client, userdata, flags, rc, properties=None):
"""
Prints the result of the connection with a reasoncode to stdout ( used as callback for connect )
:param client: the client itself
:param userdata: userdata is set when initiating the client, here it is userdata=None
:... | 41,164 |
def p(myList):
"""Print a list of strings into columns."""
nbCols = 16
print(fmtcols(myList,nbCols)) | 41,165 |
def get_all_tenants(context):
"""Returns a list of all tenants stored in repository.
:param context: context of the transaction
"""
return context.session.query(db_models.AristaProvisionedProjects) | 41,166 |
def load_sample_nni(series='short'):
"""Returns a short-term (5min) or long-term (60min) series of sample NNI found in the pyhrv/files/ directory.
Docs:
Parameters
----------
series : string, optional
If 'long', returns a 60min NNI series, if 'short', returns a 5min NNI series
Returns
-------
nni_series ... | 41,167 |
def test_sigmoid_fn():
"""Test the sigmoid function"""
fn = Sigmoid()
nose.tools.assert_is_instance(fn, Function)
nose.tools.assert_is_instance(fn, Sigmoid)
nose.tools.assert_equal(fn.compute(0), 0.5)
nose.tools.assert_equal(fn.compute_derivative(0), 0.25) | 41,168 |
def total_sub_pixels_2d_from(mask_2d: np.ndarray, sub_size: int) -> int:
"""
Returns the total number of sub-pixels in unmasked pixels in a mask.
Parameters
----------
mask_2d : np.ndarray
A 2D array of bools, where `False` values are unmasked and included when counting sub pixels.
... | 41,169 |
def connectOutputLogger(file=None, logger_name='output'):
"""
Function that connects the output logger.
This is always enabled and hardwired to
generate logging.INFO level messages only.
@params file : Output file to store these messages into.
@default None : If file is None no output file gene... | 41,170 |
def formaldehyde_conformer(formaldehyde) -> torch.Tensor:
"""Returns a conformer [A] of formaldehyde with an ordering which matches the
``formaldehyde`` fixture."""
from simtk import unit as simtk_unit
formaldehyde.generate_conformers(n_conformers=1)
conformer = formaldehyde.conformers[0].value_in... | 41,171 |
def reduce_function(op_func, input_tensor, axis=None, keepdims=None,
name=None, reduction_indices=None):
"""
Handler function for Tensorflow depreciation of keep_dims for tf 1.8
and above, but tf 1.4 requires keep_dims
:param op_func: expects the function to handle eg: tf.reduce_sum.... | 41,172 |
def filter_dict(function_or_value, dict_to_filter):
"""
Filter by value
>>> filter_dict(123, {'a': 123, 'b': 1234})
{'b': 1234}
Filter by value not applicable
>>> filter_dict(123, {'a': 1234, 'b': 5123})
{'a': 1234, 'b': 5123}
Embedded filter by value
>>> filter_dict(123,... | 41,173 |
def _buy(config, client, machine_auth, resource, info_only=False, payment_method='offchain', header=(),
method='GET', output_file=None, data=None, data_file=None, maxprice=10000):
"""Purchase a 402-enabled resource via CLI.
This function attempts to purchase the requested resource using the
`payme... | 41,174 |
def resnet50(pretrained=False, **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
return model | 41,175 |
def irfft(x, res):
"""
:param x: tensor of shape [..., m]
:return: tensor of shape [..., alpha]
"""
assert res % 2 == 1
*size, sm = x.shape
x = x.reshape(-1, sm)
x = torch.cat([
x.new_zeros(x.shape[0], (res - sm) // 2),
x,
x.new_zeros(x.shape[0], (res - sm) // 2),... | 41,176 |
def _FinishParsing(options, args):
"""Perform some parsing tasks that need to take place after optparse.
This function needs to be easily testable! Keep it free of
environment-dependent code. Put more detailed usage validation in
_PostParseCheck().
Args:
options: The options object returned by optpars... | 41,177 |
def calc_ranks(idx, label, pred_score):
"""Calculating triples score ranks.
Args:
idx ([type]): The id of the entity to be predicted.
label ([type]): The id of existing triples, to calc filtered results.
pred_score ([type]): The score of the triple predicted by the model.
Returns:
... | 41,178 |
def GBT(trainingData, testData):
"""
Gradient Boosted Tree Regression Model
:param trainingData:
:param testData:
:return: Trained model, predictions
"""
gbt = GBTRegressor( maxIter=100, maxDepth=6, seed=42)
model = gbt.fit(trainingData)
predictions = model.transform(testData)
r... | 41,179 |
def createTable(doc, fields, tableName):
"""
Create table in Microsoft Access DataBase
Arguments:
doc: C:\\Route\\To\\FILE.accdb
fields: field1, field2, ... , fieldn (String of fields sep by commas)
tableName: Name of Table in Access
"""
odbc = 'DRIVER={Microsoft Access Driver (*.mdb, *... | 41,180 |
def synchronizuj_publikacje(
client,
force_upload=False,
only_bad=False,
only_new=False,
skip=0,
export_pk_zero=None,
delete_statements_before_upload=False,
):
"""
Komenda eksportująca wszystkie publikacje w systmeie, zaczynając od książek,
przez rozdziały, po wydawnictwa ciągłe.... | 41,181 |
def fromcolumns(cols, header=None, missing=None):
"""View a sequence of columns as a table, e.g.::
>>> import petl as etl
>>> cols = [[0, 1, 2], ['a', 'b', 'c']]
>>> tbl = etl.fromcolumns(cols)
>>> tbl
+----+-----+
| f0 | f1 |
+====+=====+
| 0 | 'a'... | 41,182 |
def function_sql(field, mysql_result_list):
"""
替换MySQL查询结果的方法
:param field: 第一个参数是yaml文件里面定义的字段
:param mysql_result_list: 第二个参数是MySQL查询结果列表
:return:
"""
if "{__SQL" in field:
mysql_index_list = re.findall("{__SQL(.+?)}", field)
# 获取索引列表
for i in mysql_index_list:
... | 41,183 |
def get_data_path():
"""
Return the location of the settings file for the data readers.
"""
import os
return os.path.dirname(__file__) | 41,184 |
def enable_dropout(model, rate=None, custom_objects={}):
"""
Enables the droput layer - used for monte carlo droput based uncertainty computation
Note: the weights needs to be reloaded after calling this model
>>> model = enable_dropout(model)
>>> model.load_weights('path to model weight')
:par... | 41,185 |
def get_max_torque_norm(p_state, idx_image=-1, idx_chain=-1):
"""Returns the current maximum norm of the torque acting on any spin."""
return float(_Get_MaxTorqueNorm(ctypes.c_void_p(p_state), ctypes.c_int(idx_image), ctypes.c_int(idx_chain))) | 41,186 |
def filter_by_zscore(data, features, remove_z):
"""Remove rows with |z scores| > remove_z"""
return data[(np.abs(np.nan_to_num(zscore(data[features]), posinf=0.0, neginf=0.0)) < remove_z).all(axis=1)] | 41,187 |
def test():
"""Unit test config."""
locals().update(**FAST_CONFIG)
visitations_factory_kwargs = { # noqa: F841 pylint:disable=unused-variable
"env_name": "evaluating_rewards/PointMassLine-v0",
"parallel": False,
"policy_type": "random",
"policy_path": "dummy",
} | 41,188 |
def test_dot():
"""Tests all overloads of the dot product function.
"""
u = lin.RowVector3([0.0, 2.0, 1.0])
v = lin.Vector3([1.0, -0.5, 2.0])
assert lin.dot(u, u) == 5.0
assert lin.dot(u, v) == 1.0
assert lin.dot(v, u) == 1.0
assert lin.dot(v, v) == 5.25 | 41,189 |
def _GetProperty(obj, components):
"""Grabs a property from obj."""
if obj is None:
return None
elif not components:
return obj
elif (isinstance(components[0], _Key) and
isinstance(obj, dict)):
return _GetProperty(obj.get(components[0]), components[1:])
elif (isinstance(components[0], _... | 41,190 |
def test_d_3():
"""
Checks rotation matrix for d = 3 and number of
rotations = 3.
"""
rs = 20
d = 3
np.random.seed(rs)
number_rotations = 3
theta_1 = np.random.uniform(0, 2 * math.pi)
rotation_1 = np.identity(d)
pos_1 = np.random.randint(0, d - 1)
pos_2 = np.random.randi... | 41,191 |
def make_similarity_function(similarity=None, distance=None, radius=None):
"""
Function creating a similarity function returning True if the compared
items are similar from a variety of functions & parameters.
Basically, if a distance function is given, it will be inverted and if
a radius is given,... | 41,192 |
def prepare_error_message(message: str, error_context: Optional[str] = None) -> str:
"""
If `error_context` is not None prepend that to error message.
"""
if error_context is not None:
return error_context + ": " + message
else:
return message | 41,193 |
def _options_from_args(args):
"""Returns a QRCodeOptions instance from the provided arguments.
"""
options = args.get('options')
if options:
if not isinstance(options, QRCodeOptions):
raise TypeError('The options argument must be of type QRCodeOptions.')
else:
# Convert t... | 41,194 |
def calc_q_rq_H(region, R_type):
"""単位面積当たりの必要暖房能力
Args:
region(int): 省エネルギー地域区分
R_type(string): 暖冷房区画の種類
Returns:
float: 単位面積当たりの必要暖房能力
Raises:
ValueError: R_type が '主たる居室' または 'その他の居室' 以外の場合に発生する
"""
table_3 = get_table_3()
if R_type == '主たる居室':
return t... | 41,195 |
def tuple_compare_lt(left, right):
"""Compare two 'TupleOf' instances by comparing their individual elements."""
for i in range(min(len(left), len(right))):
if left[i] > right[i]:
return False
if left[i] < right[i]:
return True
return len(left) < len(right) | 41,196 |
def list_projects(ctx):
"""Get a list of your projects"""
r = get(f"{ctx.obj['SERVER']}/projects")
if r.status_code != 200:
click.echo(f"Failed to list projects: {r.json().reason}")
sys.exit(1)
data = r.json()
for project in data["data"]:
click.echo(f"{project.id}: {project.... | 41,197 |
def multilevel_roi_align(inputs, boxes, image_shape, crop_size: int = 7):
"""Perform a batch multilevel roi_align on the inputs
Arguments:
- *inputs*: A list of tensors of shape [batch_size, width, height, channel]
representing the pyramid.
- *boxes*: A tensor and shape [batch_size, num_b... | 41,198 |
def get_hash_map(f):
"""Construct the hash map reading the release website, writing it to f."""
splitted_version = FLAGS.minimum_version.split(".")
if len(splitted_version) != 3:
sys.stderr.write(("Invalid version '%s', "
"expected a dot-separated version with 3 components "
... | 41,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.