text
stringlengths 15
7.82k
| ids
sequencelengths 1
7
|
---|---|
def METHOD_NAME(cls, *args, **kwargs):
if cls._args_schema is not None:
return cls._args_schema
cls._args_schema = super().METHOD_NAME(*args, **kwargs)
# define Arg Group ""
_args_schema = cls._args_schema
_args_schema.resource_group = AAZResourceGroupNameArg(
required=True,
)
_args_schema.name = AAZStrArg(
options=["-n", "--name"],
help="Name of the VNet gateway.",
required=True,
id_part="name",
)
return cls._args_schema | [
56,
134,
135
] |
def METHOD_NAME(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
location=location,
api_version=api_version,
template_url=self.list.metadata["url"],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
subscription_id=self._config.subscription_id,
location=location,
api_version=api_version,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request | [
123,
377
] |
def METHOD_NAME(self):
request_started.send(sender=self)
fake_task.delay()
assert fake_task_func.call_count == 0
request_finished.send_robust(sender=self)
assert fake_task_func.call_count == 1 | [
9,
3738,
3005,
377,
17,
3351
] |
def METHOD_NAME(brightness: int, color_temp: int) -> State:
return State(
"light.test",
STATE_ON,
{
ATTR_COLOR_MODE: ColorMode.COLOR_TEMP,
ATTR_BRIGHTNESS: brightness,
ATTR_COLOR_TEMP: color_temp,
},
) | [
129,
4322,
36,
963,
551
] |
def METHOD_NAME(self):
async def serve_forever(ep):
ucx = UCX(ep)
self.comm = ucx
self.ucp_server = ucp.create_listener(serve_forever) | [
447
] |
def METHOD_NAME(self):
G = nx.cycle_graph(4)
pred = nx.predecessor(G, 0)
assert pred[0] == []
assert pred[1] == [0]
assert pred[2] in [[1, 3], [3, 1]]
assert pred[3] == [0] | [
9,
15464,
3351
] |
def METHOD_NAME(self):
with ScratchDir("bad_groot") as d:
assert d == test_dir | [
9,
1068,
1563
] |
def METHOD_NAME(data, sampling_rate=1000, **kwargs):
"""**EDA Analysis on Interval-Related Data**
Performs EDA analysis on longer periods of data (typically > 10 seconds), such as resting-state
data.
Parameters
----------
data : Union[dict, pd.DataFrame]
A DataFrame containing the different processed signal(s) as different columns, typically
generated by :func:`eda_process` or :func:`bio_process`. Can also take a dict containing
sets of separately processed DataFrames.
sampling_rate : int
The sampling frequency of ``ecg_signal`` (in Hz, i.e., samples/second). Defaults to 1000.
**kwargs
Other arguments to be passed to the functions.
Returns
-------
DataFrame
A dataframe containing the analyzed EDA features. The analyzed
features consist of the following:
* ``"SCR_Peaks_N"``: the number of occurrences of Skin Conductance Response (SCR).
* ``"SCR_Peaks_Amplitude_Mean"``: the mean amplitude of the SCR peak occurrences.
* ``"EDA_Tonic_SD"``: the mean amplitude of the SCR peak occurrences.
* ``"EDA_Sympathetic"``: see :func:`eda_sympathetic` (only computed if signal duration
> 64 sec).
* ``"EDA_Autocorrelation"``: see :func:`eda_autocor` (only computed if signal duration
> 30 sec).
See Also
--------
.bio_process, eda_eventrelated
Examples
----------
.. ipython:: python
import neurokit2 as nk
# Download data
data = nk.data("bio_resting_8min_100hz")
# Process the data
df, info = nk.eda_process(data["EDA"], sampling_rate=100)
# Single dataframe is passed
nk.eda_intervalrelated(df, sampling_rate=100)
epochs = nk.epochs_create(df, events=[0, 25300], sampling_rate=100, epochs_end=20)
nk.eda_intervalrelated(epochs, sampling_rate=100)
"""
# Format input
if isinstance(data, pd.DataFrame):
results = _eda_intervalrelated(data, sampling_rate=sampling_rate, **kwargs)
results = pd.DataFrame.from_dict(results, orient="index").T
elif isinstance(data, dict):
results = {}
for index in data:
results[index] = {} # Initialize empty container
# Add label info
results[index]["Label"] = data[index]["Label"].iloc[0]
results[index] = _eda_intervalrelated(
data[index], results[index], sampling_rate=sampling_rate, **kwargs
)
results = pd.DataFrame.from_dict(results, orient="index")
return results | [
3797,
7707
] |
def METHOD_NAME():
return 1.234567654231 | [
791
] |
def METHOD_NAME(self):
cmake = CMake(self)
cmake.configure()
cmake.METHOD_NAME(target="libscip") | [
56
] |
def METHOD_NAME(self):
"""Check defining of order clause with single expr ASC.
"""
expected = convert_output("""
x | s | sum
----+---+-----
1 | a | 2
1 | b | 2
2 | b | 4
""")
execute_query(
"SELECT x,s, sum(x) OVER (ORDER BY x ASC) AS sum FROM values('x Int8, s String', (1,'a'),(1,'b'),(2,'b'))",
expected=expected
) | [
97,
2078,
4596
] |
def METHOD_NAME(test, params, env):
"""
Test for vhba hostdev passthrough.
1. create a vhba
2. prepare hostdev xml for lun device of the newly created vhba
3.1 If hot attach, attach-device the hostdev xml to vm
3.2 If cold attach, add the hostdev to vm and start it
4. login the vm and check the attached disk
5. detach-device the hostdev xml
6. login the vm to check the partitions
"""
def check_in_vm(vm, target, old_parts):
"""
Check mount/read/write disk in VM.
:param vm: VM guest.
:param target: Disk dev in VM.
:return: True if check successfully.
"""
try:
def get_attached_disk():
session = vm.wait_for_login()
new_parts = utils_disk.get_parts_list(session)
session.close()
added_parts = list(set(new_parts).difference(set(old_parts)))
return added_parts
added_parts = utils_misc.wait_for(get_attached_disk, _TIMEOUT)
logging.info("Added parts:%s", added_parts)
if len(added_parts) != 1:
logging.error("The number of new partitions is invalid in VM")
return False
added_part = None
if target.startswith("vd"):
if added_parts[0].startswith("vd"):
added_part = added_parts[0]
elif target.startswith("hd"):
if added_parts[0].startswith("sd"):
added_part = added_parts[0]
if not added_part:
logging.error("Can't see added partition in VM")
return False
cmd = ("fdisk -l /dev/{0} && mkfs.ext4 -F /dev/{0} && "
"mkdir -p test && mount /dev/{0} test && echo"
" teststring > test/testfile && umount test"
.format(added_part))
try:
cmd_status, cmd_output = session.cmd_status_output(cmd)
except Exception as detail:
test.error("Error occurred when run cmd: fdisk, %s" % detail)
logging.info("Check disk operation in VM:\n%s", cmd_output)
session.close()
if cmd_status != 0:
return False
return True
except (remote.LoginError, virt_vm.VMError, aexpect.ShellError) as detail:
logging.error(str(detail))
return False
try:
status_error = "yes" == params.get("status_error", "no")
vm_name = params.get("main_vm", "avocado-vt-vm1")
device_target = params.get("hostdev_disk_target", "hdb")
scsi_wwnn = params.get("scsi_wwnn", "ENTER.YOUR.WWNN")
scsi_wwpn = params.get("scsi_wwpn", "ENTER.YOUR.WWPN")
attach_method = params.get('attach_method', 'hot')
vm = env.get_vm(vm_name)
vmxml_backup = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)
virsh_dargs = {'debug': True, 'ignore_status': True}
new_vhbas = []
if scsi_wwnn.count("ENTER.YOUR.WWNN") or \
scsi_wwpn.count("ENTER.YOUR.WWPN"):
test.cancel("You didn't provide proper wwpn/wwnn")
# Load sg module if necessary
process.METHOD_NAME("modprobe sg", shell=True, ignore_status=True, verbose=True)
if vm.is_dead():
vm.start()
session = vm.wait_for_login()
old_parts = utils_disk.get_parts_list(session)
# find first online hba
online_hbas = []
online_hbas = utils_npiv.find_hbas("hba")
if not online_hbas:
test.cancel("NO ONLINE HBAs!")
first_online_hba = online_hbas[0]
# enable multipath service
process.METHOD_NAME("mpathconf --enable", shell=True)
# create vhba based on the first online hba
old_vhbas = utils_npiv.find_hbas("vhba")
logging.debug("Original online vHBAs: %s", old_vhbas)
new_vhba = utils_npiv.nodedev_create_from_xml(
{"nodedev_parent": first_online_hba,
"scsi_wwnn": scsi_wwnn,
"scsi_wwpn": scsi_wwpn})
if not utils_misc.wait_for(lambda: utils_npiv.is_vhbas_added(old_vhbas),
timeout=_TIMEOUT):
test.fail("vhba not successfully created")
new_vhbas.append(new_vhba)
# find first available lun of the newly created vhba
lun_dicts = []
first_lun = {}
if not utils_misc.wait_for(lambda: utils_npiv.find_scsi_luns(new_vhba),
timeout=_TIMEOUT):
test.fail("There is no available lun storage for "
"wwpn: %s, please check your wwns or "
"contact IT admins" % scsi_wwpn)
lun_dicts = utils_npiv.find_scsi_luns(new_vhba)
logging.debug("The luns discovered are: %s", lun_dicts)
first_lun = lun_dicts[0]
# prepare hostdev xml for the first lun
kwargs = {'addr_bus': first_lun['bus'],
'addr_target': first_lun['target'],
'addr_unit': first_lun['unit']}
new_hostdev_xml = utils_npiv.create_hostdev_xml(
adapter_name="scsi_host"+first_lun['scsi'],
**kwargs)
logging.info("New hostdev xml as follow:")
logging.info(new_hostdev_xml)
new_hostdev_xml.xmltreefile.write()
if attach_method == "hot":
# attach-device the lun's hostdev xml to guest vm
result = virsh.attach_device(vm_name, new_hostdev_xml.xml)
libvirt.check_exit_status(result, status_error)
elif attach_method == "cold":
if vm.is_alive():
vm.destroy(gracefully=False)
vmxml = vm_xml.VMXML.new_from_inactive_dumpxml(vm_name)
vmxml.devices = vmxml.devices.append(new_hostdev_xml)
vmxml.sync()
vm.start()
session = vm.wait_for_login()
logging.debug("The new vm's xml is: \n%s", vmxml)
# login vm and check the disk
check_result = check_in_vm(vm, device_target, old_parts)
if not check_result:
test.fail("check disk in vm failed")
result = virsh.detach_device(vm_name, new_hostdev_xml.xml)
libvirt.check_exit_status(result, status_error)
# login vm and check disk actually removed
if not vm.session:
session = vm.wait_for_login()
parts_after_detach = utils_disk.get_parts_list(session)
old_parts.sort()
parts_after_detach.sort()
if parts_after_detach == old_parts:
logging.info("hostdev successfully detached.")
else:
test.fail("Device not successfully detached. "
"Still existing in vm's /proc/partitions")
finally:
utils_npiv.vhbas_cleanup(new_vhbas)
# recover vm
if vm.is_alive():
vm.destroy(gracefully=False)
logging.info("Restoring vm...")
vmxml_backup.sync()
process.system('service multipathd restart', verbose=True) | [
22
] |
def METHOD_NAME():
years = datetime.datetime.now().year
return '(%s)' % '|'.join((str(year) for year in range(2014, years+1))) | [
19,
306
] |
METHOD_NAME(self): | [
9,
5354,
194,
14204
] |
def METHOD_NAME(self, f):
"""
Updates the internal header buffer. Returns a frame that should replace
the current one. May throw exceptions if this frame is invalid.
"""
# Check if we're in the middle of a headers block. If we are, this
# frame *must* be a CONTINUATION frame with the same stream ID as the
# leading HEADERS or PUSH_PROMISE frame. Anything else is a
# ProtocolError. If the frame *is* valid, append it to the header
# buffer.
if self._headers_buffer:
stream_id = self._headers_buffer[0].stream_id
valid_frame = (
f is not None and
isinstance(f, ContinuationFrame) and
f.stream_id == stream_id
)
if not valid_frame:
raise ProtocolError("Invalid frame during header block.")
# Append the frame to the buffer.
self._headers_buffer.append(f)
if len(self._headers_buffer) > CONTINUATION_BACKLOG:
raise ProtocolError("Too many continuation frames received.")
# If this is the end of the header block, then we want to build a
# mutant HEADERS frame that's massive. Use the original one we got,
# then set END_HEADERS and set its data appopriately. If it's not
# the end of the block, lose the current frame: we can't yield it.
if 'END_HEADERS' in f.flags:
f = self._headers_buffer[0]
f.flags.add('END_HEADERS')
f.data = b''.join(x.data for x in self._headers_buffer)
self._headers_buffer = []
else:
f = None
elif (isinstance(f, (HeadersFrame, PushPromiseFrame)) and
'END_HEADERS' not in f.flags):
# This is the start of a headers block! Save the frame off and then
# act like we didn't receive one.
self._headers_buffer.append(f)
f = None
return f | [
86,
572,
2376
] |
def METHOD_NAME(self, tag):
draft_release = self._get_editable_release()
# If we already have a release version created and in Editable state, just use that.
if draft_release:
return draft_release
# Create a new release in replicated
params = {'name': tag, 'source': 'latest', 'sourcedata': 0}
response = requests.post(self._get_request_endpoint('CREATE'),
headers=self.auth_header, json=params)
response.raise_for_status()
return json.loads(response.text) | [
19,
894,
129,
586
] |
def METHOD_NAME(x=[]):
assert 0, ([s for s in x] +
1)
pass | [
17808
] |
def METHOD_NAME() -> Generator[dict, None, None]:
for archive_id in iter_archive_ids(category="tools"):
logger.info("Fetching tool variants for {}".format(archive_id))
for tool_name in tqdm(sorted(MetadataFactory(archive_id).fetch_tools())):
if is_blacklisted_tool(tool_name):
continue
for tool_variant in MetadataFactory(
archive_id, tool_name=tool_name
).getList():
yield {
"os_name": archive_id.host,
"target": archive_id.target,
"tool_name": tool_name,
"arch": tool_variant,
} | [
84,
3081,
7439
] |
f METHOD_NAME(self, preset_definition_values): | [
203,
1319,
2181,
199
] |
def METHOD_NAME(
self,
src_uri: str,
) -> None:
_args = [CLI, "-vvvv", self.name, "rm", src_uri]
check_invoke(_args) | [
5528
] |
def METHOD_NAME(db, client, username, password, value_id):
client.login(username=username, password=password)
url = reverse(urlnames['detail'], args=[value_id])
response = client.delete(url)
if password:
assert response.status_code == 405
else:
assert response.status_code == 401 | [
9,
34
] |
def METHOD_NAME(self):
h = self._create_pkg("somepkg")
h2 = self._create_mod("sub.py", "somepkg")
h2.write(b"test=123\n")
h2.close()
h.write(b"from .sub import *\nmain=321\n")
h.close()
s = ModuleScanner([self.d])
removed, added = s.rescan()
self.failUnlessEqual(added, ["somepkg"])
self.failUnlessEqual(s.modules["somepkg"].module.main, 321)
self.failUnlessEqual(s.modules["somepkg"].module.test, 123) | [
9,
3401,
238,
360
] |
async def METHOD_NAME(
cls, session: ProfileSession, connection_id: str
) -> bool:
"""Return whether a mediation record exists for the given connection.
Args:
session (ProfileSession): session
connection_id (str): connection_id
Returns:
bool: whether record exists
"""
tag_filter = {"connection_id": connection_id}
try:
record = await cls.retrieve_by_tag_filter(session, tag_filter)
except StorageNotFoundError:
return False
except StorageDuplicateError:
return True
return bool(record) | [
954,
43,
550,
147
] |
def METHOD_NAME(self):
# this test cannot pass because cast error
x = np.random.rand(10)
y = jt.float32(x)
np.testing.assert_allclose(x, y.numpy()) | [
9,
877,
3723
] |
def METHOD_NAME(self, obj):
return get_attribute_in_correct_language(obj, "custom_message", get_language()) | [
19,
343,
277
] |
def METHOD_NAME(self, evt):
self.EndModal(wx.ID_OK) | [
356,
7576
] |
f METHOD_NAME(self, comp, arg): | [
4311
] |
def METHOD_NAME(self):
"""Generate tests.
:param self:
:return: test to run
"""
for test_string in test_strings:
self.assertEqual(test_string, TEST_RESULT) | [
9
] |
def METHOD_NAME(self, user_idx, item_idx=None):
"""Predict the scores/ratings of a user for an item.
Parameters
----------
user_idx: int, required
The index of the user for whom to perform score prediction.
item_idx: int, optional, default: None
The index of the item for which to perform score prediction.
If None, scores for all known items will be returned.
Returns
-------
res : A scalar or a Numpy array
Relative scores that the user gives to the item or to all known items
"""
if item_idx is None:
if self.train_set.is_unk_user(user_idx):
raise ScoreException(
"Can't make score prediction for (user_id=%d)" % user_idx
)
known_item_scores = self.V.dot(self.U[user_idx, :])
return known_item_scores
else:
if self.train_set.is_unk_user(user_idx) or self.train_set.is_unk_item(
item_idx
):
raise ScoreException(
"Can't make score prediction for (user_id=%d, item_id=%d)"
% (user_idx, item_idx)
)
user_pred = self.V[item_idx, :].dot(self.U[user_idx, :])
return user_pred | [
747
] |
def METHOD_NAME():
"""
Test Cases:
- No response provided; non-uuid value given for project
"""
project = project_exists("Test_Project")
assert project.name == "Test_Project" | [
9,
155,
954
] |
def METHOD_NAME():
"""
Test to ensure that multiple kernel modules are loaded.
"""
name = "salted kernel"
mods = ["cheese", "crackers"]
ret = {"name": name, "result": True, "changes": {}}
mock_mod_list = MagicMock(return_value=mods)
with patch.dict(kmod.__salt__, {"kmod.mod_list": mock_mod_list}):
call_ret = kmod.present(name, mods=mods)
# Check comment independently: makes test more stable on PY3
comment = call_ret.pop("comment")
assert "cheese" in comment
assert "crackers" in comment
assert "are already present" in comment
# Assert against all other dictionary key/values
assert ret == call_ret
mock_mod_list = MagicMock(return_value=[])
with patch.dict(kmod.__salt__, {"kmod.mod_list": mock_mod_list}):
with patch.dict(kmod.__opts__, {"test": True}):
call_ret = kmod.present(name, mods=mods)
ret.update({"result": None})
# Check comment independently: makes test more stable on PY3
comment = call_ret.pop("comment")
assert "cheese" in comment
assert "crackers" in comment
assert "are set to be loaded" in comment
# Assert against all other dictionary key/values
assert ret == call_ret
mock_mod_list = MagicMock(return_value=[])
mock_available = MagicMock(return_value=mods)
mock_load = MagicMock(return_value=mods)
with patch.dict(
kmod.__salt__,
{
"kmod.mod_list": mock_mod_list,
"kmod.available": mock_available,
"kmod.load": mock_load,
},
):
with patch.dict(kmod.__opts__, {"test": False}):
call_ret = kmod.present(name, mods=mods)
ret.update(
{"result": True, "changes": {mods[0]: "loaded", mods[1]: "loaded"}}
)
# Check comment independently: makes test more stable on PY3
comment = call_ret.pop("comment")
assert "cheese" in comment
assert "crackers" in comment
assert "Loaded kernel modules" in comment
# Assert against all other dictionary key/values
assert ret == call_ret | [
9,
2541,
457
] |
def METHOD_NAME(self, raise_on_empty_metrics: bool = False) -> None:
self.provider.METHOD_NAME(raise_on_empty_metrics=raise_on_empty_metrics) | [
1579,
1097
] |
def METHOD_NAME():
conn = boto3.client("managedblockchain", region_name="us-east-1")
# Create network - need a good network
network_id = conn.create_network(
Name="testnetwork1",
Framework="HYPERLEDGER_FABRIC",
FrameworkVersion="1.2",
FrameworkConfiguration=helpers.default_frameworkconfiguration,
VotingPolicy=helpers.default_votingpolicy,
MemberConfiguration=helpers.default_memberconfiguration,
)["NetworkId"]
with pytest.raises(ClientError) as ex:
conn.create_proposal(
NetworkId=network_id,
MemberId="m-ABCDEFGHIJKLMNOP0123456789",
Actions=helpers.default_policy_actions,
)
err = ex.value.response["Error"]
assert err["Code"] == "ResourceNotFoundException"
assert "Member m-ABCDEFGHIJKLMNOP0123456789 not found" in err["Message"] | [
9,
129,
4229,
-1
] |
def METHOD_NAME(self):
"""
test service.get_enabled and service.enable module
"""
# disable service before test
self.assertTrue(self.run_function("service.disable", [self.service_name]))
self.assertTrue(self.run_function("service.enable", [self.service_name]))
self.assertIn(self.service_name, self.run_function("service.get_enabled")) | [
9,
549,
1317
] |
def METHOD_NAME(vm):
"""Installs tomcat on the server."""
vm.Install('tomcat')
_IncreaseMaxOpenFiles(vm)
tomcat.Start(vm) | [
123,
163
] |
def METHOD_NAME(next_link=None):
if not next_link:
request = build_list_request(
api_version=api_version,
template_url=self.list.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request | [
123,
377
] |
def METHOD_NAME(self, enable):
"""
Allow to disable the default behaviour of the QComboBox which update
the current index to 0 when the model crow from an empty state.
"""
if self.__updateDefaultIndexUpdate == enable:
return
self.__updateDefaultIndexUpdate = enable
self.__updateModelConnection(not enable)
if enable:
if self.model() is not None:
self.__modelWasEmpty = self.model().rowCount() == 0 | [
0,
86,
1056,
724,
1111
] |
def METHOD_NAME(self, n, Re):
"""Returns normalisation of the sersic profile such that Re is the half light
radius given n_sersic slope."""
bn = self.b_n(n)
k = bn * Re ** (-1.0 / n)
return k, bn | [
4407,
3849
] |
def METHOD_NAME(workload: spec.Workload,
current_param_container: spec.ParameterContainer,
current_params_types: spec.ParameterTypeTree,
model_state: spec.ModelAuxiliaryState,
hyperparameters: spec.Hyperparameters,
batch: Dict[str, spec.Tensor],
loss_type: spec.LossType,
optimizer_state: spec.OptimizerState,
eval_results: List[Tuple[int, float]],
global_step: int,
rng: spec.RandomState) -> spec.UpdateReturn:
"""Return (updated_optimizer_state, updated_params)."""
del current_params_types
del eval_results
del loss_type
lr = get_learning_rate(global_step, hyperparameters)
optimizer_state, opt_update_fn = optimizer_state
per_device_rngs = jax.random.split(rng, jax.local_device_count())
outputs = pmapped_train_step(workload,
opt_update_fn,
model_state,
optimizer_state,
current_param_container,
hyperparameters,
batch,
per_device_rngs,
lr)
new_model_state, new_optimizer_state, new_params, loss, grad_norm = outputs
if global_step <= 1000 or global_step % 100 == 0:
logging.info('%d) loss = %0.3f, grad_norm = %0.3f lr = %0.6f',
global_step,
loss.mean(),
grad_norm.mean(),
lr)
if workload.metrics_logger is not None:
workload.metrics_logger.append_scalar_metrics(
{
'train_step_ctc_loss': loss.mean(),
'grad_norm': grad_norm.mean(),
'learning_rate': lr,
},
global_step)
return (new_optimizer_state, opt_update_fn), new_params, new_model_state | [
86,
434
] |
def METHOD_NAME(state):
# For now runs on only two processes
if state.num_processes != 2:
return
tensor = create_tensor(state)
reduced_tensor = reduce(tensor, "mean")
truth_tensor = torch.tensor([2.0, 3]).to(state.device)
assert torch.allclose(reduced_tensor, truth_tensor), f"{reduced_tensor} != {truth_tensor}" | [
9,
332,
314
] |
def METHOD_NAME(self, site):
self.site = site | [
0,
1055
] |
def METHOD_NAME(self):
mags = torch.tensor([0, 0.5, 1.0], device=self.device, dtype=self.dtype)
self._assert_consistency(F.frequency_impulse_response, (mags,)) | [
9,
3702,
5925
] |
def METHOD_NAME(self):
with open(sync.DEFAULT_PATH + '/genesis/members.s.py') as f:
code = f.read()
code_obj = compile(code, '', 'exec')
code_blob = marshal.dumps(code_obj)
self.contract_driver.set_var('masternodes', CODE_KEY, value=code)
self.contract_driver.set_var('masternodes', COMPILED_KEY, value=code_blob) | [
0,
1522,
544
] |
def METHOD_NAME(path):
"""Check whether the path is probably a TF Events file containing Summary.
Args:
path: A file path to check if it is an event file containing `Summary`
protos.
Returns:
If path is formatted like a TensorFlowEventsFile. Dummy files such as
those created with the '.profile-empty' suffixes and meant to hold
no `Summary` protos are treated as `False`. For background, see:
https://github.com/tensorflow/tensorboard/issues/2084.
"""
return IsTensorFlowEventsFile(path) and not path.endswith(".profile-empty") | [
137,
2718,
239,
171
] |
def METHOD_NAME():
day = time.strftime("%a")
hour = time.strftime("%I")
minutes = time.strftime("%M")
ampm = time.strftime("%p")
date_label.config(text=f"{day} {hour}:{minutes} {ampm}")
date_label.after(1000, METHOD_NAME) | [
3329
] |
def METHOD_NAME(benchmark_spec):
"""Create metadata dict to be used in run results.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
Returns:
metadata dict
"""
metadata = mnist_benchmark.CreateMetadataDict(benchmark_spec)
metadata.update({
'model': benchmark_spec.model,
'problem': benchmark_spec.problem,
'hparams_set': benchmark_spec.hparams_set,
'data_dir': benchmark_spec.data_dir,
'model_dir': benchmark_spec.model_dir,
'train_steps': benchmark_spec.train_steps,
'eval_steps': benchmark_spec.eval_steps})
return metadata | [
129,
773,
553
] |
def METHOD_NAME():
open(SYNCFILE, "wb").close() | [
129,
164,
171
] |
def METHOD_NAME(self):
relative_time = time.time() - self.global_start
to_run = []
for job in self.jobs:
if job.due_to_run(relative_time):
to_run.append(job)
logger.debug(f'scheduler found {job.name} to run, {relative_time - job.next_run} seconds after target')
job.mark_run(relative_time)
return to_run | [
19,
61,
1743,
1359
] |
def METHOD_NAME(self, bash):
output = assert_bash_exec(bash, "__tester '\"$v\"'", want_output=True)
assert output.strip() == "<var>" | [
9,
1136,
11891,
1170
] |
def METHOD_NAME():
client = ComputeManagementClient(
credential=DefaultAzureCredential(),
subscription_id="{subscription-id}",
)
response = client.virtual_machine_scale_sets.begin_create_or_update(
resource_group_name="myResourceGroup",
vm_scale_set_name="{vmss-name}",
parameters={
"location": "eastus2euap",
"properties": {
"overprovision": True,
"upgradePolicy": {"automaticOSUpgradePolicy": {"enableAutomaticOSUpgrade": True}, "mode": "Automatic"},
"virtualMachineProfile": {
"networkProfile": {
"networkInterfaceConfigurations": [
{
"name": "{vmss-name}",
"properties": {
"enableIPForwarding": True,
"ipConfigurations": [
{
"name": "{vmss-name}",
"properties": {
"subnet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/{existing-virtual-network-name}/subnets/{existing-subnet-name}"
}
},
}
],
"primary": True,
},
}
]
},
"osProfile": {
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerNamePrefix": "{vmss-name}",
},
"serviceArtifactReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/galleries/myGalleryName/serviceArtifacts/serviceArtifactName/vmArtifactsProfiles/vmArtifactsProfilesName"
},
"storageProfile": {
"imageReference": {
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2022-Datacenter",
"version": "latest",
},
"osDisk": {"caching": "ReadWrite", "createOption": "FromImage", "name": "osDisk"},
},
},
},
"sku": {"capacity": 3, "name": "Standard_A1", "tier": "Standard"},
},
).result()
print(response) | [
57
] |
def METHOD_NAME(self, items, build_dir):
"""Write a dict containing filename->binary data"""
for filename, data in items:
# Determine where to write the file to
dest = os.path.join(build_dir, filename)
path = os.path.dirname(dest)
self._makedir(path)
# Write file
self.log.debug("Writing %i bytes to %s", len(data), dest)
with open(dest, "wb") as f:
f.write(data) | [
77,
1768
] |
def METHOD_NAME(environment_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetManagedEnvironmentAuthTokenResult:
"""
Checks if resource name is available.
:param str environment_name: Name of the Managed Environment.
:param str resource_group_name: The name of the resource group. The name is case insensitive.
"""
__args__ = dict()
__args__['environmentName'] = environment_name
__args__['resourceGroupName'] = resource_group_name
opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts)
__ret__ = pulumi.runtime.invoke('azure-native:app/v20221001:getManagedEnvironmentAuthToken', __args__, opts=opts, typ=GetManagedEnvironmentAuthTokenResult).value
return AwaitableGetManagedEnvironmentAuthTokenResult(
expires=pulumi.get(__ret__, 'expires'),
id=pulumi.get(__ret__, 'id'),
location=pulumi.get(__ret__, 'location'),
name=pulumi.get(__ret__, 'name'),
system_data=pulumi.get(__ret__, 'system_data'),
tags=pulumi.get(__ret__, 'tags'),
token=pulumi.get(__ret__, 'token'),
type=pulumi.get(__ret__, 'type')) | [
19,
3627,
1027,
2433,
466
] |
def METHOD_NAME(self, argcomplete_on):
app = MainApp()
completions = set(self.run_completer(app, "app --"))
assert completions > {'--Application.', '--MainApp.'}
assert "--SubApp1." not in completions and "--SubApp2." not in completions | [
9,
676,
10893,
57
] |
def METHOD_NAME():
for vector in PERMISSIONS_TEST_VECTORS:
(line, with_group,
permissions_owner, permissions_group, permissions_other, owner, group, path,
owned_by_root_user, owned_by_root_user_and_group,
only_root_can_read, only_root_can_write) = vector
p = FilePermissions(line)
assert p.perms_owner == permissions_owner
assert p.perms_group == permissions_group
assert p.perms_other == permissions_other
assert p.owner == owner
assert p.group == group
assert p.owned_by('root', also_check_group=False) == owned_by_root_user
assert p.owned_by('root', also_check_group=True) == owned_by_root_user_and_group
assert p.only_root_can_read(root_group_can_read=with_group) == only_root_can_read
assert p.only_root_can_write(root_group_can_write=with_group) == only_root_can_write
assert p.all_zero() == all((p.perms_owner == '---', p.perms_group == '---',
p.perms_other == '---'))
assert p.owner_can_read() == ('r' in p.perms_owner)
assert p.owner_can_write() == ('w' in p.perms_owner)
assert p.owner_can_only_read() == ('r--' == p.perms_owner)
assert p.group_can_read() == ('r' in p.perms_group)
assert p.group_can_write() == ('w' in p.perms_group)
assert p.group_can_only_read() == ('r--' == p.perms_group)
assert p.others_can_read() == ('r' in p.perms_other)
assert p.others_can_write() == ('w' in p.perms_other)
assert p.others_can_only_read() == ('r--' == p.perms_other) | [
9,
804
] |
def METHOD_NAME(self):
super(type(self), self).METHOD_NAME()
initializeTestModule_SingleInstance(self) | [
0,
1
] |
def METHOD_NAME(self):
"""Prune unkown Jenkins fails gracefully"""
with self.assertRaises(SystemExit) as ex:
self.executeBobJenkinsCmd("prune doesnotexist")
self.assertEqual(ex.exception.code, 1) | [
9,
3724,
46
] |
def METHOD_NAME(self):
self._delete("subject") | [
188,
2533
] |
def METHOD_NAME(seriesname,simname,tmplfile,maxLevel,maxCoarseSize, simplesweeps, simplerelax, usesimplec, coarsesimplesweeps, coarsesimplerelax, coarseusesimplec, relsmootype, relsmooiter, relsmoodamp, schursmootype, schursmoofill, procs, jobfile):
# generate filenames
filename_out = seriesname + simname + "_" + str(simplesweeps) + "Simple" + str(simplerelax) + "_" + str(coarsesimplesweeps) + str(usesimplec) + "Simple" + str(coarsesimplerelax) + str(coarseusesimplec) + "_" + str(relsmootype) + str(relsmooiter) + str(relsmoodamp) + "_" + str(schursmootype) + str(schursmoofill) + "_maxL" + str(maxLevel) + "_maxCoarseSize" + str(maxCoarseSize) + "_" + str(procs) + "proc"
if (relsmootype == "SGS"):
relsmootype = "Symmetric Gauss-Seidel"
elif (relsmootype == "GS"):
relsmootype = "Gauss-Seidel"
elif (relsmootype == "JAC"):
relsmootype = "Jacobi"
# generate filenames
filename_log = filename_out + ".log"
filename_xml = filename_out + ".xml"
# generate XML file for pre_exodus
if os.path.isfile(filename_xml):
os.remove(filename_xml)
o = open(filename_xml,"a")
for line in open(tmplfile):
line = line.replace("$MAXLEVEL", str(maxLevel))
line = line.replace("$MAXCOARSESIZE", str(maxCoarseSize))
line = line.replace("$RELSMOOTYPE", str(relsmootype))
line = line.replace("$RELSMOOITER", str(relsmooiter))
line = line.replace("$RELSMOODAMP", str(relsmoodamp))
line = line.replace("$SCHURSMOOTYPE", str(schursmootype))
line = line.replace("$SCHURSMOOFILL", str(schursmoofill))
line = line.replace("$COARSESIMPLESWEEPS", str(coarsesimplesweeps))
line = line.replace("$COARSESIMPLERELAX", str(coarsesimplerelax))
line = line.replace("$COARSEUSESIMPLEC", str(coarseusesimplec))
line = line.replace("$SIMPLESWEEPS", str(simplesweeps))
line = line.replace("$SIMPLERELAX", str(simplesweeps))
line = line.replace("$USESIMPLEC", str(usesimplec))
o.write(line)
o.close()
jobfile.write("mpirun -np " + str(procs) + " ./MueLu_CradaDriver.exe --xml=" + filename_xml + " --split=1 --thyra=0 --matrixfile=grid_50_50_30/A0.m --rhsfile=grid_50_50_30/b0.m --coordinatesfile=grid_50_50_30/coordinates.m --specialfile=grid_50_50_30/special.m --nspfile= --linAlgebra=Epetra --tol=1e-10 --maxits=150 --output=" + filename_out + " | tee " + filename_out + ".txt\n\n\n") | [
370,
171
] |
def METHOD_NAME(self):
"""Make sure we can build multiple simultanious builds on
both the front-end and the nodes."""
arg_parser = arguments.get_parser()
args = arg_parser.parse_args([
'run',
'-H', 'this',
'build_parallel'
])
run_cmd = commands.get_command(args.command_name)
run_ret = run_cmd.run(self.pav_cfg, args)
run_cmd.outfile.seek(0)
self.assertEqual(run_ret, 0, msg=run_cmd.outfile.read())
for test in run_cmd.last_tests:
test.wait(timeout=10)
# Make sure we actually built separate builds
builds = [test.builder for test in run_cmd.last_tests]
build_names = set([b.name for b in builds])
self.assertEqual(len(build_names), 4)
for test in run_cmd.last_tests:
if test.skipped:
continue
self.assertEqual(test.results['result'], 'PASS',
msg='Test {} status: {}'
.format(test.id, test.status.current())) | [
9,
457,
56
] |
def METHOD_NAME(curr_uttr):
"""Extract entities as topics for news request. If no entities found, extract nounphrases.
Args:
curr_uttr: current human utterance dictionary
Returns:
list of mentioned entities/nounphrases
"""
entities = get_entities(curr_uttr, only_named=True, with_labels=False)
entities = [ent.lower() for ent in entities]
entities = [
ent
for ent in entities
if not (ent == "alexa" and curr_uttr["text"].lower()[:5] == "alexa") and "news" not in ent
]
if len(entities) == 0:
for ent in get_entities(curr_uttr, only_named=False, with_labels=False):
if ent.lower() not in BANNED_UNIGRAMS and "news" not in ent.lower():
if ent in entities:
pass
else:
entities.append(ent)
entities = [ent for ent in entities if len(ent) > 0]
return entities | [
297,
8532
] |
def METHOD_NAME(period, target):
"""
:param period: 'hourly', 'daily', 'weekly', or 'monthly'
:param target: The 15-minute-aligned point in time we are targeting for a match
:return: generator of couch view kwargs to use in view query for 'reportconfig/all_notifications'
"""
assert target.minute % 15 == 0
assert target.second == 0
assert target.microsecond == 0
if target.minute == 0:
# for legacy purposes, on the hour also include reports that didn't have a minute set
minutes = (None, target.minute)
else:
minutes = (target.minute,)
if period == 'hourly' and target.minute == 0:
yield {
'startkey': [period],
'endkey': [period, {}]
}
elif period == 'daily':
for minute in minutes:
yield {
'startkey': [period, target.hour, minute],
'endkey': [period, target.hour, minute, {}],
}
elif period == 'weekly':
for minute in minutes:
yield {
'key': [period, target.hour, minute, target.weekday()],
}
else:
# monthly
for minute in minutes:
yield {
'key': [period, target.hour, minute, target.day]
}
if target.day == monthrange(target.year, target.month)[1]:
for day in range(target.day + 1, 32):
for minute in minutes:
yield {
'key': [period, target.hour, minute, day]
} | [
93,
75,
857,
1179,
219
] |
def METHOD_NAME(self, obj):
assert isinstance(obj, ASTObject)
assert not isinstance(obj, Reference)
assert len(self.scopes) > 0
if not hasattr(obj, 'name') or obj.name is None:
return
scope_type = type(obj)
if scope_type in [Group, Instance]:
scope_type = "group/component"
else:
scope_type = type(obj).__name__
duplicate = self.scopes[-1][obj.name].get(scope_type)
if duplicate is not None:
raise ParseError('duplicate definition of %s \'%s\'; previous '
'definition was at %s:%s' % (scope_type, obj.name,
duplicate.filename or '<unnamed>', duplicate.lineno),
obj.location)
self.scopes[-1][obj.name][scope_type] = obj | [
372
] |
def METHOD_NAME():
content = [
Strip([Segment("foo")]),
Strip([Segment("bar")]),
Strip([Segment("baz")]),
]
styles = Styles()
styles.padding = 1
cache = StylesCache()
lines = cache.render(
styles,
Size(5, 5),
Color.parse("blue"),
Color.parse("green"),
content.__getitem__,
Console(),
None,
None,
content_size=Size(3, 3),
)
text_content = _extract_content(lines)
expected_text = [
" ",
" foo ",
" bar ",
" baz ",
" ",
]
assert text_content == expected_text | [
9,
746
] |
def METHOD_NAME(config_content: str) -> str:
"""Return a legacy authorization header."""
conf = _load_potentially_base64_config(config_content)
auth = _get_macaroons_from_conf(conf)
return base64.b64encode(json.dumps(auth).encode()).decode() | [
19,
2433
] |
def METHOD_NAME(target, predicted_labels, predicted_probas):
figures = []
try:
#
fig = plt.figure(figsize=(10, 7))
ax1 = fig.add_subplot(1, 1, 1)
_ = skplt.metrics.plot_confusion_matrix(
target, predicted_labels, normalize=False, ax=ax1
)
figures += [
{
"title": "Confusion Matrix",
"fname": "confusion_matrix.png",
"figure": fig,
}
]
#
fig = plt.figure(figsize=(10, 7))
ax1 = fig.add_subplot(1, 1, 1)
_ = skplt.metrics.plot_confusion_matrix(
target, predicted_labels, normalize=True, ax=ax1
)
figures += [
{
"title": "Normalized Confusion Matrix",
"fname": "confusion_matrix_normalized.png",
"figure": fig,
}
]
#
fig = plt.figure(figsize=(10, 7))
ax1 = fig.add_subplot(1, 1, 1)
_ = skplt.metrics.plot_roc(target, predicted_probas, ax=ax1)
figures += [{"title": "ROC Curve", "fname": "roc_curve.png", "figure": fig}]
#
fig = plt.figure(figsize=(10, 7))
ax1 = fig.add_subplot(1, 1, 1)
_ = skplt.metrics.plot_precision_recall(target, predicted_probas, ax=ax1)
figures += [
{
"title": "Precision Recall Curve",
"fname": "precision_recall_curve.png",
"figure": fig,
}
]
plt.close("all")
except Exception as e:
print(str(e))
return figures | [
2809,
592
] |
def METHOD_NAME(dir):
assert dir == "/template_dir"
return [
"/template_dir/debian_file1.in",
"/template_dir/debian_file2.in",
"/template_dir/debian_file3",
"/template_dir/debian_file4",
] | [
248,
2778
] |
def METHOD_NAME(self,controlKey,activeFlag):
if controlKey == PlasmaControlKeys.kKeyExitMode:
self.IQuitTelescope()
elif controlKey == PlasmaControlKeys.kKeyMoveBackward or controlKey == PlasmaControlKeys.kKeyRotateLeft or controlKey == PlasmaControlKeys.kKeyRotateRight:
self.IQuitTelescope() | [
69,
401,
59,
417
] |
async def METHOD_NAME(self, n: int = None) -> bytes:
return await self.stream.receive_some(n) | [
203
] |
def METHOD_NAME(request, response):
return pluginManagerGlobal.globalPlug(request, METHOD_NAME, response) | [
72,
6702,
581
] |
def METHOD_NAME(self, mocked_init):
rm_pbspro = PBSPro(cfg=None, log=None, prof=None)
rm_pbspro._log = mock.Mock()
with mock.patch('radical.pilot.agent.resource_manager.pbspro.'
'ru.sh_callout') as mocked_callout:
mocked_callout.return_value = [
'exec_vnode = (vnode1:cpu=10)+(vnode2:cpu=10)+\n'
'(vnode3:cpu=10)\n'
'other_attr = some_value', '', 0]
nodes, cores_per_node = rm_pbspro._parse_pbspro_vnodes()
self.assertEqual(nodes, ['vnode1', 'vnode2', 'vnode3'])
self.assertEqual(cores_per_node, 10) | [
9,
214,
-1,
17251
] |
def METHOD_NAME():
"""
Run a benchmark.
BENCHMARK::
sage: from sage.misc.benchmark import *
sage: print(bench7()[0])
Compute the Mordell-Weil group of y^2 = x^3 + 37*x - 997.
"""
desc = """Compute the Mordell-Weil group of y^2 = x^3 + 37*x - 997."""
E = EllipticCurve([0,0,0,37,-997])
t = cputime()
G = E.gens()
return (desc, cputime(t)) | [
-1
] |
def METHOD_NAME(node, indent=0):
print(" " * indent, node)
for child in node.children:
METHOD_NAME(child, indent + 2) | [
38,
151
] |
async def METHOD_NAME(self, hash, params):
self._warema_shades[self._warema_channel].set_shade_position(
0
) # 0=open; 100=closed
state = self._warema_shades[self._warema_channel].get_shade_state(
True
) # Force update and get shade state
(position, ismoving, date) = state
self._warema_position = str(int(position))
self._warema_ismoving = ismoving
await self.updateDeviceReadings() | [
0,
1
] |
def METHOD_NAME(self):
response = self.publish(self.folder_path + '/set_cookie')
self.assertEqual(response.getStatus(), 200)
self.assertEqual(response.getCookie('foo').get('value'), 'Bar')
self.assertEqual(response.getCookie('foo').get('Path'), '/') | [
9,
4177
] |
def METHOD_NAME(self):
rho0 = 1
Rs = 3
m_tot = self.profile.mass_tot(rho0, Rs)
npt.assert_almost_equal(m_tot, 169.64600329384882, decimal=6) | [
9,
2858,
9419
] |
async def METHOD_NAME(pipeline_response):
deserialized = self._deserialize(
"ResourceProviderOperationList", pipeline_response
)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem) | [
297,
365
] |
def METHOD_NAME(self):
expected_str = (
"Flow run received invalid parameters:\n - num: value is not a valid"
" integer"
)
try:
ValidationTestModel(**{"num": "not an int", "string": "a string"})
except Exception as exc:
pte = ParameterTypeError.from_validation_error(exc)
assert str(pte) == expected_str
assert pte.args == ParameterTypeError(expected_str).args | [
9,
2801,
280,
97,
437,
168
] |
def METHOD_NAME(test_path):
create_secure_directory(test_path)
assert_linux_permissions(test_path) | [
9,
129,
3271,
2851,
2878,
3031
] |
def METHOD_NAME(self, dataset_values):
input_shape = INPUT_SHAPE
METHOD_NAME = [np.zeros(input_shape), np.ones(input_shape)]
for i, value in enumerate(dataset_values):
METHOD_NAME[0][i, 0, 0] = value["max"]
METHOD_NAME[0][i, 0, 1] = value["min"]
return METHOD_NAME | [
126,
700
] |
def METHOD_NAME(seeded):
"""Tests that the seed data functions can create and delete seed data"""
expected_programs = len(seeded.raw_data["programs"])
expected_courses = len(seeded.raw_data["courses"])
expected_course_runs = sum(
len(course_data.get("course_runs", []))
for course_data in seeded.raw_data["courses"]
)
# Hardcoding this value since it would be annoying to check for it programatically
expected_products = 12
expected_resource_pages = len(seeded.raw_data["resource_pages"])
assert Program.objects.count() == expected_programs
assert ProgramPage.objects.count() == expected_programs
assert Course.objects.count() == expected_courses
assert CoursePage.objects.count() == expected_courses
assert CourseRun.objects.count() == expected_course_runs
assert ResourcePage.objects.count() == expected_resource_pages
assert Product.objects.count() == expected_products
assert ProductVersion.objects.count() == expected_products
with unprotect_version_tables():
seeded.loader.delete_seed_data(seeded.raw_data)
assert Program.objects.count() == 0
assert ProgramPage.objects.count() == 0
assert Course.objects.count() == 0
assert CoursePage.objects.count() == 0
assert CourseRun.objects.count() == 0
assert ResourcePage.objects.count() == 0
assert Product.objects.count() == 0
assert ProductVersion.objects.count() == 0 | [
9,
484,
61,
-1,
365
] |
def METHOD_NAME(self, **kwargs):
return self._oauth2_connector.METHOD_NAME(**kwargs) | [
56,
1355,
274
] |
def METHOD_NAME(
benchmark_time_copy: int,
benchmark_time_unload: int,
path: str,
redshift_table: str,
redshift_con: Connection,
databases_parameters: Dict[str, str],
request,
) -> None:
df = wr.s3.read_parquet(path=[f"s3://ursa-labs-taxi-data/2018/{i}/data.parquet" for i in range(10, 13)])
with ExecutionTimer(request, "redshift_copy") as timer:
wr.redshift.copy(
df=df,
path=path,
con=redshift_con,
schema="public",
table=redshift_table,
mode="overwrite",
iam_role=databases_parameters["redshift"]["role"],
)
assert timer.elapsed_time < benchmark_time_copy
with ExecutionTimer(request, "redshift_unload") as timer:
df2 = wr.redshift.unload(
sql=f"SELECT * FROM public.{redshift_table}",
con=redshift_con,
iam_role=databases_parameters["redshift"]["role"],
path=path,
keep_files=False,
)
assert timer.elapsed_time < benchmark_time_unload
assert df.shape == df2.shape | [
9,
7477,
215,
5473
] |
def METHOD_NAME(self):
return {
"my_macro.sql": my_macro_sql,
} | [
6048
] |
def METHOD_NAME(self):
with pytest.raises(ValueError):
IPRange.from_string('10.0.0.0/8/24') | [
9,
457,
361,
427,
241
] |
def METHOD_NAME(self):
if verbose:
print '\n', '-=' * 30
print "Running %s.test02_threaded..." % self.__class__.__name__
threads = []
threads.append(Thread(target = self.theThread,
args=(db.DB_LOCK_WRITE,)))
threads.append(Thread(target = self.theThread,
args=(db.DB_LOCK_READ,)))
threads.append(Thread(target = self.theThread,
args=(db.DB_LOCK_READ,)))
threads.append(Thread(target = self.theThread,
args=(db.DB_LOCK_WRITE,)))
threads.append(Thread(target = self.theThread,
args=(db.DB_LOCK_READ,)))
threads.append(Thread(target = self.theThread,
args=(db.DB_LOCK_READ,)))
threads.append(Thread(target = self.theThread,
args=(db.DB_LOCK_WRITE,)))
threads.append(Thread(target = self.theThread,
args=(db.DB_LOCK_WRITE,)))
threads.append(Thread(target = self.theThread,
args=(db.DB_LOCK_WRITE,)))
for t in threads:
import sys
if sys.version_info[0] < 3 :
t.setDaemon(True)
else :
t.daemon = True
t.start()
for t in threads:
t.join() | [
315,
6861
] |
def METHOD_NAME(name, schema, column_names, engine, comment, data_file):
dialect = csv.dialect.SimpleDialect(data_file.delimiter, data_file.quotechar,
data_file.escapechar)
encoding = get_file_encoding(data_file.file)
table = create_string_column_table(
name=name,
schema_oid=schema.oid,
column_names=column_names,
engine=engine,
comment=comment,
)
insert_records_from_csv(
table,
engine,
data_file.file.path,
column_names,
data_file.header,
delimiter=dialect.delimiter,
escape=dialect.escapechar,
quote=dialect.quotechar,
encoding=encoding
)
return table | [
408,
2530,
280,
732,
365,
171
] |
def METHOD_NAME(self):
"""Return an ordered list of indices. Batches will be constructed based
on this order."""
if self.shuffle:
order = [np.random.permutation(len(self))]
else:
order = [np.arange(len(self))]
order.append(self.sizes)
return np.lexsort(order) | [
2687,
1894
] |
def METHOD_NAME():
test_list = [
{
"provider": "cluster-self-vpc",
"vpc_name": "cluster-name",
"cidr_block": "10.25.0.0/16",
},
{
"provider": "account-vpc",
"vpc_name": "vpc-name-1",
"cidr_block": "10.18.0.0/18",
},
{
"provider": "account-vpc",
"vpc_name": "vpc-name-2",
"cidr_block": "10.18.0.0/18",
},
]
cluster_name = "cluster-name"
assert find_cidr_overlap(cluster_name, test_list) is True | [
9,
187,
187,
7470,
2820
] |
def METHOD_NAME(self) -> str:
"""
Resource provisioning state.
"""
return pulumi.get(self, "provisioning_state") | [
1994,
551
] |
def METHOD_NAME(self, input, factor, quality=0):
if input: sr = len(input)
else: sr = 44100
METHOD_NAME = Resample(inputSampleRate = sr,
outputSampleRate = int(factor*sr),
quality = quality)
pool = Pool()
gen = VectorInput(input)
gen.data >> METHOD_NAME.signal
METHOD_NAME.signal >> (pool, 'signal')
run(gen)
if not pool.descriptorNames() : return []
return pool['signal'] | [
4182
] |
async def METHOD_NAME(
cls,
actor_pool_config: ActorPoolConfig,
process_index: int,
start_method: str = None,
):
status_queue = multiprocessing.Queue()
return (
asyncio.create_task(
cls._create_sub_pool(actor_pool_config, process_index, status_queue)
),
status_queue,
) | [
447,
1066,
1567
] |
def METHOD_NAME(model, edges=False, **kwargs):
dataset = TestDataset(
[
_get_graph(
n_nodes=n_nodes,
n_features=n_node_features,
n_edge_features=n_edge_features if edges else None,
)
for _ in range(batch_size)
]
)
loader = loaders.BatchLoader(dataset, epochs=1, batch_size=batch_size)
inputs = loader.__next__()
model_instance = model(**kwargs)
output = model_instance(inputs) | [
9,
2277,
854
] |
def METHOD_NAME(self):
return self.queryset.count() | [
1346,
29
] |
f METHOD_NAME(chars, s, start, end): | [
16115,
2147
] |
def METHOD_NAME(self):
from cbuild.util import cargo
for crate in []:
cargo.clear_vendor_checksums(self, crate, vendor_dir="third_party/rust") | [
72,
1575
] |
def METHOD_NAME(self, key):
'''Get config default_value for a specific key.
Args:
key (str): Config key
Retruns:
python object
'''
return self._get_by_key(key, 'default_value') | [
19,
235,
1259
] |
def METHOD_NAME(self, *args, **kwargs):
kwargs.setdefault("timeout", settings.DEFAULT_TIMEOUT_REQUESTS)
return self._original_request(*args, **kwargs) | [
80,
377
] |
def METHOD_NAME(data_fixture):
session_id = "1010"
user = data_fixture.create_user(session_id=session_id)
table = data_fixture.create_database_table(user=user)
grid_view = data_fixture.create_grid_view(table=table)
number_field = data_fixture.create_number_field(
table=table, name="value", number_decimal_places=1
)
assert ViewSort.objects.count() == 0
view_sort = action_type_registry.get_by_type(CreateViewSortActionType).do(
user, grid_view, number_field, "DESC"
)
assert ViewSort.objects.filter(pk=view_sort.id).count() == 1
assert view_sort.view.id == grid_view.id
assert view_sort.field.id == number_field.id
assert view_sort.order == "DESC"
ActionHandler.undo(user, [ViewActionScopeType.value(grid_view.id)], session_id)
assert ViewSort.objects.filter(pk=view_sort.id).count() == 0 | [
9,
1046,
2796,
4564,
1179,
266
] |
async def METHOD_NAME(_: "ASGIConnection", route_handler: "BaseRouteHandler") -> None:
if not route_handler.opt or not route_handler.opt.get("allow_all"):
raise PermissionDeniedException("local") | [
125,
1586
] |
def METHOD_NAME(program, model, keywords):
if not has_program(program):
pytest.skip("Program '{}' not found.".format(program))
molecule = _get_molecule(program)
inp = AtomicInput(molecule=molecule, driver="energy", model=model, keywords=keywords)
with pytest.raises(qcng.exceptions.InputError) as e:
qcng.compute(inp, program, raise_error=True)
assert "QCSchema BasisSet for model.basis not implemented" in str(e.value) | [
9,
226,
5121,
-1,
1189
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.