input
stringlengths 11
7.65k
| target
stringlengths 22
8.26k
|
---|---|
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _read_flow(self, file_name):
return _read_pfm(file_name) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self, root, split="train", transforms=None):
super().__init__(root=root, transforms=transforms)
verify_str_arg(split, "split", valid_values=("train", "test"))
root = Path(root) / "hd1k"
if split == "train":
# There are 36 "sequences" and we don't want seq i to overlap with seq i + 1, so we need this for loop
for seq_idx in range(36):
flows = sorted(glob(str(root / "hd1k_flow_gt" / "flow_occ" / f"{seq_idx:06d}_*.png")))
images = sorted(glob(str(root / "hd1k_input" / "image_2" / f"{seq_idx:06d}_*.png")))
for i in range(len(flows) - 1):
self._flow_list += [flows[i]]
self._image_list += [[images[i], images[i + 1]]]
else:
images1 = sorted(glob(str(root / "hd1k_challenge" / "image_2" / "*10.png")))
images2 = sorted(glob(str(root / "hd1k_challenge" / "image_2" / "*11.png")))
for image1, image2 in zip(images1, images2):
self._image_list += [[image1, image2]]
if not self._image_list:
raise FileNotFoundError(
"Could not find the HD1K images. Please make sure the directory structure is correct."
) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _read_flow(self, file_name):
return _read_16bits_png_with_flow_and_valid_mask(file_name) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _read_flo(file_name):
"""Read .flo file in Middlebury format"""
# Code adapted from:
# http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy
# Everything needs to be in little Endian according to
# https://vision.middlebury.edu/flow/code/flow-code/README.txt
with open(file_name, "rb") as f:
magic = np.fromfile(f, "c", count=4).tobytes()
if magic != b"PIEH":
raise ValueError("Magic number incorrect. Invalid .flo file")
w = int(np.fromfile(f, "<i4", count=1))
h = int(np.fromfile(f, "<i4", count=1))
data = np.fromfile(f, "<f4", count=2 * w * h)
return data.reshape(h, w, 2).transpose(2, 0, 1) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _read_16bits_png_with_flow_and_valid_mask(file_name):
flow_and_valid = _read_png_16(file_name).to(torch.float32)
flow, valid_flow_mask = flow_and_valid[:2, :, :], flow_and_valid[2, :, :]
flow = (flow - 2 ** 15) / 64 # This conversion is explained somewhere on the kitti archive
valid_flow_mask = valid_flow_mask.bool()
# For consistency with other datasets, we convert to numpy
return flow.numpy(), valid_flow_mask.numpy() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def LogPABotMessage(message):
_pabotlog.info(message) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_engine_module_name():
engine = salt.engines.Engine({}, "foobar.start", {}, {}, {}, {}, name="foobar")
assert engine.name == "foobar" |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def resource_setup(cls):
super(VolumesActionsTest, cls).resource_setup()
# Create a test shared volume for attach/detach tests
cls.volume = cls.create_volume() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_attach_detach_volume_to_instance(self):
"""Test attaching and detaching volume to instance"""
# Create a server
server = self.create_server()
# Volume is attached and detached successfully from an instance
self.volumes_client.attach_volume(self.volume['id'],
instance_uuid=server['id'],
mountpoint='/dev/%s' %
CONF.compute.volume_device_name)
waiters.wait_for_volume_resource_status(self.volumes_client,
self.volume['id'], 'in-use')
self.volumes_client.detach_volume(self.volume['id'])
waiters.wait_for_volume_resource_status(self.volumes_client,
self.volume['id'], 'available') |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_volume_bootable(self):
"""Test setting and retrieving bootable flag of a volume"""
for bool_bootable in [True, False]:
self.volumes_client.set_bootable_volume(self.volume['id'],
bootable=bool_bootable)
fetched_volume = self.volumes_client.show_volume(
self.volume['id'])['volume']
# Get Volume information
# NOTE(masayukig): 'bootable' is "true" or "false" in the current
# cinder implementation. So we need to cast boolean values to str
# and make it lower to compare here.
self.assertEqual(str(bool_bootable).lower(),
fetched_volume['bootable']) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_get_volume_attachment(self):
"""Test getting volume attachments
Attach a volume to a server, and then retrieve volume's attachments
info.
"""
# Create a server
server = self.create_server()
# Verify that a volume's attachment information is retrieved
self.volumes_client.attach_volume(self.volume['id'],
instance_uuid=server['id'],
mountpoint='/dev/%s' %
CONF.compute.volume_device_name)
waiters.wait_for_volume_resource_status(self.volumes_client,
self.volume['id'],
'in-use')
self.addCleanup(waiters.wait_for_volume_resource_status,
self.volumes_client,
self.volume['id'], 'available')
self.addCleanup(self.volumes_client.detach_volume, self.volume['id'])
volume = self.volumes_client.show_volume(self.volume['id'])['volume']
attachment = volume['attachments'][0]
self.assertEqual('/dev/%s' %
CONF.compute.volume_device_name,
attachment['device'])
self.assertEqual(server['id'], attachment['server_id'])
self.assertEqual(self.volume['id'], attachment['id'])
self.assertEqual(self.volume['id'], attachment['volume_id']) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_volume_upload(self):
"""Test uploading volume to create an image"""
# NOTE(gfidente): the volume uploaded in Glance comes from setUpClass,
# it is shared with the other tests. After it is uploaded in Glance,
# there is no way to delete it from Cinder, so we delete it from Glance
# using the Glance images_client and from Cinder via tearDownClass.
image_name = data_utils.rand_name(self.__class__.__name__ + '-Image')
body = self.volumes_client.upload_volume(
self.volume['id'], image_name=image_name,
disk_format=CONF.volume.disk_format)['os-volume_upload_image']
image_id = body["image_id"]
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.images_client.delete_image,
image_id)
waiters.wait_for_image_status(self.images_client, image_id, 'active')
waiters.wait_for_volume_resource_status(self.volumes_client,
self.volume['id'], 'available')
image_info = self.images_client.show_image(image_id)
self.assertEqual(image_name, image_info['name'])
self.assertEqual(CONF.volume.disk_format, image_info['disk_format']) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_reserve_unreserve_volume(self):
"""Test reserving and unreserving volume"""
# Mark volume as reserved.
self.volumes_client.reserve_volume(self.volume['id'])
# To get the volume info
body = self.volumes_client.show_volume(self.volume['id'])['volume']
self.assertIn('attaching', body['status'])
# Unmark volume as reserved.
self.volumes_client.unreserve_volume(self.volume['id'])
# To get the volume info
body = self.volumes_client.show_volume(self.volume['id'])['volume']
self.assertIn('available', body['status']) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def setup_loader(request):
setup_loader_modules = {pdbedit: {}}
with pytest.helpers.loader_mock(request, setup_loader_modules) as loader_mock:
yield loader_mock |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_disk_usage_sensor_is_stateless():
sensor = disk_usage.DiskUsage()
ok_([] != sensor.measure()) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_when_no_users_returned_no_data_should_be_returned(verbose):
expected_users = {} if verbose else []
with patch.dict(
pdbedit.__salt__,
{
"cmd.run_all": MagicMock(
return_value={"stdout": "", "stderr": "", "retcode": 0}
)
},
):
actual_users = pdbedit.list_users(verbose=verbose)
assert actual_users == expected_users |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_when_verbose_and_retcode_is_nonzero_output_should_be_had():
expected_stderr = "this is something fnord"
with patch.dict(
pdbedit.__salt__,
{
"cmd.run_all": MagicMock(
return_value={"stdout": "", "stderr": expected_stderr, "retcode": 1}
)
},
), patch("salt.modules.pdbedit.log.error", autospec=True) as fake_error_log:
pdbedit.list_users(verbose=True)
actual_error = fake_error_log.mock_calls[0].args[0]
assert actual_error == expected_stderr |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_when_verbose_and_single_good_output_expected_data_should_be_parsed():
expected_data = {
"roscivs": {
"unix username": "roscivs",
"nt username": "bottia",
"full name": "Roscivs Bottia",
"user sid": "42",
"primary group sid": "99",
"home directory": r"\\samba\roscivs",
"account desc": "separators! xxx so long and thanks for all the fish",
"logoff time": "Sat, 14 Aug 2010 15:06:39 UTC",
"kickoff time": "Sat, 14 Aug 2010 15:06:39 UTC",
"password must change": "never",
}
}
pdb_output = dedent(
r"""
Unix username: roscivs
NT username: bottia
User SID: 42
Primary Group SID: 99
Full Name: Roscivs Bottia
Home Directory: \\samba\roscivs
Account desc: separators! xxx so long and thanks for all the fish
Logoff time: Sat, 14 Aug 2010 15:06:39 UTC
Kickoff time: Sat, 14 Aug 2010 15:06:39 UTC
Password must change: never
"""
).strip()
with patch.dict(
pdbedit.__salt__,
{
"cmd.run_all": MagicMock(
return_value={"stdout": pdb_output, "stderr": "", "retcode": 0}
)
},
):
actual_data = pdbedit.list_users(verbose=True)
assert actual_data == expected_data |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def setup_args(parser=None):
if parser is None:
parser = ParlaiParser(True, True, 'Check tasks for common errors')
# Get command line arguments
parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2)
parser.add_argument('-d', '--display-examples', type='bool', default=False)
parser.set_defaults(datatype='train:stream:ordered')
return parser |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_list(arg=None):
"""get list of messages"""
frappe.form_dict['limit_start'] = int(frappe.form_dict['limit_start'])
frappe.form_dict['limit_page_length'] = int(frappe.form_dict['limit_page_length'])
frappe.form_dict['user'] = frappe.session['user']
# set all messages as read
frappe.db.begin()
frappe.db.sql("""UPDATE `tabCommunication` set seen = 1
where
communication_type in ('Chat', 'Notification')
and reference_doctype = 'User'
and reference_name = %s""", frappe.session.user)
delete_notification_count_for("Messages")
frappe.local.flags.commit = True
if frappe.form_dict['contact'] == frappe.session['user']:
# return messages
return frappe.db.sql("""select * from `tabCommunication`
where
communication_type in ('Chat', 'Notification')
and reference_doctype ='User'
and (owner=%(contact)s
or reference_name=%(user)s
or owner=reference_name)
order by creation desc
limit %(limit_start)s, %(limit_page_length)s""", frappe.local.form_dict, as_dict=1)
else:
return frappe.db.sql("""select * from `tabCommunication`
where
communication_type in ('Chat', 'Notification')
and reference_doctype ='User'
and ((owner=%(contact)s and reference_name=%(user)s)
or (owner=%(contact)s and reference_name=%(contact)s))
order by creation desc
limit %(limit_start)s, %(limit_page_length)s""", frappe.local.form_dict, as_dict=1) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def report(world, counts, log_time):
report = world.report()
log = {
'missing_text': counts['missing_text'],
'missing_labels': counts['missing_labels'],
'missing_label_candidates': counts['missing_label_candidates'],
'empty_string_label_candidates': counts['empty_string_label_candidates'],
'label_candidates_with_missing_label': counts[
'label_candidates_with_missing_label'
],
'did_not_return_message': counts['did_not_return_message'],
}
text, log = log_time.log(report['exs'], world.num_examples(), log)
return text, log |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_active_users():
data = frappe.db.sql("""select name,
(select count(*) from tabSessions where user=tabUser.name
and timediff(now(), lastupdate) < time("01:00:00")) as has_session
from tabUser
where enabled=1 and
ifnull(user_type, '')!='Website User' and
name not in ({})
order by first_name""".format(", ".join(["%s"]*len(STANDARD_USERS))), STANDARD_USERS, as_dict=1)
# make sure current user is at the top, using has_session = 100
users = [d.name for d in data]
if frappe.session.user in users:
data[users.index(frappe.session.user)]["has_session"] = 100
else:
# in case of administrator
data.append({"name": frappe.session.user, "has_session": 100})
return data |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def warn(txt, act, opt):
if opt.get('display_examples'):
print(txt + ":\n" + str(act))
else:
warn_once(txt) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def post(txt, contact, parenttype=None, notify=False, subject=None):
"""post message"""
d = frappe.new_doc('Communication')
d.communication_type = 'Notification' if parenttype else 'Chat'
d.subject = subject
d.content = txt
d.reference_doctype = 'User'
d.reference_name = contact
d.sender = frappe.session.user
d.insert(ignore_permissions=True)
delete_notification_count_for("Messages")
if notify and cint(notify):
if contact==frappe.session.user:
_notify([user.name for user in get_enabled_system_users()], txt)
else:
_notify(contact, txt, subject)
return d |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def verify(opt):
if opt['datatype'] == 'train':
logging.warning("changing datatype from train to train:ordered")
opt['datatype'] = 'train:ordered'
opt.log()
# create repeat label agent and assign it to the specified task
agent = RepeatLabelAgent(opt)
world = create_task(opt, agent)
log_every_n_secs = opt.get('log_every_n_secs', -1)
if log_every_n_secs <= 0:
log_every_n_secs = float('inf')
log_time = TimeLogger()
counts = {}
counts['missing_text'] = 0
counts['missing_labels'] = 0
counts['missing_label_candidates'] = 0
counts['empty_string_label_candidates'] = 0
counts['label_candidates_with_missing_label'] = 0
counts['did_not_return_message'] = 0
# Show some example dialogs.
while not world.epoch_done():
world.parley()
act = world.acts[0]
if not isinstance(act, Message):
counts['did_not_return_message'] += 1
if 'text' not in act and 'image' not in act:
warn("warning: missing text field:\n", act, opt)
counts['missing_text'] += 1
if 'labels' not in act and 'eval_labels' not in act:
warn("warning: missing labels/eval_labels field:\n", act, opt)
counts['missing_labels'] += 1
else:
if 'label_candidates' not in act:
counts['missing_label_candidates'] += 1
else:
labels = act.get('labels', act.get('eval_labels'))
is_label_cand = {}
for l in labels:
is_label_cand[l] = False
for c in act['label_candidates']:
if c == '':
warn("warning: empty string label_candidate:\n", act, opt)
counts['empty_string_label_candidates'] += 1
if c in is_label_cand:
if is_label_cand[c] is True:
warn(
"warning: label mentioned twice in candidate_labels:\n",
act,
opt,
)
is_label_cand[c] = True
for _, has in is_label_cand.items():
if has is False:
warn("warning: label missing in candidate_labels:\n", act, opt)
counts['label_candidates_with_missing_label'] += 1
if log_time.time() > log_every_n_secs:
text, log = report(world, counts, log_time)
print(text)
try:
# print dataset size if available
logging.info(
f'Loaded {world.num_episodes()} episodes with a '
f'total of {world.num_examples()} examples'
)
except AttributeError:
pass
counts['exs'] = int(world.report()['exs'])
return counts |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def delete(arg=None):
frappe.get_doc("Communication", frappe.form_dict['name']).delete() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def verify_data(opt):
counts = verify(opt)
print(counts)
return counts |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def setup_args(cls):
return setup_args() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def run(self):
return verify_data(self.opt) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def block_size_filter(entity):
return (
entity.size[0] * 2 >= entity.size[1] * 2
and entity.size[1] <= 16
and entity.size[3] <= 4
) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self, auth_provider):
super(SnapshotsClientJSON, self).__init__(auth_provider)
self.service = CONF.volume.catalog_type
self.build_interval = CONF.volume.build_interval
self.build_timeout = CONF.volume.build_timeout |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def list_snapshots(self, params=None):
"""List all the snapshot."""
url = 'snapshots'
if params:
url += '?%s' % urllib.urlencode(params)
resp, body = self.get(url)
body = json.loads(body)
return resp, body['snapshots'] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def list_snapshots_with_detail(self, params=None):
"""List the details of all snapshots."""
url = 'snapshots/detail'
if params:
url += '?%s' % urllib.urlencode(params)
resp, body = self.get(url)
body = json.loads(body)
return resp, body['snapshots'] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_snapshot(self, snapshot_id):
"""Returns the details of a single snapshot."""
url = "snapshots/%s" % str(snapshot_id)
resp, body = self.get(url)
body = json.loads(body)
return resp, body['snapshot'] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def create_snapshot(self, volume_id, **kwargs):
"""
Creates a new snapshot.
volume_id(Required): id of the volume.
force: Create a snapshot even if the volume attached (Default=False)
display_name: Optional snapshot Name.
display_description: User friendly snapshot description.
"""
post_body = {'volume_id': volume_id}
post_body.update(kwargs)
post_body = json.dumps({'snapshot': post_body})
resp, body = self.post('snapshots', post_body)
body = json.loads(body)
return resp, body['snapshot'] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def update_snapshot(self, snapshot_id, **kwargs):
"""Updates a snapshot."""
put_body = json.dumps({'snapshot': kwargs})
resp, body = self.put('snapshots/%s' % snapshot_id, put_body)
body = json.loads(body)
return resp, body['snapshot'] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _get_snapshot_status(self, snapshot_id):
resp, body = self.get_snapshot(snapshot_id)
status = body['status']
# NOTE(afazekas): snapshot can reach an "error"
# state in a "normal" lifecycle
if (status == 'error'):
raise exceptions.SnapshotBuildErrorException(
snapshot_id=snapshot_id)
return status |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def wait_for_snapshot_status(self, snapshot_id, status):
"""Waits for a Snapshot to reach a given status."""
start_time = time.time()
old_value = value = self._get_snapshot_status(snapshot_id)
while True:
dtime = time.time() - start_time
time.sleep(self.build_interval)
if value != old_value:
LOG.info('Value transition from "%s" to "%s"'
'in %d second(s).', old_value,
value, dtime)
if (value == status):
return value
if dtime > self.build_timeout:
message = ('Time Limit Exceeded! (%ds)'
'while waiting for %s, '
'but we got %s.' %
(self.build_timeout, status, value))
raise exceptions.TimeoutException(message)
time.sleep(self.build_interval)
old_value = value
value = self._get_snapshot_status(snapshot_id) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def delete_snapshot(self, snapshot_id):
"""Delete Snapshot."""
return self.delete("snapshots/%s" % str(snapshot_id)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def is_resource_deleted(self, id):
try:
self.get_snapshot(id)
except exceptions.NotFound:
return True
return False |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def reset_snapshot_status(self, snapshot_id, status):
"""Reset the specified snapshot's status."""
post_body = json.dumps({'os-reset_status': {"status": status}})
resp, body = self.post('snapshots/%s/action' % snapshot_id, post_body)
return resp, body |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def update_snapshot_status(self, snapshot_id, status, progress):
"""Update the specified snapshot's status."""
post_body = {
'status': status,
'progress': progress
}
post_body = json.dumps({'os-update_snapshot_status': post_body})
url = 'snapshots/%s/action' % str(snapshot_id)
resp, body = self.post(url, post_body)
return resp, body |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def create_snapshot_metadata(self, snapshot_id, metadata):
"""Create metadata for the snapshot."""
put_body = json.dumps({'metadata': metadata})
url = "snapshots/%s/metadata" % str(snapshot_id)
resp, body = self.post(url, put_body)
body = json.loads(body)
return resp, body['metadata'] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_snapshot_metadata(self, snapshot_id):
"""Get metadata of the snapshot."""
url = "snapshots/%s/metadata" % str(snapshot_id)
resp, body = self.get(url)
body = json.loads(body)
return resp, body['metadata'] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def update_snapshot_metadata(self, snapshot_id, metadata):
"""Update metadata for the snapshot."""
put_body = json.dumps({'metadata': metadata})
url = "snapshots/%s/metadata" % str(snapshot_id)
resp, body = self.put(url, put_body)
body = json.loads(body)
return resp, body['metadata'] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def update_snapshot_metadata_item(self, snapshot_id, id, meta_item):
"""Update metadata item for the snapshot."""
put_body = json.dumps({'meta': meta_item})
url = "snapshots/%s/metadata/%s" % (str(snapshot_id), str(id))
resp, body = self.put(url, put_body)
body = json.loads(body)
return resp, body['meta'] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def delete_snapshot_metadata_item(self, snapshot_id, id):
"""Delete metadata item for the snapshot."""
url = "snapshots/%s/metadata/%s" % (str(snapshot_id), str(id))
resp, body = self.delete(url)
return resp, body |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def name(self):
if self._values['name'] is None:
return None
name = str(self._values['name']).strip()
if name == '':
raise F5ModuleError(
"You must specify a name for this module"
)
return name |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self, client):
self.client = client
self.have = None
self.want = Parameters(self.client.module.params)
self.changes = Parameters() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum") |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Parameters(changed) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _update_changed_options(self):
changed = {}
for key in Parameters.updatables:
if getattr(self.want, key) is not None:
attr1 = getattr(self.want, key)
attr2 = getattr(self.have, key)
if attr1 != attr2:
changed[key] = attr1
if changed:
self.changes = Parameters(changed)
return True
return False |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _pool_is_licensed(self):
if self.have.state == 'LICENSED':
return True
return False |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _pool_is_unlicensed_eula_unaccepted(self, current):
if current.state != 'LICENSED' and not self.want.accept_eula:
return True
return False |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def exec_module(self):
changed = False
result = dict()
state = self.want.state
try:
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(str(e))
result.update(**self.changes.to_return())
result.update(dict(changed=changed))
return result |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def exists(self):
collection = self.client.api.cm.shared.licensing.pools_s.get_collection(
requests_params=dict(
params="$filter=name+eq+'{0}'".format(self.want.name)
)
)
if len(collection) == 1:
return True
elif len(collection) == 0:
return False
else:
raise F5ModuleError(
"Multiple license pools with the provided name were found!"
) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def should_update(self):
if self._pool_is_licensed():
return False
if self._pool_is_unlicensed_eula_unaccepted():
return False
return True |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def update(self):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.module.check_mode:
return True
self.update_on_device()
return True |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def update_on_device(self):
collection = self.client.api.cm.shared.licensing.pools_s.get_collection(
requests_params=dict(
params="$filter=name+eq+'{0}'".format(self.want.name)
)
)
resource = collection.pop()
resource.modify(
state='RELICENSE',
method='AUTOMATIC'
)
return self._wait_for_license_pool_state_to_activate(resource) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def create(self):
self._set_changed_options()
if self.client.check_mode:
return True
if self.want.base_key is None:
raise F5ModuleError(
"You must specify a 'base_key' when creating a license pool"
)
self.create_on_device()
return True |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def read_current_from_device(self):
collection = self.client.api.cm.shared.licensing.pools_s.get_collection(
requests_params=dict(
params="$filter=name+eq+'{0}'".format(self.want.name)
)
)
resource = collection.pop()
result = resource.attrs
return Parameters(result) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def create_on_device(self):
resource = self.client.api.cm.shared.licensing.pools_s.pool.create(
name=self.want.name,
baseRegKey=self.want.base_key,
method="AUTOMATIC"
)
return self._wait_for_license_pool_state_to_activate(resource) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _wait_for_license_pool_state_to_activate(self, pool):
error_values = ['EXPIRED', 'FAILED']
# Wait no more than 5 minutes
for x in range(1, 30):
pool.refresh()
if pool.state == 'LICENSED':
return True
elif pool.state == 'WAITING_FOR_EULA_ACCEPTANCE':
pool.modify(
eulaText=pool.eulaText,
state='ACCEPTED_EULA'
)
elif pool.state in error_values:
raise F5ModuleError(pool.errorText)
time.sleep(10) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def remove(self):
if self.client.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the license pool")
return True |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def remove_from_device(self):
collection = self.client.api.cm.shared.licensing.pools_s.get_collection(
requests_params=dict(
params="$filter=name+eq+'{0}'".format(self.want.name)
)
)
resource = collection.pop()
if resource:
resource.delete() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
accept_eula=dict(
type='bool',
default='no',
choices=BOOLEANS
),
base_key=dict(
required=False,
no_log=True
),
name=dict(
required=True
),
state=dict(
required=False,
default='present',
choices=['absent', 'present']
)
)
self.f5_product_name = 'iworkflow' |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def main():
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
spec = ArgumentSpec()
client = AnsibleF5Client(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
)
try:
mm = ModuleManager(client)
results = mm.exec_module()
client.module.exit_json(**results)
except F5ModuleError as e:
client.module.fail_json(msg=str(e)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self, protocol: ProtocolAnalyzerContainer, label_index: int, msg_index: int, proto_view: int,
parent=None):
super().__init__(parent)
self.ui = Ui_FuzzingDialog()
self.ui.setupUi(self)
self.setAttribute(Qt.WA_DeleteOnClose)
self.setWindowFlags(Qt.Window)
self.protocol = protocol
msg_index = msg_index if msg_index != -1 else 0
self.ui.spinBoxFuzzMessage.setValue(msg_index + 1)
self.ui.spinBoxFuzzMessage.setMinimum(1)
self.ui.spinBoxFuzzMessage.setMaximum(self.protocol.num_messages)
self.ui.comboBoxFuzzingLabel.addItems([l.name for l in self.message.message_type])
self.ui.comboBoxFuzzingLabel.setCurrentIndex(label_index)
self.proto_view = proto_view
self.fuzz_table_model = FuzzingTableModel(self.current_label, proto_view)
self.fuzz_table_model.remove_duplicates = self.ui.chkBRemoveDuplicates.isChecked()
self.ui.tblFuzzingValues.setModel(self.fuzz_table_model)
self.fuzz_table_model.update()
self.ui.spinBoxFuzzingStart.setValue(self.current_label_start + 1)
self.ui.spinBoxFuzzingEnd.setValue(self.current_label_end)
self.ui.spinBoxFuzzingStart.setMaximum(len(self.message_data))
self.ui.spinBoxFuzzingEnd.setMaximum(len(self.message_data))
self.update_message_data_string()
self.ui.tblFuzzingValues.resize_me()
self.create_connects()
self.restoreGeometry(settings.read("{}/geometry".format(self.__class__.__name__), type=bytes)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def setUp(self):
self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError)
self.oFile.set_indent_map(dIndentMap) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def message(self):
return self.protocol.messages[int(self.ui.spinBoxFuzzMessage.value() - 1)] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_rule_300(self):
oRule = iteration_scheme.rule_300()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'iteration_scheme')
self.assertEqual(oRule.identifier, '300')
lExpected = [13, 17]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def current_label_index(self):
return self.ui.comboBoxFuzzingLabel.currentIndex() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def current_label(self) -> ProtocolLabel:
if len(self.message.message_type) == 0:
return None
cur_label = self.message.message_type[self.current_label_index].get_copy()
self.message.message_type[self.current_label_index] = cur_label
cur_label.fuzz_values = [fv for fv in cur_label.fuzz_values if fv] # Remove empty strings
if len(cur_label.fuzz_values) == 0:
cur_label.fuzz_values.append(self.message.plain_bits_str[cur_label.start:cur_label.end])
return cur_label |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def current_label_start(self):
if self.current_label and self.message:
return self.message.get_label_range(self.current_label, self.proto_view, False)[0]
else:
return -1 |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def current_label_end(self):
if self.current_label and self.message:
return self.message.get_label_range(self.current_label, self.proto_view, False)[1]
else:
return -1 |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def message_data(self):
if self.proto_view == 0:
return self.message.plain_bits_str
elif self.proto_view == 1:
return self.message.plain_hex_str
elif self.proto_view == 2:
return self.message.plain_ascii_str
else:
return None |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def create_connects(self):
self.ui.spinBoxFuzzingStart.valueChanged.connect(self.on_fuzzing_start_changed)
self.ui.spinBoxFuzzingEnd.valueChanged.connect(self.on_fuzzing_end_changed)
self.ui.comboBoxFuzzingLabel.currentIndexChanged.connect(self.on_combo_box_fuzzing_label_current_index_changed)
self.ui.btnRepeatValues.clicked.connect(self.on_btn_repeat_values_clicked)
self.ui.btnAddRow.clicked.connect(self.on_btn_add_row_clicked)
self.ui.btnDelRow.clicked.connect(self.on_btn_del_row_clicked)
self.ui.tblFuzzingValues.deletion_wanted.connect(self.delete_lines)
self.ui.chkBRemoveDuplicates.stateChanged.connect(self.on_remove_duplicates_state_changed)
self.ui.sBAddRangeStart.valueChanged.connect(self.on_fuzzing_range_start_changed)
self.ui.sBAddRangeEnd.valueChanged.connect(self.on_fuzzing_range_end_changed)
self.ui.checkBoxLowerBound.stateChanged.connect(self.on_lower_bound_checked_changed)
self.ui.checkBoxUpperBound.stateChanged.connect(self.on_upper_bound_checked_changed)
self.ui.spinBoxLowerBound.valueChanged.connect(self.on_lower_bound_changed)
self.ui.spinBoxUpperBound.valueChanged.connect(self.on_upper_bound_changed)
self.ui.spinBoxRandomMinimum.valueChanged.connect(self.on_random_range_min_changed)
self.ui.spinBoxRandomMaximum.valueChanged.connect(self.on_random_range_max_changed)
self.ui.spinBoxFuzzMessage.valueChanged.connect(self.on_fuzz_msg_changed)
self.ui.btnAddFuzzingValues.clicked.connect(self.on_btn_add_fuzzing_values_clicked)
self.ui.comboBoxFuzzingLabel.editTextChanged.connect(self.set_current_label_name) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def update_message_data_string(self):
fuz_start = self.current_label_start
fuz_end = self.current_label_end
num_proto_bits = 10
num_fuz_bits = 16
proto_start = fuz_start - num_proto_bits
preambel = "... "
if proto_start <= 0:
proto_start = 0
preambel = ""
proto_end = fuz_end + num_proto_bits
postambel = " ..."
if proto_end >= len(self.message_data) - 1:
proto_end = len(self.message_data) - 1
postambel = ""
fuzamble = ""
if fuz_end - fuz_start > num_fuz_bits:
fuz_end = fuz_start + num_fuz_bits
fuzamble = "..."
self.ui.lPreBits.setText(preambel + self.message_data[proto_start:self.current_label_start])
self.ui.lFuzzedBits.setText(self.message_data[fuz_start:fuz_end] + fuzamble)
self.ui.lPostBits.setText(self.message_data[self.current_label_end:proto_end] + postambel)
self.set_add_spinboxes_maximum_on_label_change() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def closeEvent(self, event: QCloseEvent):
settings.write("{}/geometry".format(self.__class__.__name__), self.saveGeometry())
super().closeEvent(event) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_fuzzing_start_changed(self, value: int):
self.ui.spinBoxFuzzingEnd.setMinimum(self.ui.spinBoxFuzzingStart.value())
new_start = self.message.convert_index(value - 1, self.proto_view, 0, False)[0]
self.current_label.start = new_start
self.current_label.fuzz_values[:] = []
self.update_message_data_string()
self.fuzz_table_model.update()
self.ui.tblFuzzingValues.resize_me() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_fuzzing_end_changed(self, value: int):
self.ui.spinBoxFuzzingStart.setMaximum(self.ui.spinBoxFuzzingEnd.value())
new_end = self.message.convert_index(value - 1, self.proto_view, 0, False)[1] + 1
self.current_label.end = new_end
self.current_label.fuzz_values[:] = []
self.update_message_data_string()
self.fuzz_table_model.update()
self.ui.tblFuzzingValues.resize_me() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_combo_box_fuzzing_label_current_index_changed(self, index: int):
self.fuzz_table_model.fuzzing_label = self.current_label
self.fuzz_table_model.update()
self.update_message_data_string()
self.ui.tblFuzzingValues.resize_me()
self.ui.spinBoxFuzzingStart.blockSignals(True)
self.ui.spinBoxFuzzingStart.setValue(self.current_label_start + 1)
self.ui.spinBoxFuzzingStart.blockSignals(False)
self.ui.spinBoxFuzzingEnd.blockSignals(True)
self.ui.spinBoxFuzzingEnd.setValue(self.current_label_end)
self.ui.spinBoxFuzzingEnd.blockSignals(False) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_btn_add_row_clicked(self):
self.current_label.add_fuzz_value()
self.fuzz_table_model.update() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_btn_del_row_clicked(self):
min_row, max_row, _, _ = self.ui.tblFuzzingValues.selection_range()
self.delete_lines(min_row, max_row) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def delete_lines(self, min_row, max_row):
if min_row == -1:
self.current_label.fuzz_values = self.current_label.fuzz_values[:-1]
else:
self.current_label.fuzz_values = self.current_label.fuzz_values[:min_row] + self.current_label.fuzz_values[
max_row + 1:]
_ = self.current_label # if user deleted all, this will restore a fuzz value
self.fuzz_table_model.update() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_remove_duplicates_state_changed(self):
self.fuzz_table_model.remove_duplicates = self.ui.chkBRemoveDuplicates.isChecked()
self.fuzz_table_model.update()
self.remove_duplicates() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def set_add_spinboxes_maximum_on_label_change(self):
nbits = self.current_label.end - self.current_label.start # Use Bit Start/End for maximum calc.
if nbits >= 32:
nbits = 31
max_val = 2 ** nbits - 1
self.ui.sBAddRangeStart.setMaximum(max_val - 1)
self.ui.sBAddRangeEnd.setMaximum(max_val)
self.ui.sBAddRangeEnd.setValue(max_val)
self.ui.sBAddRangeStep.setMaximum(max_val)
self.ui.spinBoxLowerBound.setMaximum(max_val - 1)
self.ui.spinBoxUpperBound.setMaximum(max_val)
self.ui.spinBoxUpperBound.setValue(max_val)
self.ui.spinBoxBoundaryNumber.setMaximum(int(max_val / 2) + 1)
self.ui.spinBoxRandomMinimum.setMaximum(max_val - 1)
self.ui.spinBoxRandomMaximum.setMaximum(max_val)
self.ui.spinBoxRandomMaximum.setValue(max_val) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_fuzzing_range_start_changed(self, value: int):
self.ui.sBAddRangeEnd.setMinimum(value)
self.ui.sBAddRangeStep.setMaximum(self.ui.sBAddRangeEnd.value() - value) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_fuzzing_range_end_changed(self, value: int):
self.ui.sBAddRangeStart.setMaximum(value - 1)
self.ui.sBAddRangeStep.setMaximum(value - self.ui.sBAddRangeStart.value()) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_lower_bound_checked_changed(self):
if self.ui.checkBoxLowerBound.isChecked():
self.ui.spinBoxLowerBound.setEnabled(True)
self.ui.spinBoxBoundaryNumber.setEnabled(True)
elif not self.ui.checkBoxUpperBound.isChecked():
self.ui.spinBoxLowerBound.setEnabled(False)
self.ui.spinBoxBoundaryNumber.setEnabled(False)
else:
self.ui.spinBoxLowerBound.setEnabled(False) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_upper_bound_checked_changed(self):
if self.ui.checkBoxUpperBound.isChecked():
self.ui.spinBoxUpperBound.setEnabled(True)
self.ui.spinBoxBoundaryNumber.setEnabled(True)
elif not self.ui.checkBoxLowerBound.isChecked():
self.ui.spinBoxUpperBound.setEnabled(False)
self.ui.spinBoxBoundaryNumber.setEnabled(False)
else:
self.ui.spinBoxUpperBound.setEnabled(False) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_lower_bound_changed(self):
self.ui.spinBoxUpperBound.setMinimum(self.ui.spinBoxLowerBound.value())
self.ui.spinBoxBoundaryNumber.setMaximum(math.ceil((self.ui.spinBoxUpperBound.value()
- self.ui.spinBoxLowerBound.value()) / 2)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_upper_bound_changed(self):
self.ui.spinBoxLowerBound.setMaximum(self.ui.spinBoxUpperBound.value() - 1)
self.ui.spinBoxBoundaryNumber.setMaximum(math.ceil((self.ui.spinBoxUpperBound.value()
- self.ui.spinBoxLowerBound.value()) / 2)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def on_random_range_min_changed(self):
self.ui.spinBoxRandomMaximum.setMinimum(self.ui.spinBoxRandomMinimum.value()) |
Subsets and Splits