text
stringlengths 15
7.82k
| ids
sequencelengths 1
7
|
---|---|
def METHOD_NAME(user, sku, course_price):
"""
Return the course's discounted price for a user if user is eligible for any otherwise return course original price.
"""
price_details = {}
try:
api_url = urljoin(f"{get_ecommerce_api_base_url()}/", "baskets/calculate/")
response = get_ecommerce_api_client(user).get(
api_url,
params={
"sku": [sku],
"username": user.username,
}
)
response.raise_for_status()
price_details = response.json()
except RequestException as exc:
LOGGER.info(
'[e-commerce calculate endpoint] Exception raise for sku [%s] - user [%s] and exception: %s',
sku,
user.username,
str(exc)
)
LOGGER.info(
'[e-commerce calculate endpoint] The discounted price for sku [%s] and user [%s] is [%s]',
sku,
user.username,
price_details.get('total_incl_tax')
)
result = price_details.get('total_incl_tax', course_price)
# When ecommerce price has zero cents, 'result' gets 149.0
# As per REV-2260: if zero cents, then only show dollars
if int(result) == result:
result = int(result)
return result | [
19,
1122,
2316,
806
] |
def METHOD_NAME(uri_formatter: URIFormatter) -> ImageFormatter:
def formatter(image: RemoteImage) -> str:
image_str = str(image)
if image_str.startswith("image://"):
return uri_formatter(URL(image_str))
else:
return image_str
return formatter | [
660,
2931
] |
def METHOD_NAME(self):
cmd_ev = test_lib.InitCommandEvaluator(arena=self.arena,
ext_prog=self.ext_prog)
Banner('ls | cut -d . -f 1 | head')
p = process.Pipeline(False, self.job_control, self.job_list)
p.Add(self._ExtProc(['ls']))
p.Add(self._ExtProc(['cut', '-d', '.', '-f', '1']))
node = _CommandNode('head', self.arena)
p.AddLast((cmd_ev, node))
p.StartPipeline(self.waiter)
print(p.RunLastPart(self.waiter, self.fd_state))
# Simulating subshell for each command
node1 = _CommandNode('ls', self.arena)
node2 = _CommandNode('head', self.arena)
node3 = _CommandNode('sort --reverse', self.arena)
thunk1 = process.SubProgramThunk(cmd_ev, node1, self.trap_state)
thunk2 = process.SubProgramThunk(cmd_ev, node2, self.trap_state)
thunk3 = process.SubProgramThunk(cmd_ev, node3, self.trap_state)
p = process.Pipeline(False, self.job_control, self.job_list)
p.Add(Process(thunk1, self.job_control, self.job_list, self.tracer))
p.Add(Process(thunk2, self.job_control, self.job_list, self.tracer))
p.Add(Process(thunk3, self.job_control, self.job_list, self.tracer))
last_thunk = (cmd_ev, _CommandNode('cat', self.arena))
p.AddLast(last_thunk)
p.StartPipeline(self.waiter)
print(p.RunLastPart(self.waiter, self.fd_state))
# TODO: Combine pipelines for other things:
# echo foo 1>&2 | tee stdout.txt
#
# foo=$(ls | head)
#
# foo=$(<<EOF ls | head)
# stdin
# EOF
#
# ls | head &
# Or technically we could fork the whole interpreter for foo|bar|baz and
# capture stdout of that interpreter. | [
9,
15968
] |
def METHOD_NAME(self):
self.config["name"] = "test_perplexity"
self.cls_num = 10
self.shape = (5, 20, self.cls_num)
self.label_shape = (5, 20)
self.metrics = Perplexity(**self.config)
self.np_metrics = NpPerplexity() | [
0,
1
] |
def METHOD_NAME(django_client, url):
response = django_client.get(url + "?include=comments")
data = response.json().get("data")[0]
comment = response.json().get("included")[0]
comment_relationship_type = (
data.get("relationships").get("comments").get("data")[0].get("type")
)
comment_included_type = comment.get("type")
assert (
comment_relationship_type == comment_included_type
), "The resource type seen in the relationships and included do not match" | [
250,
2924,
61,
3904,
1591,
44,
472
] |
def METHOD_NAME(self):
self.cpp_info.set_property("cmake_file_name", "tlx")
self.cpp_info.set_property("cmake_target_name", "tlx")
self.cpp_info.set_property("pkg_config_name", "tlx")
self.cpp_info.libs = collect_libs(self)
if self.settings.os in ["Linux", "FreeBSD"]:
self.cpp_info.system_libs.extend(["m", "pthread"])
# TODO: to remove in conan v2 once cmake_find_package* generators removed
self.cpp_info.build_modules["cmake_find_package"] = [self._module_file_rel_path]
self.cpp_info.build_modules["cmake_find_package_multi"] = [self._module_file_rel_path] | [
360,
100
] |
def METHOD_NAME(self):
"""Return first release in which this feature was recognized.
This is a 5-tuple, of the same form as sys.version_info.
"""
return self.optional | [
19,
665,
586
] |
def METHOD_NAME(cls, parameter_set="default"):
"""Return testing parameter settings for the estimator.
Parameters
----------
parameter_set : str, default="default"
Name of the set of test parameters to return, for use in tests. If no
special parameters are defined for a value, will return `"default"` set.
SummaryClassifier provides the following special sets:
"results_comparison" - used in some classifiers to compare against
previously generated results where the default set of parameters
cannot produce suitable probability estimates
Returns
-------
params : dict or list of dict, default={}
Parameters to create testing instances of the class.
Each dict are parameters to construct an "interesting" test instance, i.e.,
`MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
`create_test_instance` uses the first (or only) dictionary in `params`.
"""
if parameter_set == "results_comparison":
return {"estimator": RandomForestClassifier(n_estimators=10)}
else:
return {
"estimator": RandomForestClassifier(n_estimators=2),
"summary_functions": ("mean", "min", "max"),
} | [
19,
9,
434
] |
def METHOD_NAME(self):
self.ActionsGet(ctx=self.ctx)() | [
750,
710
] |
def METHOD_NAME(self, itn):
return "set nexus bus %(bus)s target %(target)s lun %(lun)s ; " % itn | [
0,
5638
] |
def METHOD_NAME(self) -> list[tuple[int, DNSAddressFamily, bytes]] | None:
"""Return fallback DNS servers."""
return self.properties[DBUS_ATTR_FALLBACK_DNS] | [
1008,
2455
] |
def METHOD_NAME(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict()) | [
24,
3
] |
def METHOD_NAME(keypoint_result, batch_records):
kpts, scores = keypoint_result['keypoint']
kpts[..., 0] += batch_records[:, 0:1]
kpts[..., 1] += batch_records[:, 1:2]
return kpts, scores | [
711,
24,
7560,
3669
] |
def METHOD_NAME(self):
"""Initialize LCD display."""
try:
self.disp.fill(0)
self.disp.show()
except Exception as err:
self.logger.error(
"Could not initialize LCD. "
"Check your configuration and wiring. "
"Error: {err}".format(err=err)) | [
7488,
176
] |
def METHOD_NAME(api):
'''
test to raise the exception use_cache filter is normalized
'''
filters = getattr(api.filters, '_use_cache')\
('rules', 'access-groups/rules/filters', 'rules', True)
assert isinstance(filters, dict)
for data in filters:
check(filters[data], 'choices', list, allow_none=True)
check(filters[data], 'operators', list)
check(filters[data], 'pattern', str, allow_none=True) | [
9,
1080,
596,
2019,
469
] |
def METHOD_NAME(self, module_file, targets):
content = ""
for alias, aliased in targets.items():
content += textwrap.dedent(f"""\
if(TARGET {aliased} AND NOT TARGET {alias})
add_library({alias} INTERFACE IMPORTED)
set_property(TARGET {alias} PROPERTY INTERFACE_LINK_LIBRARIES {aliased})
endif()
""".format(alias=alias, aliased=aliased))
save(self, module_file, content) | [
129,
334,
298,
533,
465
] |
def METHOD_NAME():
before_program = """
#[version = "0.0.5"]
def @main(%x: int) {
let %y = cast(%x, dtype="bool");
let %z = if (%y) {
let %v0 = %x + %x;
let %v1 = %v0 * 2;
%v1
} else {
%x
};
%z
}
"""
after_program = """
#[version = "0.0.5"]
def @main(%x: int) {
let %y = cast(%x, dtype="bool");
let %z = if (%y) {
let %v0 = %x + %x;
let %_0 = memory.kill(%x);
let %v1 = %v0 * 2;
let %_1 = memory.kill(%v0);
%v1
} else {
%x
};
let %_1 = memory.kill(%y);
%z
}
"""
optimize_and_check(before_program, after_program, transform.ManifestLifetimes()) | [
9,
53,
217
] |
def METHOD_NAME(
self, configuration: Optional[ExpectationConfiguration] = None
) -> None:
"""
Validates the configuration of an Expectation.
For `expect_column_values_to_not_match_like_pattern_list` it is required that:
- 'like_pattern_list' is present in configuration's kwarg
- assert 'like_pattern_list' is of type list or dict
- if 'like_pattern_list' is list, assert non-empty
- if 'like_pattern_list' is dict, assert a key "$PARAMETER" is present
Args:
configuration: An `ExpectationConfiguration` to validate. If no configuration is provided, it will be pulled
from the configuration attribute of the Expectation instance.
Raises:
`InvalidExpectationConfigurationError`: The configuration does not contain the values required by the
Expectation."
"""
super().METHOD_NAME(configuration)
configuration = configuration or self.configuration
try:
assert (
"like_pattern_list" in configuration.kwargs
), "Must provide like_pattern_list"
assert isinstance(
configuration.kwargs.get("like_pattern_list"), (list, dict)
), "like_pattern_list must be a list or dict"
assert isinstance(configuration.kwargs.get("like_pattern_list"), dict) or (
len(configuration.kwargs.get("like_pattern_list")) > 0
), "At least one like_pattern must be supplied in the like_pattern_list."
if isinstance(configuration.kwargs.get("like_pattern_list"), dict):
assert "$PARAMETER" in configuration.kwargs.get(
"like_pattern_list"
), 'Evaluation Parameter dict for like_pattern_list kwarg must have "$PARAMETER" key.'
except AssertionError as e:
raise InvalidExpectationConfigurationError(str(e)) | [
187,
830
] |
def METHOD_NAME(self):
"""
Returns a dictionary, where keys are the type code defined in
ONIE EEPROM format and values are their corresponding values
found in the system EEPROM.
"""
return self.eeprom_tlv_dict | [
112,
2359,
100
] |
def METHOD_NAME():
store = FeatureStore(repo_path=".")
print("\n--- Run feast apply ---")
subprocess.run(["feast", "apply"])
print("\n--- Historical features for training ---")
fetch_historical_features_entity_df(store, for_batch_scoring=False)
print("\n--- Historical features for batch scoring ---")
fetch_historical_features_entity_df(store, for_batch_scoring=True)
print("\n--- Load features into online store ---")
store.materialize_incremental(end_date=datetime.now())
print("\n--- Online features ---")
fetch_online_features(store)
print("\n--- Online features retrieved (instead) through a feature service---")
fetch_online_features(store, source="feature_service")
print(
"\n--- Online features retrieved (using feature service v3, which uses a feature view with a push source---"
)
fetch_online_features(store, source="push")
print("\n--- Simulate a stream event ingestion of the hourly stats df ---")
event_df = pd.DataFrame.from_dict(
{
"driver_id": [1001],
"event_timestamp": [
datetime.now(),
],
"created": [
datetime.now(),
],
"conv_rate": [1.0],
"acc_rate": [1.0],
"avg_daily_trips": [1000],
}
)
print(event_df)
store.push("driver_stats_push_source", event_df, to=PushMode.ONLINE_AND_OFFLINE)
print("\n--- Online features again with updated values from a stream push---")
fetch_online_features(store, source="push")
print("\n--- Run feast teardown ---")
subprocess.run(["feast", "teardown"]) | [
22,
2660
] |
def METHOD_NAME(self) -> str:
"""
Full name of contact
"""
return pulumi.get(self, "contact_name") | [
1492,
156
] |
def METHOD_NAME(self, event):
if self.active_calltip and self.active_calltip.tipwindow:
self.open_calltip(False) | [
1920,
5282,
417
] |
def METHOD_NAME():
df = get_some_data()
store_to_s3(df)
yield AssetMaterialization(
asset_key="s3.my_asset",
description="A df I stored in s3",
)
result = do_some_transform(df)
yield Output(result) | [
1192,
3455,
441,
4119
] |
f METHOD_NAME(self): | [
9,
356,
-1
] |
def METHOD_NAME(self):
self.assertEqual(
False,
check_scopes({'read:dataset:test1.zarr'},
None,
is_substitute=False)
)
self.assertEqual(
False,
check_scopes({'read:dataset:test1.zarr'},
set(),
is_substitute=True)
)
self.assertEqual(
False,
check_scopes({'read:dataset:test1.zarr'},
{'read:dataset:test1.zarr'},
is_substitute=True)
)
self.assertEqual(
False,
check_scopes({'read:dataset:test2.zarr'},
{'read:dataset:test1.zarr'})
)
self.assertEqual(
False,
check_scopes({'read:dataset:test2.zarr'},
{'read:dataset:test1.zarr'},
is_substitute=True)
) | [
9,
250,
3040,
216
] |
def METHOD_NAME(viewid, layer, updated_nodes):
cache_key = _cache_key("topology", viewid, layer)
to_update = cache.get(cache_key)
for node in updated_nodes:
# If the node is new, it is easier just to make an early exit and
# rebuild the whole topology
if node["new_node"]:
return invalidate_topology_cache(viewid, layer)
# Otherwise, don't update nodes not cached in the topology
if node["id"] not in to_update["nodes"]:
continue
diff = {"x": node["x"], "y": node["y"]}
to_update["nodes"][node["id"]]["position"] = diff
cache.set(cache_key, to_update, CACHE_TIMEOUT) | [
86,
175,
1716,
2758
] |
def METHOD_NAME(self):
return getattr(self.registry(), name) | [
19
] |
def METHOD_NAME():
"""Clear the cache and cache statistics"""
with lock:
cache.clear()
root = nonlocal_root[0]
root[:] = [root, root, None, None]
stats[:] = [0, 0] | [
596,
537
] |
def METHOD_NAME():
config_text = _get_pyproj_toml_config()
if config_text:
default_config = toml.loads(config_text).get('tool', {}).get('pyflyby',{})
else:
default_config = {}
def _add_opts_and_defaults(parser):
_addopts(parser)
parser.set_defaults(**default_config)
options, args = parse_args(
_add_opts_and_defaults, import_format_params=True, modify_action_params=True, defaults=default_config)
def modify(x):
if options.canonicalize:
x = canonicalize_imports(x, params=options.params)
if options.transformations:
x = transform_imports(x, options.transformations,
params=options.params)
if options.replace_star_imports:
x = replace_star_imports(x, params=options.params)
return fix_unused_and_missing_imports(
x, params=options.params,
add_missing=options.add_missing,
remove_unused=options.remove_unused,
add_mandatory=options.add_mandatory,
)
process_actions(args, options.actions, modify) | [
57
] |
def METHOD_NAME():
"""Add GenericAssetType table
A GenericAssetType is created for each AssetType, MarketType and WeatherSensorType.
Optionally, additional GenericAssetTypes can be created using:
flexmeasures db upgrade +1 -x '{"name": "waste power plant"}' -x '{"name": "EVSE", "description": "Electric Vehicle Supply Equipment"}'
The +1 makes sure we only upgrade by 1 revision, as these arguments are only meant to be used by this upgrade function.
"""
upgrade_schema()
upgrade_data() | [
738
] |
def METHOD_NAME(data, data_sampler_state_dict):
assert 'dummy_metric' in data_sampler_state_dict['current_difficulties']
return data | [
365,
72,
356
] |
def METHOD_NAME(self, execute_task, tmpdir):
tmpdir.join(dirname).join('test1.mkv').write('')
hardlink = tmpdir.join(dirname).join('hardlink').join('test1.mkv')
hardlink.write('')
task = execute_task('test_hardlink')
assert len(task.failed) == 1, 'should have failed test1.mkv' | [
9,
10161,
180
] |
def METHOD_NAME(self) -> str:
"""
Unique identifier for the service account.
"""
return pulumi.get(self, "subject_id") | [
1861,
147
] |
def METHOD_NAME(self, event_idx: int) -> bool:
"""
Check that event with `event_idx` had occured or not.
Parameters
----------
event_idx : int
Returns
-------
bool
"""
return self.events[event_idx].METHOD_NAME() | [
137,
0
] |
def METHOD_NAME(loops=LOOPS):
global IntGlob
global BoolGlob
global Char1Glob
global Char2Glob
global Array1Glob
global Array2Glob
global PtrGlb
global PtrGlbNext
starttime = clock()
for i in range(loops):
pass
nulltime = clock() - starttime
PtrGlbNext = Record()
PtrGlb = Record()
PtrGlb.PtrComp = PtrGlbNext
PtrGlb.Discr = Ident1
PtrGlb.EnumComp = Ident3
PtrGlb.IntComp = 40
PtrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING"
String1Loc = "DHRYSTONE PROGRAM, 1'ST STRING"
Array2Glob[8][7] = 10
starttime = clock()
for i in range(loops):
Proc5()
Proc4()
IntLoc1 = 2
IntLoc2 = 3
String2Loc = "DHRYSTONE PROGRAM, 2'ND STRING"
EnumLoc = Ident2
BoolGlob = not Func2(String1Loc, String2Loc)
while IntLoc1 < IntLoc2:
IntLoc3 = 5 * IntLoc1 - IntLoc2
IntLoc3 = Proc7(IntLoc1, IntLoc2)
IntLoc1 = IntLoc1 + 1
Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3)
PtrGlb = Proc1(PtrGlb)
CharIndex = 'A'
while CharIndex <= Char2Glob:
if EnumLoc == Func1(CharIndex, 'C'):
EnumLoc = Proc6(Ident1)
CharIndex = chr(ord(CharIndex)+1)
IntLoc3 = IntLoc2 * IntLoc1
IntLoc2 = IntLoc3 / IntLoc1
IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1
IntLoc1 = Proc2(IntLoc1)
benchtime = clock() - starttime - nulltime
if benchtime == 0.0:
loopsPerBenchtime = 0.0
else:
loopsPerBenchtime = (loops / benchtime)
return benchtime, loopsPerBenchtime | [
15049
] |
def METHOD_NAME():
results = []
for i in range(20):
test_input = torch.rand(1, 3, 224, 224).half().cuda()
sub_label = f"[test {i}]"
results.append(
benchmark.Timer(
stmt="meta_module_resnet18(test_input)",
setup="from __main__ import meta_module_resnet18",
globals={"test_input": test_input},
sub_label=sub_label,
description="tuning by meta",
).blocked_autorange()
)
results.append(
benchmark.Timer(
stmt="jit_module_resnet18(test_input)",
setup="from __main__ import jit_module_resnet18",
globals={"test_input": test_input},
sub_label=sub_label,
description="tuning by jit",
).blocked_autorange()
)
compare = benchmark.Compare(results)
compare.print() | [
979,
5107,
11188,
24,
10858
] |
def METHOD_NAME(cls, uri_prefix, key):
assert key
return join_url(uri_prefix or settings.DEFAULT_URI_PREFIX, '/questions/', key) | [
56,
354
] |
def METHOD_NAME(self):
tool = self.tool
name = tool.selection_metadata_name
index_md = tool.component.index.metadata
value_md = tool.component.value.metadata
self.mouse_down(tool, 0, 0)
self.mouse_down(tool, 10, 10)
self.assertEqual(index_md[name], [0, 1])
self.assertEqual(value_md[name], [0, 1])
# Deselect the second point
self.mouse_down(tool, 10, 10)
self.assertEqual(index_md[name], [0])
self.assertEqual(value_md[name], [0])
# Deselect the first point
self.mouse_down(tool, 0, 0)
self.assertEqual(index_md[name], [])
self.assertEqual(value_md[name], []) | [
9,
15573
] |
def METHOD_NAME(self, nop_span):
"""Set a tag and get it back."""
r = nop_span.set_tag("test", 23)
assert nop_span._get_metric("test") == 23
assert r is nop_span | [
9,
114
] |
def METHOD_NAME() -> FrameworkInfo:
"""
Detect the information for the onnx/onnxruntime framework such as package versions,
availability for core actions such as training and inference,
sparsification support, and inference provider support.
:return: The framework info for onnx/onnxruntime
:rtype: FrameworkInfo
"""
all_providers = []
available_providers = []
if check_onnxruntime_install(raise_on_error=False):
from onnxruntime import get_all_providers, get_available_providers
available_providers = get_available_providers()
all_providers = get_all_providers()
cpu_provider = FrameworkInferenceProviderInfo(
name="cpu",
description="Base CPU provider within ONNXRuntime",
device="cpu",
supported_sparsification=SparsificationInfo(), # TODO: fill in when available
available=(
check_onnx_install(raise_on_error=False)
and check_onnxruntime_install(raise_on_error=False)
and "CPUExecutionProvider" in available_providers
),
properties={},
warnings=[],
)
gpu_provider = FrameworkInferenceProviderInfo(
name="cuda",
description="Base GPU CUDA provider within ONNXRuntime",
device="gpu",
supported_sparsification=SparsificationInfo(), # TODO: fill in when available
available=(
check_onnx_install(raise_on_error=False)
and check_onnxruntime_install(raise_on_error=False)
and "CUDAExecutionProvider" in available_providers
),
properties={},
warnings=[],
)
return FrameworkInfo(
framework=Framework.onnx,
package_versions={
"onnx": get_version(package_name="onnx", raise_on_error=False),
"onnxruntime": (
get_version(package_name="onnxruntime", raise_on_error=False)
),
"sparsezoo": get_version(
package_name="sparsezoo",
raise_on_error=False,
alternate_package_names=["sparsezoo-nightly"],
),
"sparseml": get_version(
package_name="sparseml",
raise_on_error=False,
alternate_package_names=["sparseml-nightly"],
),
},
sparsification=sparsification_info(),
inference_providers=[cpu_provider, gpu_provider],
properties={
"available_providers": available_providers,
"all_providers": all_providers,
},
training_available=False,
sparsification_available=True,
exporting_onnx_available=True,
inference_available=True,
) | [
1486,
100
] |
def METHOD_NAME(self):
imports._cache.clear() | [
0,
1
] |
def METHOD_NAME(self):
if not self.bucket:
self.bucket = self.client.create_bucket(self.name) | [
129
] |
def METHOD_NAME(onnx_path: str) -> dict:
so = onnxruntime.SessionOptions()
so.inter_op_num_threads = 1
so.intra_op_num_threads = 1
session = onnxruntime.InferenceSession(onnx_path, providers=['CPUExecutionProvider'], sess_options=so)
input_data = {}
for inp in session.get_inputs():
name = inp.name
shape = inp.shape
dtype = inp.type
if "int" in dtype:
input_data[name] = np.random.randint(low=0, high=2, size=shape)
else:
input_data[name] = np.random.rand(*shape).astype(np.float32)
pred = session.run([], input_data)
output_shape = {}
for tensor, oup_info in zip(pred, session.get_outputs()):
shape = tensor.shape
name = oup_info.name
output_shape[name] = shape
return output_shape | [
19,
146,
555
] |
def METHOD_NAME():
spawn(_run_offload_codegen, 1) | [
9,
740,
737,
2626
] |
def METHOD_NAME():
r_nchar = rinterface.baseenv['::']('base', 'nchar')
res = r_nchar('foo')
assert res[0] == 3 | [
9,
144,
1545
] |
def METHOD_NAME(test_func):
"""Augment test function to parse log files.
`tools.create_tests` creates functions that run an LBANN
experiment. This function creates augmented functions that parse
the log files after LBANN finishes running, e.g. to check metrics
or runtimes.
Note: The naive approach is to define the augmented test functions
in a loop. However, Python closures are late binding. In other
words, the function would be overwritten every time we define it.
We get around this overwriting problem by defining the augmented
function in the local scope of another function.
Args:
test_func (function): Test function created by
`tools.create_tests`.
Returns:
function: Test that can interact with PyTest.
"""
test_name = test_func.__name__
# Define test function
def func(cluster, exes, dirname):
# Run LBANN experiment
experiment_output = test_func(cluster, exes, dirname)
# Parse LBANN log file
train_accuracy = None
test_accuracy = None
mini_batch_times = []
with open(experiment_output['stdout_log_file']) as f:
for line in f:
match = re.search('training epoch [0-9]+ recon_error : ([0-9.]+)', line)
if match:
train_accuracy = float(match.group(1))
match = re.search('training epoch [0-9]+ mini-batch time statistics : ([0-9.]+)s mean', line)
if match:
mini_batch_times.append(float(match.group(1)))
# Check if training accuracy is within expected range
assert (expected_MSE_range[0]
< train_accuracy
<expected_MSE_range[1]), \
'train accuracy is outside expected range'
#Only tested on Ray. Skip if mini-batch test on another cluster. Change this when mini-batch values are available for other clusters
if (cluster == 'ray'):
# Check if mini-batch time is within expected range
# Note: Skip first epoch since its runtime is usually an outlier
mini_batch_times = mini_batch_times[1:]
mini_batch_time = sum(mini_batch_times) / len(mini_batch_times)
assert (0.75 * expected_mini_batch_times[cluster]
< mini_batch_time
< 1.25 * expected_mini_batch_times[cluster]), \
'average mini-batch time is outside expected range'
# Return test function from factory function
func.__name__ = test_name
return func | [
3725,
9,
717
] |
def METHOD_NAME(self):
self._backtranslation_dataset_helper(
remove_eos_from_input_src=False,
remove_eos_from_output_src=False,
) | [
9,
14300,
126,
41,
7743,
623,
146
] |
def METHOD_NAME(nm, row_nm, n=3):
instances = []
for i in range(n):
inp = 'INP' if i == 0 else f'X{i}'
out = 'OUT' if i == n - 1 else f'X{i+1}'
instance = {
'instance_name': f'U{i}',
'abstract_template_name': row_nm,
'fa_map': [{'formal': 'INP', 'actual': inp},
{'formal': 'OUT', 'actual': out}]
}
instances.append(instance)
topmodule = {
'name': nm,
'parameters': ["INP", "OUT"],
'instances': instances,
'constraints': [
{
'constraint': 'Order',
'direction': 'top_to_bottom',
'instances': [f'U{i}' for i in range(n)],
'abut': False
}
]
}
topmodule['constraints'].append(
{
'constraint': 'SameTemplate',
'instances': [f'U{i}' for i in range(n)]
}
)
return topmodule | [
370,
430,
298
] |
def METHOD_NAME():
text.tag_add(SEL, "1.0", END)
grep(text, flist=flist)
text.tag_remove(SEL, "1.0", END) | [
697,
3433,
1301
] |
def METHOD_NAME(self):
# Queue a call to tick in 5ms.
self.task = Action[Task](self.tick)
Task.Delay(5).ContinueWith(self.task) | [
419,
4115
] |
f METHOD_NAME(self): | [
164
] |
def METHOD_NAME(resource_group_name: Optional[pulumi.Input[str]] = None,
ssh_public_key_name: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetSshPublicKeyResult]:
"""
Retrieves information about an SSH public key.
:param str resource_group_name: The name of the resource group.
:param str ssh_public_key_name: The name of the SSH public key.
"""
... | [
19,
1264,
1609,
59,
146
] |
def METHOD_NAME():
rgb = np.zeros((5, 5, 3))
rgb[1, 1] = np.arange(1, 4)
gray = np.pad(rgb, pad_width=((0, 0), (0, 0), (1, 0)))
# Warning is raised if channel_axis is not set and shape is (M, N, 3)
with pytest.warns(
FutureWarning,
match="Automatic detection .* was deprecated .* Set `channel_axis=-1`"
):
filtered_rgb = gaussian(rgb, sigma=1, mode="reflect")
# Check that the mean value is conserved in each channel
# (color channels are not mixed together)
assert np.allclose(filtered_rgb.mean(axis=(0, 1)), rgb.mean(axis=(0, 1)))
# No warning if channel_axis is not set and shape is not (M, N, 3)
filtered_gray = gaussian(gray, sigma=1, mode="reflect")
# No warning is raised if channel_axis is explicitly set
filtered_rgb2 = gaussian(rgb, sigma=1, mode="reflect", channel_axis=-1)
assert np.array_equal(filtered_rgb, filtered_rgb2)
filtered_gray2 = gaussian(gray, sigma=1, mode="reflect", channel_axis=None)
assert np.array_equal(filtered_gray, filtered_gray2)
assert not np.array_equal(filtered_rgb, filtered_gray)
# Check how the proxy value shows up in the rendered function signature
from skimage._shared.filters import ChannelAxisNotSet
assert repr(ChannelAxisNotSet) == "<ChannelAxisNotSet>" | [
9,
2497,
4005,
307,
381
] |
def METHOD_NAME():
data = [
{
"version_affected": "?=",
"version_value": "1.3.0",
},
{
"version_affected": "=",
"version_value": "1.3.1",
},
{
"version_affected": "#=",
"version_value": "2.3.4",
},
]
fixed_versions = ["1.3.2"]
affected_version_range = ApacheHTTPDImporter().to_version_ranges(data, fixed_versions) | [
46,
2403
] |
def METHOD_NAME (f):
def counted_func (*args, **kwds):
count (f.__module__ + "." + f.__name__ + ".cnt")
return f(*args, **kwds)
counted_func.__name__ = f.__name__
counted_func.__doc__ = f.__doc__
return counted_func | [
29,
577
] |
def METHOD_NAME(self) -> VibrationalOp:
"""Returns the second quantized vibrational energy operator.
Returns:
A ``dict`` of ``VibrationalOp`` objects.
"""
truncated_integrals = self.vibrational_integrals
if self.truncation_order is not None:
truncated_integrals = VibrationalIntegrals(
{
key: value
for key, value in self.vibrational_integrals.items()
if len(key) <= 3 * self.truncation_order
},
validate=False,
)
return VibrationalOp.from_polynomial_tensor(truncated_integrals) | [
3146,
1010,
441
] |
def METHOD_NAME(self, rport):
"""
Since ROMs dont have write ports this does nothing
"""
pass | [
238,
77,
203,
2676
] |
def METHOD_NAME(self):
if self.params["os_type"] == "windows":
return
session = self.clone_vm.wait_for_login()
try:
backup_utils.refresh_mounts(self.disks_info, self.params, session)
for info in self.disks_info.values():
disk_path = info[0]
mount_point = info[1]
utils_disk.mount(disk_path, mount_point, session=session)
finally:
session.close() | [
2844,
365,
3033
] |
def METHOD_NAME(_):
from datadog_api_client.v1.model.ip_prefixes_agents import IPPrefixesAgents
from datadog_api_client.v1.model.ip_prefixes_api import IPPrefixesAPI
from datadog_api_client.v1.model.ip_prefixes_apm import IPPrefixesAPM
from datadog_api_client.v1.model.ip_prefixes_logs import IPPrefixesLogs
from datadog_api_client.v1.model.ip_prefixes_orchestrator import IPPrefixesOrchestrator
from datadog_api_client.v1.model.ip_prefixes_process import IPPrefixesProcess
from datadog_api_client.v1.model.ip_prefixes_remote_configuration import IPPrefixesRemoteConfiguration
from datadog_api_client.v1.model.ip_prefixes_synthetics import IPPrefixesSynthetics
from datadog_api_client.v1.model.ip_prefixes_synthetics_private_locations import (
IPPrefixesSyntheticsPrivateLocations,
)
from datadog_api_client.v1.model.ip_prefixes_webhooks import IPPrefixesWebhooks
return {
"agents": (IPPrefixesAgents,),
"api": (IPPrefixesAPI,),
"apm": (IPPrefixesAPM,),
"logs": (IPPrefixesLogs,),
"modified": (str,),
"orchestrator": (IPPrefixesOrchestrator,),
"process": (IPPrefixesProcess,),
"remote_configuration": (IPPrefixesRemoteConfiguration,),
"synthetics": (IPPrefixesSynthetics,),
"synthetics_private_locations": (IPPrefixesSyntheticsPrivateLocations,),
"version": (int,),
"webhooks": (IPPrefixesWebhooks,),
} | [
4597,
119
] |
METHOD_NAME(self): | [
19,
274
] |
def METHOD_NAME(self, event):
time.sleep(0.05)
now = time.time()
if now - self.last_layout_send > 1:
self.last_layout_send = now
self.state.child_pipe_send.send(win_layout.get_wx_window_layout(self)) | [
69,
1150
] |
def METHOD_NAME(self, c0, c1):
print("%s%s" % (c0.ljust(40), c1.ljust(20))) | [
38,
843
] |
def METHOD_NAME(file_name=None,
pdb_records=None,
crystal_symmetry=None):
assert [file_name, pdb_records].count(None) == 1
if (pdb_records is None):
pdb_inp = iotbx.pdb.input(file_name=file_name)
else:
pdb_inp = iotbx.pdb.input(source_info=None, lines=pdb_records)
crystal_symmetry = pdb_inp.crystal_symmetry(
crystal_symmetry=crystal_symmetry,
weak_symmetry=True)
if (not crystal_symmetry or crystal_symmetry.unit_cell() is None):
raise RuntimeError("Unit cell parameters unknown for model %s." %(
file_name))
if (crystal_symmetry.space_group_info() is None):
raise RuntimeError("Space group unknown.")
positions = []
for atom in pdb_inp.atoms_with_labels():
positions.append(emma.position(
":".join([str(len(positions)+1),
atom.name, atom.resname, atom.chain_id]),
crystal_symmetry.unit_cell().fractionalize(atom.xyz)))
assert len(positions) > 0
result = emma.model(
crystal_symmetry.special_position_settings(),
positions)
if (file_name is not None):
result.label = file_name
return result | [
19,
2498,
578,
280,
10251
] |
def METHOD_NAME(self, message):
pass | [
69,
1677
] |
def METHOD_NAME(
x: float, y: float, duration: Optional[float] = None
) -> List[HIDEvent]:
return _press_with_duration(HIDTouch(point=Point(x=x, y=y)), duration=duration) | [
4316,
24,
239
] |
def METHOD_NAME(self, y, x, str, attr=A_NORMAL):
self._goto(y, x)
# TODO: Should be "ORed"
if attr == A_NORMAL:
attr = self.bkgattr
if attr != A_NORMAL:
_wr(ATTRMAP[attr])
_wr(str)
_wr(ATTRMAP[A_NORMAL])
else:
_wr(str) | [
-1
] |
def METHOD_NAME(test, checks=None):
return step_dedicated_hsm_list3(test, checks) | [
367,
1566,
7423,
-1
] |
f METHOD_NAME(self): | [
203,
2846,
146
] |
def METHOD_NAME(a, b, msg=None):
"""Assert a in not b, with repr messaging on failure."""
assert a not in b, msg or "%r is in %r" % (a, b) | [
130,
623
] |
def METHOD_NAME():
with open('data/svm_data.pkl', 'rb') as f:
train_X, train_y, test_X, test_y = pickle.load(f)
model = SVM()
model.fit(train_X, train_y, iterations=500, disp = 1)
print(model.get_params()) | [
57
] |
def METHOD_NAME(self) -> str:
results = self.get_async_results()
any_failed = any((result.state == states.FAILURE for result in results))
all_ready = all((result.state in states.READY_STATES for result in results))
if results and (any_failed or all_ready):
return ProcessingStatuses.done
return ProcessingStatuses.in_progress | [
452
] |
def METHOD_NAME(self):
"Verify that up2dateAuth.login returns login credentials in a dict"
ret = up2dateAuth.login()
if type(ret) == type({}):
if not ret.has_key('X-RHN-Auth'):
self.fail("Expected a dict containing a X-RHN-AUTH header, didnt get it")
else:
self.fail("Expected a dict containing headers, but the return is not a dict") | [
9,
273,
6471,
44
] |
def METHOD_NAME(pSpill, cats):
cats.prepare_for_model_run()
cats.prepare_for_model_step(pSpill, time_step, model_time)
u_delta = cats.get_move(pSpill, time_step, model_time)
cats.model_step_is_done()
return u_delta | [
14146,
1751
] |
def METHOD_NAME(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output | [
76
] |
def METHOD_NAME(self, symbol: str = None) -> float:
pass | [
19,
12194
] |
def METHOD_NAME(self):
return "POST" | [
103
] |
def METHOD_NAME(self):
"""Verifies and execute cleanup if needed"""
if len(self.filter) == 0:
return
elif len(self.cache) > self.max_cache_size:
self.cleanup() | [
276,
1356
] |
def METHOD_NAME(cleaned_input):
# given
category = Category(name="test")
previous_slug_value = cleaned_input["slug"]
# when
validate_slug_and_generate_if_needed(category, "name", cleaned_input)
# then
assert previous_slug_value != cleaned_input["slug"]
assert cleaned_input["slug"] == cleaned_input["name"] | [
9,
187,
1231,
61,
567,
217,
2002
] |
def METHOD_NAME(self):
return len(self.items) | [
1318
] |
def METHOD_NAME(self):
self._patch_sources()
cmake = CMake(self)
cmake.configure()
cmake.METHOD_NAME() | [
56
] |
METHOD_NAME (self, err) : | [
168
] |
def METHOD_NAME(seed):
faker_helpers.reseed(seed)
home_page = faker_helpers.get_homepage()
print("Generating research hub")
# Only one landing page can exist
research_landing_page = wagtailpage_models.ResearchLandingPage.objects.first()
if not research_landing_page:
research_landing_page = landing_page_factory.ResearchLandingPageFactory.create(
parent=home_page, aside_cta__0="cta", aside_cta__1="cta"
)
# Only one library page can exist
research_library_page = wagtailpage_models.ResearchLibraryPage.objects.first()
if not research_library_page:
research_library_page = library_page_factory.ResearchLibraryPageFactory.create(parent=research_landing_page)
# Only one authors index page can exist
research_authors_index_page = wagtailpage_models.ResearchAuthorsIndexPage.objects.first()
if not research_authors_index_page:
research_authors_index_page = author_index_factory.ResearchAuthorsIndexPageFactory.create(
parent=research_landing_page
)
create_detail_page_for_visual_regression_tests(seed, research_library_page)
for _ in range(4):
taxonomies_factory.ResearchRegionFactory.create()
taxonomies_factory.ResearchTopicFactory.create()
for _ in range(13):
research_detail_page = detail_page_factory.ResearchDetailPageFactory.create(
parent=research_library_page,
authors=None,
related_topics=None,
related_regions=None,
)
for profile in faker_helpers.get_random_objects(source=wagtailpage_models.Profile, max_count=3):
relations_factory.ResearchAuthorRelationFactory.create(
detail_page=research_detail_page,
author_profile=profile,
)
for region in faker_helpers.get_random_objects(source=wagtailpage_models.ResearchRegion, max_count=2):
relations_factory.ResearchDetailPageResearchRegionRelationFactory.create(
detail_page=research_detail_page,
region=region,
)
for topic in faker_helpers.get_random_objects(source=wagtailpage_models.ResearchTopic, max_count=2):
relations_factory.ResearchDetailPageResearchTopicRelationFactory.create(
detail_page=research_detail_page,
topic=topic,
)
# Populating research landing page with featured research topics
for topic in faker_helpers.get_random_objects(source=wagtailpage_models.ResearchTopic, max_count=3):
relations_factory.ResearchLandingPageResearchTopicRelationFactory.create(
landing_page=research_landing_page,
topic=topic,
)
# Populating research landing page with featured authors
research_authors = research_hub_utils.get_research_authors()
for profile in faker_helpers.get_random_objects(source=research_authors, max_count=4):
relations_factory.ResearchLandingPageFeaturedAuthorsRelationFactory.create(
landing_page=research_landing_page,
author=profile,
) | [
567
] |
def METHOD_NAME(self):
email = self.validated_data.get("email")
return Participant.objects.get_or_create(
user=User.objects.get(email=email),
status=Participant.ACCEPTED,
team=self.participant_team,
) | [
73
] |
def METHOD_NAME(self,name,value):
"""Return first matching header value for 'name', or 'value'
If there is no header named 'name', add a new header with name 'name'
and value 'value'."""
result = self.get(name)
if result is None:
self._headers.append((self._convert_string_type(name),
self._convert_string_type(value)))
return value
else:
return result | [
9427
] |
def METHOD_NAME(self):
self.cmd('az cloud set -n AzureGermanCloud')
self.cmd('az cloud show -n AzureGermanCloud', checks=[self.check('isActive', True)]) | [
9,
4054,
0,
1507,
9198,
4054
] |
def METHOD_NAME(self):
spec = self.spec[self.source].copy()
source_voxel_size = self.spec[self.source].voxel_size
spec.voxel_size = self.target_voxel_size
self.pad = Coordinate(
(0,) * (len(source_voxel_size) - self.ndim)
+ source_voxel_size[-self.ndim :]
)
spec.roi = spec.roi.grow(
-self.pad, -self.pad
) # Pad w/ 1 voxel per side for interpolation to avoid edge effects
spec.roi = spec.roi.snap_to_grid(
np.lcm(source_voxel_size, self.target_voxel_size), mode="shrink"
)
self.provides(self.target, spec)
self.enable_autoskip() | [
102
] |
def METHOD_NAME(self) -> bool:
return False | [
220,
249,
2583
] |
def METHOD_NAME(frame, bit):
# rw_width_tags() aliasing interconnect on large widths
return frame not in (0, 20, 21) | [
12596
] |
def METHOD_NAME(
in_dir: pathlib.Path,
out_dir: pathlib.Path,
*,
transformer=budgetsCallTransformer(), | [
1112,
1537
] |
def METHOD_NAME():
result = openshift_configuration.OseNodeConfig(context_wrap(NODE_CONFIG))
assert result.data['apiVersion'] == "v1"
assert result.data['masterClientConnectionOverrides']['burst'] == 200 | [
9,
-1,
2614,
200
] |
def METHOD_NAME(self, current: torch.Tensor) -> Tuple[bool, str]:
should_stop, reason = super().METHOD_NAME(current)
if should_stop:
self.early_stopping_reason = reason
return should_stop, reason | [
1195,
8449,
4415
] |
def METHOD_NAME(string, format="%Y-%m-%d %H:%M:%S"):
return datetime.datetime.strptime(string, format) | [
24,
884
] |
def METHOD_NAME(self):
if self.problems_solved > 0:
return self.time_passed + self.penalties_count * self.penalty_time
else:
return 0 | [
395,
104
] |
def METHOD_NAME(self):
# _min_scale defines the point at which the exponential mapping
# function becomes useless for 64-bit floats. With scale -10, ignoring
# subnormal values, bucket indices range from -1 to 1.
return -10 | [
19,
1835,
930
] |
def METHOD_NAME(descr):
#
# Sanity check
#
if (not descr) or descr[0] != 'panel':
raise panel_error, 'panel description must start with "panel"'
#
if debug: show_panel('', descr)
#
# Create an empty panel
#
panel = pnl.mkpanel()
#
# Assign panel attributes
#
assign_members(panel, descr[1:], ['al'], '')
#
# Look for actuator list
#
al = getattrlist(descr, 'al')
#
# The order in which actuators are created is important
# because of the endgroup() operator.
# Unfortunately the Panel Editor outputs the actuator list
# in reverse order, so we reverse it here.
#
al = reverse(al)
#
for a in al:
act, name = build_actuator(a)
act.addact(panel)
if name:
stmt = 'panel.' + name + ' = act'
exec stmt + '\n'
if is_endgroup(a):
panel.endgroup()
sub_al = getattrlist(a, 'al')
if sub_al:
build_subactuators(panel, act, sub_al)
#
return panel | [
56,
519
] |
def METHOD_NAME(request):
query = request.GET.copy()
query.setlist('page', [])
query = query.urlencode()
if query:
return {'page_prefix': '%s?%s&page=' % (request.path, query),
'first_page_href': '%s?%s' % (request.path, query)}
else:
return {'page_prefix': '%s?page=' % request.path,
'first_page_href': request.path} | [
11465,
539,
198
] |
def METHOD_NAME(self, poll):
if "request" in self.context:
user = self.context["request"].user
if user.is_authenticated:
return (
models.Vote.objects.filter(
choice__question__poll=poll, creator=user
).count()
+ models.Answer.objects.filter(
question__poll=poll, creator=user
).count()
) > 0
return False | [
19,
220,
21,
9811
] |
def METHOD_NAME(self):
""" Perform an SSL handshake (usually called after renegotiate or one of
set_accept_state or set_accept_state). This can raise the same exceptions as
send and recv. """
if self.act_non_blocking:
return self.fd.METHOD_NAME()
while True:
try:
return self.fd.METHOD_NAME()
except WantReadError:
trampoline(self.fd.fileno(),
read=True,
timeout=self.gettimeout(),
timeout_exc=socket.timeout)
except WantWriteError:
trampoline(self.fd.fileno(),
write=True,
timeout=self.gettimeout(),
timeout_exc=socket.timeout) | [
74,
658
] |
def METHOD_NAME(self):
"""Accessor for thread identifier.
Returns:
This thread's `thid`
"""
return self._thid | [
15147
] |
def METHOD_NAME(tmp_path):
p = tmp_path / "npy.scp"
w = NpyScpWriter(tmp_path / "data", p)
w["a"] = np.random.randn(100, 80)
w["b"] = np.random.randn(150, 80)
return str(p) | [
9066,
3850
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.